@getcodesentinel/codesentinel 1.34.0 → 1.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../../dependency-firewall/src/domain/types.ts","../../dependency-firewall/src/domain/external-analysis.ts","../../dependency-firewall/src/application/map-with-concurrency.ts","../../dependency-firewall/src/application/collect-dependency-metadata.ts","../../dependency-firewall/src/application/dependency-exposure-pipeline.ts","../../dependency-firewall/src/infrastructure/fs-loader.ts","../../dependency-firewall/src/parsing/package-json-loader.ts","../../dependency-firewall/src/parsing/package-lock-parser.ts","../../dependency-firewall/src/parsing/pnpm-lock-parser.ts","../../dependency-firewall/src/parsing/yarn-lock-parser.ts","../../dependency-firewall/src/parsing/bun-lock-parser.ts","../../dependency-firewall/src/application/parse-lockfile-extraction.ts","../../dependency-firewall/src/infrastructure/cached-fetch.ts","../../dependency-firewall/src/infrastructure/fetch-json-with-retry.ts","../../dependency-firewall/src/infrastructure/npm-metadata-cache.ts","../../dependency-firewall/src/infrastructure/codesentinel-cache-dir.ts","../../dependency-firewall/src/infrastructure/file-cache-store.ts","../../dependency-firewall/src/application/resolve-registry-graph.ts","../../dependency-firewall/src/application/prepare-dependency-extraction.ts","../../dependency-firewall/src/infrastructure/workspace-package-manifests.ts","../../dependency-firewall/src/application/analyze-dependency-exposure.ts","../../dependency-firewall/src/application/analyze-dependency-candidate.ts","../../dependency-firewall/src/infrastructure/npm-registry-metadata-provider.ts","../../dependency-firewall/src/infrastructure/noop-metadata-provider.ts","../../dependency-firewall/src/index.ts","../../reporter/src/domain.ts","../../reporter/src/diff.ts","../../reporter/src/report.ts","../../reporter/src/renderers.ts","../../reporter/src/snapshot.ts","../../reporter/src/index.ts","../../governance/src/domain.ts","../../governance/src/evaluate-gates.ts","../../governance/src/render.ts","../../governance/src/baseline-ref.ts","../../governance/src/baseline-auto-resolver.ts","../src/application/format-analyze-output.ts","../src/application/format-explain-output.ts","../src/application/format-dependency-risk-output.ts","../src/application/logger.ts","../src/application/check-for-updates.ts","../src/application/interactive-menu.ts","../src/application/run-analyze-command.ts","../../core/src/index.ts","../../code-graph/src/domain/graph-model.ts","../../code-graph/src/domain/graph-metrics.ts","../../code-graph/src/domain/tarjan.ts","../../code-graph/src/infrastructure/typescript-project.ts","../../code-graph/src/infrastructure/workspace-discovery.ts","../../code-graph/src/application/build-project-graph-summary.ts","../../git-analyzer/src/domain/evolution-metrics.ts","../../git-analyzer/src/domain/evolution-types.ts","../../git-analyzer/src/application/analyze-repository-evolution.ts","../../git-analyzer/src/application/enrich-evolution-with-workspaces.ts","../../git-analyzer/src/infrastructure/git-command-client.ts","../../git-analyzer/src/domain/git-log-format.ts","../../git-analyzer/src/application/git-history-provider.ts","../../git-analyzer/src/parsing/git-log-parser.ts","../../git-analyzer/src/infrastructure/git-history-provider.ts","../../git-analyzer/src/index.ts","../../health-engine/src/domain/math.ts","../../health-engine/src/application/compute-repository-health-summary.ts","../../risk-engine/src/config.ts","../../risk-engine/src/domain/risk-model.ts","../../risk-engine/src/domain/math.ts","../../risk-engine/src/domain/normalization.ts","../../risk-engine/src/domain/trace-collector.ts","../../risk-engine/src/application/compute-repository-risk-summary.ts","../src/application/run-check-command.ts","../src/application/build-analysis-snapshot.ts","../src/application/run-ci-command.ts","../src/application/build-ownership-audit.ts","../../ownership/src/domain/codeowners.ts","../../ownership/src/domain/matcher.ts","../../ownership/src/domain/identity.ts","../../ownership/src/domain/classify.ts","../../ownership/src/domain/metrics.ts","../../ownership/src/application/parse-codeowners.ts","../../ownership/src/application/resolve-identities.ts","../../ownership/src/application/audit-ownership.ts","../src/application/owners-git.ts","../src/application/run-report-command.ts","../src/application/html-report.ts","../src/application/open-path.ts","../src/application/report-ownership.ts","../src/application/run-explain-command.ts","../src/application/run-owners-command.ts","../src/application/format-owners-output.ts"],"sourcesContent":["import { Command, CommanderError, Option } from \"commander\";\nimport { analyzeDependencyCandidateFromRegistry } from \"@codesentinel/dependency-firewall\";\nimport { EXIT_CODES, type GateConfig } from \"@codesentinel/governance\";\nimport {\n compareSnapshots,\n createReport,\n createSnapshot,\n formatReport,\n parseSnapshot,\n} from \"@codesentinel/reporter\";\nimport { readFileSync } from \"node:fs\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n formatAnalyzeOutput,\n type AnalyzeOutputMode,\n} from \"./application/format-analyze-output.js\";\nimport { formatExplainOutput } from \"./application/format-explain-output.js\";\nimport {\n formatDependencyRiskOutput,\n type DependencyRiskOutputMode,\n} from \"./application/format-dependency-risk-output.js\";\nimport { createStderrLogger, parseLogLevel, type LogLevel } from \"./application/logger.js\";\nimport { checkForCliUpdates, runManualCliUpdate } from \"./application/check-for-updates.js\";\nimport { runInteractiveCliMenu } from \"./application/interactive-menu.js\";\nimport {\n runAnalyzeCommand,\n type AuthorIdentityCliMode,\n type ScoringProfileCliMode,\n} from \"./application/run-analyze-command.js\";\nimport {\n GovernanceConfigurationError as CheckConfigurationError,\n runCheckCommand,\n type CheckOutputFormat,\n} from \"./application/run-check-command.js\";\nimport {\n GovernanceConfigurationError as CiConfigurationError,\n runCiCommand,\n} from \"./application/run-ci-command.js\";\nimport { runReportCommand } from \"./application/run-report-command.js\";\nimport { runExplainCommand, type ExplainFormat } from \"./application/run-explain-command.js\";\nimport {\n OWNERS_EXIT_CODES,\n OwnersConfigurationError,\n runOwnersCommand,\n type OwnersCommandOptions,\n} from \"./application/run-owners-command.js\";\nimport type { OwnersFailOn, OwnersOutputFormat } from \"./application/format-owners-output.js\";\nimport { writeHtmlReportBundle } from \"./application/html-report.js\";\nimport { openPath } from \"./application/open-path.js\";\n\nconst program = new Command();\nconst packageJsonPath = resolve(dirname(fileURLToPath(import.meta.url)), \"../package.json\");\nconst { version } = JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as { version: string };\n\nconst parseRecentWindowDays = (value: string): number => {\n const parsed = Number.parseInt(value, 10);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new Error(\"--recent-window-days must be a positive integer\");\n }\n return parsed;\n};\n\ntype RunDetail = \"compact\" | \"standard\" | \"full\";\n\nconst stripLeadingMarkdownHeading = (value: string, heading: string): string => {\n const prefix = `${heading}\\n`;\n if (value.startsWith(prefix)) {\n return value.slice(prefix.length).trimStart();\n }\n\n return value;\n};\n\nconst extractExplainTextSummary = (text: string): string => {\n const splitIndex = text.search(/\\n\\n(?:file|module|dependency|repository): /);\n if (splitIndex < 0) {\n return text.trim();\n }\n\n return text.slice(0, splitIndex).trim();\n};\n\nconst extractExplainMarkdownSummary = (markdown: string): string => {\n const splitIndex = markdown.search(/\\n\\n## (?:file|module|dependency|repository): /);\n if (splitIndex < 0) {\n return markdown.trim();\n }\n\n return markdown.slice(0, splitIndex).trim();\n};\n\nconst extractSummaryValue = (summary: string, key: string): string | undefined => {\n const prefix = `${key}: `;\n for (const rawLine of summary.split(\"\\n\")) {\n const line = rawLine.trimStart();\n if (line.startsWith(prefix)) {\n return line.slice(prefix.length).trim();\n }\n }\n\n return undefined;\n};\n\nconst renderReportHighlightsText = (\n report: Awaited<ReturnType<typeof runReportCommand>>[\"report\"],\n) => {\n const lines: string[] = [];\n lines.push(\"Repository Summary\");\n lines.push(` target: ${report.repository.targetPath}`);\n lines.push(` riskScore: ${report.repository.riskScore}`);\n lines.push(` healthScore: ${report.health.healthScore}`);\n lines.push(` normalizedScore: ${report.repository.normalizedScore}`);\n lines.push(` riskTier: ${report.repository.riskTier}`);\n lines.push(` healthTier: ${report.repository.healthTier}`);\n lines.push(\"\");\n lines.push(\"Top Hotspots\");\n for (const hotspot of report.hotspots.slice(0, 5)) {\n lines.push(` - ${hotspot.target} | score=${hotspot.score}`);\n lines.push(` priority actions: ${hotspot.suggestedActions.join(\" | \") || \"none\"}`);\n }\n\n return lines.join(\"\\n\");\n};\n\nconst renderReportHighlightsMarkdown = (\n report: Awaited<ReturnType<typeof runReportCommand>>[\"report\"],\n): string => {\n const lines: string[] = [];\n lines.push(\"## Repository Summary\");\n lines.push(`- target: \\`${report.repository.targetPath}\\``);\n lines.push(`- riskScore: \\`${report.repository.riskScore}\\``);\n lines.push(`- healthScore: \\`${report.health.healthScore}\\``);\n lines.push(`- normalizedScore: \\`${report.repository.normalizedScore}\\``);\n lines.push(`- riskTier: \\`${report.repository.riskTier}\\``);\n lines.push(`- healthTier: \\`${report.repository.healthTier}\\``);\n lines.push(\"\");\n lines.push(\"## Top Hotspots\");\n for (const hotspot of report.hotspots.slice(0, 5)) {\n lines.push(`- **${hotspot.target}** (score: \\`${hotspot.score}\\`)`);\n lines.push(` - priority actions: ${hotspot.suggestedActions.join(\" | \") || \"none\"}`);\n }\n\n return lines.join(\"\\n\");\n};\n\nconst renderCompactText = (\n report: Awaited<ReturnType<typeof runReportCommand>>[\"report\"],\n explainSummary: string,\n): string => {\n const lines: string[] = [];\n lines.push(\"CodeSentinel Run (compact)\");\n lines.push(\"\");\n lines.push(\"Repository\");\n lines.push(` target: ${report.repository.targetPath}`);\n lines.push(` riskScore: ${report.repository.riskScore}`);\n lines.push(` healthScore: ${report.health.healthScore}`);\n lines.push(` riskTier: ${report.repository.riskTier}`);\n lines.push(` healthTier: ${report.repository.healthTier}`);\n lines.push(\n ` dimensions: structural=${report.repository.dimensionScores.structural ?? \"n/a\"}, evolution=${report.repository.dimensionScores.evolution ?? \"n/a\"}, external=${report.repository.dimensionScores.external ?? \"n/a\"}, interactions=${report.repository.dimensionScores.interactions ?? \"n/a\"}`,\n );\n lines.push(\"\");\n lines.push(\n `Key Drivers: ${extractSummaryValue(explainSummary, \"key drivers\") ?? \"insufficient data\"}`,\n );\n lines.push(\n `Priority Actions: ${extractSummaryValue(explainSummary, \"priority actions\") ?? \"insufficient data\"}`,\n );\n lines.push(\"\");\n lines.push(\"Top Hotspots\");\n for (const hotspot of report.hotspots.slice(0, 3)) {\n lines.push(` - ${hotspot.target} | score=${hotspot.score}`);\n }\n\n return lines.join(\"\\n\");\n};\n\nconst renderCompactMarkdown = (\n report: Awaited<ReturnType<typeof runReportCommand>>[\"report\"],\n explainSummary: string,\n): string => {\n const lines: string[] = [];\n lines.push(\"# CodeSentinel Run (compact)\");\n lines.push(\"\");\n lines.push(\"## Repository\");\n lines.push(`- target: \\`${report.repository.targetPath}\\``);\n lines.push(`- riskScore: \\`${report.repository.riskScore}\\``);\n lines.push(`- healthScore: \\`${report.health.healthScore}\\``);\n lines.push(`- riskTier: \\`${report.repository.riskTier}\\``);\n lines.push(`- healthTier: \\`${report.repository.healthTier}\\``);\n lines.push(\n `- dimensions: structural=\\`${report.repository.dimensionScores.structural ?? \"n/a\"}\\`, evolution=\\`${report.repository.dimensionScores.evolution ?? \"n/a\"}\\`, external=\\`${report.repository.dimensionScores.external ?? \"n/a\"}\\`, interactions=\\`${report.repository.dimensionScores.interactions ?? \"n/a\"}\\``,\n );\n lines.push(\"\");\n lines.push(\n `- key drivers: ${extractSummaryValue(explainSummary, \"- key drivers\") ?? \"insufficient data\"}`,\n );\n lines.push(\n `- priority actions: ${extractSummaryValue(explainSummary, \"- priority actions\") ?? \"insufficient data\"}`,\n );\n lines.push(\"\");\n lines.push(\"## Top Hotspots\");\n for (const hotspot of report.hotspots.slice(0, 3)) {\n lines.push(`- \\`${hotspot.target}\\` (score: \\`${hotspot.score}\\`)`);\n }\n\n return lines.join(\"\\n\");\n};\n\nconst scoringProfileOption = (): Option =>\n new Option(\n \"--scoring-profile <profile>\",\n \"scoring profile: default (balanced) or personal (down-weights single-maintainer ownership penalties for risk and health ownership)\",\n )\n .choices([\"default\", \"personal\"])\n .default(\"default\");\n\nprogram\n .name(\"codesentinel\")\n .description(\"Structural and evolutionary risk analysis for TypeScript/JavaScript codebases\")\n .version(version);\n\nprogram\n .command(\"update\")\n .description(\"check for a newer CodeSentinel version and install it\")\n .action(async () => {\n process.exitCode = await runManualCliUpdate({\n packageName: \"@getcodesentinel/codesentinel\",\n currentVersion: version,\n });\n });\n\nprogram\n .command(\"analyze\")\n .argument(\"[path]\", \"path to the project to analyze\")\n .addOption(scoringProfileOption())\n .addOption(\n new Option(\n \"--author-identity <mode>\",\n \"author identity mode: likely_merge (heuristic) or strict_email (deterministic)\",\n )\n .choices([\"likely_merge\", \"strict_email\"])\n .default(\"likely_merge\"),\n )\n .addOption(\n new Option(\n \"--log-level <level>\",\n \"log verbosity: silent, error, warn, info, debug (logs are written to stderr)\",\n )\n .choices([\"silent\", \"error\", \"warn\", \"info\", \"debug\"])\n .default(parseLogLevel(process.env[\"CODESENTINEL_LOG_LEVEL\"])),\n )\n .addOption(\n new Option(\"--output <mode>\", \"output mode: summary (default) or json (full analysis object)\")\n .choices([\"summary\", \"json\"])\n .default(\"summary\"),\n )\n .option(\"--json\", \"shortcut for --output json\")\n .addOption(\n new Option(\n \"--recent-window-days <days>\",\n \"git recency window in days used for evolution volatility metrics\",\n )\n .argParser(parseRecentWindowDays)\n .default(30),\n )\n .action(\n async (\n path: string | undefined,\n options: {\n authorIdentity: AuthorIdentityCliMode;\n scoringProfile: ScoringProfileCliMode;\n logLevel: LogLevel;\n output: AnalyzeOutputMode;\n json?: boolean;\n recentWindowDays: number;\n },\n ) => {\n const logger = createStderrLogger(options.logLevel);\n const summary = await runAnalyzeCommand(\n path,\n options.authorIdentity,\n { recentWindowDays: options.recentWindowDays, scoringProfile: options.scoringProfile },\n logger,\n );\n const outputMode: AnalyzeOutputMode = options.json === true ? \"json\" : options.output;\n process.stdout.write(`${formatAnalyzeOutput(summary, outputMode)}\\n`);\n },\n );\n\nprogram\n .command(\"explain\")\n .argument(\"[path]\", \"path to the project to analyze\")\n .addOption(scoringProfileOption())\n .addOption(\n new Option(\n \"--author-identity <mode>\",\n \"author identity mode: likely_merge (heuristic) or strict_email (deterministic)\",\n )\n .choices([\"likely_merge\", \"strict_email\"])\n .default(\"likely_merge\"),\n )\n .addOption(\n new Option(\n \"--log-level <level>\",\n \"log verbosity: silent, error, warn, info, debug (logs are written to stderr)\",\n )\n .choices([\"silent\", \"error\", \"warn\", \"info\", \"debug\"])\n .default(parseLogLevel(process.env[\"CODESENTINEL_LOG_LEVEL\"])),\n )\n .option(\"--file <path>\", \"explain a specific file target\")\n .option(\"--module <name>\", \"explain a specific module target\")\n .option(\"--top <count>\", \"number of top hotspots to explain when no target is selected\", \"5\")\n .addOption(\n new Option(\n \"--recent-window-days <days>\",\n \"git recency window in days used for evolution volatility metrics\",\n )\n .argParser(parseRecentWindowDays)\n .default(30),\n )\n .addOption(\n new Option(\"--format <mode>\", \"output format: text, json, md\")\n .choices([\"text\", \"json\", \"md\"])\n .default(\"md\"),\n )\n .action(\n async (\n path: string | undefined,\n options: {\n authorIdentity: AuthorIdentityCliMode;\n scoringProfile: ScoringProfileCliMode;\n logLevel: LogLevel;\n file?: string;\n module?: string;\n top: string;\n recentWindowDays: number;\n format: ExplainFormat;\n },\n ) => {\n const logger = createStderrLogger(options.logLevel);\n const top = Number.parseInt(options.top, 10);\n const explainOptions = {\n ...(options.file === undefined ? {} : { file: options.file }),\n ...(options.module === undefined ? {} : { module: options.module }),\n top: Number.isFinite(top) ? top : 5,\n recentWindowDays: options.recentWindowDays,\n scoringProfile: options.scoringProfile,\n format: options.format,\n };\n const result = await runExplainCommand(path, options.authorIdentity, explainOptions, logger);\n process.stdout.write(`${formatExplainOutput(result, options.format)}\\n`);\n },\n );\n\nprogram\n .command(\"dependency-risk\")\n .argument(\"<dependency>\", \"dependency spec to evaluate (for example: react or react@19.0.0)\")\n .addOption(\n new Option(\n \"--log-level <level>\",\n \"log verbosity: silent, error, warn, info, debug (logs are written to stderr)\",\n )\n .choices([\"silent\", \"error\", \"warn\", \"info\", \"debug\"])\n .default(parseLogLevel(process.env[\"CODESENTINEL_LOG_LEVEL\"])),\n )\n .addOption(\n new Option(\"--output <mode>\", \"output mode: summary (default) or json (full analysis object)\")\n .choices([\"summary\", \"json\"])\n .default(\"summary\"),\n )\n .option(\"--json\", \"shortcut for --output json\")\n .option(\"--max-nodes <count>\", \"maximum dependency nodes to resolve\", \"250\")\n .option(\"--max-depth <count>\", \"maximum dependency depth to traverse\", \"6\")\n .action(\n async (\n dependency: string,\n options: {\n logLevel: LogLevel;\n output: DependencyRiskOutputMode;\n json?: boolean;\n maxNodes: string;\n maxDepth: string;\n },\n ) => {\n const logger = createStderrLogger(options.logLevel);\n const maxNodes = Number.parseInt(options.maxNodes, 10);\n const maxDepth = Number.parseInt(options.maxDepth, 10);\n\n logger.info(`analyzing dependency candidate: ${dependency}`);\n const result = await analyzeDependencyCandidateFromRegistry({\n dependency,\n maxNodes: Number.isFinite(maxNodes) ? maxNodes : 250,\n maxDepth: Number.isFinite(maxDepth) ? maxDepth : 6,\n });\n if (result.available) {\n logger.info(\n `dependency analysis completed (${result.dependency.name}@${result.dependency.resolvedVersion})`,\n );\n } else {\n logger.warn(`dependency analysis unavailable: ${result.reason}`);\n }\n\n const outputMode: DependencyRiskOutputMode = options.json === true ? \"json\" : options.output;\n process.stdout.write(`${formatDependencyRiskOutput(result, outputMode)}\\n`);\n },\n );\n\nprogram\n .command(\"report\")\n .argument(\"[path]\", \"path to the project to analyze\")\n .addOption(scoringProfileOption())\n .addOption(\n new Option(\n \"--author-identity <mode>\",\n \"author identity mode: likely_merge (heuristic) or strict_email (deterministic)\",\n )\n .choices([\"likely_merge\", \"strict_email\"])\n .default(\"likely_merge\"),\n )\n .addOption(\n new Option(\n \"--log-level <level>\",\n \"log verbosity: silent, error, warn, info, debug (logs are written to stderr)\",\n )\n .choices([\"silent\", \"error\", \"warn\", \"info\", \"debug\"])\n .default(parseLogLevel(process.env[\"CODESENTINEL_LOG_LEVEL\"])),\n )\n .addOption(\n new Option(\"--format <mode>\", \"output format: text, json, md, html\")\n .choices([\"text\", \"json\", \"md\", \"html\"])\n .default(\"md\"),\n )\n .option(\"--output <path>\", \"write rendered report to a file path\")\n .option(\"--open\", \"open the generated HTML report in the default browser\")\n .option(\"--compare <baseline>\", \"compare against a baseline snapshot JSON file\")\n .option(\"--snapshot <path>\", \"write current snapshot JSON artifact\")\n .option(\"--no-trace\", \"disable trace embedding in generated snapshot\")\n .addOption(\n new Option(\n \"--recent-window-days <days>\",\n \"git recency window in days used for evolution volatility metrics\",\n )\n .argParser(parseRecentWindowDays)\n .default(30),\n )\n .action(\n async (\n path: string | undefined,\n options: {\n authorIdentity: AuthorIdentityCliMode;\n scoringProfile: ScoringProfileCliMode;\n logLevel: LogLevel;\n format: \"text\" | \"json\" | \"md\" | \"html\";\n output?: string;\n open?: boolean;\n compare?: string;\n snapshot?: string;\n trace: boolean;\n recentWindowDays: number;\n },\n ) => {\n const logger = createStderrLogger(options.logLevel);\n const result = await runReportCommand(\n path,\n options.authorIdentity,\n {\n format: options.format,\n ...(options.output === undefined ? {} : { outputPath: options.output }),\n ...(options.compare === undefined ? {} : { comparePath: options.compare }),\n ...(options.snapshot === undefined ? {} : { snapshotPath: options.snapshot }),\n ...(options.open === undefined ? {} : { open: options.open }),\n includeTrace: options.trace,\n scoringProfile: options.scoringProfile,\n recentWindowDays: options.recentWindowDays,\n },\n logger,\n );\n\n if (options.output === undefined && options.format !== \"html\") {\n process.stdout.write(`${result.rendered}\\n`);\n return;\n }\n\n if (options.format === \"html\") {\n process.stdout.write(`${result.outputPath ?? result.rendered}\\n`);\n }\n },\n );\n\nprogram\n .command(\"run\")\n .argument(\"[path]\", \"path to the project to analyze\")\n .addOption(scoringProfileOption())\n .addOption(\n new Option(\n \"--author-identity <mode>\",\n \"author identity mode: likely_merge (heuristic) or strict_email (deterministic)\",\n )\n .choices([\"likely_merge\", \"strict_email\"])\n .default(\"likely_merge\"),\n )\n .addOption(\n new Option(\n \"--log-level <level>\",\n \"log verbosity: silent, error, warn, info, debug (logs are written to stderr)\",\n )\n .choices([\"silent\", \"error\", \"warn\", \"info\", \"debug\"])\n .default(parseLogLevel(process.env[\"CODESENTINEL_LOG_LEVEL\"])),\n )\n .addOption(\n new Option(\"--format <mode>\", \"combined output format: text, md, json\")\n .choices([\"text\", \"md\", \"json\"])\n .default(\"md\"),\n )\n .addOption(\n new Option(\"--detail <level>\", \"run detail level: compact (default), standard, full\")\n .choices([\"compact\", \"standard\", \"full\"])\n .default(\"compact\"),\n )\n .option(\"--file <path>\", \"explain a specific file target\")\n .option(\"--module <name>\", \"explain a specific module target\")\n .option(\"--top <count>\", \"number of top hotspots to explain when no target is selected\", \"5\")\n .option(\"--compare <baseline>\", \"compare against a baseline snapshot JSON file\")\n .option(\"--snapshot <path>\", \"write current snapshot JSON artifact\")\n .addOption(\n new Option(\"--report <format>\", \"write an additional report bundle during the run\")\n .choices([\"html\"])\n .default(undefined),\n )\n .option(\"--report-output <path>\", \"output path for the generated report bundle\")\n .option(\"--open\", \"open the generated HTML report in the default browser\")\n .option(\"--no-trace\", \"disable trace embedding in generated snapshot\")\n .addOption(\n new Option(\n \"--recent-window-days <days>\",\n \"git recency window in days used for evolution volatility metrics\",\n )\n .argParser(parseRecentWindowDays)\n .default(30),\n )\n .action(\n async (\n path: string | undefined,\n options: {\n authorIdentity: AuthorIdentityCliMode;\n scoringProfile: ScoringProfileCliMode;\n logLevel: LogLevel;\n format: \"text\" | \"md\" | \"json\";\n detail: RunDetail;\n file?: string;\n module?: string;\n top: string;\n compare?: string;\n snapshot?: string;\n report?: \"html\";\n reportOutput?: string;\n open?: boolean;\n trace: boolean;\n recentWindowDays: number;\n },\n ) => {\n const logger = createStderrLogger(options.logLevel);\n const top = Number.parseInt(options.top, 10);\n\n const explain = await runExplainCommand(\n path,\n options.authorIdentity,\n {\n ...(options.file === undefined ? {} : { file: options.file }),\n ...(options.module === undefined ? {} : { module: options.module }),\n top: Number.isFinite(top) ? top : 5,\n format: options.format,\n recentWindowDays: options.recentWindowDays,\n scoringProfile: options.scoringProfile,\n },\n logger,\n );\n\n const snapshot = createSnapshot({\n analysis: explain.summary,\n ...(options.trace === true ? { trace: explain.trace } : {}),\n });\n\n if (options.snapshot !== undefined) {\n await writeFile(options.snapshot, JSON.stringify(snapshot, null, 2), \"utf8\");\n logger.info(`snapshot written: ${options.snapshot}`);\n }\n\n const report =\n options.compare === undefined\n ? createReport(snapshot)\n : createReport(\n snapshot,\n compareSnapshots(snapshot, parseSnapshot(await readFile(options.compare, \"utf8\"))),\n );\n\n if (options.report === \"html\") {\n const htmlOutputPath = await writeHtmlReportBundle(report, {\n repositoryPath: explain.summary.structural.targetPath,\n ...(options.reportOutput === undefined ? {} : { outputPath: options.reportOutput }),\n });\n if (options.open === true) {\n const opened = await openPath(`${htmlOutputPath}/index.html`);\n if (!opened) {\n logger.warn(\"unable to open html report automatically on this platform\");\n }\n }\n logger.info(`html report written: ${htmlOutputPath}`);\n } else if (options.open === true) {\n logger.warn(\"--open has no effect unless --report html is set\");\n }\n\n if (options.format === \"json\") {\n const analyzeSummaryOutput = formatAnalyzeOutput(explain.summary, \"summary\");\n\n if (options.detail === \"compact\") {\n process.stdout.write(\n `${JSON.stringify(\n {\n schemaVersion: \"codesentinel.run.v1\",\n generatedAt: new Date().toISOString(),\n repository: report.repository,\n keyDrivers: extractSummaryValue(\n extractExplainTextSummary(formatExplainOutput(explain, \"text\")),\n \"key drivers\",\n ),\n priorityActions: extractSummaryValue(\n extractExplainTextSummary(formatExplainOutput(explain, \"text\")),\n \"priority actions\",\n ),\n topHotspots: report.hotspots.slice(0, 3).map((hotspot) => ({\n target: hotspot.target,\n score: hotspot.score,\n })),\n },\n null,\n 2,\n )}\\n`,\n );\n return;\n }\n\n if (options.detail === \"standard\") {\n const analyzeSummaryPayload: unknown = JSON.parse(analyzeSummaryOutput);\n\n process.stdout.write(\n `${JSON.stringify(\n {\n schemaVersion: \"codesentinel.run.v1\",\n generatedAt: new Date().toISOString(),\n analyze: analyzeSummaryPayload,\n explain: {\n summary: extractExplainTextSummary(formatExplainOutput(explain, \"text\")),\n },\n report: {\n repository: report.repository,\n health: report.health,\n hotspots: report.hotspots.slice(0, 5),\n structural: report.structural,\n external: report.external,\n },\n },\n null,\n 2,\n )}\\n`,\n );\n return;\n }\n\n process.stdout.write(\n `${JSON.stringify(\n {\n schemaVersion: \"codesentinel.run.v1\",\n generatedAt: new Date().toISOString(),\n analyze: explain.summary,\n explain,\n report,\n },\n null,\n 2,\n )}\\n`,\n );\n return;\n }\n\n const analyzeRendered = formatAnalyzeOutput(explain.summary, \"summary\");\n const explainRendered = formatExplainOutput(explain, options.format);\n\n if (options.detail === \"compact\") {\n if (options.format === \"md\") {\n process.stdout.write(\n `${renderCompactMarkdown(\n report,\n extractExplainMarkdownSummary(formatExplainOutput(explain, \"md\")),\n )}\\n`,\n );\n return;\n }\n\n process.stdout.write(\n `${renderCompactText(report, extractExplainTextSummary(formatExplainOutput(explain, \"text\")))}\\n`,\n );\n return;\n }\n\n if (options.detail === \"standard\") {\n if (options.format === \"md\") {\n process.stdout.write(\n `# CodeSentinel Run\\n\\n## Analyze\\n\\`\\`\\`json\\n${analyzeRendered}\\n\\`\\`\\`\\n\\n## Explain\\n${extractExplainMarkdownSummary(\n formatExplainOutput(explain, \"md\"),\n )}\\n\\n${renderReportHighlightsMarkdown(report)}\\n`,\n );\n return;\n }\n\n process.stdout.write(\n `CodeSentinel Run\\n\\nAnalyze\\n${analyzeRendered}\\n\\nExplain\\n${extractExplainTextSummary(\n formatExplainOutput(explain, \"text\"),\n )}\\n\\nReport\\n${renderReportHighlightsText(report)}\\n`,\n );\n return;\n }\n\n const reportRendered = formatReport(report, options.format);\n\n if (options.format === \"md\") {\n const explainSection = stripLeadingMarkdownHeading(\n explainRendered,\n \"# CodeSentinel Explanation\",\n );\n const reportSection = stripLeadingMarkdownHeading(reportRendered, \"# CodeSentinel Report\");\n\n process.stdout.write(\n `# CodeSentinel Run\\n\\n## Analyze\\n\\`\\`\\`json\\n${analyzeRendered}\\n\\`\\`\\`\\n\\n## Explain\\n${explainSection}\\n\\n## Report\\n${reportSection}\\n`,\n );\n return;\n }\n\n process.stdout.write(\n `CodeSentinel Run\\n\\nAnalyze\\n${analyzeRendered}\\n\\nExplain\\n${explainRendered}\\n\\nReport\\n${reportRendered}\\n`,\n );\n },\n );\n\nconst parseGateNumber = (value: string | undefined, optionName: string): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n\n const parsed = Number.parseFloat(value);\n if (!Number.isFinite(parsed)) {\n throw new CheckConfigurationError(`${optionName} must be numeric`);\n }\n\n return parsed;\n};\n\nconst collectOptionValues = (value: string, previous: string[] = []): string[] => {\n return [...previous, value];\n};\n\nconst parseMainBranches = (options: {\n mainBranch?: string[];\n mainBranches?: string;\n}): readonly string[] | undefined => {\n const fromRepeated = options.mainBranch ?? [];\n const fromCsv =\n options.mainBranches === undefined\n ? []\n : options.mainBranches\n .split(\",\")\n .map((value) => value.trim())\n .filter((value) => value.length > 0);\n\n const merged = [...fromRepeated, ...fromCsv];\n if (merged.length === 0) {\n return undefined;\n }\n\n const unique = Array.from(new Set(merged));\n return unique.length > 0 ? unique : undefined;\n};\n\nconst parseCiCount = (value: string | undefined, optionName: string): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n\n const trimmed = value.trim();\n const parsed = Number.parseInt(trimmed, 10);\n if (!/^\\d+$/.test(trimmed) || !Number.isInteger(parsed) || parsed < 0) {\n throw new CiConfigurationError(`${optionName} must be an integer >= 0`);\n }\n\n return parsed;\n};\n\nconst parseCiRatio = (value: string | undefined, optionName: string): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n\n const parsed = Number.parseFloat(value.trim());\n if (!Number.isFinite(parsed) || parsed < 0 || parsed > 1) {\n throw new CiConfigurationError(`${optionName} must be a number between 0 and 1`);\n }\n\n return parsed;\n};\n\nconst buildGateConfigFromOptions = (options: {\n maxRiskDelta?: string;\n maxHealthDelta?: string;\n noNewCycles?: boolean;\n noNewHighRiskDeps?: boolean;\n maxNewHotspots?: string;\n maxRiskScore?: string;\n minHealthScore?: string;\n newHotspotScoreThreshold?: string;\n maxUnownedCritical?: string;\n maxGhostOwners?: string;\n maxDrift?: string;\n failOn: \"error\" | \"warn\";\n}): GateConfig => {\n const maxRiskDelta = parseGateNumber(options.maxRiskDelta, \"--max-risk-delta\");\n const maxHealthDelta = parseGateNumber(options.maxHealthDelta, \"--max-health-delta\");\n const maxNewHotspots = parseGateNumber(options.maxNewHotspots, \"--max-new-hotspots\");\n const maxRiskScore = parseGateNumber(options.maxRiskScore, \"--max-risk-score\");\n const minHealthScore = parseGateNumber(options.minHealthScore, \"--min-health-score\");\n const newHotspotScoreThreshold = parseGateNumber(\n options.newHotspotScoreThreshold,\n \"--new-hotspot-score-threshold\",\n );\n const maxUnownedCritical = parseCiCount(options.maxUnownedCritical, \"--max-unowned-critical\");\n const maxGhostOwners = parseCiCount(options.maxGhostOwners, \"--max-ghost-owners\");\n const maxDrift = parseCiRatio(options.maxDrift, \"--max-drift\");\n\n return {\n ...(maxRiskDelta === undefined ? {} : { maxRiskDelta }),\n ...(maxHealthDelta === undefined ? {} : { maxHealthDelta }),\n ...(options.noNewCycles === true ? { noNewCycles: true } : {}),\n ...(options.noNewHighRiskDeps === true ? { noNewHighRiskDeps: true } : {}),\n ...(maxNewHotspots === undefined ? {} : { maxNewHotspots }),\n ...(maxRiskScore === undefined ? {} : { maxRiskScore }),\n ...(minHealthScore === undefined ? {} : { minHealthScore }),\n ...(newHotspotScoreThreshold === undefined ? {} : { newHotspotScoreThreshold }),\n ...(maxUnownedCritical === undefined ? {} : { maxUnownedCritical }),\n ...(maxGhostOwners === undefined ? {} : { maxGhostOwners }),\n ...(maxDrift === undefined ? {} : { maxDrift }),\n failOn: options.failOn,\n };\n};\n\nprogram\n .command(\"check\")\n .argument(\"[path]\", \"path to the project to analyze\")\n .addOption(scoringProfileOption())\n .addOption(\n new Option(\n \"--author-identity <mode>\",\n \"author identity mode: likely_merge (heuristic) or strict_email (deterministic)\",\n )\n .choices([\"likely_merge\", \"strict_email\"])\n .default(\"likely_merge\"),\n )\n .addOption(\n new Option(\n \"--log-level <level>\",\n \"log verbosity: silent, error, warn, info, debug (logs are written to stderr)\",\n )\n .choices([\"silent\", \"error\", \"warn\", \"info\", \"debug\"])\n .default(parseLogLevel(process.env[\"CODESENTINEL_LOG_LEVEL\"])),\n )\n .option(\"--compare <baseline>\", \"baseline snapshot path\")\n .option(\"--max-risk-delta <value>\", \"maximum allowed normalized risk score increase\")\n .option(\n \"--max-health-delta <value>\",\n \"maximum allowed normalized health score regression versus baseline (requires --compare)\",\n )\n .option(\"--no-new-cycles\", \"fail if new structural cycles are introduced\")\n .option(\"--no-new-high-risk-deps\", \"fail if new high-risk direct dependencies are introduced\")\n .option(\"--max-new-hotspots <count>\", \"maximum allowed number of new hotspots\")\n .option(\"--new-hotspot-score-threshold <score>\", \"minimum hotspot score to count as new hotspot\")\n .option(\"--max-risk-score <score>\", \"absolute risk score limit (0..100)\")\n .option(\"--min-health-score <score>\", \"minimum health score threshold (0..100)\")\n .addOption(\n new Option(\"--fail-on <level>\", \"failing severity threshold\")\n .choices([\"error\", \"warn\"])\n .default(\"error\"),\n )\n .addOption(\n new Option(\"--format <mode>\", \"output format: text, json, md\")\n .choices([\"text\", \"json\", \"md\"])\n .default(\"text\"),\n )\n .option(\"--output <path>\", \"write check output to a file path\")\n .option(\"--no-trace\", \"disable trace embedding in generated snapshot\")\n .addOption(\n new Option(\n \"--recent-window-days <days>\",\n \"git recency window in days used for evolution volatility metrics\",\n )\n .argParser(parseRecentWindowDays)\n .default(30),\n )\n .action(\n async (\n path: string | undefined,\n options: {\n authorIdentity: AuthorIdentityCliMode;\n scoringProfile: ScoringProfileCliMode;\n logLevel: LogLevel;\n compare?: string;\n maxRiskDelta?: string;\n maxHealthDelta?: string;\n noNewCycles?: boolean;\n noNewHighRiskDeps?: boolean;\n maxNewHotspots?: string;\n newHotspotScoreThreshold?: string;\n maxRiskScore?: string;\n minHealthScore?: string;\n failOn: \"error\" | \"warn\";\n format: CheckOutputFormat;\n output?: string;\n trace: boolean;\n recentWindowDays: number;\n },\n ) => {\n const logger = createStderrLogger(options.logLevel);\n\n try {\n const gateConfig = buildGateConfigFromOptions(options);\n const result = await runCheckCommand(\n path,\n options.authorIdentity,\n {\n ...(options.compare === undefined ? {} : { baselinePath: options.compare }),\n includeTrace: options.trace,\n scoringProfile: options.scoringProfile,\n recentWindowDays: options.recentWindowDays,\n gateConfig,\n outputFormat: options.format,\n ...(options.output === undefined ? {} : { outputPath: options.output }),\n },\n logger,\n );\n\n if (options.output === undefined) {\n process.stdout.write(`${result.rendered}\\n`);\n }\n\n process.exitCode = result.gateResult.exitCode;\n } catch (error) {\n if (error instanceof CheckConfigurationError) {\n logger.error(error.message);\n process.exitCode = EXIT_CODES.invalidConfiguration;\n return;\n }\n\n logger.error(error instanceof Error ? error.message : \"internal error\");\n process.exitCode = EXIT_CODES.internalError;\n }\n },\n );\n\nprogram\n .command(\"ci\")\n .argument(\"[path]\", \"path to the project to analyze\")\n .addOption(scoringProfileOption())\n .addOption(\n new Option(\n \"--author-identity <mode>\",\n \"author identity mode: likely_merge (heuristic) or strict_email (deterministic)\",\n )\n .choices([\"likely_merge\", \"strict_email\"])\n .default(\"likely_merge\"),\n )\n .addOption(\n new Option(\n \"--log-level <level>\",\n \"log verbosity: silent, error, warn, info, debug (logs are written to stderr)\",\n )\n .choices([\"silent\", \"error\", \"warn\", \"info\", \"debug\"])\n .default(parseLogLevel(process.env[\"CODESENTINEL_LOG_LEVEL\"])),\n )\n .option(\"--baseline <path>\", \"baseline snapshot path\")\n .option(\n \"--baseline-ref <gitRef>\",\n \"resolve baseline snapshot from a git reference (for example origin/main)\",\n )\n .option(\n \"--baseline-sha <sha>\",\n \"explicit baseline commit SHA (only valid with --baseline-ref auto)\",\n )\n .addOption(\n new Option(\n \"--main-branch <name>\",\n \"add a default branch candidate for auto baseline resolution (repeatable)\",\n ).argParser(collectOptionValues),\n )\n .option(\n \"--main-branches <names>\",\n \"comma-separated default branch candidates for auto baseline resolution (for example: main,master)\",\n )\n .option(\"--snapshot <path>\", \"write current snapshot JSON to path\")\n .option(\"--report <path>\", \"write markdown CI summary report\")\n .option(\"--json-output <path>\", \"write machine-readable CI JSON output\")\n .option(\"--max-risk-delta <value>\", \"maximum allowed normalized risk score increase\")\n .option(\n \"--max-health-delta <value>\",\n \"maximum allowed normalized health score regression versus baseline\",\n )\n .option(\"--no-new-cycles\", \"fail if new structural cycles are introduced\")\n .option(\"--no-new-high-risk-deps\", \"fail if new high-risk direct dependencies are introduced\")\n .option(\"--max-new-hotspots <count>\", \"maximum allowed number of new hotspots\")\n .option(\"--new-hotspot-score-threshold <score>\", \"minimum hotspot score to count as new hotspot\")\n .option(\"--max-risk-score <score>\", \"absolute risk score limit (0..100)\")\n .option(\"--min-health-score <score>\", \"minimum health score threshold (0..100)\")\n .option(\n \"--max-unowned-critical <count>\",\n \"maximum allowed unowned critical files (requires CODEOWNERS)\",\n )\n .option(\n \"--max-ghost-owners <count>\",\n \"maximum allowed owners without activity (requires CODEOWNERS)\",\n )\n .option(\n \"--max-drift <ratio>\",\n \"maximum allowed ownership drift ratio between 0 and 1 (requires CODEOWNERS)\",\n )\n .addOption(\n new Option(\"--fail-on <level>\", \"failing severity threshold\")\n .choices([\"error\", \"warn\"])\n .default(\"error\"),\n )\n .option(\"--no-trace\", \"disable trace embedding in generated snapshot\")\n .addOption(\n new Option(\n \"--recent-window-days <days>\",\n \"git recency window in days used for evolution volatility metrics\",\n )\n .argParser(parseRecentWindowDays)\n .default(30),\n )\n .action(\n async (\n path: string | undefined,\n options: {\n authorIdentity: AuthorIdentityCliMode;\n scoringProfile: ScoringProfileCliMode;\n logLevel: LogLevel;\n baseline?: string;\n baselineRef?: string;\n baselineSha?: string;\n mainBranch?: string[];\n mainBranches?: string;\n snapshot?: string;\n report?: string;\n jsonOutput?: string;\n maxRiskDelta?: string;\n maxHealthDelta?: string;\n noNewCycles?: boolean;\n noNewHighRiskDeps?: boolean;\n maxNewHotspots?: string;\n newHotspotScoreThreshold?: string;\n maxRiskScore?: string;\n minHealthScore?: string;\n maxUnownedCritical?: string;\n maxGhostOwners?: string;\n maxDrift?: string;\n failOn: \"error\" | \"warn\";\n trace: boolean;\n recentWindowDays: number;\n },\n ) => {\n const logger = createStderrLogger(options.logLevel);\n\n try {\n const gateConfig = buildGateConfigFromOptions(options);\n const mainBranchCandidates = parseMainBranches(options);\n const result = await runCiCommand(\n path,\n options.authorIdentity,\n {\n ...(options.baseline === undefined ? {} : { baselinePath: options.baseline }),\n ...(options.baselineRef === undefined ? {} : { baselineRef: options.baselineRef }),\n ...(options.baselineSha === undefined ? {} : { baselineSha: options.baselineSha }),\n ...(mainBranchCandidates === undefined ? {} : { mainBranchCandidates }),\n ...(options.snapshot === undefined ? {} : { snapshotPath: options.snapshot }),\n ...(options.report === undefined ? {} : { reportPath: options.report }),\n ...(options.jsonOutput === undefined ? {} : { jsonOutputPath: options.jsonOutput }),\n includeTrace: options.trace,\n scoringProfile: options.scoringProfile,\n recentWindowDays: options.recentWindowDays,\n gateConfig,\n },\n logger,\n );\n\n if (options.report === undefined) {\n process.stdout.write(`${result.markdownSummary}\\n`);\n }\n\n process.exitCode = result.gateResult.exitCode;\n } catch (error) {\n if (error instanceof CiConfigurationError) {\n logger.error(error.message);\n process.exitCode = EXIT_CODES.invalidConfiguration;\n return;\n }\n\n logger.error(error instanceof Error ? error.message : \"internal error\");\n process.exitCode = EXIT_CODES.internalError;\n }\n },\n );\n\nconst parseOwnersInteger = (\n value: string | undefined,\n optionName: string,\n minimum: number,\n): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n\n const trimmed = value.trim();\n const parsed = Number.parseInt(trimmed, 10);\n if (!/^\\d+$/.test(trimmed) || !Number.isInteger(parsed) || parsed < minimum) {\n throw new OwnersConfigurationError(\n `${optionName} must be an integer greater than or equal to ${minimum}`,\n );\n }\n\n return parsed;\n};\n\nconst parseOwnersRatio = (value: string | undefined, optionName: string): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n\n const parsed = Number.parseFloat(value.trim());\n if (!Number.isFinite(parsed) || parsed < 0 || parsed > 1) {\n throw new OwnersConfigurationError(`${optionName} must be a ratio between 0 and 1`);\n }\n\n return parsed;\n};\n\nprogram\n .command(\"owners\")\n .alias(\"ownership\")\n // The owners command owns the ESLint-style 0/1/2 contract, so a usage error has to surface as\n // the configuration exit code (2) instead of commander's default 1.\n .exitOverride()\n .argument(\"[path]\", \"path to the repository to audit\")\n .option(\n \"--codeowners <file>\",\n \"explicit CODEOWNERS path, relative to the repository root (default: auto-discovery)\",\n )\n .option(\"--ref <ref>\", \"git ref to read CODEOWNERS and the tracked tree from\", \"HEAD\")\n .option(\"--window-days <days>\", \"authorship observation window in days\", \"90\")\n .option(\"--min-commits <count>\", \"minimum per-file commits before a verdict is emitted\", \"2\")\n .option(\"--top <count>\", \"rows per console and markdown section\", \"10\")\n .addOption(\n new Option(\n \"--format <mode>\",\n \"output format: console (default), json (stable, sorted payload) or md (pastes into a PR)\",\n )\n .choices([\"console\", \"json\", \"md\"])\n .default(\"console\"),\n )\n .option(\"--output <file>\", \"write the rendered output to a file instead of stdout\")\n .option(\"--aliases <file>\", \"identity alias map\", \".codesentinel/owners.json\")\n .option(\n \"--resolve-github\",\n \"accepted for compatibility; not implemented in this iteration, the audit stays offline\",\n )\n .addOption(\n new Option(\"--fail-on <level>\", \"failing severity threshold: none, warn or error\")\n .choices([\"none\", \"warn\", \"error\"])\n .default(\"none\"),\n )\n .option(\"--max-unowned-critical <count>\", \"maximum allowed unowned critical files\")\n .option(\"--max-ghost-owners <count>\", \"maximum allowed owners without activity\")\n .option(\"--max-drift <ratio>\", \"maximum allowed drift ratio between 0 and 1\")\n .addOption(\n new Option(\n \"--log-level <level>\",\n \"log verbosity: silent, error, warn, info, debug (logs are written to stderr)\",\n )\n .choices([\"silent\", \"error\", \"warn\", \"info\", \"debug\"])\n .default(parseLogLevel(process.env[\"CODESENTINEL_LOG_LEVEL\"])),\n )\n .action(\n async (\n path: string | undefined,\n options: {\n codeowners?: string;\n ref: string;\n windowDays: string;\n minCommits: string;\n top: string;\n format: OwnersOutputFormat;\n output?: string;\n aliases: string;\n resolveGithub?: boolean;\n failOn: OwnersFailOn;\n maxUnownedCritical?: string;\n maxGhostOwners?: string;\n maxDrift?: string;\n logLevel: LogLevel;\n },\n ) => {\n const logger = createStderrLogger(options.logLevel);\n\n try {\n const windowDays = parseOwnersInteger(options.windowDays, \"--window-days\", 1) ?? 90;\n const minCommits = parseOwnersInteger(options.minCommits, \"--min-commits\", 0) ?? 2;\n const top = parseOwnersInteger(options.top, \"--top\", 1) ?? 10;\n const commandOptions: OwnersCommandOptions = {\n ...(options.codeowners === undefined ? {} : { codeownersPath: options.codeowners }),\n ref: options.ref,\n windowDays,\n minCommits,\n top,\n format: options.format,\n ...(options.output === undefined ? {} : { outputPath: options.output }),\n aliasesPath: options.aliases,\n ...(options.resolveGithub === true ? { resolveGithub: true } : {}),\n thresholds: {\n failOn: options.failOn,\n maxUnownedCritical:\n parseOwnersInteger(options.maxUnownedCritical, \"--max-unowned-critical\", 0) ?? null,\n maxGhostOwners:\n parseOwnersInteger(options.maxGhostOwners, \"--max-ghost-owners\", 0) ?? null,\n maxDrift: parseOwnersRatio(options.maxDrift, \"--max-drift\") ?? null,\n },\n };\n\n const result = await runOwnersCommand(path, commandOptions, logger);\n\n if (result.outputPath === undefined) {\n process.stdout.write(`${result.rendered}\\n`);\n }\n\n process.exitCode = result.exitCode;\n } catch (error) {\n if (error instanceof OwnersConfigurationError) {\n logger.error(error.message);\n process.exitCode = OWNERS_EXIT_CODES.invalidConfiguration;\n return;\n }\n\n logger.error(error instanceof Error ? error.message : \"internal error\");\n process.exitCode = OWNERS_EXIT_CODES.invalidConfiguration;\n }\n },\n );\n\nconst executablePath = process.argv[0] ?? \"\";\nconst scriptPath = process.argv[1] ?? \"\";\n\nconst argv =\n process.argv[2] === \"--\" ? [executablePath, scriptPath, ...process.argv.slice(3)] : process.argv;\n\nif (argv.length <= 2) {\n if (process.stdin.isTTY && process.stdout.isTTY && process.stderr.isTTY) {\n process.exitCode = await runInteractiveCliMenu({\n currentVersion: version,\n scriptPath,\n });\n process.exit(process.exitCode ?? 0);\n }\n\n program.outputHelp();\n process.exit(0);\n}\n\nif (argv[2] !== \"update\") {\n await checkForCliUpdates({\n packageName: \"@getcodesentinel/codesentinel\",\n currentVersion: version,\n argv: process.argv,\n env: process.env,\n });\n}\n\ntry {\n await program.parseAsync(argv);\n} catch (error) {\n if (!(error instanceof CommanderError)) {\n throw error;\n }\n // `--help` and usage errors both travel through `exitOverride`; only real usage errors are\n // configuration failures for the command that opted into the ESLint-style exit codes.\n if (error.exitCode !== 0) {\n process.exitCode = OWNERS_EXIT_CODES.invalidConfiguration;\n }\n}\n","import type { WorkspacePackage } from \"@codesentinel/core\";\n\nexport type LockfileKind = \"pnpm\" | \"npm\" | \"npm-shrinkwrap\" | \"yarn\" | \"bun\";\n\nexport type DirectDependencySpec = {\n name: string;\n requestedRange: string;\n scope: \"prod\" | \"dev\";\n};\n\nexport type LockedDependencyNode = {\n name: string;\n version: string;\n dependencies: readonly string[];\n};\n\nexport type LockfileExtraction = {\n kind: LockfileKind;\n directDependencies: readonly DirectDependencySpec[];\n nodes: readonly LockedDependencyNode[];\n};\n\nexport type WorkspaceDependencyManifest = WorkspacePackage & {\n directDependencies: readonly DirectDependencySpec[];\n};\n\nexport type DependencyMetadata = {\n name: string;\n version: string;\n weeklyDownloads: number | null;\n maintainerCount: number | null;\n releaseFrequencyDays: number | null;\n daysSinceLastRelease: number | null;\n repositoryActivity30d: number | null;\n busFactor: number | null;\n};\n\nexport type DependencyMetadataRequestContext = {\n directDependency: boolean;\n};\n\nexport interface DependencyMetadataProvider {\n getMetadata(\n name: string,\n version: string,\n context: DependencyMetadataRequestContext,\n ): Promise<DependencyMetadata | null>;\n}\n\nexport type ExternalAnalysisConfig = {\n abandonedDaysThreshold: number;\n deepChainThreshold: number;\n fanOutHighThreshold: number;\n centralityTopN: number;\n maxHighRiskDependencies: number;\n metadataRequestConcurrency: number;\n};\n\nexport const DEFAULT_EXTERNAL_ANALYSIS_CONFIG: ExternalAnalysisConfig = {\n abandonedDaysThreshold: 540,\n deepChainThreshold: 6,\n fanOutHighThreshold: 25,\n centralityTopN: 20,\n maxHighRiskDependencies: 100,\n metadataRequestConcurrency: 8,\n};\n","import type {\n CentralDependency,\n DependencyExposureRecord,\n DependencyRiskSignal,\n ExternalAnalysisSummary,\n WorkspaceDependencyExposureSummary,\n} from \"@codesentinel/core\";\nimport type {\n DependencyMetadata,\n ExternalAnalysisConfig,\n LockfileExtraction,\n LockedDependencyNode,\n WorkspaceDependencyManifest,\n} from \"./types.js\";\n\nconst round4 = (value: number): number => Number(value.toFixed(4));\n\ntype NormalizedNode = {\n key: string;\n name: string;\n version: string;\n dependencies: readonly string[];\n};\n\nconst normalizeNodes = (nodes: readonly LockedDependencyNode[]): readonly NormalizedNode[] => {\n const byName = new Map<string, LockedDependencyNode[]>();\n\n for (const node of nodes) {\n const bucket = byName.get(node.name) ?? [];\n bucket.push(node);\n byName.set(node.name, bucket);\n }\n\n const normalized: NormalizedNode[] = [];\n\n for (const [name, candidates] of byName.entries()) {\n if (candidates.length === 0) {\n continue;\n }\n\n candidates.sort((a, b) => b.version.localeCompare(a.version));\n const selected = candidates[0];\n if (selected === undefined) {\n continue;\n }\n\n const deps = selected.dependencies\n .map((dep) => {\n const at = dep.lastIndexOf(\"@\");\n return at <= 0 ? dep : dep.slice(0, at);\n })\n .filter((depName) => depName.length > 0)\n .sort((a, b) => a.localeCompare(b));\n\n normalized.push({\n key: `${name}@${selected.version}`,\n name,\n version: selected.version,\n dependencies: deps,\n });\n }\n\n return normalized.sort((a, b) => a.name.localeCompare(b.name));\n};\n\nconst computeDepths = (\n nodeByName: ReadonlyMap<string, NormalizedNode>,\n directNames: ReadonlySet<string>,\n): { depthByName: ReadonlyMap<string, number>; maxDepth: number } => {\n const visiting = new Set<string>();\n const depthByName = new Map<string, number>();\n\n const compute = (name: string): number => {\n const known = depthByName.get(name);\n if (known !== undefined) {\n return known;\n }\n\n if (visiting.has(name)) {\n return 0;\n }\n\n visiting.add(name);\n\n const node = nodeByName.get(name);\n if (node === undefined) {\n visiting.delete(name);\n depthByName.set(name, 0);\n return 0;\n }\n\n let maxChildDepth = 0;\n for (const dependencyName of node.dependencies) {\n const childDepth = compute(dependencyName);\n if (childDepth > maxChildDepth) {\n maxChildDepth = childDepth;\n }\n }\n\n visiting.delete(name);\n const ownDepth = directNames.has(name) ? 0 : maxChildDepth + 1;\n depthByName.set(name, ownDepth);\n return ownDepth;\n };\n\n for (const name of nodeByName.keys()) {\n compute(name);\n }\n\n let maxDepth = 0;\n for (const depth of depthByName.values()) {\n if (depth > maxDepth) {\n maxDepth = depth;\n }\n }\n\n return { depthByName, maxDepth };\n};\n\nconst rankCentrality = (\n nodes: readonly NormalizedNode[],\n dependentsByName: ReadonlyMap<string, number>,\n directNames: ReadonlySet<string>,\n topN: number,\n): readonly CentralDependency[] =>\n [...nodes]\n .map((node) => ({\n name: node.name,\n dependents: dependentsByName.get(node.name) ?? 0,\n fanOut: node.dependencies.length,\n direct: directNames.has(node.name),\n }))\n .sort(\n (a, b) => b.dependents - a.dependents || b.fanOut - a.fanOut || a.name.localeCompare(b.name),\n )\n .slice(0, topN);\n\nconst canPropagateSignal = (signal: DependencyRiskSignal): boolean =>\n signal === \"abandoned\" ||\n signal === \"high_centrality\" ||\n signal === \"deep_chain\" ||\n signal === \"high_fanout\";\n\nconst collectTransitiveDependencies = (\n rootName: string,\n nodeByName: ReadonlyMap<string, NormalizedNode>,\n): readonly string[] => {\n const seen = new Set<string>();\n const stack = [...(nodeByName.get(rootName)?.dependencies ?? [])];\n\n while (stack.length > 0) {\n const current = stack.pop();\n if (current === undefined || seen.has(current) || current === rootName) {\n continue;\n }\n\n seen.add(current);\n const currentNode = nodeByName.get(current);\n if (currentNode === undefined) {\n continue;\n }\n\n for (const next of currentNode.dependencies) {\n if (!seen.has(next)) {\n stack.push(next);\n }\n }\n }\n\n return [...seen].sort((a, b) => a.localeCompare(b));\n};\n\nconst hasHighRiskSignals = (\n dependency: DependencyExposureRecord,\n config: ExternalAnalysisConfig,\n): boolean =>\n dependency.ownRiskSignals.includes(\"abandoned\") ||\n dependency.ownRiskSignals.filter(\n (signal) => signal === \"high_centrality\" || signal === \"deep_chain\" || signal === \"high_fanout\",\n ).length >= 2 ||\n (dependency.ownRiskSignals.includes(\"single_maintainer\") &&\n ((dependency.daysSinceLastRelease ?? 0) >= config.abandonedDaysThreshold / 2 ||\n (dependency.repositoryActivity30d ?? 1) <= 0));\n\nconst buildWorkspaceExposureSummaries = (\n workspaceManifests: readonly WorkspaceDependencyManifest[],\n allByName: ReadonlyMap<string, DependencyExposureRecord>,\n nodeByName: ReadonlyMap<string, NormalizedNode>,\n config: ExternalAnalysisConfig,\n): readonly WorkspaceDependencyExposureSummary[] => {\n if (workspaceManifests.length === 0) {\n return [];\n }\n\n const workspaceNames = new Set(workspaceManifests.map((workspace) => workspace.name));\n const externalDependencyNamesByWorkspace = new Map<string, readonly string[]>();\n const workspaceCountByDependency = new Map<string, number>();\n\n for (const workspace of workspaceManifests) {\n const dependencyNames = [\n ...new Set(\n workspace.directDependencies\n .map((dependency) => dependency.name)\n .filter((dependencyName) => !workspaceNames.has(dependencyName)),\n ),\n ].sort((a, b) => a.localeCompare(b));\n\n externalDependencyNamesByWorkspace.set(workspace.path, dependencyNames);\n\n for (const dependencyName of dependencyNames) {\n workspaceCountByDependency.set(\n dependencyName,\n (workspaceCountByDependency.get(dependencyName) ?? 0) + 1,\n );\n }\n }\n\n return [...workspaceManifests]\n .map((workspace) => {\n const dependencyNames = externalDependencyNamesByWorkspace.get(workspace.path) ?? [];\n const directSpecByName = new Map(\n workspace.directDependencies.map((dependency) => [dependency.name, dependency]),\n );\n const resolvedDependencies = dependencyNames\n .map((dependencyName) => allByName.get(dependencyName))\n .filter((dependency): dependency is DependencyExposureRecord => dependency !== undefined);\n const unresolvedDependencies = dependencyNames.filter(\n (dependencyName) => !allByName.has(dependencyName),\n );\n\n const highRiskDependencies = resolvedDependencies\n .filter(\n (dependency) =>\n (directSpecByName.get(dependency.name)?.scope ?? dependency.dependencyScope) ===\n \"prod\" && hasHighRiskSignals(dependency, config),\n )\n .map((dependency) => dependency.name)\n .sort((a, b) => a.localeCompare(b));\n\n const highRiskDevelopmentDependencies = resolvedDependencies\n .filter(\n (dependency) =>\n (directSpecByName.get(dependency.name)?.scope ?? dependency.dependencyScope) ===\n \"dev\" && hasHighRiskSignals(dependency, config),\n )\n .map((dependency) => dependency.name)\n .sort((a, b) => a.localeCompare(b));\n\n const transitiveExposureDependencies = resolvedDependencies\n .filter((dependency) => {\n const transitiveDependencies = collectTransitiveDependencies(dependency.name, nodeByName);\n return transitiveDependencies.some((transitiveName) => {\n const transitive = allByName.get(transitiveName);\n return transitive?.riskSignals.some(canPropagateSignal) ?? false;\n });\n })\n .map((dependency) => dependency.name)\n .sort((a, b) => a.localeCompare(b));\n\n const singleMaintainerDependencies = resolvedDependencies\n .filter((dependency) => dependency.ownRiskSignals.includes(\"single_maintainer\"))\n .map((dependency) => dependency.name)\n .sort((a, b) => a.localeCompare(b));\n\n const abandonedDependencies = resolvedDependencies\n .filter((dependency) => dependency.ownRiskSignals.includes(\"abandoned\"))\n .map((dependency) => dependency.name)\n .sort((a, b) => a.localeCompare(b));\n\n return {\n name: workspace.name,\n path: workspace.path,\n kind: workspace.kind,\n directDependencies: dependencyNames.length,\n directProductionDependencies: dependencyNames.filter(\n (dependencyName) => directSpecByName.get(dependencyName)?.scope === \"prod\",\n ).length,\n directDevelopmentDependencies: dependencyNames.filter(\n (dependencyName) => directSpecByName.get(dependencyName)?.scope === \"dev\",\n ).length,\n unresolvedDependencies,\n dependencyNames,\n sharedDependencies: dependencyNames.filter(\n (dependencyName) => (workspaceCountByDependency.get(dependencyName) ?? 0) > 1,\n ),\n highRiskDependencies,\n highRiskDevelopmentDependencies,\n transitiveExposureDependencies,\n singleMaintainerDependencies,\n abandonedDependencies,\n };\n })\n .sort(\n (a, b) =>\n b.highRiskDependencies.length - a.highRiskDependencies.length ||\n b.transitiveExposureDependencies.length - a.transitiveExposureDependencies.length ||\n b.directDependencies - a.directDependencies ||\n a.path.localeCompare(b.path),\n );\n};\n\nexport const buildExternalAnalysisSummary = (\n targetPath: string,\n extraction: LockfileExtraction,\n metadataByKey: ReadonlyMap<string, DependencyMetadata | null>,\n config: ExternalAnalysisConfig,\n workspaceManifests: readonly WorkspaceDependencyManifest[] = [],\n): ExternalAnalysisSummary => {\n const nodes = normalizeNodes(extraction.nodes);\n const directNames = new Set(extraction.directDependencies.map((dep) => dep.name));\n const directSpecByName = new Map(extraction.directDependencies.map((dep) => [dep.name, dep]));\n\n const nodeByName = new Map(nodes.map((node) => [node.name, node]));\n const dependentsByName = new Map<string, number>();\n\n for (const node of nodes) {\n dependentsByName.set(node.name, dependentsByName.get(node.name) ?? 0);\n }\n\n for (const node of nodes) {\n for (const dependencyName of node.dependencies) {\n if (!nodeByName.has(dependencyName)) {\n continue;\n }\n\n dependentsByName.set(dependencyName, (dependentsByName.get(dependencyName) ?? 0) + 1);\n }\n }\n\n const { depthByName, maxDepth } = computeDepths(nodeByName, directNames);\n const centralityRanking = rankCentrality(\n nodes,\n dependentsByName,\n directNames,\n config.centralityTopN,\n );\n\n const topCentralNames = new Set(\n centralityRanking\n .slice(0, Math.max(1, Math.ceil(centralityRanking.length * 0.25)))\n .map((entry) => entry.name),\n );\n\n const allDependencies: DependencyExposureRecord[] = [];\n let metadataAvailableCount = 0;\n\n for (const node of nodes) {\n const metadata = metadataByKey.get(node.key) ?? null;\n if (metadata !== null) {\n metadataAvailableCount += 1;\n }\n\n const dependencyDepth = depthByName.get(node.name) ?? 0;\n const dependents = dependentsByName.get(node.name) ?? 0;\n\n const riskSignals: DependencyRiskSignal[] = [];\n\n if ((metadata?.maintainerCount ?? 0) === 1) {\n riskSignals.push(\"single_maintainer\");\n }\n\n if ((metadata?.daysSinceLastRelease ?? 0) >= config.abandonedDaysThreshold) {\n riskSignals.push(\"abandoned\");\n }\n\n if (topCentralNames.has(node.name) && dependents > 0) {\n riskSignals.push(\"high_centrality\");\n }\n\n if (dependencyDepth >= config.deepChainThreshold) {\n riskSignals.push(\"deep_chain\");\n }\n\n if (node.dependencies.length >= config.fanOutHighThreshold) {\n riskSignals.push(\"high_fanout\");\n }\n\n if (metadata === null) {\n riskSignals.push(\"metadata_unavailable\");\n }\n\n allDependencies.push({\n name: node.name,\n direct: directNames.has(node.name),\n dependencyScope: directSpecByName.get(node.name)?.scope ?? \"prod\",\n requestedRange: directSpecByName.get(node.name)?.requestedRange ?? null,\n resolvedVersion: node.version,\n transitiveDependencies: [],\n weeklyDownloads: metadata?.weeklyDownloads ?? null,\n dependencyDepth,\n fanOut: node.dependencies.length,\n dependents,\n maintainerCount: metadata?.maintainerCount ?? null,\n releaseFrequencyDays: metadata?.releaseFrequencyDays ?? null,\n daysSinceLastRelease: metadata?.daysSinceLastRelease ?? null,\n repositoryActivity30d: metadata?.repositoryActivity30d ?? null,\n busFactor: metadata?.busFactor ?? null,\n ownRiskSignals: [...riskSignals].sort((a, b) => a.localeCompare(b)),\n inheritedRiskSignals: [],\n riskSignals,\n });\n }\n\n allDependencies.sort((a, b) => a.name.localeCompare(b.name));\n\n const allByName = new Map(allDependencies.map((dep) => [dep.name, dep]));\n\n const dependencies: DependencyExposureRecord[] = allDependencies\n .filter((dep) => dep.direct)\n .map((dep) => {\n const transitiveDependencies = collectTransitiveDependencies(dep.name, nodeByName);\n const inheritedSignals = new Set<DependencyRiskSignal>();\n const allSignals = new Set(dep.ownRiskSignals);\n\n for (const transitiveName of transitiveDependencies) {\n const transitive = allByName.get(transitiveName);\n if (transitive === undefined) {\n continue;\n }\n\n for (const signal of transitive.riskSignals) {\n if (canPropagateSignal(signal)) {\n inheritedSignals.add(signal);\n allSignals.add(signal);\n }\n }\n }\n\n return {\n ...dep,\n transitiveDependencies,\n inheritedRiskSignals: [...inheritedSignals].sort((a, b) => a.localeCompare(b)),\n riskSignals: [...allSignals].sort((a, b) => a.localeCompare(b)),\n };\n })\n .sort((a, b) => a.name.localeCompare(b.name));\n\n const highRiskDependencies = dependencies\n .filter(\n (dep) =>\n dep.ownRiskSignals.includes(\"abandoned\") ||\n dep.ownRiskSignals.filter(\n (signal) =>\n signal === \"high_centrality\" || signal === \"deep_chain\" || signal === \"high_fanout\",\n ).length >= 2 ||\n (dep.ownRiskSignals.includes(\"single_maintainer\") &&\n ((dep.daysSinceLastRelease ?? 0) >= config.abandonedDaysThreshold / 2 ||\n (dep.repositoryActivity30d ?? 1) <= 0)),\n )\n .filter((dep) => dep.dependencyScope === \"prod\")\n .sort(\n (a, b) => b.ownRiskSignals.length - a.ownRiskSignals.length || a.name.localeCompare(b.name),\n )\n .slice(0, config.maxHighRiskDependencies)\n .map((dep) => dep.name);\n\n const highRiskDevelopmentDependencies = dependencies\n .filter(\n (dep) =>\n dep.dependencyScope === \"dev\" &&\n (dep.ownRiskSignals.includes(\"abandoned\") ||\n dep.ownRiskSignals.filter(\n (signal) =>\n signal === \"high_centrality\" || signal === \"deep_chain\" || signal === \"high_fanout\",\n ).length >= 2 ||\n (dep.ownRiskSignals.includes(\"single_maintainer\") &&\n ((dep.daysSinceLastRelease ?? 0) >= config.abandonedDaysThreshold / 2 ||\n (dep.repositoryActivity30d ?? 1) <= 0))),\n )\n .sort(\n (a, b) => b.ownRiskSignals.length - a.ownRiskSignals.length || a.name.localeCompare(b.name),\n )\n .slice(0, config.maxHighRiskDependencies)\n .map((dep) => dep.name);\n\n const transitiveExposureDependencies = dependencies\n .filter((dep) => dep.inheritedRiskSignals.length > 0)\n .sort(\n (a, b) =>\n b.inheritedRiskSignals.length - a.inheritedRiskSignals.length ||\n a.name.localeCompare(b.name),\n )\n .map((dep) => dep.name);\n\n const singleMaintainerDependencies = dependencies\n .filter((dep) => dep.ownRiskSignals.includes(\"single_maintainer\"))\n .map((dep) => dep.name)\n .sort((a, b) => a.localeCompare(b));\n\n const abandonedDependencies = dependencies\n .filter((dep) => dep.ownRiskSignals.includes(\"abandoned\"))\n .map((dep) => dep.name)\n .sort((a, b) => a.localeCompare(b));\n\n const workspaces = buildWorkspaceExposureSummaries(\n workspaceManifests,\n allByName,\n nodeByName,\n config,\n );\n const workspaceSummary = workspaces.length > 0 ? { workspaces } : {};\n\n return {\n targetPath,\n available: true,\n metrics: {\n totalDependencies: allDependencies.length,\n directDependencies: dependencies.length,\n directProductionDependencies: dependencies.filter(\n (dependency) => dependency.dependencyScope === \"prod\",\n ).length,\n directDevelopmentDependencies: dependencies.filter(\n (dependency) => dependency.dependencyScope === \"dev\",\n ).length,\n transitiveDependencies: allDependencies.length - dependencies.length,\n dependencyDepth: maxDepth,\n lockfileKind: extraction.kind,\n metadataCoverage:\n allDependencies.length === 0 ? 0 : round4(metadataAvailableCount / allDependencies.length),\n },\n dependencies,\n ...workspaceSummary,\n highRiskDependencies,\n highRiskDevelopmentDependencies,\n transitiveExposureDependencies,\n singleMaintainerDependencies,\n abandonedDependencies,\n centralityRanking,\n };\n};\n","export const mapWithConcurrency = async <T, R>(\n values: readonly T[],\n limit: number,\n handler: (value: T) => Promise<R>,\n): Promise<readonly R[]> => {\n const effectiveLimit = Math.max(1, limit);\n const workerCount = Math.min(effectiveLimit, values.length);\n const UNSET = Symbol(\"map_with_concurrency_unset\");\n const results = new Array<R | typeof UNSET>(values.length).fill(UNSET);\n let index = 0;\n\n const workers: Promise<void>[] = Array.from({ length: workerCount }, async () => {\n // This loop always terminates: each iteration advances `index`,\n // and workers return once `index >= values.length`.\n while (true) {\n const current = index;\n index += 1;\n if (current >= values.length) {\n return;\n }\n\n const value = values[current] as T;\n results[current] = await handler(value);\n }\n });\n\n await Promise.all(workers);\n if (results.some((value) => value === UNSET)) {\n throw new Error(\"map_with_concurrency_incomplete_results\");\n }\n return results as R[];\n};\n","import type { LockfileExtraction, DependencyMetadataProvider } from \"../domain/types.js\";\nimport { mapWithConcurrency } from \"./map-with-concurrency.js\";\n\ntype MetadataEntry = {\n key: string;\n metadata: Awaited<ReturnType<DependencyMetadataProvider[\"getMetadata\"]>>;\n};\n\ntype MetadataProgressEvent = {\n completed: number;\n total: number;\n packageName: string;\n};\n\nexport const collectDependencyMetadata = async (\n extraction: LockfileExtraction,\n metadataProvider: DependencyMetadataProvider,\n concurrency: number,\n onProgress?: (event: MetadataProgressEvent) => void,\n): Promise<readonly MetadataEntry[]> => {\n const directNames = new Set(extraction.directDependencies.map((dependency) => dependency.name));\n let completed = 0;\n\n return mapWithConcurrency(extraction.nodes, concurrency, async (node) => {\n const result = {\n key: `${node.name}@${node.version}`,\n metadata: await metadataProvider.getMetadata(node.name, node.version, {\n directDependency: directNames.has(node.name),\n }),\n };\n completed += 1;\n onProgress?.({\n completed,\n total: extraction.nodes.length,\n packageName: node.name,\n });\n return result;\n });\n};\n","import type { ExternalAnalysisSummary } from \"@codesentinel/core\";\nimport { buildExternalAnalysisSummary } from \"../domain/external-analysis.js\";\nimport type {\n DependencyMetadata,\n DependencyMetadataProvider,\n ExternalAnalysisConfig,\n LockfileExtraction,\n WorkspaceDependencyManifest,\n} from \"../domain/types.js\";\nimport { collectDependencyMetadata } from \"./collect-dependency-metadata.js\";\n\nexport type DependencyExposureMetadataProgressEvent = {\n completed: number;\n total: number;\n packageName: string;\n};\n\nexport type BuildDependencyExposureSummaryInput = {\n targetPath: string;\n extraction: LockfileExtraction;\n metadataProvider: DependencyMetadataProvider;\n config: ExternalAnalysisConfig;\n workspaceManifests?: readonly WorkspaceDependencyManifest[];\n onMetadataProgress?: (event: DependencyExposureMetadataProgressEvent) => void;\n};\n\nexport const buildDependencyExposureSummary = async (\n input: BuildDependencyExposureSummaryInput,\n): Promise<ExternalAnalysisSummary> => {\n const metadataEntries = await collectDependencyMetadata(\n input.extraction,\n input.metadataProvider,\n input.config.metadataRequestConcurrency,\n input.onMetadataProgress,\n );\n\n const metadataByKey = new Map<string, DependencyMetadata | null>();\n for (const entry of metadataEntries) {\n metadataByKey.set(entry.key, entry.metadata);\n }\n\n return buildExternalAnalysisSummary(\n input.targetPath,\n input.extraction,\n metadataByKey,\n input.config,\n input.workspaceManifests ?? [],\n );\n};\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport type RepositoryFiles = {\n packageJsonPath: string;\n packageJsonRaw: string;\n lockfilePath: string;\n lockfileRaw: string;\n};\n\nconst LOCKFILE_CANDIDATES: readonly {\n fileName: string;\n kind: \"pnpm\" | \"npm\" | \"npm-shrinkwrap\" | \"yarn\" | \"bun\";\n}[] = [\n { fileName: \"pnpm-lock.yaml\", kind: \"pnpm\" },\n { fileName: \"package-lock.json\", kind: \"npm\" },\n { fileName: \"npm-shrinkwrap.json\", kind: \"npm-shrinkwrap\" },\n { fileName: \"yarn.lock\", kind: \"yarn\" },\n { fileName: \"bun.lock\", kind: \"bun\" },\n { fileName: \"bun.lockb\", kind: \"bun\" },\n];\n\nexport type LockfileSelection = {\n path: string;\n kind: \"pnpm\" | \"npm\" | \"npm-shrinkwrap\" | \"yarn\" | \"bun\";\n raw: string;\n};\n\nexport const loadPackageJson = (repositoryPath: string): { path: string; raw: string } | null => {\n const packageJsonPath = join(repositoryPath, \"package.json\");\n if (!existsSync(packageJsonPath)) {\n return null;\n }\n\n return {\n path: packageJsonPath,\n raw: readFileSync(packageJsonPath, \"utf8\"),\n };\n};\n\nexport const selectLockfile = (repositoryPath: string): LockfileSelection | null => {\n for (const candidate of LOCKFILE_CANDIDATES) {\n const absolutePath = join(repositoryPath, candidate.fileName);\n if (!existsSync(absolutePath)) {\n continue;\n }\n\n return {\n path: absolutePath,\n kind: candidate.kind,\n raw: readFileSync(absolutePath, \"utf8\"),\n };\n }\n\n return null;\n};\n","import type { DirectDependencySpec } from \"../domain/types.js\";\n\ntype ParsedPackageJson = {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n optionalDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n};\n\nexport const parsePackageJson = (raw: string): readonly DirectDependencySpec[] => {\n const parsed = JSON.parse(raw) as ParsedPackageJson;\n const merged = new Map<string, DirectDependencySpec>();\n\n const addBlock = (block: Record<string, string> | undefined, scope: \"prod\" | \"dev\"): void => {\n if (block === undefined) {\n return;\n }\n\n for (const [name, versionRange] of Object.entries(block)) {\n const existing = merged.get(name);\n // Production scope wins when the same package appears in both scopes.\n if (existing?.scope === \"prod\" && scope === \"dev\") {\n continue;\n }\n\n merged.set(name, { name, requestedRange: versionRange, scope });\n }\n };\n\n addBlock(parsed.dependencies, \"prod\");\n addBlock(parsed.optionalDependencies, \"prod\");\n addBlock(parsed.peerDependencies, \"prod\");\n addBlock(parsed.devDependencies, \"dev\");\n\n return [...merged.values()].sort((a, b) => a.name.localeCompare(b.name));\n};\n","import type {\n DirectDependencySpec,\n LockfileExtraction,\n LockedDependencyNode,\n} from \"../domain/types.js\";\n\ntype PackageLockNode = {\n version?: string;\n dependencies?: Record<string, string>;\n};\n\ntype PackageLockShape = {\n lockfileVersion?: number;\n packages?: Record<string, PackageLockNode>;\n dependencies?: Record<string, { version?: string; dependencies?: Record<string, unknown> }>;\n};\n\nexport const parsePackageLock = (\n raw: string,\n directSpecs: readonly DirectDependencySpec[],\n): LockfileExtraction => {\n const parsed = JSON.parse(raw) as PackageLockShape;\n const nodes: LockedDependencyNode[] = [];\n\n if (parsed.packages !== undefined) {\n for (const [packagePath, packageData] of Object.entries(parsed.packages)) {\n if (packagePath.length === 0 || packageData.version === undefined) {\n continue;\n }\n\n const segments = packagePath.split(\"node_modules/\");\n const name = segments[segments.length - 1] ?? \"\";\n if (name.length === 0) {\n continue;\n }\n\n const dependencies = Object.entries(packageData.dependencies ?? {})\n .map(([depName, depRange]) => `${depName}@${String(depRange)}`)\n .sort((a, b) => a.localeCompare(b));\n\n nodes.push({\n name,\n version: packageData.version,\n dependencies,\n });\n }\n } else if (parsed.dependencies !== undefined) {\n for (const [name, dep] of Object.entries(parsed.dependencies)) {\n if (dep.version === undefined) {\n continue;\n }\n\n const dependencies = Object.entries(dep.dependencies ?? {})\n .map(([depName, depVersion]) => `${depName}@${String(depVersion)}`)\n .sort((a, b) => a.localeCompare(b));\n\n nodes.push({\n name,\n version: dep.version,\n dependencies,\n });\n }\n }\n\n nodes.sort((a, b) => a.name.localeCompare(b.name) || a.version.localeCompare(b.version));\n\n return {\n kind: \"npm\",\n directDependencies: directSpecs,\n nodes,\n };\n};\n","import type {\n DirectDependencySpec,\n LockfileExtraction,\n LockedDependencyNode,\n} from \"../domain/types.js\";\n\ntype ParserState = \"root\" | \"importers\" | \"packages\" | \"packageDeps\";\n\nconst sanitizeValue = (value: string): string => value.replace(/^['\"]|['\"]$/g, \"\").trim();\n\nconst parsePackageKey = (rawKey: string): { name: string; version: string } | null => {\n const key = sanitizeValue(rawKey.replace(/:$/, \"\"));\n const withoutSlash = key.startsWith(\"/\") ? key.slice(1) : key;\n\n const lastAt = withoutSlash.lastIndexOf(\"@\");\n if (lastAt <= 0) {\n return null;\n }\n\n const name = withoutSlash.slice(0, lastAt);\n const versionWithPeers = withoutSlash.slice(lastAt + 1);\n const version = versionWithPeers.split(\"(\")[0] ?? versionWithPeers;\n\n if (name.length === 0 || version.length === 0) {\n return null;\n }\n\n return { name, version };\n};\n\nexport const parsePnpmLockfile = (\n raw: string,\n directSpecs: readonly DirectDependencySpec[],\n): LockfileExtraction => {\n const lines = raw.split(\"\\n\");\n let state: ParserState = \"root\";\n let currentPackage: string | null = null;\n let currentDependencyName: string | null = null;\n const dependenciesByNode = new Map<string, Set<string>>();\n\n for (const line of lines) {\n if (line.trim().length === 0 || line.trimStart().startsWith(\"#\")) {\n continue;\n }\n\n if (line.startsWith(\"importers:\")) {\n state = \"importers\";\n continue;\n }\n\n if (line.startsWith(\"packages:\")) {\n state = \"packages\";\n continue;\n }\n\n if (state === \"packages\" || state === \"packageDeps\") {\n const packageMatch = line.match(/^\\s{2}([^\\s].+):\\s*$/);\n if (packageMatch !== null) {\n const parsedKey = parsePackageKey(packageMatch[1] ?? \"\");\n if (parsedKey !== null) {\n currentPackage = `${parsedKey.name}@${parsedKey.version}`;\n dependenciesByNode.set(currentPackage, new Set());\n state = \"packageDeps\";\n currentDependencyName = null;\n }\n continue;\n }\n }\n\n if (state === \"packageDeps\" && currentPackage !== null) {\n const depLine = line.match(/^\\s{6}([^:\\s]+):\\s*(.+)$/);\n if (depLine !== null) {\n const depName = sanitizeValue(depLine[1] ?? \"\");\n const depRef = sanitizeValue(depLine[2] ?? \"\");\n const depVersion = depRef.split(\"(\")[0] ?? depRef;\n\n if (depName.length > 0 && depVersion.length > 0) {\n dependenciesByNode.get(currentPackage)?.add(`${depName}@${depVersion}`);\n }\n currentDependencyName = null;\n continue;\n }\n\n const depBlockLine = line.match(/^\\s{6}([^:\\s]+):\\s*$/);\n if (depBlockLine !== null) {\n currentDependencyName = sanitizeValue(depBlockLine[1] ?? \"\");\n continue;\n }\n\n const depVersionLine = line.match(/^\\s{8}version:\\s*(.+)$/);\n if (depVersionLine !== null && currentDependencyName !== null) {\n const depRef = sanitizeValue(depVersionLine[1] ?? \"\");\n const depVersion = depRef.split(\"(\")[0] ?? depRef;\n if (depVersion.length > 0) {\n dependenciesByNode.get(currentPackage)?.add(`${currentDependencyName}@${depVersion}`);\n }\n currentDependencyName = null;\n continue;\n }\n\n if (line.match(/^\\s{4}(dependencies|optionalDependencies):\\s*$/) !== null) {\n continue;\n }\n }\n }\n\n const nodes: LockedDependencyNode[] = [...dependenciesByNode.entries()]\n .map(([nodeId, deps]) => {\n const at = nodeId.lastIndexOf(\"@\");\n return {\n name: nodeId.slice(0, at),\n version: nodeId.slice(at + 1),\n dependencies: [...deps].sort((a, b) => a.localeCompare(b)),\n };\n })\n .sort((a, b) => a.name.localeCompare(b.name) || a.version.localeCompare(b.version));\n\n return {\n kind: \"pnpm\",\n directDependencies: directSpecs,\n nodes,\n };\n};\n","import type {\n DirectDependencySpec,\n LockfileExtraction,\n LockedDependencyNode,\n} from \"../domain/types.js\";\n\nconst stripQuotes = (value: string): string => value.replace(/^['\"]|['\"]$/g, \"\");\n\nconst parseVersionSelector = (selector: string): string | null => {\n const npmIndex = selector.lastIndexOf(\"@npm:\");\n if (npmIndex >= 0) {\n return selector.slice(npmIndex + 5);\n }\n\n const lastAt = selector.lastIndexOf(\"@\");\n if (lastAt <= 0) {\n return null;\n }\n\n return selector.slice(lastAt + 1);\n};\n\nexport const parseYarnLock = (\n raw: string,\n directSpecs: readonly DirectDependencySpec[],\n): LockfileExtraction => {\n const lines = raw.split(\"\\n\");\n const nodes: LockedDependencyNode[] = [];\n\n let selectors: string[] = [];\n let version: string | null = null;\n let readingDependencies = false;\n let dependencies: string[] = [];\n\n const flushEntry = (): void => {\n if (selectors.length === 0 || version === null) {\n selectors = [];\n version = null;\n dependencies = [];\n readingDependencies = false;\n return;\n }\n\n for (const selector of selectors) {\n const parsedVersion = parseVersionSelector(selector);\n const at = selector.lastIndexOf(\"@\");\n const name = at <= 0 ? selector : selector.slice(0, at);\n if (name.length === 0) {\n continue;\n }\n\n nodes.push({\n name,\n version,\n dependencies: [...dependencies].sort((a, b) => a.localeCompare(b)),\n });\n\n if (parsedVersion !== null) {\n nodes.push({\n name,\n version: parsedVersion,\n dependencies: [...dependencies].sort((a, b) => a.localeCompare(b)),\n });\n }\n }\n\n selectors = [];\n version = null;\n dependencies = [];\n readingDependencies = false;\n };\n\n for (const line of lines) {\n if (line.trim().length === 0) {\n continue;\n }\n\n if (!line.startsWith(\" \") && line.endsWith(\":\")) {\n flushEntry();\n const keyText = line.slice(0, -1);\n selectors = keyText\n .split(\",\")\n .map((part) => stripQuotes(part.trim()))\n .filter((part) => part.length > 0);\n continue;\n }\n\n if (line.match(/^\\s{2}version\\s+/) !== null) {\n const value = line.replace(/^\\s{2}version\\s+/, \"\").trim();\n version = stripQuotes(value);\n readingDependencies = false;\n continue;\n }\n\n if (line.match(/^\\s{2}dependencies:\\s*$/) !== null) {\n readingDependencies = true;\n continue;\n }\n\n if (readingDependencies && line.match(/^\\s{4}[^\\s].+$/) !== null) {\n const depLine = line.trim();\n const firstSpace = depLine.indexOf(\" \");\n if (firstSpace <= 0) {\n continue;\n }\n\n const depName = stripQuotes(depLine.slice(0, firstSpace));\n const depRef = stripQuotes(depLine.slice(firstSpace + 1).trim());\n const depVersion = parseVersionSelector(depRef) ?? depRef;\n dependencies.push(`${depName}@${depVersion}`);\n continue;\n }\n\n readingDependencies = false;\n }\n\n flushEntry();\n\n const deduped = new Map<string, LockedDependencyNode>();\n for (const node of nodes) {\n const key = `${node.name}@${node.version}`;\n if (!deduped.has(key)) {\n deduped.set(key, node);\n }\n }\n\n return {\n kind: \"yarn\",\n directDependencies: directSpecs,\n nodes: [...deduped.values()].sort(\n (a, b) => a.name.localeCompare(b.name) || a.version.localeCompare(b.version),\n ),\n };\n};\n","import type { DirectDependencySpec, LockfileExtraction } from \"../domain/types.js\";\n\nexport const parseBunLock = (\n _raw: string,\n _directSpecs: readonly DirectDependencySpec[],\n): LockfileExtraction => {\n throw new Error(\"unsupported_lockfile_format\");\n};\n","import type { LockfileExtraction } from \"../domain/types.js\";\nimport type { parsePackageJson } from \"../parsing/package-json-loader.js\";\nimport { parsePackageLock } from \"../parsing/package-lock-parser.js\";\nimport { parsePnpmLockfile } from \"../parsing/pnpm-lock-parser.js\";\nimport { parseYarnLock } from \"../parsing/yarn-lock-parser.js\";\nimport { parseBunLock } from \"../parsing/bun-lock-parser.js\";\n\ntype SupportedLockfileKind = \"pnpm\" | \"npm\" | \"npm-shrinkwrap\" | \"yarn\" | \"bun\";\n\nexport const parseLockfileExtraction = (\n lockfileKind: SupportedLockfileKind,\n lockfileRaw: string,\n directSpecs: ReturnType<typeof parsePackageJson>,\n): LockfileExtraction => {\n switch (lockfileKind) {\n case \"pnpm\":\n return parsePnpmLockfile(lockfileRaw, directSpecs);\n case \"npm\":\n case \"npm-shrinkwrap\":\n return {\n ...parsePackageLock(lockfileRaw, directSpecs),\n kind: lockfileKind,\n };\n case \"yarn\":\n return parseYarnLock(lockfileRaw, directSpecs);\n case \"bun\":\n return parseBunLock(lockfileRaw, directSpecs);\n default:\n throw new Error(\"unsupported_lockfile_format\");\n }\n};\n","import type { CacheStore } from \"./cache-store.js\";\n\ntype CachedFetchOptions<T> = {\n key: string;\n ttlMs: number;\n cacheStore: CacheStore | null;\n fetchFresh: () => Promise<T | null>;\n nowMs?: number;\n};\n\nexport const cachedFetch = async <T>(options: CachedFetchOptions<T>): Promise<T | null> => {\n const nowMs = options.nowMs ?? Date.now();\n const cachedEntry =\n options.cacheStore === null ? null : await options.cacheStore.get<T>(options.key);\n\n if (cachedEntry !== null && nowMs - cachedEntry.fetchedAtMs <= options.ttlMs) {\n return cachedEntry.value;\n }\n\n try {\n const fresh = await options.fetchFresh();\n if (fresh !== null) {\n void options.cacheStore?.set(options.key, { value: fresh, fetchedAtMs: nowMs }).catch(() => {\n // Cache persistence failures should not impact the primary fetch path.\n });\n return fresh;\n }\n } catch {\n // Network failures should not block stale fallback.\n }\n\n return cachedEntry?.value ?? null;\n};\n","import { setTimeout as sleep } from \"node:timers/promises\";\n\nexport type FetchRetryOptions = {\n retries: number;\n baseDelayMs: number;\n};\n\nconst parseRetryAfterMs = (value: string | null): number | null => {\n if (value === null) {\n return null;\n }\n\n const seconds = Number.parseInt(value, 10);\n if (!Number.isFinite(seconds) || seconds <= 0) {\n return null;\n }\n\n return seconds * 1000;\n};\n\nconst shouldRetryStatus = (status: number): boolean => status === 429 || status >= 500;\n\nexport const fetchJsonWithRetry = async <T>(\n url: string,\n options: FetchRetryOptions,\n): Promise<T | null> => {\n for (let attempt = 0; attempt <= options.retries; attempt += 1) {\n const response = await fetch(url);\n if (response.ok) {\n return (await response.json()) as T;\n }\n\n if (!shouldRetryStatus(response.status) || attempt === options.retries) {\n return null;\n }\n\n const retryAfterMs = parseRetryAfterMs(response.headers.get(\"retry-after\"));\n const backoffMs = retryAfterMs ?? options.baseDelayMs * 2 ** attempt;\n await sleep(backoffMs);\n }\n\n return null;\n};\n","import { join } from \"node:path\";\nimport type { CacheStore } from \"./cache-store.js\";\nimport { resolveCodesentinelCacheDir } from \"./codesentinel-cache-dir.js\";\nimport { FileCacheStore } from \"./file-cache-store.js\";\n\nconst SIX_HOURS_MS = 6 * 60 * 60 * 1000;\nconst ONE_DAY_MS = 24 * 60 * 60 * 1000;\nconst DEFAULT_MAX_BYTES = 20 * 1024 * 1024;\nconst DEFAULT_MAX_ENTRY_BYTES = 4 * 1024 * 1024;\nconst DEFAULT_SWEEP_INTERVAL_WRITES = 25;\n\nlet cacheStoreSingleton: CacheStore | null | undefined;\n\nconst parsePositiveIntegerFromEnv = (value: string | undefined, fallback: number): number => {\n if (value === undefined) {\n return fallback;\n }\n const parsed = Number.parseInt(value, 10);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n return fallback;\n }\n return parsed;\n};\n\nconst cacheDisabled = (env: NodeJS.ProcessEnv): boolean => {\n const mode = env[\"CODESENTINEL_CACHE_MODE\"]?.trim().toLowerCase();\n return mode === \"none\";\n};\n\nexport const getNpmMetadataCacheStore = (): CacheStore | null => {\n if (cacheStoreSingleton !== undefined) {\n return cacheStoreSingleton;\n }\n\n if (cacheDisabled(process.env)) {\n cacheStoreSingleton = null;\n return cacheStoreSingleton;\n }\n\n const path = join(resolveCodesentinelCacheDir(process.env), \"npm-metadata-v2\");\n const packumentTtlMs = getPackumentCacheTtlMs();\n const downloadsTtlMs = getWeeklyDownloadsCacheTtlMs();\n cacheStoreSingleton = new FileCacheStore(path, {\n maxBytes: parsePositiveIntegerFromEnv(\n process.env[\"CODESENTINEL_CACHE_MAX_BYTES\"],\n DEFAULT_MAX_BYTES,\n ),\n maxEntryBytes: parsePositiveIntegerFromEnv(\n process.env[\"CODESENTINEL_CACHE_MAX_ENTRY_BYTES\"],\n DEFAULT_MAX_ENTRY_BYTES,\n ),\n sweepIntervalWrites: parsePositiveIntegerFromEnv(\n process.env[\"CODESENTINEL_CACHE_SWEEP_INTERVAL_WRITES\"],\n DEFAULT_SWEEP_INTERVAL_WRITES,\n ),\n bucketForKey: (key) => {\n if (key.startsWith(\"npm:downloads:last-week:\")) {\n return \"downloads\";\n }\n if (key.startsWith(\"npm:packument:\")) {\n return \"packument\";\n }\n return \"default\";\n },\n maxAgeMsByBucket: {\n downloads: downloadsTtlMs,\n packument: packumentTtlMs,\n },\n });\n return cacheStoreSingleton;\n};\n\nexport const getPackumentCacheTtlMs = (): number =>\n parsePositiveIntegerFromEnv(process.env[\"CODESENTINEL_CACHE_TTL_PACKUMENT_MS\"], SIX_HOURS_MS);\n\nexport const getWeeklyDownloadsCacheTtlMs = (): number =>\n parsePositiveIntegerFromEnv(process.env[\"CODESENTINEL_CACHE_TTL_DOWNLOADS_MS\"], ONE_DAY_MS);\n\nexport const toMetadataPackumentCacheKey = (name: string): string =>\n `npm:packument:metadata:${name}`;\nexport const toGraphPackumentCacheKey = (name: string): string => `npm:packument:graph:${name}`;\nexport const toWeeklyDownloadsCacheKey = (name: string): string =>\n `npm:downloads:last-week:${name}`;\n","import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport const resolveCodesentinelCacheDir = (env: NodeJS.ProcessEnv = process.env): string => {\n const explicit = env[\"CODESENTINEL_CACHE_DIR\"]?.trim();\n if (explicit !== undefined && explicit.length > 0) {\n return explicit;\n }\n\n if (process.platform === \"win32\") {\n const localAppData = env[\"LOCALAPPDATA\"]?.trim();\n if (localAppData !== undefined && localAppData.length > 0) {\n return join(localAppData, \"codesentinel\", \"Cache\");\n }\n return join(homedir(), \"AppData\", \"Local\", \"codesentinel\", \"Cache\");\n }\n\n const xdgCacheHome = env[\"XDG_CACHE_HOME\"]?.trim();\n if (xdgCacheHome !== undefined && xdgCacheHome.length > 0) {\n return join(xdgCacheHome, \"codesentinel\");\n }\n\n return join(homedir(), \".cache\", \"codesentinel\");\n};\n","import { createHash } from \"node:crypto\";\nimport { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { CacheEntry, CacheStore } from \"./cache-store.js\";\n\ntype CacheEntryPayload = {\n key: string;\n fetchedAtMs: number;\n value: unknown;\n};\n\nconst parseCacheEntryPayload = (value: unknown): CacheEntryPayload | null => {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n\n const payload = value as { key?: unknown; fetchedAtMs?: unknown; value?: unknown };\n if (typeof payload.key !== \"string\" || payload.key.length === 0) {\n return null;\n }\n if (typeof payload.fetchedAtMs !== \"number\" || !Number.isFinite(payload.fetchedAtMs)) {\n return null;\n }\n\n return {\n key: payload.key,\n fetchedAtMs: payload.fetchedAtMs,\n value: payload.value,\n };\n};\n\ntype FileCacheStoreOptions = {\n maxBytes: number;\n maxEntryBytes: number;\n sweepIntervalWrites: number;\n bucketForKey?: (key: string) => string;\n maxAgeMsByBucket?: Readonly<Record<string, number>>;\n};\n\nconst DEFAULT_OPTIONS: FileCacheStoreOptions = {\n maxBytes: 100 * 1024 * 1024,\n maxEntryBytes: 4 * 1024 * 1024,\n sweepIntervalWrites: 25,\n};\n\nconst DEFAULT_BUCKET = \"default\";\n\nconst normalizeBucket = (value: string): string => {\n const trimmed = value.trim().toLowerCase();\n if (trimmed.length === 0) {\n return DEFAULT_BUCKET;\n }\n return trimmed.replace(/[^a-z0-9_-]/g, \"_\");\n};\n\nexport class FileCacheStore implements CacheStore {\n private readonly byKey = new Map<string, CacheEntry<unknown> | null>();\n private readonly inFlightWrites = new Map<string, Promise<void>>();\n private writesSinceSweep = 0;\n private sweepPromise: Promise<void> = Promise.resolve();\n\n constructor(\n private readonly directoryPath: string,\n private readonly options: FileCacheStoreOptions = DEFAULT_OPTIONS,\n ) {}\n\n private bucketForKey(key: string): string {\n const configured = this.options.bucketForKey?.(key);\n if (configured === undefined) {\n return DEFAULT_BUCKET;\n }\n return normalizeBucket(configured);\n }\n\n private toEntryPath(key: string): string {\n const bucket = this.bucketForKey(key);\n const digest = createHash(\"sha256\").update(key).digest(\"hex\");\n return join(this.directoryPath, bucket, `${digest}.json`);\n }\n\n private async writeEntry(key: string, entry: CacheEntry<unknown>): Promise<void> {\n const filePath = this.toEntryPath(key);\n const bucketPath = join(this.directoryPath, this.bucketForKey(key));\n await mkdir(bucketPath, { recursive: true });\n const tempPath = `${filePath}.tmp`;\n const payload: CacheEntryPayload = {\n key,\n fetchedAtMs: entry.fetchedAtMs,\n value: entry.value,\n };\n const raw = JSON.stringify(payload);\n if (Buffer.byteLength(raw, \"utf8\") > this.options.maxEntryBytes) {\n return;\n }\n\n await writeFile(tempPath, raw, \"utf8\");\n await rename(tempPath, filePath);\n }\n\n private async sweepIfNeeded(): Promise<void> {\n this.writesSinceSweep += 1;\n if (this.writesSinceSweep < this.options.sweepIntervalWrites) {\n return;\n }\n this.writesSinceSweep = 0;\n\n this.sweepPromise = this.sweepPromise\n .catch(() => {\n // Keep sweep queue alive across failures.\n })\n .then(async () => {\n await this.evictToSizeLimit();\n });\n await this.sweepPromise;\n }\n\n private async evictToSizeLimit(): Promise<void> {\n const nowMs = Date.now();\n let entries: Array<{ path: string; size: number; mtimeMs: number; bucket: string }>;\n try {\n const bucketEntries = await readdir(this.directoryPath, { withFileTypes: true });\n const bucketNames = bucketEntries\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name);\n entries = (\n await Promise.all(\n bucketNames.map(async (bucket) => {\n const bucketPath = join(this.directoryPath, bucket);\n const files = await readdir(bucketPath, { withFileTypes: true });\n return await Promise.all(\n files\n .filter((entry) => entry.isFile() && entry.name.endsWith(\".json\"))\n .map(async (entry) => {\n const path = join(bucketPath, entry.name);\n const info = await stat(path);\n return {\n path,\n size: info.size,\n mtimeMs: info.mtimeMs,\n bucket,\n };\n }),\n );\n }),\n )\n )\n .flat()\n .filter((entry) => Number.isFinite(entry.size) && entry.size > 0);\n } catch {\n return;\n }\n\n if (this.options.maxAgeMsByBucket !== undefined) {\n const retained: typeof entries = [];\n let deletedAny = false;\n for (const entry of entries) {\n const maxAgeMs = this.options.maxAgeMsByBucket[entry.bucket];\n const expired =\n typeof maxAgeMs === \"number\" &&\n Number.isFinite(maxAgeMs) &&\n nowMs - entry.mtimeMs > maxAgeMs;\n if (!expired) {\n retained.push(entry);\n continue;\n }\n\n try {\n await unlink(entry.path);\n deletedAny = true;\n } catch {\n retained.push(entry);\n }\n }\n entries = retained;\n if (deletedAny) {\n this.byKey.clear();\n }\n }\n\n let totalBytes = entries.reduce((sum, entry) => sum + entry.size, 0);\n if (totalBytes <= this.options.maxBytes) {\n return;\n }\n\n entries.sort((a, b) => a.mtimeMs - b.mtimeMs);\n let deletedAny = false;\n for (const entry of entries) {\n if (totalBytes <= this.options.maxBytes) {\n break;\n }\n try {\n await unlink(entry.path);\n deletedAny = true;\n totalBytes -= entry.size;\n } catch {\n // Ignore eviction failures for individual files.\n }\n }\n if (deletedAny) {\n this.byKey.clear();\n }\n }\n\n async get<T>(key: string): Promise<CacheEntry<T> | null> {\n if (this.byKey.has(key)) {\n return (this.byKey.get(key) as CacheEntry<T> | null) ?? null;\n }\n\n try {\n const raw = await readFile(this.toEntryPath(key), \"utf8\");\n const parsed = parseCacheEntryPayload(JSON.parse(raw));\n if (parsed === null || parsed.key !== key) {\n this.byKey.set(key, null);\n return null;\n }\n\n const value = { fetchedAtMs: parsed.fetchedAtMs, value: parsed.value as T };\n this.byKey.set(key, value as CacheEntry<unknown>);\n return value;\n } catch {\n this.byKey.set(key, null);\n return null;\n }\n }\n\n async set<T>(key: string, entry: CacheEntry<T>): Promise<void> {\n const normalized = entry as CacheEntry<unknown>;\n this.byKey.set(key, normalized);\n\n const previous = this.inFlightWrites.get(key) ?? Promise.resolve();\n const next = previous\n .catch(() => {\n // Keep write chain active even after previous failures.\n })\n .then(async () => {\n await this.writeEntry(key, normalized);\n await this.sweepIfNeeded();\n });\n this.inFlightWrites.set(key, next);\n await next;\n }\n}\n","import type { DirectDependencySpec, LockedDependencyNode } from \"../domain/types.js\";\nimport { cachedFetch } from \"../infrastructure/cached-fetch.js\";\nimport { fetchJsonWithRetry } from \"../infrastructure/fetch-json-with-retry.js\";\nimport {\n getNpmMetadataCacheStore,\n getPackumentCacheTtlMs,\n toGraphPackumentCacheKey,\n} from \"../infrastructure/npm-metadata-cache.js\";\n\ntype NpmPackageManifest = {\n dependencies?: Record<string, string>;\n};\n\ntype NpmPackumentRaw = {\n \"dist-tags\"?: Record<string, string>;\n versions?: Record<string, NpmPackageManifest>;\n};\n\ntype NpmPackumentGraph = {\n \"dist-tags\"?: Record<string, string>;\n versionNames: readonly string[];\n dependenciesByVersion: Readonly<Record<string, Record<string, string>>>;\n};\n\ntype ParsedSemver = {\n major: number;\n minor: number;\n patch: number;\n prerelease: readonly (string | number)[];\n};\n\ntype ResolvedVersion = {\n version: string;\n resolution: \"exact\" | \"tag\" | \"range\" | \"latest\";\n fallbackUsed: boolean;\n};\n\ntype QueueItem = {\n name: string;\n requested: string | null;\n depth: number;\n};\n\nexport type ResolvedDirectDependency = {\n name: string;\n requestedRange: string;\n resolvedVersion: string;\n resolution: \"exact\" | \"tag\" | \"range\" | \"latest\";\n scope: \"prod\" | \"dev\";\n};\n\nexport type ResolveRegistryGraphResult = {\n nodes: readonly LockedDependencyNode[];\n directDependencies: readonly ResolvedDirectDependency[];\n assumptions: readonly string[];\n truncated: boolean;\n};\n\nexport type ResolveRegistryGraphOptions = {\n maxNodes: number;\n maxDepth: number;\n};\n\nconst MAX_RETRIES = 3;\nconst RETRY_BASE_DELAY_MS = 500;\nconst PACKUMENT_CACHE_STORE = getNpmMetadataCacheStore();\n\nconst parsePrerelease = (value: string | undefined): readonly (string | number)[] => {\n if (value === undefined || value.length === 0) {\n return [];\n }\n\n return value.split(\".\").map((part) => {\n const asNumber = Number.parseInt(part, 10);\n if (!Number.isNaN(asNumber) && `${asNumber}` === part) {\n return asNumber;\n }\n\n return part;\n });\n};\n\nconst parseSemver = (value: string): ParsedSemver | null => {\n const trimmed = value.trim();\n const semverMatch = trimmed.match(\n /^v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/,\n );\n if (semverMatch === null) {\n return null;\n }\n\n const major = Number.parseInt(semverMatch[1] ?? \"\", 10);\n const minor = Number.parseInt(semverMatch[2] ?? \"\", 10);\n const patch = Number.parseInt(semverMatch[3] ?? \"\", 10);\n if (!Number.isFinite(major) || !Number.isFinite(minor) || !Number.isFinite(patch)) {\n return null;\n }\n\n return {\n major,\n minor,\n patch,\n prerelease: parsePrerelease(semverMatch[4]),\n };\n};\n\nconst compareIdentifier = (left: string | number, right: string | number): number => {\n if (typeof left === \"number\" && typeof right === \"number\") {\n return left - right;\n }\n\n if (typeof left === \"number\") {\n return -1;\n }\n\n if (typeof right === \"number\") {\n return 1;\n }\n\n return left.localeCompare(right);\n};\n\nconst compareSemver = (left: ParsedSemver, right: ParsedSemver): number => {\n if (left.major !== right.major) {\n return left.major - right.major;\n }\n if (left.minor !== right.minor) {\n return left.minor - right.minor;\n }\n if (left.patch !== right.patch) {\n return left.patch - right.patch;\n }\n\n if (left.prerelease.length === 0 && right.prerelease.length === 0) {\n return 0;\n }\n if (left.prerelease.length === 0) {\n return 1;\n }\n if (right.prerelease.length === 0) {\n return -1;\n }\n\n const maxLength = Math.max(left.prerelease.length, right.prerelease.length);\n for (let i = 0; i < maxLength; i += 1) {\n const leftPart = left.prerelease[i];\n const rightPart = right.prerelease[i];\n\n if (leftPart === undefined && rightPart === undefined) {\n return 0;\n }\n if (leftPart === undefined) {\n return -1;\n }\n if (rightPart === undefined) {\n return 1;\n }\n\n const diff = compareIdentifier(leftPart, rightPart);\n if (diff !== 0) {\n return diff;\n }\n }\n\n return 0;\n};\n\nconst isWildcardPart = (value: string | undefined): boolean =>\n value === undefined || value === \"*\" || value.toLowerCase() === \"x\";\n\nconst matchesPartialVersion = (version: ParsedSemver, token: string): boolean => {\n const normalized = token.trim().replace(/^v/, \"\");\n if (normalized === \"*\" || normalized.length === 0) {\n return true;\n }\n\n const [majorPart, minorPart, patchPart] = normalized.split(\".\");\n if (majorPart !== undefined && !isWildcardPart(majorPart)) {\n const major = Number.parseInt(majorPart, 10);\n if (!Number.isFinite(major) || major !== version.major) {\n return false;\n }\n }\n\n if (minorPart !== undefined && !isWildcardPart(minorPart)) {\n const minor = Number.parseInt(minorPart, 10);\n if (!Number.isFinite(minor) || minor !== version.minor) {\n return false;\n }\n }\n\n if (patchPart !== undefined && !isWildcardPart(patchPart)) {\n const patch = Number.parseInt(patchPart, 10);\n if (!Number.isFinite(patch) || patch !== version.patch) {\n return false;\n }\n }\n\n return true;\n};\n\nconst parseComparatorToken = (token: string): { operator: string; versionToken: string } => {\n const operators = [\">=\", \"<=\", \">\", \"<\", \"=\"];\n for (const operator of operators) {\n if (token.startsWith(operator)) {\n return {\n operator,\n versionToken: token.slice(operator.length).trim(),\n };\n }\n }\n\n return {\n operator: \"=\",\n versionToken: token.trim(),\n };\n};\n\nconst satisfiesComparator = (version: ParsedSemver, token: string): boolean | null => {\n if (token.length === 0 || token === \"*\") {\n return true;\n }\n\n if (token.startsWith(\"^\")) {\n const base = parseSemver(token.slice(1));\n if (base === null) {\n return null;\n }\n\n let upper: ParsedSemver;\n if (base.major > 0) {\n upper = { major: base.major + 1, minor: 0, patch: 0, prerelease: [] };\n } else if (base.minor > 0) {\n upper = { major: 0, minor: base.minor + 1, patch: 0, prerelease: [] };\n } else {\n upper = { major: 0, minor: 0, patch: base.patch + 1, prerelease: [] };\n }\n\n return compareSemver(version, base) >= 0 && compareSemver(version, upper) < 0;\n }\n\n if (token.startsWith(\"~\")) {\n const base = parseSemver(token.slice(1));\n if (base === null) {\n return null;\n }\n\n const upper: ParsedSemver = {\n major: base.major,\n minor: base.minor + 1,\n patch: 0,\n prerelease: [],\n };\n\n return compareSemver(version, base) >= 0 && compareSemver(version, upper) < 0;\n }\n\n const parsedComparator = parseComparatorToken(token);\n const hasWildcard = /(^|[.])(?:x|X|\\*)($|[.])/.test(parsedComparator.versionToken);\n if (hasWildcard) {\n if (parsedComparator.operator !== \"=\") {\n return null;\n }\n return matchesPartialVersion(version, parsedComparator.versionToken);\n }\n\n const parsedVersion = parseSemver(parsedComparator.versionToken);\n if (parsedVersion === null) {\n if (parsedComparator.operator !== \"=\") {\n return null;\n }\n\n return matchesPartialVersion(version, parsedComparator.versionToken);\n }\n\n const comparison = compareSemver(version, parsedVersion);\n switch (parsedComparator.operator) {\n case \">\":\n return comparison > 0;\n case \">=\":\n return comparison >= 0;\n case \"<\":\n return comparison < 0;\n case \"<=\":\n return comparison <= 0;\n case \"=\":\n return comparison === 0;\n default:\n return null;\n }\n};\n\nconst satisfiesRangeClause = (version: ParsedSemver, clause: string): boolean | null => {\n const hyphenMatch = clause.match(/^\\s*(.+?)\\s+-\\s+(.+?)\\s*$/);\n if (hyphenMatch !== null) {\n const lower = hyphenMatch[1];\n const upper = hyphenMatch[2];\n if (lower === undefined || upper === undefined) {\n return null;\n }\n\n const lowerResult = satisfiesComparator(version, `>=${lower}`);\n const upperResult = satisfiesComparator(version, `<=${upper}`);\n if (lowerResult === null || upperResult === null) {\n return null;\n }\n\n return lowerResult && upperResult;\n }\n\n const tokens = clause\n .split(/\\s+/)\n .map((token) => token.trim())\n .filter((token) => token.length > 0);\n\n if (tokens.length === 0) {\n return true;\n }\n\n for (const token of tokens) {\n const matched = satisfiesComparator(version, token);\n if (matched === null) {\n return null;\n }\n\n if (!matched) {\n return false;\n }\n }\n\n return true;\n};\n\nconst resolveRangeVersion = (versions: readonly string[], requested: string): string | null => {\n const clauses = requested\n .split(\"||\")\n .map((clause) => clause.trim())\n .filter((clause) => clause.length > 0);\n\n if (clauses.length === 0) {\n return null;\n }\n\n const parsedVersions = versions\n .map((version) => ({ version, parsed: parseSemver(version) }))\n .filter(\n (candidate): candidate is { version: string; parsed: ParsedSemver } =>\n candidate.parsed !== null,\n )\n .sort((a, b) => compareSemver(b.parsed, a.parsed));\n\n for (const candidate of parsedVersions) {\n let clauseMatched = false;\n let clauseUnsupported = false;\n\n for (const clause of clauses) {\n const matched = satisfiesRangeClause(candidate.parsed, clause);\n if (matched === null) {\n clauseUnsupported = true;\n continue;\n }\n\n if (matched) {\n clauseMatched = true;\n break;\n }\n }\n\n if (clauseMatched) {\n return candidate.version;\n }\n\n if (clauseUnsupported && clauses.length === 1) {\n return null;\n }\n }\n\n return null;\n};\n\nconst slimPackumentForGraph = (payload: NpmPackumentRaw): NpmPackumentGraph => {\n const versions = payload.versions ?? {};\n const dependenciesByVersion: Record<string, Record<string, string>> = {};\n const versionNames = Object.keys(versions);\n\n for (const [version, manifest] of Object.entries(versions)) {\n const dependenciesRaw = manifest?.dependencies ?? {};\n const dependencies: Record<string, string> = {};\n for (const [dependencyName, dependencyRange] of Object.entries(dependenciesRaw)) {\n if (dependencyName.length > 0 && dependencyRange.length > 0) {\n dependencies[dependencyName] = dependencyRange;\n }\n }\n\n if (Object.keys(dependencies).length > 0) {\n dependenciesByVersion[version] = dependencies;\n }\n }\n\n const slim: NpmPackumentGraph = {\n versionNames,\n dependenciesByVersion,\n };\n if (payload[\"dist-tags\"] !== undefined) {\n slim[\"dist-tags\"] = payload[\"dist-tags\"];\n }\n return slim;\n};\n\nconst fetchPackument = async (name: string): Promise<NpmPackumentGraph | null> => {\n const encodedName = encodeURIComponent(name);\n try {\n return await cachedFetch<NpmPackumentGraph>({\n key: toGraphPackumentCacheKey(name),\n ttlMs: getPackumentCacheTtlMs(),\n cacheStore: PACKUMENT_CACHE_STORE,\n fetchFresh: async () => {\n const payload = await fetchJsonWithRetry<NpmPackumentRaw>(\n `https://registry.npmjs.org/${encodedName}`,\n {\n retries: MAX_RETRIES,\n baseDelayMs: RETRY_BASE_DELAY_MS,\n },\n );\n if (payload === null) {\n return null;\n }\n return slimPackumentForGraph(payload);\n },\n });\n } catch {\n return null;\n }\n};\n\nconst resolveRequestedVersion = (\n packument: NpmPackumentGraph,\n requested: string | null,\n): ResolvedVersion | null => {\n const versionKeys = [...packument.versionNames];\n const versionSet = new Set(versionKeys);\n const tags = packument[\"dist-tags\"] ?? {};\n const latest = tags[\"latest\"];\n\n if (requested !== null && versionSet.has(requested)) {\n return {\n version: requested,\n resolution: \"exact\",\n fallbackUsed: false,\n };\n }\n\n if (requested !== null) {\n const tagged = tags[requested];\n if (tagged !== undefined && versionSet.has(tagged)) {\n return {\n version: tagged,\n resolution: \"tag\",\n fallbackUsed: false,\n };\n }\n }\n\n if (requested !== null) {\n const matched = resolveRangeVersion(versionKeys, requested);\n if (matched !== null && versionSet.has(matched)) {\n return {\n version: matched,\n resolution: \"range\",\n fallbackUsed: false,\n };\n }\n }\n\n if (latest !== undefined && versionSet.has(latest)) {\n return {\n version: latest,\n resolution: \"latest\",\n fallbackUsed: requested !== null,\n };\n }\n\n const semverSorted = versionKeys\n .map((version) => ({ version, parsed: parseSemver(version) }))\n .filter(\n (candidate): candidate is { version: string; parsed: ParsedSemver } =>\n candidate.parsed !== null,\n )\n .sort((a, b) => compareSemver(b.parsed, a.parsed))\n .map((candidate) => candidate.version);\n const fallbackVersion = semverSorted[0] ?? versionKeys.sort((a, b) => b.localeCompare(a))[0];\n if (fallbackVersion === undefined) {\n return null;\n }\n\n return {\n version: fallbackVersion,\n resolution: \"latest\",\n fallbackUsed: requested !== null,\n };\n};\n\nexport const resolveRegistryGraphFromDirectSpecs = async (\n directSpecs: readonly DirectDependencySpec[],\n options: ResolveRegistryGraphOptions,\n): Promise<ResolveRegistryGraphResult> => {\n const maxNodes = Math.max(1, options.maxNodes);\n const maxDepth = Math.max(0, options.maxDepth);\n\n const queue: QueueItem[] = directSpecs.map((spec) => ({\n name: spec.name,\n requested: spec.requestedRange,\n depth: 0,\n }));\n const scopeByName = new Map(directSpecs.map((spec) => [spec.name, spec.scope]));\n const requestedByName = new Map(directSpecs.map((spec) => [spec.name, spec.requestedRange]));\n const packumentByName = new Map<string, NpmPackumentGraph | null>();\n const nodesByKey = new Map<string, LockedDependencyNode>();\n const directByName = new Map<string, ResolvedDirectDependency>();\n const assumptions = new Set<string>();\n let truncated = false;\n\n while (queue.length > 0) {\n if (nodesByKey.size >= maxNodes) {\n truncated = true;\n assumptions.add(`Dependency graph truncated at ${maxNodes} nodes.`);\n break;\n }\n\n const item = queue.shift();\n if (item === undefined) {\n break;\n }\n\n let packument = packumentByName.get(item.name) ?? null;\n if (!packumentByName.has(item.name)) {\n packument = await fetchPackument(item.name);\n packumentByName.set(item.name, packument);\n }\n\n if (packument === null) {\n if (scopeByName.has(item.name)) {\n assumptions.add(`Could not resolve direct dependency from registry: ${item.name}.`);\n }\n continue;\n }\n\n const resolved = resolveRequestedVersion(packument, item.requested);\n if (resolved === null) {\n if (scopeByName.has(item.name)) {\n assumptions.add(`Could not resolve direct dependency version: ${item.name}.`);\n }\n continue;\n }\n\n if (scopeByName.has(item.name) && !directByName.has(item.name)) {\n directByName.set(item.name, {\n name: item.name,\n requestedRange: requestedByName.get(item.name) ?? \"latest\",\n resolvedVersion: resolved.version,\n resolution: resolved.resolution,\n scope: scopeByName.get(item.name) ?? \"prod\",\n });\n }\n\n if (resolved.fallbackUsed && item.requested !== null) {\n assumptions.add(\n `Resolved ${item.name}@${item.requested} to latest (${resolved.version}) because exact/tag/range match was unavailable.`,\n );\n }\n\n const nodeKey = `${item.name}@${resolved.version}`;\n if (nodesByKey.has(nodeKey)) {\n continue;\n }\n\n const manifestDependencies = packument.dependenciesByVersion[resolved.version] ?? {};\n const dependencies = Object.entries(manifestDependencies)\n .filter(\n ([dependencyName, dependencyRange]) =>\n dependencyName.length > 0 && dependencyRange.length > 0,\n )\n .sort((a, b) => a[0].localeCompare(b[0]));\n\n nodesByKey.set(nodeKey, {\n name: item.name,\n version: resolved.version,\n dependencies: dependencies.map(\n ([dependencyName, dependencyRange]) => `${dependencyName}@${dependencyRange}`,\n ),\n });\n\n if (item.depth >= maxDepth && dependencies.length > 0) {\n truncated = true;\n assumptions.add(`Dependency graph truncated at depth ${maxDepth}.`);\n continue;\n }\n\n for (const [dependencyName, dependencyRange] of dependencies) {\n if (nodesByKey.size + queue.length >= maxNodes) {\n truncated = true;\n assumptions.add(`Dependency graph truncated at ${maxNodes} nodes.`);\n break;\n }\n\n queue.push({\n name: dependencyName,\n requested: dependencyRange,\n depth: item.depth + 1,\n });\n }\n }\n\n return {\n nodes: [...nodesByKey.values()].sort(\n (a, b) => a.name.localeCompare(b.name) || a.version.localeCompare(b.version),\n ),\n directDependencies: [...directByName.values()].sort((a, b) => a.name.localeCompare(b.name)),\n assumptions: [...assumptions].sort((a, b) => a.localeCompare(b)),\n truncated,\n };\n};\n","import type { LockfileExtraction } from \"../domain/types.js\";\nimport { loadPackageJson, selectLockfile } from \"../infrastructure/fs-loader.js\";\nimport { parsePackageJson } from \"../parsing/package-json-loader.js\";\nimport { parseLockfileExtraction } from \"./parse-lockfile-extraction.js\";\nimport { resolveRegistryGraphFromDirectSpecs } from \"./resolve-registry-graph.js\";\n\ntype LockfileKind = \"pnpm\" | \"npm\" | \"npm-shrinkwrap\" | \"yarn\" | \"bun\";\n\nexport type PreparedDependencyExtraction =\n | {\n available: false;\n reason: \"package_json_not_found\" | \"lockfile_not_found\";\n }\n | {\n available: true;\n lockfileKind: LockfileKind;\n extraction: LockfileExtraction;\n };\n\nexport const prepareDependencyExtraction = async (\n repositoryPath: string,\n): Promise<PreparedDependencyExtraction> => {\n const packageJson = loadPackageJson(repositoryPath);\n if (packageJson === null) {\n return {\n available: false,\n reason: \"package_json_not_found\",\n };\n }\n\n const directSpecs = parsePackageJson(packageJson.raw);\n const lockfile = selectLockfile(repositoryPath);\n\n if (lockfile === null) {\n const resolvedGraph = await resolveRegistryGraphFromDirectSpecs(directSpecs, {\n maxNodes: 500,\n maxDepth: 8,\n });\n if (resolvedGraph.nodes.length === 0) {\n return {\n available: false,\n reason: \"lockfile_not_found\",\n };\n }\n\n return {\n available: true,\n lockfileKind: \"npm\",\n extraction: {\n kind: \"npm\",\n directDependencies: resolvedGraph.directDependencies.map((dependency) => ({\n name: dependency.name,\n requestedRange: dependency.requestedRange,\n scope: dependency.scope,\n })),\n nodes: resolvedGraph.nodes,\n },\n };\n }\n\n return {\n available: true,\n lockfileKind: lockfile.kind,\n extraction: parseLockfileExtraction(lockfile.kind, lockfile.raw, directSpecs),\n };\n};\n","import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { basename, join, relative, resolve } from \"node:path\";\nimport type { WorkspaceKind } from \"@codesentinel/core\";\nimport type { WorkspaceDependencyManifest } from \"../domain/types.js\";\nimport { parsePackageJson } from \"../parsing/package-json-loader.js\";\n\ntype PackageJsonWorkspaceConfig = {\n name?: string;\n workspaces?: readonly string[] | { packages?: readonly string[] };\n};\n\nconst normalizePath = (pathValue: string): string => pathValue.replaceAll(\"\\\\\", \"/\");\n\nconst stripQuotes = (value: string): string => value.replace(/^['\"]|['\"]$/g, \"\");\n\nconst readPackageJson = (path: string): PackageJsonWorkspaceConfig | null => {\n try {\n return JSON.parse(readFileSync(path, \"utf8\")) as PackageJsonWorkspaceConfig;\n } catch {\n return null;\n }\n};\n\nconst inferWorkspaceKind = (workspacePath: string): WorkspaceKind => {\n const segments = workspacePath.split(\"/\");\n const first = segments[0] ?? \"\";\n\n if (first === \"apps\" || first === \"app\") {\n return \"app\";\n }\n\n if (first === \"packages\" || first === \"package\") {\n return \"package\";\n }\n\n if (first === \"docs\" || first === \"documentation\") {\n return \"docs\";\n }\n\n if (first === \"examples\" || first === \"example-apps\" || first === \"playground\") {\n return \"example\";\n }\n\n if (first === \"tooling\" || first === \"tools\") {\n return \"tooling\";\n }\n\n return \"unknown\";\n};\n\nconst readWorkspacePatternsFromPackageJson = (projectRoot: string): readonly string[] => {\n const packageJson = readPackageJson(join(projectRoot, \"package.json\"));\n if (packageJson?.workspaces === undefined) {\n return [];\n }\n\n const workspaces = packageJson.workspaces;\n if (Array.isArray(workspaces)) {\n const workspaceArray: readonly unknown[] = workspaces;\n return workspaceArray.filter((workspace): workspace is string => typeof workspace === \"string\");\n }\n\n const workspaceObject = workspaces as { packages?: readonly string[] };\n return workspaceObject.packages ?? [];\n};\n\nconst readWorkspacePatternsFromPnpmWorkspace = (projectRoot: string): readonly string[] => {\n const workspacePath = join(projectRoot, \"pnpm-workspace.yaml\");\n if (!existsSync(workspacePath)) {\n return [];\n }\n\n const patterns: string[] = [];\n const lines = readFileSync(workspacePath, \"utf8\").split(\"\\n\");\n let readingPackages = false;\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.length === 0 || trimmed.startsWith(\"#\")) {\n continue;\n }\n\n if (!line.startsWith(\" \") && !line.startsWith(\"-\")) {\n readingPackages = trimmed === \"packages:\";\n continue;\n }\n\n if (!readingPackages) {\n continue;\n }\n\n const match = trimmed.match(/^-\\s+(.+)$/);\n if (match?.[1] !== undefined) {\n patterns.push(stripQuotes(match[1].trim()));\n }\n }\n\n return patterns;\n};\n\nconst expandPattern = (projectRoot: string, pattern: string): readonly string[] => {\n const segments = normalizePath(pattern)\n .split(\"/\")\n .filter((segment) => segment.length > 0);\n let current = [projectRoot];\n\n for (const segment of segments) {\n const next: string[] = [];\n if (segment === \"*\") {\n for (const directory of current) {\n if (!existsSync(directory)) {\n continue;\n }\n\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n if (entry.isDirectory()) {\n next.push(join(directory, entry.name));\n }\n }\n }\n } else {\n for (const directory of current) {\n const candidate = join(directory, segment);\n if (existsSync(candidate) && statSync(candidate).isDirectory()) {\n next.push(candidate);\n }\n }\n }\n\n current = next;\n }\n\n return current;\n};\n\nexport const loadWorkspaceDependencyManifests = (\n projectRoot: string,\n): readonly WorkspaceDependencyManifest[] => {\n const absoluteRoot = resolve(projectRoot);\n const packageJsonPatterns = readWorkspacePatternsFromPackageJson(absoluteRoot);\n const pnpmPatterns = readWorkspacePatternsFromPnpmWorkspace(absoluteRoot);\n const patterns = packageJsonPatterns.length > 0 ? packageJsonPatterns : pnpmPatterns;\n const includePatterns = patterns.filter((pattern) => !pattern.startsWith(\"!\"));\n const excludePatterns = patterns\n .filter((pattern) => pattern.startsWith(\"!\"))\n .map((pattern) => pattern.slice(1));\n\n const excludedPaths = new Set(\n excludePatterns\n .flatMap((pattern) => expandPattern(absoluteRoot, pattern))\n .map((path) => normalizePath(relative(absoluteRoot, path))),\n );\n\n const manifestsByPath = new Map<string, WorkspaceDependencyManifest>();\n for (const pattern of includePatterns) {\n for (const absoluteWorkspacePath of expandPattern(absoluteRoot, pattern)) {\n const relativePath = normalizePath(relative(absoluteRoot, absoluteWorkspacePath));\n if (\n relativePath.length === 0 ||\n relativePath.startsWith(\"..\") ||\n excludedPaths.has(relativePath)\n ) {\n continue;\n }\n\n const packageJsonPath = join(absoluteWorkspacePath, \"package.json\");\n if (!existsSync(packageJsonPath)) {\n continue;\n }\n\n const rawPackageJson = readFileSync(packageJsonPath, \"utf8\");\n const packageJson = readPackageJson(packageJsonPath);\n manifestsByPath.set(relativePath, {\n name: packageJson?.name ?? basename(absoluteWorkspacePath),\n path: relativePath,\n kind: inferWorkspaceKind(relativePath),\n directDependencies: parsePackageJson(rawPackageJson),\n });\n }\n }\n\n return [...manifestsByPath.values()].sort((a, b) => a.path.localeCompare(b.path));\n};\n","import type { ExternalAnalysisSummary } from \"@codesentinel/core\";\nimport {\n DEFAULT_EXTERNAL_ANALYSIS_CONFIG,\n type DependencyMetadataProvider,\n type ExternalAnalysisConfig,\n type WorkspaceDependencyManifest,\n} from \"../domain/types.js\";\nimport { buildDependencyExposureSummary } from \"./dependency-exposure-pipeline.js\";\nimport { prepareDependencyExtraction } from \"./prepare-dependency-extraction.js\";\nimport { loadWorkspaceDependencyManifests } from \"../infrastructure/workspace-package-manifests.js\";\n\nexport type AnalyzeDependencyExposureInput = {\n repositoryPath: string;\n config?: Partial<ExternalAnalysisConfig>;\n};\n\nexport type DependencyExposureProgressEvent =\n | { stage: \"package_json_loaded\" }\n | { stage: \"lockfile_selected\"; kind: \"pnpm\" | \"npm\" | \"npm-shrinkwrap\" | \"yarn\" | \"bun\" }\n | { stage: \"lockfile_parsed\"; dependencyNodes: number; directDependencies: number }\n | { stage: \"metadata_fetch_started\"; total: number }\n | { stage: \"metadata_fetch_progress\"; completed: number; total: number; packageName: string }\n | { stage: \"metadata_fetch_completed\"; total: number }\n | { stage: \"summary_built\"; totalDependencies: number; directDependencies: number };\n\nexport type WorkspaceDependencyManifestLoader = (\n repositoryPath: string,\n) => readonly WorkspaceDependencyManifest[];\n\nconst withDefaults = (\n overrides: Partial<ExternalAnalysisConfig> | undefined,\n): ExternalAnalysisConfig => ({\n ...DEFAULT_EXTERNAL_ANALYSIS_CONFIG,\n ...overrides,\n});\n\nexport const analyzeDependencyExposure = async (\n input: AnalyzeDependencyExposureInput,\n metadataProvider: DependencyMetadataProvider,\n onProgress?: (event: DependencyExposureProgressEvent) => void,\n loadWorkspaceManifests: WorkspaceDependencyManifestLoader = loadWorkspaceDependencyManifests,\n): Promise<ExternalAnalysisSummary> => {\n const config = withDefaults(input.config);\n\n try {\n const prepared = await prepareDependencyExtraction(input.repositoryPath);\n if (!prepared.available) {\n return {\n targetPath: input.repositoryPath,\n available: false,\n reason: prepared.reason,\n };\n }\n\n onProgress?.({ stage: \"package_json_loaded\" });\n onProgress?.({ stage: \"lockfile_selected\", kind: prepared.lockfileKind });\n\n const { extraction } = prepared;\n\n onProgress?.({\n stage: \"lockfile_parsed\",\n dependencyNodes: extraction.nodes.length,\n directDependencies: extraction.directDependencies.length,\n });\n onProgress?.({ stage: \"metadata_fetch_started\", total: extraction.nodes.length });\n const summary = await buildDependencyExposureSummary({\n targetPath: input.repositoryPath,\n extraction,\n metadataProvider,\n config,\n workspaceManifests: loadWorkspaceManifests(input.repositoryPath),\n onMetadataProgress: (event) =>\n onProgress?.({\n stage: \"metadata_fetch_progress\",\n completed: event.completed,\n total: event.total,\n packageName: event.packageName,\n }),\n });\n onProgress?.({ stage: \"metadata_fetch_completed\", total: extraction.nodes.length });\n if (summary.available) {\n onProgress?.({\n stage: \"summary_built\",\n totalDependencies: summary.metrics.totalDependencies,\n directDependencies: summary.metrics.directDependencies,\n });\n }\n\n return summary;\n } catch (error) {\n const message = error instanceof Error ? error.message : \"unknown\";\n if (message.includes(\"unsupported_lockfile_format\")) {\n return {\n targetPath: input.repositoryPath,\n available: false,\n reason: \"unsupported_lockfile_format\",\n };\n }\n\n return {\n targetPath: input.repositoryPath,\n available: false,\n reason: \"invalid_lockfile\",\n };\n }\n};\n","import type { ExternalAnalysisSummary } from \"@codesentinel/core\";\nimport {\n DEFAULT_EXTERNAL_ANALYSIS_CONFIG,\n type DependencyMetadataProvider,\n type ExternalAnalysisConfig,\n type LockfileExtraction,\n} from \"../domain/types.js\";\nimport { buildDependencyExposureSummary } from \"./dependency-exposure-pipeline.js\";\nimport { resolveRegistryGraphFromDirectSpecs } from \"./resolve-registry-graph.js\";\n\nexport type AnalyzeDependencyCandidateInput = {\n dependency: string;\n config?: Partial<ExternalAnalysisConfig>;\n maxNodes?: number;\n maxDepth?: number;\n};\n\nexport type AnalyzeDependencyCandidateResult =\n | {\n available: false;\n reason: \"invalid_dependency_spec\" | \"package_not_found\";\n dependency: string;\n }\n | {\n available: true;\n dependency: {\n name: string;\n requested: string | null;\n resolvedVersion: string;\n resolution: \"exact\" | \"tag\" | \"range\" | \"latest\";\n };\n graph: {\n nodeCount: number;\n truncated: boolean;\n maxNodes: number;\n maxDepth: number;\n };\n assumptions: readonly string[];\n external: ExternalAnalysisSummary;\n };\n\nconst DEFAULT_MAX_NODES = 250;\nconst DEFAULT_MAX_DEPTH = 6;\n\nconst withDefaults = (\n overrides: Partial<ExternalAnalysisConfig> | undefined,\n): ExternalAnalysisConfig => ({\n ...DEFAULT_EXTERNAL_ANALYSIS_CONFIG,\n ...overrides,\n});\n\nconst parseDependencySpec = (value: string): { name: string; requested: string | null } | null => {\n const trimmed = value.trim();\n if (trimmed.length === 0 || /\\s/.test(trimmed)) {\n return null;\n }\n\n if (trimmed.startsWith(\"@\")) {\n const splitIndex = trimmed.lastIndexOf(\"@\");\n if (splitIndex <= 0) {\n return { name: trimmed, requested: null };\n }\n\n const name = trimmed.slice(0, splitIndex);\n const requested = trimmed.slice(splitIndex + 1);\n if (name.length === 0 || requested.length === 0) {\n return null;\n }\n\n return { name, requested };\n }\n\n const splitIndex = trimmed.lastIndexOf(\"@\");\n if (splitIndex <= 0) {\n return { name: trimmed, requested: null };\n }\n\n const name = trimmed.slice(0, splitIndex);\n const requested = trimmed.slice(splitIndex + 1);\n if (name.length === 0 || requested.length === 0) {\n return null;\n }\n\n return { name, requested };\n};\n\nexport const analyzeDependencyCandidate = async (\n input: AnalyzeDependencyCandidateInput,\n metadataProvider: DependencyMetadataProvider,\n): Promise<AnalyzeDependencyCandidateResult> => {\n const parsed = parseDependencySpec(input.dependency);\n if (parsed === null) {\n return {\n available: false,\n reason: \"invalid_dependency_spec\",\n dependency: input.dependency,\n };\n }\n\n const maxNodes = Math.max(1, input.maxNodes ?? DEFAULT_MAX_NODES);\n const maxDepth = Math.max(0, input.maxDepth ?? DEFAULT_MAX_DEPTH);\n const config = withDefaults(input.config);\n\n const graph = await resolveRegistryGraphFromDirectSpecs(\n [\n {\n name: parsed.name,\n requestedRange: parsed.requested ?? \"latest\",\n scope: \"prod\",\n },\n ],\n { maxNodes, maxDepth },\n );\n\n const direct = graph.directDependencies.find((dependency) => dependency.name === parsed.name);\n if (direct === undefined || graph.nodes.length === 0) {\n return {\n available: false,\n reason: \"package_not_found\",\n dependency: input.dependency,\n };\n }\n\n const extraction: LockfileExtraction = {\n kind: \"npm\",\n directDependencies: [\n {\n name: parsed.name,\n requestedRange: parsed.requested ?? \"latest\",\n scope: \"prod\",\n },\n ],\n nodes: graph.nodes,\n };\n\n const external = await buildDependencyExposureSummary({\n targetPath: `npm:${parsed.name}`,\n extraction,\n metadataProvider,\n config,\n });\n\n return {\n available: true,\n dependency: {\n name: parsed.name,\n requested: parsed.requested,\n resolvedVersion: direct.resolvedVersion,\n resolution: direct.resolution,\n },\n graph: {\n nodeCount: graph.nodes.length,\n truncated: graph.truncated,\n maxNodes,\n maxDepth,\n },\n assumptions: graph.assumptions,\n external,\n };\n};\n","import type {\n DependencyMetadata,\n DependencyMetadataProvider,\n DependencyMetadataRequestContext,\n} from \"../domain/types.js\";\nimport { cachedFetch } from \"./cached-fetch.js\";\nimport { fetchJsonWithRetry } from \"./fetch-json-with-retry.js\";\nimport {\n getNpmMetadataCacheStore,\n getPackumentCacheTtlMs,\n getWeeklyDownloadsCacheTtlMs,\n toMetadataPackumentCacheKey,\n toWeeklyDownloadsCacheKey,\n} from \"./npm-metadata-cache.js\";\n\ntype NpmPackagePayload = {\n time?: Record<string, string>;\n maintainers?: Array<{ name?: string; email?: string }>;\n};\n\ntype NpmDownloadsPayload = {\n downloads?: number;\n};\n\nconst ONE_DAY_MS = 24 * 60 * 60 * 1000;\nconst MAX_RETRIES = 3;\nconst RETRY_BASE_DELAY_MS = 500;\nconst round4 = (value: number): number => Number(value.toFixed(4));\n\nconst parseDate = (iso: string | undefined): number | null => {\n if (iso === undefined) {\n return null;\n }\n\n const value = Date.parse(iso);\n return Number.isNaN(value) ? null : value;\n};\n\nexport class NpmRegistryMetadataProvider implements DependencyMetadataProvider {\n private readonly cache = new Map<string, DependencyMetadata | null>();\n private readonly cacheStore = getNpmMetadataCacheStore();\n\n private async fetchWeeklyDownloads(name: string): Promise<number | null> {\n const encodedName = encodeURIComponent(name);\n const payload = await cachedFetch<NpmDownloadsPayload>({\n key: toWeeklyDownloadsCacheKey(name),\n ttlMs: getWeeklyDownloadsCacheTtlMs(),\n cacheStore: this.cacheStore,\n fetchFresh: async () =>\n await fetchJsonWithRetry<NpmDownloadsPayload>(\n `https://api.npmjs.org/downloads/point/last-week/${encodedName}`,\n { retries: MAX_RETRIES, baseDelayMs: RETRY_BASE_DELAY_MS },\n ),\n });\n if (payload === null) {\n return null;\n }\n\n const downloads = payload.downloads;\n if (typeof downloads !== \"number\" || Number.isNaN(downloads) || downloads < 0) {\n return null;\n }\n\n return Math.floor(downloads);\n }\n\n async getMetadata(\n name: string,\n version: string,\n context: DependencyMetadataRequestContext,\n ): Promise<DependencyMetadata | null> {\n const key = `${name}@${version}`;\n if (this.cache.has(key)) {\n return this.cache.get(key) ?? null;\n }\n\n try {\n const encodedName = encodeURIComponent(name);\n const payload = await cachedFetch<NpmPackagePayload>({\n key: toMetadataPackumentCacheKey(name),\n ttlMs: getPackumentCacheTtlMs(),\n cacheStore: this.cacheStore,\n fetchFresh: async () => {\n const fresh = await fetchJsonWithRetry<NpmPackagePayload>(\n `https://registry.npmjs.org/${encodedName}`,\n {\n retries: MAX_RETRIES,\n baseDelayMs: RETRY_BASE_DELAY_MS,\n },\n );\n if (fresh === null) {\n return null;\n }\n const slim: NpmPackagePayload = {};\n if (fresh.time !== undefined) {\n slim.time = fresh.time;\n }\n if (fresh.maintainers !== undefined) {\n slim.maintainers = fresh.maintainers;\n }\n return slim;\n },\n });\n if (payload === null) {\n this.cache.set(key, null);\n return null;\n }\n const timeEntries = payload.time ?? {};\n\n const publishDates = Object.entries(timeEntries)\n .filter(([tag]) => tag !== \"created\" && tag !== \"modified\")\n .map(([, date]) => parseDate(date))\n .filter((value): value is number => value !== null)\n .sort((a, b) => a - b);\n\n const modifiedAt = parseDate(timeEntries[\"modified\"]);\n const now = Date.now();\n const daysSinceLastRelease =\n modifiedAt === null ? null : Math.max(0, round4((now - modifiedAt) / ONE_DAY_MS));\n\n let releaseFrequencyDays: number | null = null;\n if (publishDates.length >= 2) {\n const totalIntervals = publishDates.length - 1;\n let sum = 0;\n for (let i = 1; i < publishDates.length; i += 1) {\n const current = publishDates[i];\n const previous = publishDates[i - 1];\n if (current !== undefined && previous !== undefined) {\n sum += current - previous;\n }\n }\n\n releaseFrequencyDays = round4(sum / totalIntervals / ONE_DAY_MS);\n }\n\n const maintainers = payload.maintainers ?? [];\n const maintainerCount = maintainers.length > 0 ? maintainers.length : null;\n const weeklyDownloads = context.directDependency\n ? await this.fetchWeeklyDownloads(name).catch(() => null)\n : null;\n\n const metadata: DependencyMetadata = {\n name,\n version,\n weeklyDownloads,\n maintainerCount,\n releaseFrequencyDays,\n daysSinceLastRelease,\n repositoryActivity30d: null,\n busFactor: null,\n };\n\n this.cache.set(key, metadata);\n return metadata;\n } catch {\n this.cache.set(key, null);\n return null;\n }\n }\n}\n","import type { DependencyMetadata, DependencyMetadataProvider } from \"../domain/types.js\";\n\nexport class NoopMetadataProvider implements DependencyMetadataProvider {\n getMetadata(\n _name: string,\n _version: string,\n _context: { directDependency: boolean },\n ): Promise<DependencyMetadata | null> {\n return Promise.resolve(null);\n }\n}\n","import type { ExternalAnalysisSummary } from \"@codesentinel/core\";\nimport {\n analyzeDependencyExposure,\n type DependencyExposureProgressEvent,\n type AnalyzeDependencyExposureInput,\n} from \"./application/analyze-dependency-exposure.js\";\nimport {\n analyzeDependencyCandidate,\n type AnalyzeDependencyCandidateInput,\n type AnalyzeDependencyCandidateResult,\n} from \"./application/analyze-dependency-candidate.js\";\nimport { NpmRegistryMetadataProvider } from \"./infrastructure/npm-registry-metadata-provider.js\";\nimport { NoopMetadataProvider } from \"./infrastructure/noop-metadata-provider.js\";\n\nexport type { AnalyzeDependencyExposureInput } from \"./application/analyze-dependency-exposure.js\";\nexport type { DependencyExposureProgressEvent } from \"./application/analyze-dependency-exposure.js\";\nexport type {\n AnalyzeDependencyCandidateInput,\n AnalyzeDependencyCandidateResult,\n} from \"./application/analyze-dependency-candidate.js\";\n\nexport const analyzeDependencyExposureFromProject = async (\n input: AnalyzeDependencyExposureInput,\n onProgress?: (event: DependencyExposureProgressEvent) => void,\n): Promise<ExternalAnalysisSummary> => {\n const metadataProvider =\n process.env[\"CODESENTINEL_EXTERNAL_METADATA\"] === \"none\"\n ? new NoopMetadataProvider()\n : new NpmRegistryMetadataProvider();\n\n return analyzeDependencyExposure(input, metadataProvider, onProgress);\n};\n\nexport const analyzeDependencyCandidateFromRegistry = async (\n input: AnalyzeDependencyCandidateInput,\n): Promise<AnalyzeDependencyCandidateResult> => {\n const metadataProvider =\n process.env[\"CODESENTINEL_EXTERNAL_METADATA\"] === \"none\"\n ? new NoopMetadataProvider()\n : new NpmRegistryMetadataProvider();\n\n return analyzeDependencyCandidate(input, metadataProvider);\n};\n","import type {\n AnalyzeSummary,\n FileAuthorChurnShare,\n FileAuthorShare,\n HealthIssue,\n RecentActivityPoint,\n RepositoryHealthSummary,\n RiskFactors,\n RiskFactorTrace,\n RiskTrace,\n} from \"@codesentinel/core\";\n\nexport type { HealthIssue };\n\nexport const SNAPSHOT_SCHEMA_VERSION = \"codesentinel.snapshot.v1\" as const;\nexport const REPORT_SCHEMA_VERSION = \"codesentinel.report.v1\" as const;\nexport const RISK_MODEL_VERSION = \"deterministic-v1\" as const;\n\nexport type SnapshotSchemaVersion = typeof SNAPSHOT_SCHEMA_VERSION;\nexport type ReportSchemaVersion = typeof REPORT_SCHEMA_VERSION;\n\nexport type RiskTier = \"low\" | \"moderate\" | \"elevated\" | \"high\" | \"very_high\";\nexport type HealthTier = \"critical\" | \"weak\" | \"fair\" | \"good\" | \"excellent\";\n\nexport type ReportFormat = \"json\" | \"text\" | \"md\";\n\nexport type CodeSentinelSnapshot = {\n schemaVersion: SnapshotSchemaVersion;\n generatedAt: string;\n riskModelVersion: string;\n source: {\n targetPath: string;\n };\n analysis: AnalyzeSummary;\n trace?: RiskTrace;\n analysisConfig?: Readonly<Record<string, string | number | boolean | null>>;\n};\n\nexport type RenderedFactor = {\n id: string;\n label: string;\n contribution: number;\n confidence: number;\n evidence: string;\n};\n\nexport type HotspotReportItem = {\n rank: number;\n target: string;\n module: string;\n score: number;\n normalizedScore: number;\n commitCount: number | null;\n recentCommitCount: number | null;\n recentVolatility: number | null;\n churnTotal: number | null;\n ownerCount: number | null;\n topAuthorShareByCommits: number | null;\n busFactorByCommits: number | null;\n authorDistributionByCommits: readonly FileAuthorShare[];\n riskContributions: RiskFactors;\n reason: string;\n topFactors: readonly RenderedFactor[];\n suggestedActions: readonly string[];\n biggestLevers: readonly string[];\n};\n\nexport type StructuralFileExtreme = {\n file: string;\n module: string;\n value: number;\n};\n\nexport type StructuralCycleDetail = {\n id: string;\n size: number;\n nodes: readonly string[];\n path: string;\n};\n\nexport type StructuralArchitectureMetrics = {\n nodeCount: number;\n edgeCount: number;\n graphDepth: number;\n maxFanIn: number;\n maxFanOut: number;\n couplingDensity: number;\n entryPointCount: number;\n};\n\nexport type StructuralModuleAnatomyItem = {\n module: string;\n dependencyCount: number;\n fanIn: number;\n fanOut: number;\n depth: number;\n};\n\nexport type ChangeOwnershipMetrics = {\n totalCommits: number;\n totalFiles: number;\n recentWindowDays: number;\n meanBusFactorByCommits: number | null;\n averageRecentVolatility: number | null;\n sharedOwnershipPercent: number | null;\n concentratedOwnershipPercent: number | null;\n singleMaintainerPercent: number | null;\n staleOwnedFilesPercent: number | null;\n};\n\nexport type OwnershipPostureStatus = \"balanced\" | \"concentrated\" | \"siloed\" | \"stale\";\n\nexport type OwnershipPostureReportItem = {\n status: OwnershipPostureStatus;\n title: string;\n summary: string;\n activeContributors: number;\n largestContributorSharePercent: number | null;\n singleOwnerModulesPercent: number | null;\n};\n\nexport type CoChangePairReportItem = {\n fileA: string;\n fileB: string;\n coChangeCommits: number;\n couplingScore: number;\n};\n\nexport type ModuleKnowledgeReportItem = {\n module: string;\n totalCommits: number;\n recentCommits: number;\n activeAuthors: number;\n topAuthorShareByCommits: number;\n ownershipLabel: \"distributed\" | \"sparse\" | \"siloed\";\n};\n\nexport type FileOwnershipReportItem = {\n filePath: string;\n module: string;\n commitCount: number;\n churnTotal: number;\n ownershipLabel: \"shared\" | \"concentrated\" | \"singleMaintainer\";\n topAuthorShareByCommits: number;\n busFactorByCommits: number;\n authorDistributionByCommits: readonly FileAuthorShare[];\n topAuthorShareByChurn: number;\n busFactorByChurn: number;\n authorDistributionByChurn: readonly FileAuthorChurnShare[];\n};\n\nexport type OwnershipRiskAreaReportItem = {\n module: string;\n totalCommits: number;\n recentCommits: number;\n activeAuthors: number;\n topAuthorShareByCommits: number;\n ownershipLabel: \"distributed\" | \"sparse\" | \"siloed\";\n};\n\nexport type OwnershipContributorReportItem = {\n authorId: string;\n singleMaintainerFiles: number;\n concentratedFiles: number;\n ownedFiles: number;\n totalCommitTouches: number;\n totalCommitShare: number;\n ownedChurnShare: number;\n};\n\nexport type RecentActivityReportItem = RecentActivityPoint;\n\nexport type RiskyDependencyReportItem = {\n name: string;\n score: number;\n normalizedScore: number;\n dependencyScope: \"prod\" | \"dev\" | \"unknown\";\n direct: boolean;\n resolvedVersion: string | null;\n transitiveDependencyCount: number;\n dependentCount: number;\n fanOut: number;\n dependencyDepth: number;\n weeklyDownloads: number | null;\n maintainerCount: number | null;\n releaseFrequencyDays: number | null;\n daysSinceLastRelease: number | null;\n repositoryActivity30d: number | null;\n busFactor: number | null;\n ownRiskSignals: readonly string[];\n inheritedRiskSignals: readonly string[];\n riskSignals: readonly string[];\n reason: string;\n};\n\nexport type ExternalMetricsReportItem = {\n totalDependencies: number;\n directDependencies: number;\n directProductionDependencies: number;\n directDevelopmentDependencies: number;\n transitiveDependencies: number;\n dependencyDepth: number;\n lockfileKind: \"pnpm\" | \"npm\" | \"npm-shrinkwrap\" | \"yarn\" | \"bun\";\n metadataCoverage: number;\n};\n\nexport type ExternalCentralityReportItem = {\n name: string;\n dependents: number;\n fanOut: number;\n direct: boolean;\n};\n\nexport type WorkspaceStructuralReportItem = {\n name: string;\n path: string;\n kind: string;\n fileCount: number;\n internalEdgeCount: number;\n incomingEdgeCount: number;\n outgoingEdgeCount: number;\n};\n\nexport type WorkspaceRiskReportItem = {\n name: string;\n path: string;\n kind: string;\n score: number;\n normalizedScore: number;\n fileCount: number;\n averageFileRisk: number;\n peakFileRisk: number;\n internalEdgeCount: number;\n incomingEdgeCount: number;\n outgoingEdgeCount: number;\n topFiles: ReadonlyArray<{\n file: string;\n score: number;\n }>;\n};\n\nexport type WorkspaceEvolutionReportItem = {\n name: string;\n path: string;\n kind: string;\n fileCount: number;\n commitCount: number;\n churnTotal: number;\n recentCommitCount: number;\n recentVolatility: number;\n topAuthorShareByCommits: number;\n busFactorByCommits: number;\n hotspotCount: number;\n topHotspots: ReadonlyArray<{\n filePath: string;\n rank: number;\n commitCount: number;\n churnTotal: number;\n }>;\n internalCouplingPairCount: number;\n incomingCouplingPairCount: number;\n outgoingCouplingPairCount: number;\n};\n\nexport type WorkspaceDependencyExposureReportItem = {\n name: string;\n path: string;\n kind: string;\n directDependencies: number;\n directProductionDependencies: number;\n directDevelopmentDependencies: number;\n unresolvedDependencies: readonly string[];\n dependencyNames: readonly string[];\n sharedDependencies: readonly string[];\n highRiskDependencies: readonly string[];\n highRiskDevelopmentDependencies: readonly string[];\n transitiveExposureDependencies: readonly string[];\n singleMaintainerDependencies: readonly string[];\n abandonedDependencies: readonly string[];\n};\n\nexport type WorkspaceReportSummary = {\n structural: readonly WorkspaceStructuralReportItem[];\n risk: readonly WorkspaceRiskReportItem[];\n evolution: readonly WorkspaceEvolutionReportItem[];\n external: readonly WorkspaceDependencyExposureReportItem[];\n};\n\nexport type RepositoryDimensionScores = {\n structural: number | null;\n evolution: number | null;\n external: number | null;\n interactions: number | null;\n};\n\nexport type SnapshotDiff = {\n baselineGeneratedAt: string;\n riskScoreDelta: number;\n normalizedScoreDelta: number;\n externalDimensionDelta: number | null;\n fileRiskChanges: ReadonlyArray<{ target: string; before: number; after: number; delta: number }>;\n moduleRiskChanges: ReadonlyArray<{\n target: string;\n before: number;\n after: number;\n delta: number;\n }>;\n newHotspots: readonly string[];\n resolvedHotspots: readonly string[];\n newCycles: readonly string[];\n resolvedCycles: readonly string[];\n externalChanges: {\n highRiskAdded: readonly string[];\n highRiskRemoved: readonly string[];\n singleMaintainerAdded: readonly string[];\n singleMaintainerRemoved: readonly string[];\n abandonedAdded: readonly string[];\n abandonedRemoved: readonly string[];\n };\n};\n\n// Mirrors the audit shape from `@codesentinel/ownership` structurally. The reporter must not\n// depend on that package, so this duplication is deliberate and kept field-for-field.\nexport type DeclaredOwnerReportItem =\n | { kind: \"user\"; handle: string }\n | { kind: \"team\"; org: string; slug: string }\n | { kind: \"email\"; address: string };\n\nexport type OwnershipAuditStatus =\n | \"aligned\"\n | \"drifted\"\n | \"ghosted\"\n | \"unowned\"\n | \"unowned-critical\"\n | \"insufficient-evidence\"\n | \"unknown\";\n\nexport type OwnershipFileReportItem = {\n filePath: string;\n declared: readonly DeclaredOwnerReportItem[];\n matchLine: number | null;\n status: OwnershipAuditStatus;\n observed: {\n commits: number;\n authors: number;\n topAuthorId: string | null;\n topAuthorShare: number | null;\n busFactor: number | null;\n lastCommitUnix: number | null;\n };\n criticality: {\n fanIn: number | null;\n isHotspot: boolean;\n riskScore: number | null;\n isCritical: boolean;\n };\n};\n\nexport type OwnershipAuditReportMetrics = {\n declaredCoveragePercent: number;\n declaredCoverageCriticalPercent: number;\n driftPercent: number;\n ghostOwnerCount: number;\n unownedCriticalCount: number;\n singleOwnerModuleCount: number;\n};\n\nexport type OwnershipAuditReport =\n | {\n available: false;\n reason: \"codeowners_not_found\" | \"audit_unavailable\";\n warnings: readonly string[];\n }\n | {\n available: true;\n codeowners: {\n source: string;\n ignoredSources: readonly string[];\n errors: readonly { line: number; reason: string }[];\n };\n metrics: OwnershipAuditReportMetrics;\n ghostOwners: readonly {\n owner: DeclaredOwnerReportItem;\n samplePaths: readonly string[];\n }[];\n files: readonly OwnershipFileReportItem[];\n warnings: readonly string[];\n };\n\nexport type ReportExtras = {\n ownership?: OwnershipAuditReport;\n repositoryWebUrl?: string | null;\n};\n\nexport type CodeSentinelReport = {\n schemaVersion: ReportSchemaVersion;\n generatedAt: string;\n repository: {\n name: string;\n targetPath: string;\n riskScore: number;\n normalizedScore: number;\n riskTier: RiskTier;\n healthTier: HealthTier;\n confidence: number | null;\n dimensionScores: RepositoryDimensionScores;\n webUrl?: string | null;\n };\n health: RepositoryHealthSummary;\n workspaces: WorkspaceReportSummary;\n hotspots: readonly HotspotReportItem[];\n structural: {\n cycleCount: number;\n cycles: readonly string[];\n cycleDetails: readonly StructuralCycleDetail[];\n metrics: StructuralArchitectureMetrics;\n moduleAnatomy: readonly StructuralModuleAnatomyItem[];\n fanInOutExtremes: {\n highestFanIn: readonly StructuralFileExtreme[];\n highestFanOut: readonly StructuralFileExtreme[];\n deepestFiles: readonly StructuralFileExtreme[];\n };\n fragileClusters: ReadonlyArray<{\n id: string;\n kind: string;\n score: number;\n files: readonly string[];\n }>;\n };\n changeOwnership:\n | {\n available: false;\n reason: string;\n }\n | {\n available: true;\n metrics: ChangeOwnershipMetrics;\n posture: OwnershipPostureReportItem;\n recentActivity: readonly RecentActivityReportItem[];\n coChangePairs: readonly CoChangePairReportItem[];\n moduleKnowledge: readonly ModuleKnowledgeReportItem[];\n fragileAreas: readonly OwnershipRiskAreaReportItem[];\n contributorOwnership: readonly OwnershipContributorReportItem[];\n fileOwnership: readonly FileOwnershipReportItem[];\n };\n external:\n | {\n available: false;\n reason: string;\n }\n | {\n available: true;\n metrics: ExternalMetricsReportItem;\n highRiskDependencies: readonly string[];\n highRiskDevelopmentDependencies: readonly string[];\n transitiveExposureDependencies: readonly string[];\n singleMaintainerDependencies: readonly string[];\n abandonedDependencies: readonly string[];\n centralityRanking: readonly ExternalCentralityReportItem[];\n riskyDependencies: readonly RiskyDependencyReportItem[];\n };\n ownership?: OwnershipAuditReport;\n appendix: {\n snapshotSchemaVersion: string;\n riskModelVersion: string;\n timestamp: string;\n normalization: string;\n analysisConfig?: Readonly<Record<string, string | number | boolean | null>>;\n };\n diff?: SnapshotDiff;\n};\n\nexport const round4 = (value: number): number => Number(value.toFixed(4));\n\nexport const toRiskTier = (score: number): RiskTier => {\n if (score < 20) {\n return \"low\";\n }\n if (score < 40) {\n return \"moderate\";\n }\n if (score < 60) {\n return \"elevated\";\n }\n if (score < 80) {\n return \"high\";\n }\n return \"very_high\";\n};\n\nexport const toHealthTier = (score: number): HealthTier => {\n if (score < 20) {\n return \"critical\";\n }\n if (score < 40) {\n return \"weak\";\n }\n if (score < 60) {\n return \"fair\";\n }\n if (score < 80) {\n return \"good\";\n }\n return \"excellent\";\n};\n\nconst factorLabelById: Readonly<Record<string, string>> = {\n \"repository.structural\": \"Structural complexity\",\n \"repository.evolution\": \"Change volatility\",\n \"repository.external\": \"External dependency pressure\",\n \"repository.composite.interactions\": \"Intersection amplification\",\n \"file.structural\": \"File structural complexity\",\n \"file.evolution\": \"File change volatility\",\n \"file.external\": \"File external pressure\",\n \"file.composite.interactions\": \"File interaction amplification\",\n \"module.average_file_risk\": \"Average file risk\",\n \"module.peak_file_risk\": \"Peak file risk\",\n \"dependency.signals\": \"Dependency risk signals\",\n \"dependency.staleness\": \"Dependency staleness\",\n \"dependency.maintainer_concentration\": \"Maintainer concentration\",\n \"dependency.topology\": \"Dependency topology pressure\",\n \"dependency.bus_factor\": \"Dependency bus factor\",\n \"dependency.popularity_dampening\": \"Popularity dampening\",\n};\n\nexport const factorLabel = (factorId: string): string => factorLabelById[factorId] ?? factorId;\n\nexport const summarizeEvidence = (factor: RiskFactorTrace): string => {\n const entries = Object.entries(factor.rawMetrics)\n .filter(([, value]) => value !== null)\n .sort((a, b) => a[0].localeCompare(b[0]))\n .slice(0, 3)\n .map(([key, value]) => `${key}=${value}`);\n\n if (entries.length > 0) {\n return entries.join(\", \");\n }\n\n const evidence = [...factor.evidence]\n .map((entry) => {\n if (entry.kind === \"file_metric\") {\n return `${entry.target}:${entry.metric}`;\n }\n if (entry.kind === \"dependency_metric\") {\n return `${entry.target}:${entry.metric}`;\n }\n if (entry.kind === \"repository_metric\") {\n return entry.metric;\n }\n if (entry.kind === \"graph_cycle\") {\n return `cycle:${entry.cycleId}`;\n }\n return `${entry.fileA}<->${entry.fileB}`;\n })\n .sort((a, b) => a.localeCompare(b));\n\n return evidence.join(\", \");\n};\n","import type { CodeSentinelSnapshot, SnapshotDiff } from \"./domain.js\";\nimport { round4 } from \"./domain.js\";\n\ntype ScoreEntry = { target: string; before: number; after: number; delta: number };\n\nconst diffSets = (\n current: readonly string[],\n baseline: readonly string[],\n): { added: readonly string[]; removed: readonly string[] } => {\n const currentSet = new Set(current);\n const baselineSet = new Set(baseline);\n\n const added = [...currentSet]\n .filter((item) => !baselineSet.has(item))\n .sort((a, b) => a.localeCompare(b));\n const removed = [...baselineSet]\n .filter((item) => !currentSet.has(item))\n .sort((a, b) => a.localeCompare(b));\n\n return { added, removed };\n};\n\nconst diffScoreMap = (\n current: ReadonlyMap<string, number>,\n baseline: ReadonlyMap<string, number>,\n): readonly ScoreEntry[] => {\n const keys = [...new Set([...current.keys(), ...baseline.keys()])].sort((a, b) =>\n a.localeCompare(b),\n );\n\n return keys\n .map((key) => {\n const before = baseline.get(key) ?? 0;\n const after = current.get(key) ?? 0;\n const delta = round4(after - before);\n return {\n target: key,\n before: round4(before),\n after: round4(after),\n delta,\n };\n })\n .filter((entry) => entry.delta !== 0)\n .sort((a, b) => Math.abs(b.delta) - Math.abs(a.delta) || a.target.localeCompare(b.target));\n};\n\nconst cycleKey = (nodes: readonly string[]): string =>\n [...nodes].sort((a, b) => a.localeCompare(b)).join(\" -> \");\n\nconst repositoryExternalDimension = (snapshot: CodeSentinelSnapshot): number | null => {\n const factor = snapshot.trace?.targets\n .find(\n (target) =>\n target.targetType === \"repository\" &&\n target.targetId === snapshot.analysis.structural.targetPath,\n )\n ?.factors.find((item) => item.factorId === \"repository.external\");\n\n const raw = factor?.rawMetrics[\"externalDimension\"];\n return typeof raw === \"number\" ? round4(raw * 100) : null;\n};\n\nexport const compareSnapshots = (\n current: CodeSentinelSnapshot,\n baseline: CodeSentinelSnapshot,\n): SnapshotDiff => {\n const currentFileScores = new Map(\n current.analysis.risk.fileScores.map((item) => [item.file, item.score]),\n );\n const baselineFileScores = new Map(\n baseline.analysis.risk.fileScores.map((item) => [item.file, item.score]),\n );\n\n const currentModuleScores = new Map(\n current.analysis.risk.moduleScores.map((item) => [item.module, item.score]),\n );\n const baselineModuleScores = new Map(\n baseline.analysis.risk.moduleScores.map((item) => [item.module, item.score]),\n );\n\n const currentHotspots = current.analysis.risk.hotspots.slice(0, 10).map((item) => item.file);\n const baselineHotspots = baseline.analysis.risk.hotspots.slice(0, 10).map((item) => item.file);\n\n const currentCycles = current.analysis.structural.cycles.map((cycle) => cycleKey(cycle.nodes));\n const baselineCycles = baseline.analysis.structural.cycles.map((cycle) => cycleKey(cycle.nodes));\n\n const currentExternal = current.analysis.external.available\n ? current.analysis.external\n : {\n highRiskDependencies: [] as string[],\n singleMaintainerDependencies: [] as string[],\n abandonedDependencies: [] as string[],\n };\n const baselineExternal = baseline.analysis.external.available\n ? baseline.analysis.external\n : {\n highRiskDependencies: [] as string[],\n singleMaintainerDependencies: [] as string[],\n abandonedDependencies: [] as string[],\n };\n\n const highRisk = diffSets(\n currentExternal.highRiskDependencies,\n baselineExternal.highRiskDependencies,\n );\n const singleMaintainer = diffSets(\n currentExternal.singleMaintainerDependencies,\n baselineExternal.singleMaintainerDependencies,\n );\n const abandoned = diffSets(\n currentExternal.abandonedDependencies,\n baselineExternal.abandonedDependencies,\n );\n\n const hotspots = diffSets(currentHotspots, baselineHotspots);\n const cycles = diffSets(currentCycles, baselineCycles);\n\n return {\n baselineGeneratedAt: baseline.generatedAt,\n riskScoreDelta: round4(current.analysis.risk.riskScore - baseline.analysis.risk.riskScore),\n normalizedScoreDelta: round4(\n current.analysis.risk.normalizedScore - baseline.analysis.risk.normalizedScore,\n ),\n externalDimensionDelta:\n repositoryExternalDimension(current) === null ||\n repositoryExternalDimension(baseline) === null\n ? null\n : round4(repositoryExternalDimension(current)! - repositoryExternalDimension(baseline)!),\n fileRiskChanges: diffScoreMap(currentFileScores, baselineFileScores),\n moduleRiskChanges: diffScoreMap(currentModuleScores, baselineModuleScores),\n newHotspots: hotspots.added,\n resolvedHotspots: hotspots.removed,\n newCycles: cycles.added,\n resolvedCycles: cycles.removed,\n externalChanges: {\n highRiskAdded: highRisk.added,\n highRiskRemoved: highRisk.removed,\n singleMaintainerAdded: singleMaintainer.added,\n singleMaintainerRemoved: singleMaintainer.removed,\n abandonedAdded: abandoned.added,\n abandonedRemoved: abandoned.removed,\n },\n };\n};\n","import { basename, posix } from \"node:path\";\nimport type { TargetTrace } from \"@codesentinel/core\";\nimport {\n REPORT_SCHEMA_VERSION,\n factorLabel,\n round4,\n toHealthTier,\n summarizeEvidence,\n toRiskTier,\n type CodeSentinelReport,\n type CodeSentinelSnapshot,\n type FileOwnershipReportItem,\n type HotspotReportItem,\n type ReportExtras,\n type RepositoryDimensionScores,\n type RenderedFactor,\n type RiskyDependencyReportItem,\n type SnapshotDiff,\n type StructuralCycleDetail,\n type StructuralFileExtreme,\n type WorkspaceReportSummary,\n} from \"./domain.js\";\n\nconst toPosixDirname = (value: string): string => {\n const normalized = value.replaceAll(\"\\\\\", \"/\");\n const directory = posix.dirname(normalized);\n return directory === \".\" ? \"root\" : directory;\n};\n\nconst findTraceTarget = (\n snapshot: CodeSentinelSnapshot,\n targetType: TargetTrace[\"targetType\"],\n targetId: string,\n): TargetTrace | undefined =>\n snapshot.trace?.targets.find(\n (target) => target.targetType === targetType && target.targetId === targetId,\n );\n\nconst toRenderedFactors = (target: TargetTrace | undefined): readonly RenderedFactor[] => {\n if (target === undefined) {\n return [];\n }\n\n return [...target.factors]\n .sort((a, b) => b.contribution - a.contribution || a.factorId.localeCompare(b.factorId))\n .slice(0, 4)\n .map((factor) => ({\n id: factor.factorId,\n label: factorLabel(factor.factorId),\n contribution: round4(factor.contribution),\n confidence: round4(factor.confidence),\n evidence: summarizeEvidence(factor),\n }));\n};\n\nconst suggestedActions = (target: TargetTrace | undefined): readonly string[] => {\n if (target === undefined) {\n return [];\n }\n\n const actions: string[] = [];\n for (const lever of target.reductionLevers) {\n switch (lever.factorId) {\n case \"file.evolution\":\n case \"repository.evolution\":\n actions.push(\"Reduce recent churn and volatile edit frequency in this area.\");\n break;\n case \"file.structural\":\n case \"repository.structural\":\n actions.push(\"Reduce fan-in/fan-out concentration and simplify deep dependency paths.\");\n break;\n case \"file.composite.interactions\":\n case \"repository.composite.interactions\":\n actions.push(\"Stabilize central files before concurrent structural changes.\");\n break;\n case \"file.external\":\n case \"repository.external\":\n actions.push(\"Review external dependency pressure for this hotspot.\");\n break;\n default:\n actions.push(`Reduce ${factorLabel(lever.factorId).toLowerCase()} influence.`);\n break;\n }\n }\n\n return [...new Set(actions)].slice(0, 3);\n};\n\nconst hotspotReason = (factors: readonly RenderedFactor[]): string => {\n if (factors.length === 0) {\n return \"Limited trace data available for this hotspot.\";\n }\n\n return factors\n .slice(0, 2)\n .map((factor) => `${factor.label} (${factor.contribution})`)\n .join(\" + \");\n};\n\nconst hotspotItems = (snapshot: CodeSentinelSnapshot): readonly HotspotReportItem[] =>\n snapshot.analysis.risk.hotspots.slice(0, 10).map((hotspot, index) => {\n const fileScore = snapshot.analysis.risk.fileScores.find((item) => item.file === hotspot.file);\n const evolutionMetrics = snapshot.analysis.evolution.available\n ? snapshot.analysis.evolution.files.find((item) => item.filePath === hotspot.file)\n : undefined;\n const traceTarget = findTraceTarget(snapshot, \"file\", hotspot.file);\n const factors = toRenderedFactors(traceTarget);\n\n return {\n rank: index + 1,\n target: hotspot.file,\n module: toPosixDirname(hotspot.file),\n score: hotspot.score,\n normalizedScore: fileScore?.normalizedScore ?? round4(hotspot.score / 100),\n commitCount: evolutionMetrics?.commitCount ?? null,\n recentCommitCount: evolutionMetrics?.recentCommitCount ?? null,\n recentVolatility: evolutionMetrics?.recentVolatility ?? null,\n churnTotal: evolutionMetrics?.churnTotal ?? null,\n ownerCount: evolutionMetrics?.authorDistributionByCommits.length ?? null,\n topAuthorShareByCommits: evolutionMetrics?.topAuthorShareByCommits ?? null,\n busFactorByCommits: evolutionMetrics?.busFactorByCommits ?? null,\n authorDistributionByCommits: evolutionMetrics?.authorDistributionByCommits ?? [],\n riskContributions: hotspot.factors,\n reason: hotspotReason(factors),\n topFactors: factors,\n suggestedActions: suggestedActions(traceTarget),\n biggestLevers: (traceTarget?.reductionLevers ?? [])\n .slice(0, 3)\n .map((lever) => `${factorLabel(lever.factorId)} (${lever.estimatedImpact})`),\n };\n });\n\nconst repositoryConfidence = (snapshot: CodeSentinelSnapshot): number | null => {\n const target = findTraceTarget(snapshot, \"repository\", snapshot.analysis.structural.targetPath);\n if (target === undefined || target.factors.length === 0) {\n return null;\n }\n\n const weight = target.factors.reduce((sum, factor) => sum + factor.contribution, 0);\n if (weight <= 0) {\n return null;\n }\n\n const weighted = target.factors.reduce(\n (sum, factor) => sum + factor.confidence * factor.contribution,\n 0,\n );\n return round4(weighted / weight);\n};\n\nconst normalizeDependencyScope = (\n scope: string | undefined,\n): RiskyDependencyReportItem[\"dependencyScope\"] => {\n switch (scope) {\n case \"prod\":\n case \"dev\":\n return scope;\n default:\n return \"unknown\";\n }\n};\n\nconst topStructuralFiles = (\n snapshot: CodeSentinelSnapshot,\n selector: (value: (typeof snapshot.analysis.structural.files)[number]) => number,\n): readonly StructuralFileExtreme[] =>\n [...snapshot.analysis.structural.files]\n .sort((a, b) => selector(b) - selector(a) || a.relativePath.localeCompare(b.relativePath))\n .slice(0, 5)\n .map((file) => ({\n file: file.relativePath,\n module: toPosixDirname(file.relativePath),\n value: selector(file),\n }));\n\nconst cycleDetails = (snapshot: CodeSentinelSnapshot): readonly StructuralCycleDetail[] =>\n snapshot.analysis.structural.cycles.map((cycle, index) => {\n const nodes = [...cycle.nodes].sort((a, b) => a.localeCompare(b));\n return {\n id: `cycle-${index + 1}`,\n size: nodes.length,\n nodes,\n path: nodes.join(\" -> \"),\n };\n });\n\nconst structuralArchitectureMetrics = (snapshot: CodeSentinelSnapshot) => {\n const metrics = snapshot.analysis.structural.metrics;\n const nodeCount = metrics.nodeCount;\n const edgeCount = metrics.edgeCount;\n const maxPossibleEdges = nodeCount <= 1 ? 0 : nodeCount * (nodeCount - 1);\n const couplingDensity = maxPossibleEdges === 0 ? 0 : round4((edgeCount / maxPossibleEdges) * 100);\n const entryPointCount = snapshot.analysis.structural.files.filter(\n (file) => file.fanIn === 0 && file.fanOut > 0,\n ).length;\n\n return {\n nodeCount,\n edgeCount,\n graphDepth: metrics.graphDepth,\n maxFanIn: metrics.maxFanIn,\n maxFanOut: metrics.maxFanOut,\n couplingDensity,\n entryPointCount,\n };\n};\n\nconst structuralModuleAnatomy = (snapshot: CodeSentinelSnapshot) => {\n const moduleMap = new Map<\n string,\n { module: string; dependencyCount: number; fanIn: number; fanOut: number; depth: number }\n >();\n\n for (const file of snapshot.analysis.structural.files) {\n const module = toPosixDirname(file.relativePath);\n const current = moduleMap.get(module) ?? {\n module,\n dependencyCount: 0,\n fanIn: 0,\n fanOut: 0,\n depth: 0,\n };\n\n current.dependencyCount += file.directDependencies.length;\n current.fanIn = Math.max(current.fanIn, file.fanIn);\n current.fanOut = Math.max(current.fanOut, file.fanOut);\n current.depth = Math.max(current.depth, file.depth);\n moduleMap.set(module, current);\n }\n\n return [...moduleMap.values()]\n .sort(\n (a, b) =>\n b.dependencyCount - a.dependencyCount ||\n b.fanIn - a.fanIn ||\n b.depth - a.depth ||\n a.module.localeCompare(b.module),\n )\n .slice(0, 5);\n};\n\nconst average = (values: readonly number[]): number | null =>\n values.length === 0\n ? null\n : round4(values.reduce((sum, value) => sum + value, 0) / values.length);\n\nconst toPercent = (value: number): number => round4(value * 100);\nconst STALE_OWNED_FILE_DAYS = 180;\nconst MODULE_KNOWLEDGE_LABEL_PRIORITY = {\n siloed: 0,\n sparse: 1,\n distributed: 2,\n} as const;\n\nconst clamp01 = (value: number): number => Math.max(0, Math.min(1, value));\nconst MIN_FRAGILE_AREA_TOTAL_COMMITS = 3;\n\nconst fileOwnershipItems = (\n files: Extract<CodeSentinelSnapshot[\"analysis\"][\"evolution\"], { available: true }>[\"files\"],\n): Extract<CodeSentinelReport[\"changeOwnership\"], { available: true }>[\"fileOwnership\"] => {\n const labelPriority = {\n singleMaintainer: 0,\n concentrated: 1,\n shared: 2,\n } as const;\n\n return files\n .filter((file) => file.commitCount > 0 && file.authorDistributionByCommits.length > 0)\n .map((file) => {\n const ownershipLabel: FileOwnershipReportItem[\"ownershipLabel\"] =\n file.authorDistributionByCommits.length <= 1\n ? \"singleMaintainer\"\n : file.topAuthorShareByCommits > 0.6\n ? \"concentrated\"\n : \"shared\";\n\n return {\n filePath: file.filePath,\n module: toPosixDirname(file.filePath),\n commitCount: file.commitCount,\n churnTotal: file.churnTotal,\n ownershipLabel,\n topAuthorShareByCommits: file.topAuthorShareByCommits,\n busFactorByCommits: file.busFactorByCommits,\n authorDistributionByCommits: file.authorDistributionByCommits,\n topAuthorShareByChurn: file.topAuthorShareByChurn,\n busFactorByChurn: file.busFactorByChurn,\n authorDistributionByChurn: file.authorDistributionByChurn,\n };\n })\n .sort(\n (a, b) =>\n labelPriority[a.ownershipLabel] - labelPriority[b.ownershipLabel] ||\n b.topAuthorShareByCommits - a.topAuthorShareByCommits ||\n b.commitCount - a.commitCount ||\n a.filePath.localeCompare(b.filePath),\n );\n};\n\ntype ChangeOwnershipAvailable = Extract<CodeSentinelReport[\"changeOwnership\"], { available: true }>;\ntype ChangeOwnershipFileOwnership = ChangeOwnershipAvailable[\"fileOwnership\"];\ntype ChangeOwnershipModuleKnowledge = ChangeOwnershipAvailable[\"moduleKnowledge\"];\ntype ChangeOwnershipMetrics = ChangeOwnershipAvailable[\"metrics\"];\ntype ChangeOwnershipPosture = ChangeOwnershipAvailable[\"posture\"];\ntype ChangeOwnershipContributorOwnership = ChangeOwnershipAvailable[\"contributorOwnership\"];\n\nconst moduleKnowledgeItems = (\n files: Extract<CodeSentinelSnapshot[\"analysis\"][\"evolution\"], { available: true }>[\"files\"],\n): readonly ChangeOwnershipModuleKnowledge[number][] => {\n const moduleKnowledgeMap = new Map<\n string,\n {\n module: string;\n totalCommits: number;\n recentCommits: number;\n authors: Set<string>;\n weightedTopAuthorShare: number;\n weight: number;\n }\n >();\n\n for (const file of files) {\n const module = toPosixDirname(file.filePath);\n const current = moduleKnowledgeMap.get(module) ?? {\n module,\n totalCommits: 0,\n recentCommits: 0,\n authors: new Set<string>(),\n weightedTopAuthorShare: 0,\n weight: 0,\n };\n\n current.totalCommits += file.commitCount;\n current.recentCommits += file.recentCommitCount;\n for (const author of file.authorDistributionByCommits) {\n current.authors.add(author.authorId);\n }\n\n current.weightedTopAuthorShare += file.topAuthorShareByCommits * Math.max(1, file.commitCount);\n current.weight += Math.max(1, file.commitCount);\n moduleKnowledgeMap.set(module, current);\n }\n\n return [...moduleKnowledgeMap.values()]\n .map((entry) => {\n const topAuthorShareByCommits =\n entry.weight <= 0 ? 0 : round4(entry.weightedTopAuthorShare / entry.weight);\n const activeAuthors = entry.authors.size;\n const ownershipLabel: \"distributed\" | \"sparse\" | \"siloed\" =\n activeAuthors <= 1 || topAuthorShareByCommits >= 0.85\n ? \"siloed\"\n : activeAuthors <= 2 || topAuthorShareByCommits >= 0.65\n ? \"sparse\"\n : \"distributed\";\n\n return {\n module: entry.module,\n totalCommits: entry.totalCommits,\n recentCommits: entry.recentCommits,\n activeAuthors,\n topAuthorShareByCommits,\n ownershipLabel,\n };\n })\n .sort(\n (a, b) =>\n MODULE_KNOWLEDGE_LABEL_PRIORITY[a.ownershipLabel] -\n MODULE_KNOWLEDGE_LABEL_PRIORITY[b.ownershipLabel] ||\n b.totalCommits - a.totalCommits ||\n a.module.localeCompare(b.module),\n );\n};\n\nconst ownershipPosture = (\n fileOwnership: ChangeOwnershipFileOwnership,\n moduleKnowledge: ChangeOwnershipModuleKnowledge,\n metrics: ChangeOwnershipMetrics,\n): ChangeOwnershipPosture => {\n const authorTouchCounts = new Map<string, number>();\n for (const file of fileOwnership) {\n for (const author of file.authorDistributionByCommits) {\n authorTouchCounts.set(\n author.authorId,\n (authorTouchCounts.get(author.authorId) ?? 0) + author.commits,\n );\n }\n }\n\n const totalTouches = [...authorTouchCounts.values()].reduce((sum, value) => sum + value, 0);\n const largestContributorSharePercent =\n totalTouches <= 0\n ? null\n : round4((Math.max(...authorTouchCounts.values()) / totalTouches) * 100);\n const activeContributors = authorTouchCounts.size;\n const dominatedModules = moduleKnowledge.filter(\n (module) => module.ownershipLabel === \"siloed\" || module.topAuthorShareByCommits >= 0.8,\n ).length;\n const singleOwnerModulesPercent =\n moduleKnowledge.length === 0 ? null : round4((dominatedModules / moduleKnowledge.length) * 100);\n const concentratedOrSingle =\n (metrics.concentratedOwnershipPercent ?? 0) + (metrics.singleMaintainerPercent ?? 0);\n const staleOwnedFilesPercent = metrics.staleOwnedFilesPercent ?? 0;\n const singleMaintainerPercent = metrics.singleMaintainerPercent ?? 0;\n\n let status: ChangeOwnershipPosture[\"status\"] = \"balanced\";\n\n if (staleOwnedFilesPercent >= 25) {\n status = \"stale\";\n } else if (\n singleMaintainerPercent >= 35 ||\n (singleOwnerModulesPercent ?? 0) >= 35 ||\n (largestContributorSharePercent ?? 0) >= 55\n ) {\n status = \"siloed\";\n } else if (concentratedOrSingle >= 45 || (largestContributorSharePercent ?? 0) >= 30) {\n status = \"concentrated\";\n }\n\n const titleByStatus = {\n balanced: \"Balanced Ownership\",\n concentrated: \"Concentrated Ownership\",\n siloed: \"Siloed Ownership\",\n stale: \"Stale Ownership\",\n } as const;\n\n const summaryByStatus = {\n balanced: `Knowledge is broadly distributed across the repository. ${metrics.sharedOwnershipPercent ?? 0}% of ownership-ready files are shared, with limited module concentration.`,\n concentrated: `The repository still depends on a narrow set of contributors in key paths. ${round4(concentratedOrSingle)}% of ownership-ready files are concentrated or single-maintainer.`,\n siloed: `Knowledge silos are material. Single-maintainer files or module dominance are high enough that handoff risk is no longer isolated.`,\n stale: `A meaningful slice of owned files has gone cold. Stale ownership areas are large enough to distort the repo's operating posture.`,\n } as const;\n\n return {\n status,\n title: titleByStatus[status],\n summary: summaryByStatus[status],\n activeContributors,\n largestContributorSharePercent,\n singleOwnerModulesPercent,\n };\n};\n\nconst ownershipContributors = (\n fileOwnership: ChangeOwnershipFileOwnership,\n): ChangeOwnershipContributorOwnership => {\n const commitTouchesByAuthor = new Map<string, number>();\n let totalCommitTouches = 0;\n let totalChurn = 0;\n\n const contributorMap = new Map<\n string,\n {\n authorId: string;\n singleMaintainerFiles: number;\n concentratedFiles: number;\n ownedFiles: number;\n totalCommitTouches: number;\n ownedChurnTotal: number;\n }\n >();\n\n for (const file of fileOwnership) {\n for (const author of file.authorDistributionByCommits) {\n commitTouchesByAuthor.set(\n author.authorId,\n (commitTouchesByAuthor.get(author.authorId) ?? 0) + author.commits,\n );\n totalCommitTouches += author.commits;\n }\n\n for (const author of file.authorDistributionByChurn) {\n totalChurn += author.churnTotal;\n }\n\n const dominantAuthor = file.authorDistributionByCommits[0];\n if (dominantAuthor === undefined) {\n continue;\n }\n\n const current = contributorMap.get(dominantAuthor.authorId) ?? {\n authorId: dominantAuthor.authorId,\n singleMaintainerFiles: 0,\n concentratedFiles: 0,\n ownedFiles: 0,\n totalCommitTouches: 0,\n ownedChurnTotal: 0,\n };\n\n current.ownedFiles += 1;\n current.totalCommitTouches += dominantAuthor.commits;\n\n const dominantChurnShare = file.authorDistributionByChurn.find(\n (entry) => entry.authorId === dominantAuthor.authorId,\n );\n current.ownedChurnTotal += dominantChurnShare?.churnTotal ?? 0;\n\n if (file.ownershipLabel === \"singleMaintainer\") {\n current.singleMaintainerFiles += 1;\n } else if (file.ownershipLabel === \"concentrated\") {\n current.concentratedFiles += 1;\n }\n\n contributorMap.set(dominantAuthor.authorId, current);\n }\n\n return [...contributorMap.values()]\n .map((entry) => ({\n authorId: entry.authorId,\n singleMaintainerFiles: entry.singleMaintainerFiles,\n concentratedFiles: entry.concentratedFiles,\n ownedFiles: entry.ownedFiles,\n totalCommitTouches: entry.totalCommitTouches,\n totalCommitShare:\n totalCommitTouches === 0\n ? 0\n : round4((entry.totalCommitTouches / totalCommitTouches) * 100),\n ownedChurnShare: totalChurn === 0 ? 0 : round4((entry.ownedChurnTotal / totalChurn) * 100),\n }))\n .sort(\n (a, b) =>\n b.singleMaintainerFiles - a.singleMaintainerFiles ||\n b.concentratedFiles - a.concentratedFiles ||\n b.ownedFiles - a.ownedFiles ||\n b.totalCommitShare - a.totalCommitShare ||\n a.authorId.localeCompare(b.authorId),\n )\n .slice(0, 8);\n};\n\nconst ownershipFragilityScore = (module: ChangeOwnershipModuleKnowledge[number]): number => {\n const severityBase =\n module.ownershipLabel === \"siloed\" ? 0.85 : module.ownershipLabel === \"sparse\" ? 0.55 : 0.2;\n const severity = clamp01(severityBase + Math.max(0, module.topAuthorShareByCommits - 0.6));\n const activityWeight =\n clamp01(module.recentCommits / 6) * 0.65 + clamp01(module.totalCommits / 20) * 0.35;\n\n return round4(severity * activityWeight);\n};\n\nconst changeOwnershipSummary = (\n snapshot: CodeSentinelSnapshot,\n): CodeSentinelReport[\"changeOwnership\"] => {\n if (!snapshot.analysis.evolution.available) {\n return {\n available: false,\n reason: snapshot.analysis.evolution.reason,\n };\n }\n\n const evolution = snapshot.analysis.evolution;\n const files = evolution.files;\n const ownershipReadyFiles = files.filter(\n (file) => file.topAuthorShareByCommits !== null && file.authorDistributionByCommits.length > 0,\n );\n\n const sharedOwnershipCount = ownershipReadyFiles.filter(\n (file) => file.authorDistributionByCommits.length >= 2 && file.topAuthorShareByCommits <= 0.6,\n ).length;\n const concentratedOwnershipCount = ownershipReadyFiles.filter(\n (file) => file.authorDistributionByCommits.length >= 2 && file.topAuthorShareByCommits > 0.6,\n ).length;\n const singleMaintainerCount = ownershipReadyFiles.filter(\n (file) => file.authorDistributionByCommits.length <= 1,\n ).length;\n const headCommitTimestamp = evolution.metrics.headCommitTimestamp;\n const staleOwnedFilesCount = ownershipReadyFiles.filter(\n (file) =>\n file.commitCount > 0 &&\n file.lastCommitTimestamp !== null &&\n headCommitTimestamp !== null &&\n headCommitTimestamp - file.lastCommitTimestamp >= STALE_OWNED_FILE_DAYS * 86_400,\n ).length;\n const ownershipDivisor = ownershipReadyFiles.length || 0;\n const metrics = {\n totalCommits: evolution.metrics.totalCommits,\n totalFiles: evolution.metrics.totalFiles,\n recentWindowDays: evolution.metrics.recentWindowDays,\n meanBusFactorByCommits: average(\n files.map((file) => file.busFactorByCommits).filter((value) => value !== null),\n ),\n averageRecentVolatility: average(files.map((file) => toPercent(file.recentVolatility))),\n sharedOwnershipPercent:\n ownershipDivisor === 0 ? null : round4((sharedOwnershipCount / ownershipDivisor) * 100),\n concentratedOwnershipPercent:\n ownershipDivisor === 0 ? null : round4((concentratedOwnershipCount / ownershipDivisor) * 100),\n singleMaintainerPercent:\n ownershipDivisor === 0 ? null : round4((singleMaintainerCount / ownershipDivisor) * 100),\n staleOwnedFilesPercent:\n ownershipDivisor === 0 ? null : round4((staleOwnedFilesCount / ownershipDivisor) * 100),\n } satisfies ChangeOwnershipMetrics;\n\n const fileOwnership = fileOwnershipItems(files);\n const allModuleKnowledge = moduleKnowledgeItems(files);\n const posture = ownershipPosture(fileOwnership, allModuleKnowledge, metrics);\n const contributorOwnership = ownershipContributors(fileOwnership);\n const moduleKnowledge = allModuleKnowledge.slice(0, 8);\n const fragileAreas = allModuleKnowledge\n .slice()\n .filter((module) => module.totalCommits >= MIN_FRAGILE_AREA_TOTAL_COMMITS)\n .sort(\n (a, b) =>\n ownershipFragilityScore(b) - ownershipFragilityScore(a) ||\n b.topAuthorShareByCommits - a.topAuthorShareByCommits ||\n b.recentCommits - a.recentCommits ||\n b.totalCommits - a.totalCommits ||\n a.module.localeCompare(b.module),\n )\n .slice(0, 5);\n\n const coChangePairs = [...evolution.coupling.pairs]\n .sort(\n (a, b) =>\n b.couplingScore - a.couplingScore ||\n b.coChangeCommits - a.coChangeCommits ||\n a.fileA.localeCompare(b.fileA) ||\n a.fileB.localeCompare(b.fileB),\n )\n .slice(0, 5)\n .map((pair) => ({\n fileA: pair.fileA,\n fileB: pair.fileB,\n coChangeCommits: pair.coChangeCommits,\n couplingScore: round4(pair.couplingScore),\n }));\n\n return {\n available: true,\n metrics,\n posture,\n recentActivity: evolution.recentActivity ?? [],\n coChangePairs,\n moduleKnowledge,\n fragileAreas,\n contributorOwnership,\n fileOwnership,\n };\n};\n\nconst riskyDependencies = (\n snapshot: CodeSentinelSnapshot,\n): readonly RiskyDependencyReportItem[] => {\n if (!snapshot.analysis.external.available) {\n return [];\n }\n\n const dependencyByName = new Map(\n snapshot.analysis.external.dependencies.map((dependency) => [dependency.name, dependency]),\n );\n\n return snapshot.analysis.risk.dependencyScores\n .map((score) => {\n const dependency = dependencyByName.get(score.dependency);\n const riskSignals = [...new Set([...score.ownRiskSignals, ...score.inheritedRiskSignals])];\n\n return {\n name: score.dependency,\n score: score.score,\n normalizedScore: score.normalizedScore,\n dependencyScope: normalizeDependencyScope(dependency?.dependencyScope),\n direct: dependency?.direct ?? false,\n resolvedVersion: dependency?.resolvedVersion ?? null,\n transitiveDependencyCount: dependency?.transitiveDependencies.length ?? 0,\n dependentCount: dependency?.dependents ?? 0,\n fanOut: dependency?.fanOut ?? 0,\n dependencyDepth: dependency?.dependencyDepth ?? 0,\n weeklyDownloads: dependency?.weeklyDownloads ?? null,\n maintainerCount: dependency?.maintainerCount ?? null,\n releaseFrequencyDays: dependency?.releaseFrequencyDays ?? null,\n daysSinceLastRelease: dependency?.daysSinceLastRelease ?? null,\n repositoryActivity30d: dependency?.repositoryActivity30d ?? null,\n busFactor: dependency?.busFactor ?? null,\n ownRiskSignals: dependency?.ownRiskSignals ?? [],\n inheritedRiskSignals: dependency?.inheritedRiskSignals ?? [],\n riskSignals,\n reason:\n riskSignals.length === 0\n ? \"Derived from aggregate dependency risk signals.\"\n : riskSignals.join(\", \"),\n };\n })\n .filter((dependency) => dependency.score > 0)\n .sort((a, b) => b.score - a.score || a.name.localeCompare(b.name))\n .slice(0, 20);\n};\n\nconst repositoryDimensionScores = (snapshot: CodeSentinelSnapshot): RepositoryDimensionScores => {\n const target = findTraceTarget(snapshot, \"repository\", snapshot.analysis.structural.targetPath);\n if (target === undefined) {\n return {\n structural: null,\n evolution: null,\n external: null,\n interactions: null,\n };\n }\n\n const structural = target.factors.find((factor) => factor.factorId === \"repository.structural\");\n const evolution = target.factors.find((factor) => factor.factorId === \"repository.evolution\");\n const external = target.factors.find((factor) => factor.factorId === \"repository.external\");\n const interactions = target.factors.find(\n (factor) => factor.factorId === \"repository.composite.interactions\",\n );\n\n const interactionScore =\n interactions === undefined\n ? null\n : round4(\n ((interactions.rawMetrics[\"structuralEvolution\"] ?? 0) +\n (interactions.rawMetrics[\"centralInstability\"] ?? 0) +\n (interactions.rawMetrics[\"dependencyAmplification\"] ?? 0)) *\n 100,\n );\n\n return {\n structural:\n structural === undefined\n ? null\n : round4((structural.rawMetrics[\"structuralDimension\"] ?? 0) * 100),\n evolution:\n evolution === undefined\n ? null\n : round4((evolution.rawMetrics[\"evolutionDimension\"] ?? 0) * 100),\n external:\n external === undefined ? null : round4((external.rawMetrics[\"externalDimension\"] ?? 0) * 100),\n interactions: interactionScore,\n };\n};\n\nconst workspaceSummary = (snapshot: CodeSentinelSnapshot): WorkspaceReportSummary => ({\n structural: [...(snapshot.analysis.structural.workspaces ?? [])]\n .sort(\n (a, b) =>\n b.incomingEdgeCount +\n b.outgoingEdgeCount +\n b.internalEdgeCount -\n (a.incomingEdgeCount + a.outgoingEdgeCount + a.internalEdgeCount) ||\n b.fileCount - a.fileCount ||\n a.path.localeCompare(b.path),\n )\n .map((workspace) => ({\n name: workspace.name,\n path: workspace.path,\n kind: workspace.kind,\n fileCount: workspace.fileCount,\n internalEdgeCount: workspace.internalEdgeCount,\n incomingEdgeCount: workspace.incomingEdgeCount,\n outgoingEdgeCount: workspace.outgoingEdgeCount,\n })),\n risk: [...snapshot.analysis.risk.workspaceScores]\n .sort((a, b) => b.score - a.score || a.path.localeCompare(b.path))\n .map((workspace) => ({\n name: workspace.name,\n path: workspace.path,\n kind: workspace.kind,\n score: workspace.score,\n normalizedScore: workspace.normalizedScore,\n fileCount: workspace.fileCount,\n averageFileRisk: workspace.averageFileRisk,\n peakFileRisk: workspace.peakFileRisk,\n internalEdgeCount: workspace.internalEdgeCount,\n incomingEdgeCount: workspace.incomingEdgeCount,\n outgoingEdgeCount: workspace.outgoingEdgeCount,\n topFiles: workspace.topFiles.slice(0, 5).map((file) => ({\n file: file.file,\n score: file.score,\n })),\n })),\n evolution: snapshot.analysis.evolution.available\n ? [...(snapshot.analysis.evolution.workspaces ?? [])]\n .sort(\n (a, b) =>\n b.recentVolatility - a.recentVolatility ||\n b.churnTotal - a.churnTotal ||\n b.commitCount - a.commitCount ||\n a.path.localeCompare(b.path),\n )\n .map((workspace) => ({\n name: workspace.name,\n path: workspace.path,\n kind: workspace.kind,\n fileCount: workspace.fileCount,\n commitCount: workspace.commitCount,\n churnTotal: workspace.churnTotal,\n recentCommitCount: workspace.recentCommitCount,\n recentVolatility: workspace.recentVolatility,\n topAuthorShareByCommits: workspace.topAuthorShareByCommits,\n busFactorByCommits: workspace.busFactorByCommits,\n hotspotCount: workspace.hotspotCount,\n topHotspots: workspace.topHotspots.slice(0, 5).map((hotspot) => ({\n filePath: hotspot.filePath,\n rank: hotspot.rank,\n commitCount: hotspot.commitCount,\n churnTotal: hotspot.churnTotal,\n })),\n internalCouplingPairCount: workspace.internalCouplingPairCount,\n incomingCouplingPairCount: workspace.incomingCouplingPairCount,\n outgoingCouplingPairCount: workspace.outgoingCouplingPairCount,\n }))\n : [],\n external: snapshot.analysis.external.available\n ? [...(snapshot.analysis.external.workspaces ?? [])]\n .sort(\n (a, b) =>\n b.highRiskDependencies.length - a.highRiskDependencies.length ||\n b.transitiveExposureDependencies.length - a.transitiveExposureDependencies.length ||\n b.directDependencies - a.directDependencies ||\n a.path.localeCompare(b.path),\n )\n .map((workspace) => ({\n name: workspace.name,\n path: workspace.path,\n kind: workspace.kind,\n directDependencies: workspace.directDependencies,\n directProductionDependencies: workspace.directProductionDependencies,\n directDevelopmentDependencies: workspace.directDevelopmentDependencies,\n unresolvedDependencies: [...workspace.unresolvedDependencies].sort((a, b) =>\n a.localeCompare(b),\n ),\n dependencyNames: [...workspace.dependencyNames].sort((a, b) => a.localeCompare(b)),\n sharedDependencies: [...workspace.sharedDependencies].sort((a, b) => a.localeCompare(b)),\n highRiskDependencies: [...workspace.highRiskDependencies].sort((a, b) =>\n a.localeCompare(b),\n ),\n highRiskDevelopmentDependencies: [...workspace.highRiskDevelopmentDependencies].sort(\n (a, b) => a.localeCompare(b),\n ),\n transitiveExposureDependencies: [...workspace.transitiveExposureDependencies].sort(\n (a, b) => a.localeCompare(b),\n ),\n singleMaintainerDependencies: [...workspace.singleMaintainerDependencies].sort((a, b) =>\n a.localeCompare(b),\n ),\n abandonedDependencies: [...workspace.abandonedDependencies].sort((a, b) =>\n a.localeCompare(b),\n ),\n }))\n : [],\n});\n\nexport const createReport = (\n snapshot: CodeSentinelSnapshot,\n diff?: SnapshotDiff,\n extras: ReportExtras = {},\n): CodeSentinelReport => {\n const external = snapshot.analysis.external;\n\n return {\n schemaVersion: REPORT_SCHEMA_VERSION,\n generatedAt: new Date().toISOString(),\n repository: {\n name:\n basename(snapshot.analysis.structural.targetPath) ||\n snapshot.analysis.structural.targetPath,\n targetPath: snapshot.analysis.structural.targetPath,\n riskScore: snapshot.analysis.risk.riskScore,\n normalizedScore: snapshot.analysis.risk.normalizedScore,\n riskTier: toRiskTier(snapshot.analysis.risk.riskScore),\n healthTier: toHealthTier(snapshot.analysis.health.healthScore),\n confidence: repositoryConfidence(snapshot),\n dimensionScores: repositoryDimensionScores(snapshot),\n webUrl: extras.repositoryWebUrl ?? null,\n },\n health: snapshot.analysis.health,\n workspaces: workspaceSummary(snapshot),\n hotspots: hotspotItems(snapshot),\n structural: {\n cycleCount: snapshot.analysis.structural.metrics.cycleCount,\n cycles: snapshot.analysis.structural.cycles.map((cycle) =>\n [...cycle.nodes].sort((a, b) => a.localeCompare(b)).join(\" -> \"),\n ),\n cycleDetails: cycleDetails(snapshot),\n metrics: structuralArchitectureMetrics(snapshot),\n moduleAnatomy: structuralModuleAnatomy(snapshot),\n fanInOutExtremes: {\n highestFanIn: topStructuralFiles(snapshot, (file) => file.fanIn),\n highestFanOut: topStructuralFiles(snapshot, (file) => file.fanOut),\n deepestFiles: topStructuralFiles(snapshot, (file) => file.depth),\n },\n fragileClusters: snapshot.analysis.risk.fragileClusters.map((cluster) => ({\n id: cluster.id,\n kind: cluster.kind,\n score: cluster.score,\n files: [...cluster.files].sort((a, b) => a.localeCompare(b)),\n })),\n },\n changeOwnership: changeOwnershipSummary(snapshot),\n external: !external.available\n ? {\n available: false,\n reason: external.reason,\n }\n : {\n available: true,\n metrics: external.metrics,\n highRiskDependencies: [...external.highRiskDependencies].sort((a, b) =>\n a.localeCompare(b),\n ),\n highRiskDevelopmentDependencies: [...external.highRiskDevelopmentDependencies].sort(\n (a, b) => a.localeCompare(b),\n ),\n transitiveExposureDependencies: [...external.transitiveExposureDependencies].sort(\n (a, b) => a.localeCompare(b),\n ),\n singleMaintainerDependencies: [...external.singleMaintainerDependencies].sort((a, b) =>\n a.localeCompare(b),\n ),\n abandonedDependencies: [...external.abandonedDependencies].sort((a, b) =>\n a.localeCompare(b),\n ),\n centralityRanking: [...external.centralityRanking].sort(\n (a, b) =>\n b.dependents - a.dependents || b.fanOut - a.fanOut || a.name.localeCompare(b.name),\n ),\n riskyDependencies: riskyDependencies(snapshot),\n },\n ...(extras.ownership === undefined ? {} : { ownership: extras.ownership }),\n appendix: {\n snapshotSchemaVersion: snapshot.schemaVersion,\n riskModelVersion: snapshot.riskModelVersion,\n timestamp: snapshot.generatedAt,\n normalization:\n \"Scores are deterministic 0-100 outputs from risk-engine normalized factors and interaction terms.\",\n ...(snapshot.analysisConfig === undefined ? {} : { analysisConfig: snapshot.analysisConfig }),\n },\n ...(diff === undefined ? {} : { diff }),\n };\n};\n","import type { CodeSentinelReport } from \"./domain.js\";\n\nconst renderTextDiff = (report: CodeSentinelReport): string[] => {\n if (report.diff === undefined) {\n return [];\n }\n\n return [\n \"\",\n \"Diff\",\n ` riskScoreDelta: ${report.diff.riskScoreDelta}`,\n ` normalizedScoreDelta: ${report.diff.normalizedScoreDelta}`,\n ` newHotspots: ${report.diff.newHotspots.join(\", \") || \"none\"}`,\n ` resolvedHotspots: ${report.diff.resolvedHotspots.join(\", \") || \"none\"}`,\n ` newCycles: ${report.diff.newCycles.join(\", \") || \"none\"}`,\n ` resolvedCycles: ${report.diff.resolvedCycles.join(\", \") || \"none\"}`,\n ];\n};\n\nconst renderTextWorkspaceSummary = (report: CodeSentinelReport): string[] => {\n const workspaceCount = Math.max(\n report.workspaces.structural.length,\n report.workspaces.risk.length,\n report.workspaces.evolution.length,\n report.workspaces.external.length,\n );\n\n if (workspaceCount === 0) {\n return [];\n }\n\n const lines = [\"\", \"Workspace Summary\"];\n lines.push(\" topRisk:\");\n for (const workspace of report.workspaces.risk.slice(0, 5)) {\n lines.push(\n ` - ${workspace.path} | score=${workspace.score} files=${workspace.fileCount} peakFileRisk=${workspace.peakFileRisk}`,\n );\n }\n if (report.workspaces.risk.length === 0) {\n lines.push(\" - none\");\n }\n\n lines.push(\" structuralCoupling:\");\n for (const workspace of report.workspaces.structural.slice(0, 5)) {\n lines.push(\n ` - ${workspace.path} | internal=${workspace.internalEdgeCount} incoming=${workspace.incomingEdgeCount} outgoing=${workspace.outgoingEdgeCount}`,\n );\n }\n if (report.workspaces.structural.length === 0) {\n lines.push(\" - none\");\n }\n\n lines.push(\" evolutionHotspots:\");\n for (const workspace of report.workspaces.evolution.slice(0, 5)) {\n lines.push(\n ` - ${workspace.path} | commits=${workspace.commitCount} churn=${workspace.churnTotal} recentVolatility=${workspace.recentVolatility}`,\n );\n }\n if (report.workspaces.evolution.length === 0) {\n lines.push(\" - none\");\n }\n\n lines.push(\" dependencyExposure:\");\n for (const workspace of report.workspaces.external.slice(0, 5)) {\n lines.push(\n ` - ${workspace.path} | direct=${workspace.directDependencies} shared=${workspace.sharedDependencies.length} highRisk=${workspace.highRiskDependencies.length} transitiveExposure=${workspace.transitiveExposureDependencies.length}`,\n );\n }\n if (report.workspaces.external.length === 0) {\n lines.push(\" - none\");\n }\n\n return lines;\n};\n\nexport const renderTextReport = (report: CodeSentinelReport): string => {\n const lines: string[] = [];\n lines.push(\"Repository Summary\");\n lines.push(` target: ${report.repository.targetPath}`);\n lines.push(` riskScore: ${report.repository.riskScore}`);\n lines.push(` normalizedScore: ${report.repository.normalizedScore}`);\n lines.push(` riskTier: ${report.repository.riskTier}`);\n lines.push(` healthTier: ${report.repository.healthTier}`);\n lines.push(` confidence: ${report.repository.confidence ?? \"n/a\"}`);\n\n lines.push(\"\");\n lines.push(\"Dimension Scores (0-100)\");\n lines.push(` structural: ${report.repository.dimensionScores.structural ?? \"n/a\"}`);\n lines.push(` evolution: ${report.repository.dimensionScores.evolution ?? \"n/a\"}`);\n lines.push(` external: ${report.repository.dimensionScores.external ?? \"n/a\"}`);\n lines.push(` interactions: ${report.repository.dimensionScores.interactions ?? \"n/a\"}`);\n\n lines.push(\"\");\n lines.push(\"Health Summary\");\n lines.push(` healthScore: ${report.health.healthScore}`);\n lines.push(` normalizedScore: ${report.health.normalizedScore}`);\n lines.push(` modularity: ${report.health.dimensions.modularity}`);\n lines.push(` changeHygiene: ${report.health.dimensions.changeHygiene}`);\n lines.push(` testHealth: ${report.health.dimensions.testHealth}`);\n lines.push(` ownershipDistribution: ${report.health.dimensions.ownershipDistribution}`);\n lines.push(\" topIssues:\");\n for (const issue of report.health.topIssues.slice(0, 5)) {\n const ruleSuffix = issue.ruleId === undefined ? \"\" : ` [rule=${issue.ruleId}]`;\n lines.push(\n ` - [${issue.severity}] (${issue.dimension}) ${issue.id}${ruleSuffix} @ ${issue.target}: ${issue.message}`,\n );\n }\n if (report.health.topIssues.length === 0) {\n lines.push(\" - none\");\n }\n\n lines.push(\"\");\n lines.push(\"Ownership Posture\");\n if (!report.changeOwnership.available) {\n lines.push(` unavailable: ${report.changeOwnership.reason}`);\n } else {\n lines.push(` status: ${report.changeOwnership.posture.title}`);\n lines.push(` summary: ${report.changeOwnership.posture.summary}`);\n lines.push(` activeContributors: ${report.changeOwnership.posture.activeContributors}`);\n lines.push(\n ` largestContributorSharePercent: ${report.changeOwnership.posture.largestContributorSharePercent ?? \"n/a\"}`,\n );\n lines.push(\n ` singleOwnerModulesPercent: ${report.changeOwnership.posture.singleOwnerModulesPercent ?? \"n/a\"}`,\n );\n }\n\n lines.push(\"\");\n lines.push(\"Top Hotspots\");\n for (const hotspot of report.hotspots) {\n lines.push(` - ${hotspot.target} | score=${hotspot.score}`);\n for (const factor of hotspot.topFactors) {\n lines.push(\n ` factor: ${factor.label} contribution=${factor.contribution} confidence=${factor.confidence}`,\n );\n lines.push(` evidence: ${factor.evidence}`);\n }\n lines.push(` priority actions: ${hotspot.suggestedActions.join(\" | \") || \"none\"}`);\n }\n\n lines.push(\"\");\n lines.push(\"Structural Observations\");\n lines.push(` cycleCount: ${report.structural.cycleCount}`);\n lines.push(` cycles: ${report.structural.cycles.join(\" ; \") || \"none\"}`);\n lines.push(` fragileClusters: ${report.structural.fragileClusters.length}`);\n\n lines.push(...renderTextWorkspaceSummary(report));\n\n lines.push(\"\");\n lines.push(\"External Exposure\");\n if (!report.external.available) {\n lines.push(` unavailable: ${report.external.reason}`);\n } else {\n lines.push(\n ` highRiskDependencies: ${report.external.highRiskDependencies.join(\", \") || \"none\"}`,\n );\n lines.push(\n ` highRiskDevelopmentDependencies: ${report.external.highRiskDevelopmentDependencies.join(\", \") || \"none\"}`,\n );\n lines.push(\n ` singleMaintainerDependencies: ${report.external.singleMaintainerDependencies.join(\", \") || \"none\"}`,\n );\n lines.push(\n ` abandonedDependencies: ${report.external.abandonedDependencies.join(\", \") || \"none\"}`,\n );\n }\n\n lines.push(\"\");\n lines.push(\"Appendix\");\n lines.push(` snapshotSchemaVersion: ${report.appendix.snapshotSchemaVersion}`);\n lines.push(` riskModelVersion: ${report.appendix.riskModelVersion}`);\n lines.push(` timestamp: ${report.appendix.timestamp}`);\n lines.push(` normalization: ${report.appendix.normalization}`);\n\n lines.push(...renderTextDiff(report));\n\n return lines.join(\"\\n\");\n};\n\nconst renderMarkdownDiff = (report: CodeSentinelReport): string[] => {\n if (report.diff === undefined) {\n return [];\n }\n\n return [\n \"\",\n \"## Diff\",\n `- riskScoreDelta: \\`${report.diff.riskScoreDelta}\\``,\n `- normalizedScoreDelta: \\`${report.diff.normalizedScoreDelta}\\``,\n `- newHotspots: ${report.diff.newHotspots.map((item) => `\\`${item}\\``).join(\", \") || \"none\"}`,\n `- resolvedHotspots: ${report.diff.resolvedHotspots.map((item) => `\\`${item}\\``).join(\", \") || \"none\"}`,\n `- newCycles: ${report.diff.newCycles.map((item) => `\\`${item}\\``).join(\", \") || \"none\"}`,\n `- resolvedCycles: ${report.diff.resolvedCycles.map((item) => `\\`${item}\\``).join(\", \") || \"none\"}`,\n ];\n};\n\nconst renderMarkdownWorkspaceSummary = (report: CodeSentinelReport): string[] => {\n const workspaceCount = Math.max(\n report.workspaces.structural.length,\n report.workspaces.risk.length,\n report.workspaces.evolution.length,\n report.workspaces.external.length,\n );\n\n if (workspaceCount === 0) {\n return [];\n }\n\n const lines = [\"\", \"## Workspace Summary\"];\n lines.push(\"- top risk:\");\n if (report.workspaces.risk.length === 0) {\n lines.push(\" - none\");\n } else {\n for (const workspace of report.workspaces.risk.slice(0, 5)) {\n lines.push(\n ` - \\`${workspace.path}\\`: score=\\`${workspace.score}\\`, files=\\`${workspace.fileCount}\\`, peak file risk=\\`${workspace.peakFileRisk}\\``,\n );\n }\n }\n\n lines.push(\"- structural coupling:\");\n if (report.workspaces.structural.length === 0) {\n lines.push(\" - none\");\n } else {\n for (const workspace of report.workspaces.structural.slice(0, 5)) {\n lines.push(\n ` - \\`${workspace.path}\\`: internal=\\`${workspace.internalEdgeCount}\\`, incoming=\\`${workspace.incomingEdgeCount}\\`, outgoing=\\`${workspace.outgoingEdgeCount}\\``,\n );\n }\n }\n\n lines.push(\"- evolution hotspots:\");\n if (report.workspaces.evolution.length === 0) {\n lines.push(\" - none\");\n } else {\n for (const workspace of report.workspaces.evolution.slice(0, 5)) {\n lines.push(\n ` - \\`${workspace.path}\\`: commits=\\`${workspace.commitCount}\\`, churn=\\`${workspace.churnTotal}\\`, recent volatility=\\`${workspace.recentVolatility}\\``,\n );\n }\n }\n\n lines.push(\"- dependency exposure:\");\n if (report.workspaces.external.length === 0) {\n lines.push(\" - none\");\n } else {\n for (const workspace of report.workspaces.external.slice(0, 5)) {\n lines.push(\n ` - \\`${workspace.path}\\`: direct=\\`${workspace.directDependencies}\\`, shared=\\`${workspace.sharedDependencies.length}\\`, high risk=\\`${workspace.highRiskDependencies.length}\\`, transitive exposure=\\`${workspace.transitiveExposureDependencies.length}\\``,\n );\n }\n }\n\n return lines;\n};\n\nexport const renderMarkdownReport = (report: CodeSentinelReport): string => {\n const lines: string[] = [];\n lines.push(\"# CodeSentinel Report\");\n lines.push(\"\");\n lines.push(\"## Repository Summary\");\n lines.push(`- target: \\`${report.repository.targetPath}\\``);\n lines.push(`- riskScore: \\`${report.repository.riskScore}\\``);\n lines.push(`- normalizedScore: \\`${report.repository.normalizedScore}\\``);\n lines.push(`- riskTier: \\`${report.repository.riskTier}\\``);\n lines.push(`- healthTier: \\`${report.repository.healthTier}\\``);\n lines.push(`- confidence: \\`${report.repository.confidence ?? \"n/a\"}\\``);\n\n lines.push(\"\");\n lines.push(\"## Dimension Scores (0-100)\");\n lines.push(`- structural: \\`${report.repository.dimensionScores.structural ?? \"n/a\"}\\``);\n lines.push(`- evolution: \\`${report.repository.dimensionScores.evolution ?? \"n/a\"}\\``);\n lines.push(`- external: \\`${report.repository.dimensionScores.external ?? \"n/a\"}\\``);\n lines.push(`- interactions: \\`${report.repository.dimensionScores.interactions ?? \"n/a\"}\\``);\n\n lines.push(\"\");\n lines.push(\"## Health Summary\");\n lines.push(`- healthScore: \\`${report.health.healthScore}\\``);\n lines.push(`- normalizedScore: \\`${report.health.normalizedScore}\\``);\n lines.push(`- modularity: \\`${report.health.dimensions.modularity}\\``);\n lines.push(`- changeHygiene: \\`${report.health.dimensions.changeHygiene}\\``);\n lines.push(`- testHealth: \\`${report.health.dimensions.testHealth}\\``);\n lines.push(`- ownershipDistribution: \\`${report.health.dimensions.ownershipDistribution}\\``);\n if (report.health.topIssues.length === 0) {\n lines.push(\"- top issues: none\");\n } else {\n lines.push(\"- top issues:\");\n for (const issue of report.health.topIssues.slice(0, 5)) {\n const ruleSuffix = issue.ruleId === undefined ? \"\" : ` [rule=${issue.ruleId}]`;\n lines.push(\n ` - [${issue.severity}] \\`${issue.id}\\`${ruleSuffix} (\\`${issue.dimension}\\`) @ \\`${issue.target}\\`: ${issue.message}`,\n );\n }\n }\n\n lines.push(\"\");\n lines.push(\"## Ownership Posture\");\n if (!report.changeOwnership.available) {\n lines.push(`- unavailable: \\`${report.changeOwnership.reason}\\``);\n } else {\n lines.push(`- status: \\`${report.changeOwnership.posture.title}\\``);\n lines.push(`- summary: ${report.changeOwnership.posture.summary}`);\n lines.push(`- active contributors: \\`${report.changeOwnership.posture.activeContributors}\\``);\n lines.push(\n `- largest contributor share percent: \\`${report.changeOwnership.posture.largestContributorSharePercent ?? \"n/a\"}\\``,\n );\n lines.push(\n `- single-owner modules percent: \\`${report.changeOwnership.posture.singleOwnerModulesPercent ?? \"n/a\"}\\``,\n );\n }\n\n lines.push(\"\");\n lines.push(\"## Top Hotspots\");\n for (const hotspot of report.hotspots) {\n lines.push(`- **${hotspot.target}** (score: \\`${hotspot.score}\\`)`);\n lines.push(` - Top factors:`);\n for (const factor of hotspot.topFactors) {\n lines.push(\n ` - ${factor.label}: contribution=\\`${factor.contribution}\\`, confidence=\\`${factor.confidence}\\``,\n );\n lines.push(` - evidence: \\`${factor.evidence}\\``);\n }\n lines.push(` - Priority actions: ${hotspot.suggestedActions.join(\" | \") || \"none\"}`);\n }\n\n lines.push(\"\");\n lines.push(\"## Structural Observations\");\n lines.push(`- cycles detected: \\`${report.structural.cycleCount}\\``);\n lines.push(\n `- cycles: ${report.structural.cycles.map((cycle) => `\\`${cycle}\\``).join(\", \") || \"none\"}`,\n );\n lines.push(`- fragile clusters: \\`${report.structural.fragileClusters.length}\\``);\n\n lines.push(...renderMarkdownWorkspaceSummary(report));\n\n lines.push(\"\");\n lines.push(\"## External Exposure Summary\");\n if (!report.external.available) {\n lines.push(`- unavailable: \\`${report.external.reason}\\``);\n } else {\n lines.push(\n `- high-risk dependencies: ${report.external.highRiskDependencies.map((item) => `\\`${item}\\``).join(\", \") || \"none\"}`,\n );\n lines.push(\n `- high-risk development dependencies: ${report.external.highRiskDevelopmentDependencies.map((item) => `\\`${item}\\``).join(\", \") || \"none\"}`,\n );\n lines.push(\n `- single maintainer dependencies: ${report.external.singleMaintainerDependencies.map((item) => `\\`${item}\\``).join(\", \") || \"none\"}`,\n );\n lines.push(\n `- abandoned dependencies: ${report.external.abandonedDependencies.map((item) => `\\`${item}\\``).join(\", \") || \"none\"}`,\n );\n }\n\n lines.push(\"\");\n lines.push(\"## Appendix\");\n lines.push(`- snapshot schema: \\`${report.appendix.snapshotSchemaVersion}\\``);\n lines.push(`- risk model version: \\`${report.appendix.riskModelVersion}\\``);\n lines.push(`- timestamp: \\`${report.appendix.timestamp}\\``);\n lines.push(`- normalization: ${report.appendix.normalization}`);\n\n lines.push(...renderMarkdownDiff(report));\n\n return lines.join(\"\\n\");\n};\n","import type { AnalyzeSummary, RiskTrace } from \"@codesentinel/core\";\nimport {\n RISK_MODEL_VERSION,\n SNAPSHOT_SCHEMA_VERSION,\n type CodeSentinelSnapshot,\n} from \"./domain.js\";\n\nexport type CreateSnapshotInput = {\n analysis: AnalyzeSummary;\n trace?: RiskTrace;\n generatedAt?: string;\n analysisConfig?: Readonly<Record<string, string | number | boolean | null>>;\n};\n\nexport const createSnapshot = (input: CreateSnapshotInput): CodeSentinelSnapshot => ({\n schemaVersion: SNAPSHOT_SCHEMA_VERSION,\n generatedAt: input.generatedAt ?? new Date().toISOString(),\n riskModelVersion: RISK_MODEL_VERSION,\n source: {\n targetPath: input.analysis.structural.targetPath,\n },\n analysis: input.analysis,\n ...(input.trace === undefined ? {} : { trace: input.trace }),\n ...(input.analysisConfig === undefined ? {} : { analysisConfig: input.analysisConfig }),\n});\n\nexport const parseSnapshot = (raw: string): CodeSentinelSnapshot => {\n const parsed = JSON.parse(raw) as Partial<CodeSentinelSnapshot>;\n if (parsed.schemaVersion !== SNAPSHOT_SCHEMA_VERSION) {\n throw new Error(\"unsupported_snapshot_schema\");\n }\n\n if (typeof parsed.generatedAt !== \"string\") {\n throw new Error(\"invalid_snapshot_generated_at\");\n }\n\n if (parsed.analysis === undefined || parsed.analysis === null) {\n throw new Error(\"invalid_snapshot_analysis\");\n }\n\n if (parsed.source === undefined || typeof parsed.source.targetPath !== \"string\") {\n throw new Error(\"invalid_snapshot_source\");\n }\n\n return parsed as CodeSentinelSnapshot;\n};\n","import type { CodeSentinelReport, ReportFormat } from \"./domain.js\";\nimport { compareSnapshots } from \"./diff.js\";\nimport { createReport } from \"./report.js\";\nimport { renderMarkdownReport, renderTextReport } from \"./renderers.js\";\nimport { createSnapshot, parseSnapshot } from \"./snapshot.js\";\n\nexport {\n SNAPSHOT_SCHEMA_VERSION,\n REPORT_SCHEMA_VERSION,\n RISK_MODEL_VERSION,\n factorLabel,\n summarizeEvidence,\n type CodeSentinelSnapshot,\n type CodeSentinelReport,\n type CoChangePairReportItem,\n type ChangeOwnershipMetrics,\n type DeclaredOwnerReportItem,\n type HealthIssue,\n type ExternalCentralityReportItem,\n type ExternalMetricsReportItem,\n type FileOwnershipReportItem,\n type HotspotReportItem,\n type OwnershipAuditReport,\n type OwnershipAuditReportMetrics,\n type OwnershipAuditStatus,\n type OwnershipFileReportItem,\n type ModuleKnowledgeReportItem,\n type OwnershipContributorReportItem,\n type OwnershipPostureReportItem,\n type OwnershipPostureStatus,\n type OwnershipRiskAreaReportItem,\n type RecentActivityReportItem,\n type SnapshotDiff,\n type RiskTier,\n type StructuralCycleDetail,\n type StructuralArchitectureMetrics,\n type StructuralFileExtreme,\n type RiskyDependencyReportItem,\n type WorkspaceDependencyExposureReportItem,\n type WorkspaceEvolutionReportItem,\n type WorkspaceReportSummary,\n type WorkspaceRiskReportItem,\n type WorkspaceStructuralReportItem,\n type ReportExtras,\n type ReportFormat,\n} from \"./domain.js\";\n\nexport { createSnapshot, parseSnapshot, compareSnapshots, createReport };\n\nexport const formatReport = (report: CodeSentinelReport, format: ReportFormat): string => {\n if (format === \"json\") {\n return JSON.stringify(report, null, 2);\n }\n\n if (format === \"md\") {\n return renderMarkdownReport(report);\n }\n\n return renderTextReport(report);\n};\n","import type { EvidenceRef } from \"@codesentinel/core\";\nimport type { CodeSentinelSnapshot, SnapshotDiff } from \"@codesentinel/reporter\";\n\nexport type ViolationSeverity = \"info\" | \"warn\" | \"error\";\n\nexport type Violation = {\n id: string;\n severity: ViolationSeverity;\n message: string;\n targets: readonly string[];\n evidenceRefs: readonly EvidenceRef[];\n};\n\nexport type FailOnLevel = \"error\" | \"warn\";\n\nexport type OwnershipGateMetrics = {\n declaredCoveragePercent: number;\n declaredCoverageCriticalPercent: number;\n driftPercent: number;\n ghostOwnerCount: number;\n unownedCriticalCount: number;\n};\n\nexport type OwnershipGateInput =\n | { available: true; source: string; metrics: OwnershipGateMetrics }\n | { available: false; warnings: readonly string[] };\n\nexport type OwnershipGateResult = {\n evaluated: boolean;\n source: string | null;\n metrics: OwnershipGateMetrics | null;\n};\n\nexport type GateConfig = {\n maxRiskDelta?: number;\n maxHealthDelta?: number;\n noNewCycles?: boolean;\n noNewHighRiskDeps?: boolean;\n maxNewHotspots?: number;\n maxRiskScore?: number;\n minHealthScore?: number;\n newHotspotScoreThreshold?: number;\n maxUnownedCritical?: number;\n maxGhostOwners?: number;\n maxDrift?: number;\n failOn: FailOnLevel;\n};\n\nexport type GateEvaluationInput = {\n current: CodeSentinelSnapshot;\n baseline?: CodeSentinelSnapshot;\n diff?: SnapshotDiff;\n gateConfig: GateConfig;\n ownership?: OwnershipGateInput;\n};\n\nexport type GateEvaluationResult = {\n violations: readonly Violation[];\n highestSeverity: ViolationSeverity | null;\n exitCode: 0 | 1 | 2;\n evaluatedGates: readonly string[];\n warnings: readonly string[];\n ownership?: OwnershipGateResult;\n};\n\nexport const EXIT_CODES = {\n ok: 0,\n errorViolation: 1,\n warnViolation: 2,\n invalidConfiguration: 3,\n internalError: 4,\n} as const;\n\nexport class GovernanceConfigurationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"GovernanceConfigurationError\";\n }\n}\n\nexport const DEFAULT_NEW_HOTSPOT_SCORE_THRESHOLD = 60;\n","import type { EvidenceRef } from \"@codesentinel/core\";\nimport {\n DEFAULT_NEW_HOTSPOT_SCORE_THRESHOLD,\n GovernanceConfigurationError,\n type GateEvaluationInput,\n type GateEvaluationResult,\n type OwnershipGateResult,\n type Violation,\n type ViolationSeverity,\n} from \"./domain.js\";\n\nconst severityRank: Readonly<Record<ViolationSeverity, number>> = {\n info: 0,\n warn: 1,\n error: 2,\n};\n\nconst compareSeverity = (\n left: ViolationSeverity | null,\n right: ViolationSeverity | null,\n): ViolationSeverity | null => {\n if (left === null) {\n return right;\n }\n if (right === null) {\n return left;\n }\n\n return severityRank[left] >= severityRank[right] ? left : right;\n};\n\nconst stableSortViolations = (violations: readonly Violation[]): readonly Violation[] =>\n [...violations].sort((a, b) => {\n const severity = severityRank[b.severity] - severityRank[a.severity];\n if (severity !== 0) {\n return severity;\n }\n\n if (a.id !== b.id) {\n return a.id.localeCompare(b.id);\n }\n\n const aTarget = a.targets[0] ?? \"\";\n const bTarget = b.targets[0] ?? \"\";\n if (aTarget !== bTarget) {\n return aTarget.localeCompare(bTarget);\n }\n\n return a.message.localeCompare(b.message);\n });\n\nconst makeViolation = (\n id: string,\n severity: ViolationSeverity,\n message: string,\n targets: readonly string[],\n evidenceRefs: readonly EvidenceRef[],\n): Violation => ({\n id,\n severity,\n message,\n targets: [...targets].sort((a, b) => a.localeCompare(b)),\n evidenceRefs,\n});\n\nconst requireDiff = (input: GateEvaluationInput, gateId: string): void => {\n if (input.baseline === undefined || input.diff === undefined) {\n throw new GovernanceConfigurationError(`${gateId} requires --compare <baseline.json>`);\n }\n};\n\nconst validateGateConfig = (input: GateEvaluationInput): void => {\n const config = input.gateConfig;\n\n if (\n config.maxRiskDelta !== undefined &&\n (!Number.isFinite(config.maxRiskDelta) || config.maxRiskDelta < 0)\n ) {\n throw new GovernanceConfigurationError(\"max-risk-delta must be a finite number >= 0\");\n }\n\n if (\n config.maxHealthDelta !== undefined &&\n (!Number.isFinite(config.maxHealthDelta) || config.maxHealthDelta < 0)\n ) {\n throw new GovernanceConfigurationError(\"max-health-delta must be a finite number >= 0\");\n }\n\n if (\n config.maxNewHotspots !== undefined &&\n (!Number.isInteger(config.maxNewHotspots) || config.maxNewHotspots < 0)\n ) {\n throw new GovernanceConfigurationError(\"max-new-hotspots must be an integer >= 0\");\n }\n\n if (\n config.maxRiskScore !== undefined &&\n (!Number.isFinite(config.maxRiskScore) || config.maxRiskScore < 0 || config.maxRiskScore > 100)\n ) {\n throw new GovernanceConfigurationError(\"max-risk-score must be a number in [0, 100]\");\n }\n\n if (\n config.minHealthScore !== undefined &&\n (!Number.isFinite(config.minHealthScore) ||\n config.minHealthScore < 0 ||\n config.minHealthScore > 100)\n ) {\n throw new GovernanceConfigurationError(\"min-health-score must be a number in [0, 100]\");\n }\n\n if (\n config.newHotspotScoreThreshold !== undefined &&\n (!Number.isFinite(config.newHotspotScoreThreshold) ||\n config.newHotspotScoreThreshold < 0 ||\n config.newHotspotScoreThreshold > 100)\n ) {\n throw new GovernanceConfigurationError(\n \"new-hotspot-score-threshold must be a number in [0, 100]\",\n );\n }\n\n if (\n config.maxUnownedCritical !== undefined &&\n (!Number.isInteger(config.maxUnownedCritical) || config.maxUnownedCritical < 0)\n ) {\n throw new GovernanceConfigurationError(\"max-unowned-critical must be an integer >= 0\");\n }\n\n if (\n config.maxGhostOwners !== undefined &&\n (!Number.isInteger(config.maxGhostOwners) || config.maxGhostOwners < 0)\n ) {\n throw new GovernanceConfigurationError(\"max-ghost-owners must be an integer >= 0\");\n }\n\n if (\n config.maxDrift !== undefined &&\n (!Number.isFinite(config.maxDrift) || config.maxDrift < 0 || config.maxDrift > 1)\n ) {\n throw new GovernanceConfigurationError(\"max-drift must be a ratio between 0 and 1\");\n }\n};\n\nexport const evaluateGates = (input: GateEvaluationInput): GateEvaluationResult => {\n validateGateConfig(input);\n\n const config = input.gateConfig;\n const violations: Violation[] = [];\n const evaluatedGates: string[] = [];\n const warnings: string[] = [];\n\n if (config.maxRiskScore !== undefined) {\n evaluatedGates.push(\"max-risk-score\");\n const current = input.current.analysis.risk.riskScore;\n if (current > config.maxRiskScore) {\n violations.push(\n makeViolation(\n \"max-risk-score\",\n \"error\",\n `Risk score ${current} exceeds configured max ${config.maxRiskScore}.`,\n [input.current.analysis.structural.targetPath],\n [{ kind: \"repository_metric\", metric: \"riskScore\" }],\n ),\n );\n }\n }\n\n if (config.minHealthScore !== undefined) {\n evaluatedGates.push(\"min-health-score\");\n const current = input.current.analysis.health.healthScore;\n if (current < config.minHealthScore) {\n violations.push(\n makeViolation(\n \"min-health-score\",\n \"error\",\n `Health score ${current} is below configured minimum ${config.minHealthScore}.`,\n [input.current.analysis.structural.targetPath],\n [{ kind: \"repository_metric\", metric: \"healthScore\" }],\n ),\n );\n }\n }\n\n if (config.maxRiskDelta !== undefined) {\n evaluatedGates.push(\"max-risk-delta\");\n requireDiff(input, \"max-risk-delta\");\n const baseline = input.baseline;\n if (baseline === undefined) {\n throw new GovernanceConfigurationError(\"max-risk-delta requires baseline snapshot\");\n }\n\n const delta =\n input.current.analysis.risk.normalizedScore - baseline.analysis.risk.normalizedScore;\n if (delta > config.maxRiskDelta) {\n violations.push(\n makeViolation(\n \"max-risk-delta\",\n \"error\",\n `Risk normalized score delta ${delta.toFixed(4)} exceeds allowed ${config.maxRiskDelta}.`,\n [input.current.analysis.structural.targetPath],\n [{ kind: \"repository_metric\", metric: \"normalizedScore\" }],\n ),\n );\n }\n }\n\n if (config.maxHealthDelta !== undefined) {\n evaluatedGates.push(\"max-health-delta\");\n requireDiff(input, \"max-health-delta\");\n const baseline = input.baseline;\n if (baseline === undefined) {\n throw new GovernanceConfigurationError(\"max-health-delta requires baseline snapshot\");\n }\n\n const delta =\n input.current.analysis.health.normalizedScore - baseline.analysis.health.normalizedScore;\n if (delta < -config.maxHealthDelta) {\n violations.push(\n makeViolation(\n \"max-health-delta\",\n \"error\",\n `Health normalized score delta ${delta.toFixed(4)} is below allowed minimum ${(-config.maxHealthDelta).toFixed(4)}.`,\n [input.current.analysis.structural.targetPath],\n [{ kind: \"repository_metric\", metric: \"healthNormalizedScore\" }],\n ),\n );\n }\n }\n\n if (config.noNewCycles === true) {\n evaluatedGates.push(\"no-new-cycles\");\n requireDiff(input, \"no-new-cycles\");\n const diff = input.diff;\n if (diff === undefined) {\n throw new GovernanceConfigurationError(\"no-new-cycles requires diff\");\n }\n if (diff.newCycles.length > 0) {\n violations.push(\n makeViolation(\n \"no-new-cycles\",\n \"error\",\n `Detected ${diff.newCycles.length} new structural cycle(s).`,\n diff.newCycles,\n [{ kind: \"repository_metric\", metric: \"cycleCount\" }],\n ),\n );\n }\n }\n\n if (config.noNewHighRiskDeps === true) {\n evaluatedGates.push(\"no-new-high-risk-deps\");\n requireDiff(input, \"no-new-high-risk-deps\");\n const diff = input.diff;\n if (diff === undefined) {\n throw new GovernanceConfigurationError(\"no-new-high-risk-deps requires diff\");\n }\n if (diff.externalChanges.highRiskAdded.length > 0) {\n violations.push(\n makeViolation(\n \"no-new-high-risk-deps\",\n \"error\",\n `Detected ${diff.externalChanges.highRiskAdded.length} new high-risk dependency(ies).`,\n diff.externalChanges.highRiskAdded,\n diff.externalChanges.highRiskAdded.map((name) => ({\n kind: \"dependency_metric\",\n target: name,\n metric: \"highRiskDependencies\",\n })),\n ),\n );\n }\n }\n\n if (config.maxNewHotspots !== undefined) {\n evaluatedGates.push(\"max-new-hotspots\");\n requireDiff(input, \"max-new-hotspots\");\n const diff = input.diff;\n if (diff === undefined) {\n throw new GovernanceConfigurationError(\"max-new-hotspots requires diff\");\n }\n\n const scoreByFile = new Map(\n input.current.analysis.risk.fileScores.map((item) => [item.file, item.score]),\n );\n const threshold = config.newHotspotScoreThreshold ?? DEFAULT_NEW_HOTSPOT_SCORE_THRESHOLD;\n const counted = diff.newHotspots.filter((file) => (scoreByFile.get(file) ?? 0) >= threshold);\n\n if (counted.length > config.maxNewHotspots) {\n violations.push(\n makeViolation(\n \"max-new-hotspots\",\n \"warn\",\n `Detected ${counted.length} new hotspot(s) above score ${threshold}; allowed max is ${config.maxNewHotspots}.`,\n counted,\n counted.map((file) => ({ kind: \"file_metric\", target: file, metric: \"score\" })),\n ),\n );\n }\n }\n\n const ownershipConfigured =\n config.maxUnownedCritical !== undefined ||\n config.maxGhostOwners !== undefined ||\n config.maxDrift !== undefined;\n\n let ownership: OwnershipGateResult | undefined;\n\n if (ownershipConfigured) {\n const ownershipInput = input.ownership;\n if (ownershipInput === undefined) {\n warnings.push(\"ownership gates were not evaluated: no ownership input was provided.\");\n ownership = { evaluated: false, source: null, metrics: null };\n } else if (!ownershipInput.available) {\n warnings.push(...ownershipInput.warnings);\n warnings.push(\"ownership gates were not evaluated: no CODEOWNERS file was found.\");\n ownership = { evaluated: false, source: null, metrics: null };\n } else {\n const metrics = ownershipInput.metrics;\n ownership = {\n evaluated: true,\n source: ownershipInput.source,\n metrics,\n };\n\n if (config.maxUnownedCritical !== undefined) {\n evaluatedGates.push(\"max-unowned-critical\");\n if (metrics.unownedCriticalCount > config.maxUnownedCritical) {\n violations.push(\n makeViolation(\n \"max-unowned-critical\",\n \"error\",\n `Unowned critical files ${metrics.unownedCriticalCount} exceeds configured max ${config.maxUnownedCritical}.`,\n [],\n [{ kind: \"repository_metric\", metric: \"unownedCriticalCount\" }],\n ),\n );\n }\n }\n\n if (config.maxGhostOwners !== undefined) {\n evaluatedGates.push(\"max-ghost-owners\");\n if (metrics.ghostOwnerCount > config.maxGhostOwners) {\n violations.push(\n makeViolation(\n \"max-ghost-owners\",\n \"error\",\n `Ghost owners ${metrics.ghostOwnerCount} exceeds configured max ${config.maxGhostOwners}.`,\n [],\n [{ kind: \"repository_metric\", metric: \"ghostOwnerCount\" }],\n ),\n );\n }\n }\n\n if (config.maxDrift !== undefined) {\n evaluatedGates.push(\"max-drift\");\n const ratio = metrics.driftPercent / 100;\n if (ratio > config.maxDrift) {\n violations.push(\n makeViolation(\n \"max-drift\",\n \"error\",\n `Ownership drift ratio ${ratio.toFixed(4)} exceeds configured max ${config.maxDrift}.`,\n [],\n [{ kind: \"repository_metric\", metric: \"driftPercent\" }],\n ),\n );\n }\n }\n }\n }\n\n const ordered = stableSortViolations(violations);\n const highestSeverity = ordered.reduce<ViolationSeverity | null>(\n (current, violation) => compareSeverity(current, violation.severity),\n null,\n );\n\n const exitCode: 0 | 1 | 2 =\n highestSeverity === \"error\"\n ? 1\n : highestSeverity === \"warn\" && config.failOn === \"warn\"\n ? 2\n : 0;\n\n return {\n violations: ordered,\n highestSeverity,\n exitCode,\n evaluatedGates: [...evaluatedGates].sort((a, b) => a.localeCompare(b)),\n warnings: [...warnings],\n ...(ownership === undefined ? {} : { ownership }),\n };\n};\n","import { factorLabel, summarizeEvidence, type CodeSentinelSnapshot } from \"@codesentinel/reporter\";\nimport type { GateEvaluationResult, Violation } from \"./domain.js\";\n\nconst renderViolationText = (violation: Violation): string => {\n const targets = violation.targets.join(\", \") || \"n/a\";\n return `- [${violation.severity}] ${violation.id}: ${violation.message} (targets: ${targets})`;\n};\n\nexport const renderCheckText = (\n snapshot: CodeSentinelSnapshot,\n result: GateEvaluationResult,\n): string => {\n const lines: string[] = [];\n lines.push(\"CodeSentinel Check\");\n lines.push(`target: ${snapshot.analysis.structural.targetPath}`);\n lines.push(`riskScore: ${snapshot.analysis.risk.riskScore}`);\n lines.push(`evaluatedGates: ${result.evaluatedGates.join(\", \") || \"none\"}`);\n lines.push(`violations: ${result.violations.length}`);\n lines.push(`exitCode: ${result.exitCode}`);\n lines.push(\"\");\n lines.push(\"Violations\");\n if (result.violations.length === 0) {\n lines.push(\"- none\");\n } else {\n for (const violation of result.violations) {\n lines.push(renderViolationText(violation));\n }\n }\n\n if (result.ownership !== undefined) {\n lines.push(\"\");\n lines.push(\"Ownership\");\n lines.push(`evaluated: ${result.ownership.evaluated}`);\n lines.push(`source: ${result.ownership.source ?? \"none\"}`);\n if (result.ownership.metrics !== null) {\n const metrics = result.ownership.metrics;\n lines.push(`declaredCoverage: ${metrics.declaredCoveragePercent}`);\n lines.push(`declaredCoverageCritical: ${metrics.declaredCoverageCriticalPercent}`);\n lines.push(`unownedCritical: ${metrics.unownedCriticalCount}`);\n lines.push(`ghostOwners: ${metrics.ghostOwnerCount}`);\n lines.push(`driftPercent: ${metrics.driftPercent}`);\n }\n }\n\n if (result.warnings.length > 0) {\n lines.push(\"\");\n lines.push(\"Warnings\");\n for (const warning of result.warnings) {\n lines.push(`- ${warning}`);\n }\n }\n\n return lines.join(\"\\n\");\n};\n\nexport const renderCheckMarkdown = (\n snapshot: CodeSentinelSnapshot,\n result: GateEvaluationResult,\n): string => {\n const lines: string[] = [];\n lines.push(\"## CodeSentinel CI Summary\");\n lines.push(`- target: \\`${snapshot.analysis.structural.targetPath}\\``);\n lines.push(`- riskScore: \\`${snapshot.analysis.risk.riskScore}\\``);\n lines.push(\n `- evaluatedGates: ${result.evaluatedGates.map((item) => `\\`${item}\\``).join(\", \") || \"none\"}`,\n );\n lines.push(`- violations: \\`${result.violations.length}\\``);\n lines.push(`- exitCode: \\`${result.exitCode}\\``);\n\n const repositoryTrace = snapshot.trace?.targets.find(\n (target) =>\n target.targetType === \"repository\" &&\n target.targetId === snapshot.analysis.structural.targetPath,\n );\n if (repositoryTrace !== undefined) {\n lines.push(\"\");\n lines.push(\"### Why\");\n const topFactors = [...repositoryTrace.factors]\n .sort((a, b) => b.contribution - a.contribution || a.factorId.localeCompare(b.factorId))\n .slice(0, 3);\n\n for (const factor of topFactors) {\n lines.push(\n `- ${factorLabel(factor.factorId)}: contribution=\\`${factor.contribution}\\`, evidence=\\`${summarizeEvidence(factor)}\\``,\n );\n }\n }\n\n if (result.ownership !== undefined) {\n lines.push(\"\");\n lines.push(\"### Ownership\");\n lines.push(\n `- codeowners: ${result.ownership.source === null ? \"none\" : `\\`${result.ownership.source}\\``}`,\n );\n lines.push(`- evaluated: \\`${result.ownership.evaluated}\\``);\n if (result.ownership.metrics !== null) {\n const metrics = result.ownership.metrics;\n lines.push(\n `- declared coverage: \\`${metrics.declaredCoveragePercent}%\\` (critical \\`${metrics.declaredCoverageCriticalPercent}%\\`)`,\n );\n lines.push(`- unowned critical: \\`${metrics.unownedCriticalCount}\\``);\n lines.push(`- ghost owners: \\`${metrics.ghostOwnerCount}\\``);\n lines.push(`- drift: \\`${metrics.driftPercent}%\\``);\n }\n }\n\n if (result.warnings.length > 0) {\n lines.push(\"\");\n lines.push(\"### Warnings\");\n for (const warning of result.warnings) {\n lines.push(`- ${warning}`);\n }\n }\n\n lines.push(\"\");\n lines.push(\"### Violations\");\n if (result.violations.length === 0) {\n lines.push(\"- none\");\n } else {\n for (const violation of result.violations) {\n lines.push(`- [${violation.severity}] **${violation.id}**: ${violation.message}`);\n if (violation.targets.length > 0) {\n lines.push(` - targets: ${violation.targets.map((target) => `\\`${target}\\``).join(\", \")}`);\n }\n }\n }\n\n return lines.join(\"\\n\");\n};\n","import { mkdirSync, rmSync } from \"node:fs\";\nimport { basename, join, resolve } from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { CodeSentinelSnapshot } from \"@codesentinel/reporter\";\nimport {\n BaselineAutoResolutionError,\n resolveAutoBaseline,\n type BaselineAutoResolution,\n type GitCommandResult,\n} from \"./baseline-auto-resolver.js\";\n\nconst execFileAsync = promisify(execFile);\n\nconst SENTINEL_TMP_DIR = \".codesentinel-tmp\";\nconst WORKTREE_DIR = \"worktrees\";\n\nexport class BaselineRefResolutionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"BaselineRefResolutionError\";\n }\n}\n\nconst runGit = async (repositoryPath: string, args: readonly string[]): Promise<string> => {\n const result = await tryRunGit(repositoryPath, args);\n if (result.ok) {\n return result.stdout;\n }\n throw new BaselineRefResolutionError(result.message);\n};\n\nconst tryRunGit = async (\n repositoryPath: string,\n args: readonly string[],\n): Promise<GitCommandResult> => {\n try {\n const { stdout } = await execFileAsync(\"git\", [\"-C\", repositoryPath, ...args], {\n encoding: \"utf8\",\n });\n return { ok: true, stdout: stdout.trim() };\n } catch (error) {\n const message = error instanceof Error ? error.message : \"unknown git error\";\n return { ok: false, message };\n }\n};\n\nconst buildWorktreePath = (repoRoot: string, sha: string): string => {\n const tmpRoot = join(repoRoot, SENTINEL_TMP_DIR, WORKTREE_DIR);\n mkdirSync(tmpRoot, { recursive: true });\n\n const baseName = `baseline-${sha.slice(0, 12)}-${process.pid}`;\n const candidate = resolve(tmpRoot, baseName);\n return candidate;\n};\n\nconst sanitizeSnapshotForWorktree = (\n snapshot: CodeSentinelSnapshot,\n worktreePath: string,\n canonicalPath: string,\n): CodeSentinelSnapshot => {\n const replacePrefix = (value: string): string =>\n value.startsWith(worktreePath) ? `${canonicalPath}${value.slice(worktreePath.length)}` : value;\n\n const structural = snapshot.analysis.structural;\n\n return {\n ...snapshot,\n source: {\n targetPath: replacePrefix(snapshot.source.targetPath),\n },\n analysis: {\n ...snapshot.analysis,\n structural: {\n ...structural,\n targetPath: replacePrefix(structural.targetPath),\n nodes: structural.nodes.map((node) => ({\n ...node,\n absolutePath: replacePrefix(node.absolutePath),\n })),\n },\n evolution: {\n ...snapshot.analysis.evolution,\n targetPath: replacePrefix(snapshot.analysis.evolution.targetPath),\n },\n external: {\n ...snapshot.analysis.external,\n targetPath: replacePrefix(snapshot.analysis.external.targetPath),\n },\n },\n };\n};\n\nexport type BaselineRefResolutionResult = {\n baselineSnapshot: CodeSentinelSnapshot;\n resolvedRef: string;\n resolvedSha: string;\n};\n\nexport type ResolveBaselineFromRefInput = {\n repositoryPath: string;\n baselineRef: string;\n analyzeWorktree: (worktreePath: string, repositoryRoot: string) => Promise<CodeSentinelSnapshot>;\n};\n\nexport type ResolveAutoBaselineRefInput = {\n repositoryPath: string;\n baselineSha?: string;\n mainBranchCandidates?: readonly string[];\n environment?: Readonly<Record<string, string | undefined>>;\n};\n\nexport const resolveBaselineSnapshotFromRef = async (\n input: ResolveBaselineFromRefInput,\n): Promise<BaselineRefResolutionResult> => {\n const repositoryPath = resolve(input.repositoryPath);\n const ref = input.baselineRef.trim();\n if (ref.length === 0) {\n throw new BaselineRefResolutionError(\"baseline-ref cannot be empty\");\n }\n\n const repoRoot = await runGit(repositoryPath, [\"rev-parse\", \"--show-toplevel\"]);\n const sha = await runGit(repositoryPath, [\"rev-parse\", \"--verify\", `${ref}^{commit}`]);\n\n const worktreePath = buildWorktreePath(repoRoot, sha);\n\n const cleanup = (): void => {\n try {\n rmSync(worktreePath, { recursive: true, force: true });\n } catch {\n // Best-effort fallback cleanup if worktree remove fails.\n }\n };\n\n try {\n await runGit(repoRoot, [\"worktree\", \"add\", \"--detach\", worktreePath, sha]);\n\n const snapshot = await input.analyzeWorktree(worktreePath, repoRoot);\n const sanitized = sanitizeSnapshotForWorktree(snapshot, worktreePath, repoRoot);\n\n return {\n baselineSnapshot: sanitized,\n resolvedRef: ref,\n resolvedSha: sha,\n };\n } finally {\n try {\n await runGit(repoRoot, [\"worktree\", \"remove\", \"--force\", worktreePath]);\n } catch {\n cleanup();\n }\n }\n};\n\nexport const baselineTempDirectoryName = (): string =>\n basename(join(SENTINEL_TMP_DIR, WORKTREE_DIR));\n\nexport const resolveAutoBaselineRef = async (\n input: ResolveAutoBaselineRefInput,\n): Promise<BaselineAutoResolution> => {\n const repositoryPath = resolve(input.repositoryPath);\n const repoRoot = await runGit(repositoryPath, [\"rev-parse\", \"--show-toplevel\"]);\n\n try {\n return await resolveAutoBaseline({\n ...(input.baselineSha === undefined ? {} : { baselineSha: input.baselineSha }),\n ...(input.environment === undefined ? {} : { environment: input.environment }),\n ...(input.mainBranchCandidates === undefined\n ? {}\n : { mainBranchCandidates: input.mainBranchCandidates }),\n git: {\n resolveCommit: async (ref: string): Promise<GitCommandResult> =>\n tryRunGit(repoRoot, [\"rev-parse\", \"--verify\", ref]),\n mergeBase: async (leftRef: string, rightRef: string): Promise<GitCommandResult> =>\n tryRunGit(repoRoot, [\"merge-base\", leftRef, rightRef]),\n currentBranch: async (): Promise<GitCommandResult> =>\n tryRunGit(repoRoot, [\"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"]),\n isShallowRepository: async (): Promise<GitCommandResult> =>\n tryRunGit(repoRoot, [\"rev-parse\", \"--is-shallow-repository\"]),\n },\n });\n } catch (error) {\n if (error instanceof BaselineAutoResolutionError) {\n throw new BaselineRefResolutionError(error.message);\n }\n throw error;\n }\n};\n","export class BaselineAutoResolutionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"BaselineAutoResolutionError\";\n }\n}\n\nexport type BaselineAutoResolutionStrategy =\n | \"explicit_sha\"\n | \"ci_base_branch\"\n | \"main_branch_previous_commit\"\n | \"feature_branch_merge_base\";\n\nexport type BaselineAutoResolutionAttempt = {\n step: string;\n candidate: string;\n outcome: \"resolved\" | \"failed\" | \"skipped\";\n detail?: string;\n};\n\nexport type BaselineAutoResolution = {\n strategy: BaselineAutoResolutionStrategy;\n resolvedRef: string;\n resolvedSha: string;\n attempts: readonly BaselineAutoResolutionAttempt[];\n baseBranch?: string;\n};\n\nexport type GitCommandResult = { ok: true; stdout: string } | { ok: false; message: string };\n\nexport type BaselineAutoGitAdapter = {\n resolveCommit: (ref: string) => Promise<GitCommandResult>;\n mergeBase: (leftRef: string, rightRef: string) => Promise<GitCommandResult>;\n currentBranch: () => Promise<GitCommandResult>;\n isShallowRepository: () => Promise<GitCommandResult>;\n};\n\nexport type ResolveAutoBaselineInput = {\n baselineSha?: string;\n environment?: Readonly<Record<string, string | undefined>>;\n mainBranchCandidates?: readonly string[];\n git: BaselineAutoGitAdapter;\n};\n\nconst DEFAULT_MAIN_BRANCH_CANDIDATES = [\"main\", \"master\"] as const;\n\nconst providerBaseBranchKeys = [\n \"GITHUB_BASE_REF\",\n \"CI_MERGE_REQUEST_TARGET_BRANCH_NAME\",\n \"BITBUCKET_PR_DESTINATION_BRANCH\",\n] as const;\n\nconst normalizeMainBranches = (input: readonly string[] | undefined): readonly string[] => {\n const source = input === undefined || input.length === 0 ? DEFAULT_MAIN_BRANCH_CANDIDATES : input;\n const seen = new Set<string>();\n const values: string[] = [];\n\n for (const candidate of source) {\n const trimmed = candidate.trim();\n if (trimmed.length === 0 || seen.has(trimmed)) {\n continue;\n }\n seen.add(trimmed);\n values.push(trimmed);\n }\n\n return values.length > 0 ? values : DEFAULT_MAIN_BRANCH_CANDIDATES;\n};\n\nconst firstNonEmptyEnv = (\n environment: Readonly<Record<string, string | undefined>>,\n): { key: string; value: string } | undefined => {\n for (const key of providerBaseBranchKeys) {\n const value = environment[key]?.trim();\n if (value !== undefined && value.length > 0) {\n return { key, value };\n }\n }\n return undefined;\n};\n\nconst asBoolean = (value: string): boolean => {\n return value.trim().toLowerCase() === \"true\";\n};\n\nconst buildNoBaselineMessage = (): string => {\n return \"unable to resolve auto baseline; set --baseline-ref <ref> explicitly or provide --baseline <snapshot.json>\";\n};\n\nexport const resolveAutoBaseline = async (\n input: ResolveAutoBaselineInput,\n): Promise<BaselineAutoResolution> => {\n const attempts: BaselineAutoResolutionAttempt[] = [];\n const mainBranches = normalizeMainBranches(input.mainBranchCandidates);\n const environment = input.environment ?? {};\n\n const baselineSha = input.baselineSha?.trim();\n if (baselineSha !== undefined && baselineSha.length > 0) {\n const result = await input.git.resolveCommit(`${baselineSha}^{commit}`);\n if (result.ok) {\n attempts.push({ step: \"explicit-sha\", candidate: baselineSha, outcome: \"resolved\" });\n return {\n strategy: \"explicit_sha\",\n resolvedRef: baselineSha,\n resolvedSha: result.stdout,\n attempts,\n };\n }\n\n attempts.push({\n step: \"explicit-sha\",\n candidate: baselineSha,\n outcome: \"failed\",\n detail: result.message,\n });\n throw new BaselineAutoResolutionError(\n `invalid --baseline-sha '${baselineSha}': ${result.message}`,\n );\n }\n\n const providerBaseBranch = firstNonEmptyEnv(environment);\n if (providerBaseBranch !== undefined) {\n const originRef = `origin/${providerBaseBranch.value}`;\n const originResult = await input.git.resolveCommit(`${originRef}^{commit}`);\n if (originResult.ok) {\n attempts.push({\n step: `ci-base-branch:${providerBaseBranch.key}`,\n candidate: originRef,\n outcome: \"resolved\",\n });\n return {\n strategy: \"ci_base_branch\",\n resolvedRef: originRef,\n resolvedSha: originResult.stdout,\n attempts,\n baseBranch: providerBaseBranch.value,\n };\n }\n attempts.push({\n step: `ci-base-branch:${providerBaseBranch.key}`,\n candidate: originRef,\n outcome: \"failed\",\n detail: originResult.message,\n });\n\n const localRef = providerBaseBranch.value;\n const localResult = await input.git.resolveCommit(`${localRef}^{commit}`);\n if (localResult.ok) {\n attempts.push({\n step: `ci-base-branch-local:${providerBaseBranch.key}`,\n candidate: localRef,\n outcome: \"resolved\",\n });\n return {\n strategy: \"ci_base_branch\",\n resolvedRef: localRef,\n resolvedSha: localResult.stdout,\n attempts,\n baseBranch: providerBaseBranch.value,\n };\n }\n attempts.push({\n step: `ci-base-branch-local:${providerBaseBranch.key}`,\n candidate: localRef,\n outcome: \"failed\",\n detail: localResult.message,\n });\n } else {\n attempts.push({\n step: \"ci-base-branch\",\n candidate: providerBaseBranchKeys.join(\",\"),\n outcome: \"skipped\",\n detail: \"no CI base branch environment variable found\",\n });\n }\n\n const branchResult = await input.git.currentBranch();\n const branchName = branchResult.ok ? branchResult.stdout.trim() : undefined;\n if (branchName !== undefined && mainBranches.includes(branchName)) {\n const headPrevious = await input.git.resolveCommit(\"HEAD~1^{commit}\");\n if (headPrevious.ok) {\n attempts.push({\n step: \"main-branch-head-previous\",\n candidate: \"HEAD~1\",\n outcome: \"resolved\",\n });\n return {\n strategy: \"main_branch_previous_commit\",\n resolvedRef: \"HEAD~1\",\n resolvedSha: headPrevious.stdout,\n attempts,\n };\n }\n attempts.push({\n step: \"main-branch-head-previous\",\n candidate: \"HEAD~1\",\n outcome: \"failed\",\n detail: headPrevious.message,\n });\n throw new BaselineAutoResolutionError(\n `unable to resolve baseline from HEAD~1 on branch '${branchName}': ${headPrevious.message}`,\n );\n }\n\n if (branchName === undefined) {\n attempts.push({\n step: \"current-branch\",\n candidate: \"HEAD\",\n outcome: \"skipped\",\n detail: \"detached HEAD or symbolic-ref unavailable\",\n });\n } else {\n attempts.push({\n step: \"current-branch\",\n candidate: branchName,\n outcome: \"resolved\",\n detail: \"feature branch detected\",\n });\n }\n\n const mergeBaseCandidates = [\n ...mainBranches.map((candidate) => `origin/${candidate}`),\n ...mainBranches,\n ];\n\n for (const candidate of mergeBaseCandidates) {\n const mergeBase = await input.git.mergeBase(\"HEAD\", candidate);\n if (mergeBase.ok) {\n attempts.push({\n step: \"merge-base\",\n candidate: `HEAD..${candidate}`,\n outcome: \"resolved\",\n });\n return {\n strategy: \"feature_branch_merge_base\",\n resolvedRef: mergeBase.stdout,\n resolvedSha: mergeBase.stdout,\n attempts,\n };\n }\n attempts.push({\n step: \"merge-base\",\n candidate: `HEAD..${candidate}`,\n outcome: \"failed\",\n detail: mergeBase.message,\n });\n }\n\n const shallowResult = await input.git.isShallowRepository();\n const shallowRepository = shallowResult.ok && asBoolean(shallowResult.stdout);\n if (shallowRepository) {\n throw new BaselineAutoResolutionError(\n `${buildNoBaselineMessage()}; repository appears shallow. Fetch full history (for example: git fetch --unshallow or fetch-depth: 0).`,\n );\n }\n\n throw new BaselineAutoResolutionError(buildNoBaselineMessage());\n};\n","import type { AnalyzeSummary } from \"@codesentinel/core\";\n\nexport type AnalyzeOutputMode = \"summary\" | \"json\";\n\ntype EvolutionAvailable = Extract<AnalyzeSummary[\"evolution\"], { available: true }>;\ntype ExternalAvailable = Extract<AnalyzeSummary[\"external\"], { available: true }>;\ntype WorkspaceSummaryShape = {\n structuralTop: ReadonlyArray<{\n path: string;\n fileCount: number;\n internalEdgeCount: number;\n incomingEdgeCount: number;\n outgoingEdgeCount: number;\n }>;\n riskTop: ReadonlyArray<{\n path: string;\n score: number;\n fileCount: number;\n peakFileRisk: number;\n }>;\n evolutionTop: ReadonlyArray<{\n path: string;\n commitCount: number;\n churnTotal: number;\n recentVolatility: number;\n }>;\n dependencyExposureTop: ReadonlyArray<{\n path: string;\n directDependencies: number;\n sharedDependencies: number;\n highRiskDependencies: number;\n transitiveExposureDependencies: number;\n }>;\n};\n\nconst toHealthTier = (score: number): \"critical\" | \"weak\" | \"fair\" | \"good\" | \"excellent\" => {\n if (score < 20) {\n return \"critical\";\n }\n if (score < 40) {\n return \"weak\";\n }\n if (score < 60) {\n return \"fair\";\n }\n if (score < 80) {\n return \"good\";\n }\n return \"excellent\";\n};\n\ntype SummaryShape = {\n targetPath: string;\n structural: AnalyzeSummary[\"structural\"][\"metrics\"];\n evolution:\n | {\n available: false;\n reason: \"not_git_repository\";\n }\n | {\n available: true;\n metrics: EvolutionAvailable[\"metrics\"];\n hotspotsTop: readonly string[];\n };\n external:\n | {\n available: false;\n reason:\n | \"package_json_not_found\"\n | \"lockfile_not_found\"\n | \"unsupported_lockfile_format\"\n | \"invalid_lockfile\";\n }\n | {\n available: true;\n metrics: ExternalAvailable[\"metrics\"];\n highRiskDependenciesTop: readonly string[];\n highRiskDevelopmentDependenciesTop: readonly string[];\n transitiveExposureDependenciesTop: readonly string[];\n };\n risk: {\n riskScore: number;\n normalizedScore: number;\n hotspotsTop: ReadonlyArray<{\n file: string;\n score: number;\n }>;\n fragileClusterCount: number;\n dependencyAmplificationZoneCount: number;\n };\n workspaces: WorkspaceSummaryShape;\n health: {\n healthScore: number;\n healthTier: \"critical\" | \"weak\" | \"fair\" | \"good\" | \"excellent\";\n normalizedScore: number;\n dimensions: AnalyzeSummary[\"health\"][\"dimensions\"];\n topIssues: AnalyzeSummary[\"health\"][\"topIssues\"];\n };\n};\n\nconst createWorkspaceSummaryShape = (summary: AnalyzeSummary): WorkspaceSummaryShape => ({\n structuralTop: [...(summary.structural.workspaces ?? [])]\n .sort(\n (a, b) =>\n b.incomingEdgeCount +\n b.outgoingEdgeCount +\n b.internalEdgeCount -\n (a.incomingEdgeCount + a.outgoingEdgeCount + a.internalEdgeCount) ||\n b.fileCount - a.fileCount ||\n a.path.localeCompare(b.path),\n )\n .slice(0, 5)\n .map((workspace) => ({\n path: workspace.path,\n fileCount: workspace.fileCount,\n internalEdgeCount: workspace.internalEdgeCount,\n incomingEdgeCount: workspace.incomingEdgeCount,\n outgoingEdgeCount: workspace.outgoingEdgeCount,\n })),\n riskTop: [...summary.risk.workspaceScores]\n .sort((a, b) => b.score - a.score || a.path.localeCompare(b.path))\n .slice(0, 5)\n .map((workspace) => ({\n path: workspace.path,\n score: workspace.score,\n fileCount: workspace.fileCount,\n peakFileRisk: workspace.peakFileRisk,\n })),\n evolutionTop: summary.evolution.available\n ? [...(summary.evolution.workspaces ?? [])]\n .sort(\n (a, b) =>\n b.recentVolatility - a.recentVolatility ||\n b.churnTotal - a.churnTotal ||\n b.commitCount - a.commitCount ||\n a.path.localeCompare(b.path),\n )\n .slice(0, 5)\n .map((workspace) => ({\n path: workspace.path,\n commitCount: workspace.commitCount,\n churnTotal: workspace.churnTotal,\n recentVolatility: workspace.recentVolatility,\n }))\n : [],\n dependencyExposureTop: summary.external.available\n ? [...(summary.external.workspaces ?? [])]\n .sort(\n (a, b) =>\n b.highRiskDependencies.length - a.highRiskDependencies.length ||\n b.transitiveExposureDependencies.length - a.transitiveExposureDependencies.length ||\n b.directDependencies - a.directDependencies ||\n a.path.localeCompare(b.path),\n )\n .slice(0, 5)\n .map((workspace) => ({\n path: workspace.path,\n directDependencies: workspace.directDependencies,\n sharedDependencies: workspace.sharedDependencies.length,\n highRiskDependencies: workspace.highRiskDependencies.length,\n transitiveExposureDependencies: workspace.transitiveExposureDependencies.length,\n }))\n : [],\n});\n\nconst createSummaryShape = (summary: AnalyzeSummary): SummaryShape => ({\n targetPath: summary.structural.targetPath,\n structural: summary.structural.metrics,\n evolution: summary.evolution.available\n ? {\n available: true,\n metrics: summary.evolution.metrics,\n hotspotsTop: summary.evolution.hotspots.slice(0, 5).map((hotspot) => hotspot.filePath),\n }\n : {\n available: false,\n reason: summary.evolution.reason,\n },\n external: summary.external.available\n ? {\n available: true,\n metrics: summary.external.metrics,\n highRiskDependenciesTop: summary.external.highRiskDependencies.slice(0, 10),\n highRiskDevelopmentDependenciesTop: summary.external.highRiskDevelopmentDependencies.slice(\n 0,\n 10,\n ),\n transitiveExposureDependenciesTop: summary.external.transitiveExposureDependencies.slice(\n 0,\n 10,\n ),\n }\n : {\n available: false,\n reason: summary.external.reason,\n },\n risk: {\n riskScore: summary.risk.riskScore,\n normalizedScore: summary.risk.normalizedScore,\n hotspotsTop: summary.risk.hotspots.slice(0, 5).map((hotspot) => ({\n file: hotspot.file,\n score: hotspot.score,\n })),\n fragileClusterCount: summary.risk.fragileClusters.length,\n dependencyAmplificationZoneCount: summary.risk.dependencyAmplificationZones.length,\n },\n workspaces: createWorkspaceSummaryShape(summary),\n health: {\n healthScore: summary.health.healthScore,\n healthTier: toHealthTier(summary.health.healthScore),\n normalizedScore: summary.health.normalizedScore,\n dimensions: summary.health.dimensions,\n topIssues: summary.health.topIssues.slice(0, 5),\n },\n});\n\nexport const formatAnalyzeOutput = (summary: AnalyzeSummary, mode: AnalyzeOutputMode): string =>\n mode === \"json\"\n ? JSON.stringify(summary, null, 2)\n : JSON.stringify(createSummaryShape(summary), null, 2);\n","import type { AnalyzeSummary, RiskFactorTrace, RiskTrace, TargetTrace } from \"@codesentinel/core\";\nimport type { ExplainFormat } from \"./run-explain-command.js\";\n\nexport type ExplainOutputPayload = {\n summary: AnalyzeSummary;\n trace: RiskTrace;\n selectedTargets: readonly TargetTrace[];\n};\n\nconst sortFactorByContribution = (left: RiskFactorTrace, right: RiskFactorTrace): number =>\n right.contribution - left.contribution || left.factorId.localeCompare(right.factorId);\n\nconst toRiskBand = (score: number): \"low\" | \"moderate\" | \"elevated\" | \"high\" | \"very_high\" => {\n if (score < 20) {\n return \"low\";\n }\n if (score < 40) {\n return \"moderate\";\n }\n if (score < 60) {\n return \"elevated\";\n }\n if (score < 80) {\n return \"high\";\n }\n return \"very_high\";\n};\n\nconst factorLabelById: Readonly<Record<string, string>> = {\n \"repository.structural\": \"Structural complexity\",\n \"repository.evolution\": \"Change volatility\",\n \"repository.external\": \"External dependency pressure\",\n \"repository.composite.interactions\": \"Intersection amplification\",\n \"file.structural\": \"File structural complexity\",\n \"file.evolution\": \"File change volatility\",\n \"file.external\": \"File external pressure\",\n \"file.composite.interactions\": \"File interaction amplification\",\n \"module.average_file_risk\": \"Average file risk\",\n \"module.peak_file_risk\": \"Peak file risk\",\n \"dependency.signals\": \"Dependency risk signals\",\n \"dependency.staleness\": \"Dependency staleness\",\n \"dependency.maintainer_concentration\": \"Maintainer concentration\",\n \"dependency.topology\": \"Dependency topology pressure\",\n \"dependency.bus_factor\": \"Dependency bus factor\",\n \"dependency.popularity_dampening\": \"Popularity dampening\",\n};\n\nconst formatFactorLabel = (factorId: string): string => factorLabelById[factorId] ?? factorId;\n\nconst formatNumber = (value: number | null | undefined): string =>\n value === null || value === undefined ? \"n/a\" : `${value}`;\n\nconst formatDimension = (value: number | null): string => (value === null ? \"n/a\" : `${value}`);\n\nconst formatFactorSummary = (factor: RiskFactorTrace): string =>\n `${formatFactorLabel(factor.factorId)} (+${factor.contribution}, confidence=${factor.confidence})`;\n\nconst formatFactorContribution = (factor: RiskFactorTrace): string =>\n `${formatFactorLabel(factor.factorId)}=${factor.contribution}`;\n\nconst formatFactorEvidence = (factor: RiskFactorTrace): string => {\n if (factor.factorId === \"repository.structural\") {\n return `structural dimension=${formatNumber(factor.rawMetrics[\"structuralDimension\"])}`;\n }\n\n if (factor.factorId === \"repository.evolution\") {\n return `evolution dimension=${formatNumber(factor.rawMetrics[\"evolutionDimension\"])}`;\n }\n\n if (factor.factorId === \"repository.external\") {\n return `external dimension=${formatNumber(factor.rawMetrics[\"externalDimension\"])}`;\n }\n\n if (factor.factorId === \"repository.composite.interactions\") {\n return `structural×evolution=${formatNumber(factor.rawMetrics[\"structuralEvolution\"])}, central instability=${formatNumber(factor.rawMetrics[\"centralInstability\"])}, dependency amplification=${formatNumber(factor.rawMetrics[\"dependencyAmplification\"])}`;\n }\n\n if (factor.factorId === \"file.structural\") {\n return `fanIn=${formatNumber(factor.rawMetrics[\"fanIn\"])}, fanOut=${formatNumber(factor.rawMetrics[\"fanOut\"])}, depth=${formatNumber(factor.rawMetrics[\"depth\"])}, inCycle=${formatNumber(factor.rawMetrics[\"cycleParticipation\"])}, structuralAttenuation=${formatNumber(factor.rawMetrics[\"structuralAttenuation\"])}`;\n }\n\n if (factor.factorId === \"file.evolution\") {\n return `commitCount=${formatNumber(factor.rawMetrics[\"commitCount\"])}, churnTotal=${formatNumber(factor.rawMetrics[\"churnTotal\"])}, recentVolatility=${formatNumber(factor.rawMetrics[\"recentVolatility\"])}`;\n }\n\n if (factor.factorId === \"file.external\") {\n return `repositoryExternalPressure=${formatNumber(factor.rawMetrics[\"repositoryExternalPressure\"])}, dependencyAffinity=${formatNumber(factor.rawMetrics[\"dependencyAffinity\"])}`;\n }\n\n if (factor.factorId === \"file.composite.interactions\") {\n return `structural×evolution=${formatNumber(factor.rawMetrics[\"structuralEvolutionInteraction\"])}, central instability=${formatNumber(factor.rawMetrics[\"centralInstabilityInteraction\"])}, dependency amplification=${formatNumber(factor.rawMetrics[\"dependencyAmplificationInteraction\"])}`;\n }\n\n return \"evidence available in trace\";\n};\n\nconst findRepositoryTarget = (targets: readonly TargetTrace[]): TargetTrace | undefined =>\n targets.find((target) => target.targetType === \"repository\");\n\nconst repositoryDimensionScores = (\n repositoryTarget: TargetTrace | undefined,\n): {\n structural: number | null;\n evolution: number | null;\n external: number | null;\n interactions: number | null;\n} => {\n if (repositoryTarget === undefined) {\n return {\n structural: null,\n evolution: null,\n external: null,\n interactions: null,\n };\n }\n\n const structural = repositoryTarget.factors.find(\n (factor) => factor.factorId === \"repository.structural\",\n );\n const evolution = repositoryTarget.factors.find(\n (factor) => factor.factorId === \"repository.evolution\",\n );\n const external = repositoryTarget.factors.find(\n (factor) => factor.factorId === \"repository.external\",\n );\n const interactions = repositoryTarget.factors.find(\n (factor) => factor.factorId === \"repository.composite.interactions\",\n );\n\n return {\n structural:\n structural === undefined\n ? null\n : Number(((structural.rawMetrics[\"structuralDimension\"] ?? 0) * 100).toFixed(4)),\n evolution:\n evolution === undefined\n ? null\n : Number(((evolution.rawMetrics[\"evolutionDimension\"] ?? 0) * 100).toFixed(4)),\n external:\n external === undefined\n ? null\n : Number(((external.rawMetrics[\"externalDimension\"] ?? 0) * 100).toFixed(4)),\n interactions:\n interactions === undefined\n ? null\n : Number(\n (\n ((interactions.rawMetrics[\"structuralEvolution\"] ?? 0) +\n (interactions.rawMetrics[\"centralInstability\"] ?? 0) +\n (interactions.rawMetrics[\"dependencyAmplification\"] ?? 0)) *\n 100\n ).toFixed(4),\n ),\n };\n};\n\nconst buildRepositoryActions = (\n payload: ExplainOutputPayload,\n repositoryTarget: TargetTrace | undefined,\n): readonly string[] => {\n if (repositoryTarget === undefined) {\n return [\"No repository trace available.\"];\n }\n\n const topHotspots = payload.summary.risk.hotspots.slice(0, 3).map((hotspot) => hotspot.file);\n const highRiskDependencies = payload.summary.external.available\n ? payload.summary.external.highRiskDependencies.slice(0, 3)\n : [];\n\n const actions: string[] = [];\n for (const lever of repositoryTarget.reductionLevers) {\n if (lever.factorId === \"repository.evolution\") {\n actions.push(\n `Reduce volatility/churn in top hotspots first: ${topHotspots.join(\", \") || \"no hotspots available\"}.`,\n );\n continue;\n }\n\n if (lever.factorId === \"repository.structural\") {\n actions.push(\n `Lower fan-in/fan-out and break cycles in central files: ${topHotspots.join(\", \") || \"no hotspots available\"}.`,\n );\n continue;\n }\n\n if (lever.factorId === \"repository.composite.interactions\") {\n actions.push(\n \"Stabilize central files before refactors; interaction effects are amplifying risk.\",\n );\n continue;\n }\n\n if (lever.factorId === \"repository.external\") {\n actions.push(\n `Review high-risk direct dependencies: ${highRiskDependencies.join(\", \") || \"none detected\"}.`,\n );\n continue;\n }\n }\n\n if (actions.length === 0) {\n actions.push(\"No clear reduction levers available from current trace.\");\n }\n\n return actions.slice(0, 3);\n};\n\nconst renderTargetText = (target: TargetTrace): string => {\n const lines: string[] = [];\n lines.push(`${target.targetType}: ${target.targetId}`);\n lines.push(` score: ${target.totalScore} (${target.normalizedScore})`);\n lines.push(\" top factors:\");\n\n const topFactors = [...target.factors].sort(sortFactorByContribution).slice(0, 5);\n for (const factor of topFactors) {\n lines.push(` - ${formatFactorSummary(factor)}`);\n lines.push(` evidence: ${formatFactorEvidence(factor)}`);\n }\n\n lines.push(\" reduction levers:\");\n for (const lever of target.reductionLevers) {\n lines.push(\n ` - ${formatFactorLabel(lever.factorId)} | estimatedImpact=${lever.estimatedImpact}`,\n );\n }\n\n return lines.join(\"\\n\");\n};\n\nconst renderText = (payload: ExplainOutputPayload): string => {\n const lines: string[] = [];\n const repositoryTarget =\n findRepositoryTarget(payload.selectedTargets) ?? findRepositoryTarget(payload.trace.targets);\n const repositoryTopFactors =\n repositoryTarget === undefined\n ? []\n : [...repositoryTarget.factors].sort(sortFactorByContribution).slice(0, 3);\n const dimensionScores = repositoryDimensionScores(repositoryTarget);\n const compositeFactors = repositoryTopFactors.filter((factor) => factor.family === \"composite\");\n\n lines.push(`target: ${payload.summary.structural.targetPath}`);\n lines.push(`riskScore: ${payload.summary.risk.riskScore}`);\n lines.push(`riskBand: ${toRiskBand(payload.summary.risk.riskScore)}`);\n lines.push(`selectedTargets: ${payload.selectedTargets.length}`);\n lines.push(\"dimensionScores:\");\n lines.push(` structural: ${formatDimension(dimensionScores.structural)}`);\n lines.push(` evolution: ${formatDimension(dimensionScores.evolution)}`);\n lines.push(` external: ${formatDimension(dimensionScores.external)}`);\n lines.push(` interactions: ${formatDimension(dimensionScores.interactions)}`);\n lines.push(\"\");\n lines.push(\"explanation:\");\n lines.push(\n ` key drivers: ${repositoryTopFactors.map(formatFactorSummary).join(\"; \") || \"insufficient data\"}`,\n );\n lines.push(\n ` contributions: ${repositoryTopFactors.map(formatFactorContribution).join(\", \") || \"insufficient data\"}`,\n );\n lines.push(\n ` interaction effects: ${compositeFactors.map((factor) => `${formatFactorLabel(factor.factorId)} [${formatFactorEvidence(factor)}]`).join(\"; \") || \"none\"}`,\n );\n lines.push(` priority actions: ${buildRepositoryActions(payload, repositoryTarget).join(\" \")}`);\n lines.push(\"\");\n\n for (const target of payload.selectedTargets) {\n lines.push(renderTargetText(target));\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\").trimEnd();\n};\n\nconst renderMarkdown = (payload: ExplainOutputPayload): string => {\n const lines: string[] = [];\n const repositoryTarget =\n findRepositoryTarget(payload.selectedTargets) ?? findRepositoryTarget(payload.trace.targets);\n const repositoryTopFactors =\n repositoryTarget === undefined\n ? []\n : [...repositoryTarget.factors].sort(sortFactorByContribution).slice(0, 3);\n const dimensionScores = repositoryDimensionScores(repositoryTarget);\n const compositeFactors = repositoryTopFactors.filter((factor) => factor.family === \"composite\");\n\n lines.push(`# CodeSentinel Explanation`);\n lines.push(`- target: \\`${payload.summary.structural.targetPath}\\``);\n lines.push(`- riskScore: \\`${payload.summary.risk.riskScore}\\``);\n lines.push(`- riskBand: \\`${toRiskBand(payload.summary.risk.riskScore)}\\``);\n lines.push(`- selectedTargets: \\`${payload.selectedTargets.length}\\``);\n lines.push(\"\");\n lines.push(\"## Dimension Scores (0-100)\");\n lines.push(`- structural: \\`${formatDimension(dimensionScores.structural)}\\``);\n lines.push(`- evolution: \\`${formatDimension(dimensionScores.evolution)}\\``);\n lines.push(`- external: \\`${formatDimension(dimensionScores.external)}\\``);\n lines.push(`- interactions: \\`${formatDimension(dimensionScores.interactions)}\\``);\n lines.push(\"\");\n lines.push(`## Summary`);\n lines.push(\n `- key drivers: ${repositoryTopFactors.map(formatFactorSummary).join(\"; \") || \"insufficient data\"}`,\n );\n lines.push(\n `- contributions: ${repositoryTopFactors.map(formatFactorContribution).join(\", \") || \"insufficient data\"}`,\n );\n lines.push(\n `- interaction effects: ${compositeFactors.map((factor) => `${formatFactorLabel(factor.factorId)} [${formatFactorEvidence(factor)}]`).join(\"; \") || \"none\"}`,\n );\n lines.push(`- priority actions: ${buildRepositoryActions(payload, repositoryTarget).join(\" \")}`);\n lines.push(\"\");\n\n for (const target of payload.selectedTargets) {\n lines.push(`## ${target.targetType}: \\`${target.targetId}\\``);\n lines.push(`- score: \\`${target.totalScore}\\` (\\`${target.normalizedScore}\\`)`);\n lines.push(`- Top factors:`);\n for (const factor of [...target.factors].sort(sortFactorByContribution).slice(0, 5)) {\n lines.push(\n ` - \\`${formatFactorLabel(factor.factorId)}\\` contribution=\\`${factor.contribution}\\` confidence=\\`${factor.confidence}\\``,\n );\n lines.push(` - evidence: \\`${formatFactorEvidence(factor)}\\``);\n }\n lines.push(`- Reduction levers:`);\n for (const lever of target.reductionLevers) {\n lines.push(\n ` - \\`${formatFactorLabel(lever.factorId)}\\` estimatedImpact=\\`${lever.estimatedImpact}\\``,\n );\n }\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\").trimEnd();\n};\n\nexport const formatExplainOutput = (\n payload: ExplainOutputPayload,\n format: ExplainFormat,\n): string => {\n if (format === \"json\") {\n return JSON.stringify(payload, null, 2);\n }\n\n if (format === \"md\") {\n return renderMarkdown(payload);\n }\n\n return renderText(payload);\n};\n","import type { AnalyzeDependencyCandidateResult } from \"@codesentinel/dependency-firewall\";\n\nexport type DependencyRiskOutputMode = \"summary\" | \"json\";\n\ntype UnavailableResult = Extract<AnalyzeDependencyCandidateResult, { available: false }>;\ntype AvailableResult = Extract<AnalyzeDependencyCandidateResult, { available: true }>;\n\ntype DependencyRiskSummaryShape =\n | {\n available: false;\n reason: UnavailableResult[\"reason\"];\n dependency: string;\n }\n | {\n available: true;\n dependency: AvailableResult[\"dependency\"];\n graph: AvailableResult[\"graph\"];\n assumptions: readonly string[];\n external: {\n available: boolean;\n metrics: Record<string, unknown> | null;\n ownRiskSignals: readonly string[];\n inheritedRiskSignals: readonly string[];\n highRiskDependenciesTop: readonly string[];\n transitiveExposureDependenciesTop: readonly string[];\n };\n };\n\nconst createSummaryShape = (\n result: AnalyzeDependencyCandidateResult,\n): DependencyRiskSummaryShape => {\n if (!result.available) {\n return {\n available: false,\n reason: result.reason,\n dependency: result.dependency,\n };\n }\n\n const direct = result.external.available ? result.external.dependencies[0] : undefined;\n\n return {\n available: true,\n dependency: result.dependency,\n graph: result.graph,\n assumptions: result.assumptions,\n external: {\n available: result.external.available,\n metrics: result.external.available ? result.external.metrics : null,\n ownRiskSignals: direct?.ownRiskSignals ?? [],\n inheritedRiskSignals: direct?.inheritedRiskSignals ?? [],\n highRiskDependenciesTop: result.external.available\n ? result.external.highRiskDependencies.slice(0, 10)\n : [],\n transitiveExposureDependenciesTop: result.external.available\n ? result.external.transitiveExposureDependencies.slice(0, 10)\n : [],\n },\n };\n};\n\nexport const formatDependencyRiskOutput = (\n result: AnalyzeDependencyCandidateResult,\n mode: DependencyRiskOutputMode,\n): string =>\n mode === \"json\"\n ? JSON.stringify(result, null, 2)\n : JSON.stringify(createSummaryShape(result), null, 2);\n","export type LogLevel = \"silent\" | \"error\" | \"warn\" | \"info\" | \"debug\";\n\nconst logLevelRank: Readonly<Record<Exclude<LogLevel, \"silent\">, number>> = {\n error: 0,\n warn: 1,\n info: 2,\n debug: 3,\n};\n\nexport type Logger = {\n error: (message: string) => void;\n warn: (message: string) => void;\n info: (message: string) => void;\n debug: (message: string) => void;\n};\n\nconst noop = (): void => {};\n\nexport const createSilentLogger = (): Logger => ({\n error: noop,\n warn: noop,\n info: noop,\n debug: noop,\n});\n\nconst shouldLog = (\n configuredLevel: LogLevel,\n messageLevel: Exclude<LogLevel, \"silent\">,\n): boolean => {\n if (configuredLevel === \"silent\") {\n return false;\n }\n\n return logLevelRank[messageLevel] <= logLevelRank[configuredLevel];\n};\n\nconst write = (messageLevel: Exclude<LogLevel, \"silent\">, message: string): void => {\n process.stderr.write(`[codesentinel] ${messageLevel.toUpperCase()} ${message}\\n`);\n};\n\nexport const createStderrLogger = (level: LogLevel): Logger => {\n if (level === \"silent\") {\n return createSilentLogger();\n }\n\n return {\n error: (message) => {\n if (shouldLog(level, \"error\")) {\n write(\"error\", message);\n }\n },\n warn: (message) => {\n if (shouldLog(level, \"warn\")) {\n write(\"warn\", message);\n }\n },\n info: (message) => {\n if (shouldLog(level, \"info\")) {\n write(\"info\", message);\n }\n },\n debug: (message) => {\n if (shouldLog(level, \"debug\")) {\n write(\"debug\", message);\n }\n },\n };\n};\n\nexport const parseLogLevel = (value: string | undefined): LogLevel => {\n switch (value) {\n case \"silent\":\n case \"error\":\n case \"warn\":\n case \"info\":\n case \"debug\":\n return value;\n default:\n return \"info\";\n }\n};\n","import { spawn } from \"node:child_process\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { stderr, stdin } from \"node:process\";\nimport { clearScreenDown, cursorTo, emitKeypressEvents } from \"node:readline\";\n\nconst UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;\nconst UPDATE_CACHE_PATH = join(homedir(), \".cache\", \"codesentinel\", \"update-check.json\");\nconst SEMVER_PATTERN =\n /^(?<major>\\d+)\\.(?<minor>\\d+)\\.(?<patch>\\d+)(?:-(?<prerelease>[0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/;\nconst ANSI = {\n reset: \"\\x1b[0m\",\n bold: \"\\x1b[1m\",\n dim: \"\\x1b[2m\",\n cyan: \"\\x1b[36m\",\n green: \"\\x1b[32m\",\n yellow: \"\\x1b[33m\",\n} as const;\n\nconst hideCursor = (): void => {\n stderr.write(\"\\x1b[?25l\");\n};\n\nconst showCursor = (): void => {\n stderr.write(\"\\x1b[?25h\");\n};\n\ntype Semver = {\n major: number;\n minor: number;\n patch: number;\n prerelease: readonly (number | string)[];\n};\n\ntype UpdateCheckCache = {\n lastCheckedAt: string;\n};\n\nconst parsePrereleaseIdentifier = (identifier: string): number | string => {\n if (/^\\d+$/.test(identifier)) {\n return Number.parseInt(identifier, 10);\n }\n return identifier;\n};\n\nconst parseSemver = (value: string): Semver | null => {\n const match = SEMVER_PATTERN.exec(value.trim());\n if (match === null) {\n return null;\n }\n\n const groups = match.groups;\n if (groups === undefined) {\n return null;\n }\n\n const majorRaw = groups[\"major\"];\n const minorRaw = groups[\"minor\"];\n const patchRaw = groups[\"patch\"];\n const prereleaseRaw = groups[\"prerelease\"];\n if (majorRaw === undefined || minorRaw === undefined || patchRaw === undefined) {\n return null;\n }\n\n const prerelease =\n prereleaseRaw === undefined || prereleaseRaw.length === 0\n ? []\n : prereleaseRaw.split(\".\").map(parsePrereleaseIdentifier);\n\n return {\n major: Number.parseInt(majorRaw, 10),\n minor: Number.parseInt(minorRaw, 10),\n patch: Number.parseInt(patchRaw, 10),\n prerelease,\n };\n};\n\nconst comparePrerelease = (\n left: readonly (number | string)[],\n right: readonly (number | string)[],\n): number => {\n if (left.length === 0 && right.length === 0) {\n return 0;\n }\n if (left.length === 0) {\n return 1;\n }\n if (right.length === 0) {\n return -1;\n }\n\n const length = Math.max(left.length, right.length);\n for (let index = 0; index < length; index += 1) {\n const leftValue = left[index];\n const rightValue = right[index];\n if (leftValue === undefined) {\n return -1;\n }\n if (rightValue === undefined) {\n return 1;\n }\n\n if (typeof leftValue === \"number\" && typeof rightValue === \"number\") {\n if (leftValue !== rightValue) {\n return leftValue > rightValue ? 1 : -1;\n }\n continue;\n }\n\n if (typeof leftValue === \"number\" && typeof rightValue === \"string\") {\n return -1;\n }\n if (typeof leftValue === \"string\" && typeof rightValue === \"number\") {\n return 1;\n }\n\n if (leftValue !== rightValue) {\n return leftValue > rightValue ? 1 : -1;\n }\n }\n\n return 0;\n};\n\nexport const compareVersions = (left: string, right: string): number | null => {\n const leftParsed = parseSemver(left);\n const rightParsed = parseSemver(right);\n if (leftParsed === null || rightParsed === null) {\n return null;\n }\n\n if (leftParsed.major !== rightParsed.major) {\n return leftParsed.major > rightParsed.major ? 1 : -1;\n }\n if (leftParsed.minor !== rightParsed.minor) {\n return leftParsed.minor > rightParsed.minor ? 1 : -1;\n }\n if (leftParsed.patch !== rightParsed.patch) {\n return leftParsed.patch > rightParsed.patch ? 1 : -1;\n }\n\n return comparePrerelease(leftParsed.prerelease, rightParsed.prerelease);\n};\n\nconst isTruthy = (value: string | undefined): boolean => {\n if (value === undefined) {\n return false;\n }\n return [\"1\", \"true\", \"yes\", \"on\"].includes(value.trim().toLowerCase());\n};\n\nexport const parseNpmViewVersionOutput = (output: string): string | null => {\n const trimmed = output.trim();\n if (trimmed.length === 0) {\n return null;\n }\n\n try {\n const parsed = JSON.parse(trimmed) as unknown;\n if (typeof parsed === \"string\" && parsed.trim().length > 0) {\n return parsed.trim();\n }\n if (Array.isArray(parsed) && parsed.length > 0) {\n const latest = (parsed as unknown[]).at(-1);\n if (typeof latest === \"string\" && latest.trim().length > 0) {\n return latest.trim();\n }\n }\n } catch {\n return trimmed;\n }\n\n return null;\n};\n\nexport const renderUpdateInProgressMessage = (packageName: string): string =>\n `Updating CodeSentinel via \\`npm install -g ${packageName}\\`...\\n`;\n\nexport const renderUpdateSuccessMessage = (): string =>\n \"🎉 Update ran successfully! Please restart CodeSentinel.\\n\";\n\nexport const renderAlreadyUpToDateMessage = (currentVersion: string): string =>\n `CodeSentinel is already up to date (${currentVersion}).\\n`;\n\nexport const renderUpdateCheckFailedMessage = (): string =>\n \"CodeSentinel could not check for updates right now. Please try again later.\\n\";\n\nconst readCache = async (): Promise<UpdateCheckCache | null> => {\n try {\n const raw = await readFile(UPDATE_CACHE_PATH, \"utf8\");\n const parsed = JSON.parse(raw) as unknown;\n if (\n typeof parsed === \"object\" &&\n parsed !== null &&\n typeof (parsed as { lastCheckedAt?: unknown }).lastCheckedAt === \"string\"\n ) {\n return { lastCheckedAt: (parsed as { lastCheckedAt: string }).lastCheckedAt };\n }\n } catch {\n return null;\n }\n\n return null;\n};\n\nconst writeCache = async (cache: UpdateCheckCache): Promise<void> => {\n await mkdir(dirname(UPDATE_CACHE_PATH), { recursive: true });\n await writeFile(UPDATE_CACHE_PATH, JSON.stringify(cache), \"utf8\");\n};\n\nexport const shouldRunUpdateCheck = (input: {\n argv: readonly string[];\n env: NodeJS.ProcessEnv;\n isInteractive: boolean;\n nowMs: number;\n lastCheckedAt: string | null;\n}): boolean => {\n if (!input.isInteractive) {\n return false;\n }\n if (isTruthy(input.env[\"CI\"])) {\n return false;\n }\n if (isTruthy(input.env[\"CODESENTINEL_NO_UPDATE_NOTIFIER\"])) {\n return false;\n }\n if (input.argv.some((argument) => argument === \"--help\" || argument === \"-h\")) {\n return false;\n }\n if (input.argv.some((argument) => argument === \"--version\" || argument === \"-V\")) {\n return false;\n }\n\n if (input.lastCheckedAt === null) {\n return true;\n }\n\n const lastCheckedMs = Date.parse(input.lastCheckedAt);\n if (!Number.isFinite(lastCheckedMs)) {\n return true;\n }\n\n return input.nowMs - lastCheckedMs >= UPDATE_CHECK_INTERVAL_MS;\n};\n\nconst runCommand = async (\n command: string,\n args: readonly string[],\n mode: \"capture\" | \"inherit\",\n): Promise<{ code: number; stdout: string }> => {\n return await new Promise((resolvePromise, reject) => {\n const child = spawn(command, [...args], {\n stdio: mode === \"inherit\" ? \"inherit\" : [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n let stdoutRaw = \"\";\n if (mode === \"capture\" && child.stdout !== null) {\n child.stdout.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk: string) => {\n stdoutRaw += chunk;\n });\n }\n\n child.on(\"error\", (error) => {\n reject(error);\n });\n child.on(\"close\", (code) => {\n resolvePromise({ code: code ?? 1, stdout: stdoutRaw });\n });\n });\n};\n\nconst fetchLatestVersion = async (packageName: string): Promise<string | null> => {\n const result = await runCommand(\"npm\", [\"view\", packageName, \"version\", \"--json\"], \"capture\");\n if (result.code !== 0) {\n return null;\n }\n return parseNpmViewVersionOutput(result.stdout);\n};\n\ntype UpdatePromptChoice = \"install\" | \"skip\";\n\nconst renderUpdatePrompt = (\n packageName: string,\n latestVersion: string,\n currentVersion: string,\n selectedIndex: number,\n): number => {\n const options: readonly string[] = [\n `1. Update now (runs \\`npm install -g ${packageName}\\`)`,\n \"2. Skip\",\n ];\n\n const lines = [\n ` ${ANSI.bold}${ANSI.cyan}✨ Update available! ${currentVersion} -> ${latestVersion}${ANSI.reset}`,\n \"\",\n ` ${ANSI.dim}Release notes: https://github.com/getcodesentinel/codesentinel/releases/latest${ANSI.reset}`,\n \"\",\n ...options.map((option, index) => {\n const selected = index === selectedIndex;\n const prefix = selected ? `${ANSI.green}>${ANSI.reset}` : \" \";\n const text = selected ? `${ANSI.bold}${option}${ANSI.reset}` : option;\n return `${prefix} ${text}`;\n }),\n \"\",\n ` ${ANSI.dim}Use ↑/↓ to choose. Press enter to continue. Press q or Ctrl+C to exit.${ANSI.reset}`,\n ];\n\n stderr.write(lines.join(\"\\n\"));\n return lines.length;\n};\n\nconst promptInstall = async (\n packageName: string,\n latestVersion: string,\n currentVersion: string,\n): Promise<UpdatePromptChoice> => {\n if (!stdin.isTTY || !stderr.isTTY || typeof stdin.setRawMode !== \"function\") {\n stderr.write(\n `New version ${latestVersion} is available (current ${currentVersion}). Run: npm install -g @getcodesentinel/codesentinel@latest\\n`,\n );\n return \"skip\";\n }\n\n return await new Promise<UpdatePromptChoice>((resolve) => {\n emitKeypressEvents(stdin);\n\n let selectedIndex = 0;\n const previousRawMode = stdin.isRaw;\n\n const clearPromptArea = (): void => {\n cursorTo(stderr, 0, 0);\n clearScreenDown(stderr);\n };\n\n const redraw = (): void => {\n clearPromptArea();\n renderUpdatePrompt(packageName, latestVersion, currentVersion, selectedIndex);\n };\n\n const cleanup = (choice: UpdatePromptChoice): void => {\n stdin.off(\"keypress\", onKeypress);\n stdin.pause();\n if (typeof stdin.setRawMode === \"function\") {\n stdin.setRawMode(previousRawMode);\n }\n clearPromptArea();\n showCursor();\n if (choice === \"install\") {\n stderr.write(`${ANSI.yellow}${renderUpdateInProgressMessage(packageName)}${ANSI.reset}`);\n } else {\n stderr.write(\"\\n\");\n }\n resolve(choice);\n };\n\n const onKeypress = (_str: string, key: { name?: string; ctrl?: boolean }): void => {\n if (key.ctrl === true && key.name === \"c\") {\n cleanup(\"skip\");\n return;\n }\n\n if (key.name === \"q\") {\n cleanup(\"skip\");\n return;\n }\n\n if (key.name === \"up\") {\n selectedIndex = selectedIndex > 0 ? selectedIndex - 1 : 1;\n redraw();\n return;\n }\n if (key.name === \"down\") {\n selectedIndex = selectedIndex < 1 ? selectedIndex + 1 : 0;\n redraw();\n return;\n }\n if (key.name === \"return\" || key.name === \"enter\") {\n cleanup(selectedIndex === 0 ? \"install\" : \"skip\");\n }\n };\n\n stdin.on(\"keypress\", onKeypress);\n if (typeof stdin.setRawMode === \"function\") {\n hideCursor();\n stdin.setRawMode(true);\n }\n stdin.resume();\n redraw();\n });\n};\n\nconst installLatestVersion = async (packageName: string): Promise<boolean> => {\n const result = await runCommand(\"npm\", [\"install\", \"-g\", `${packageName}@latest`], \"inherit\");\n return result.code === 0;\n};\n\nexport const runManualCliUpdate = async (input: {\n packageName: string;\n currentVersion: string;\n}): Promise<number> => {\n const latestVersion = await fetchLatestVersion(input.packageName);\n if (latestVersion === null) {\n stderr.write(renderUpdateCheckFailedMessage());\n return 1;\n }\n\n const comparison = compareVersions(latestVersion, input.currentVersion);\n if (comparison === null) {\n stderr.write(renderUpdateCheckFailedMessage());\n return 1;\n }\n\n if (comparison <= 0) {\n stderr.write(renderAlreadyUpToDateMessage(input.currentVersion));\n return 0;\n }\n\n const choice = await promptInstall(input.packageName, latestVersion, input.currentVersion);\n if (choice !== \"install\") {\n return 0;\n }\n\n const installed = await installLatestVersion(input.packageName);\n if (installed) {\n stderr.write(renderUpdateSuccessMessage());\n return 0;\n }\n\n stderr.write(\n \"CodeSentinel update failed. You can retry with: npm install -g @getcodesentinel/codesentinel@latest\\n\",\n );\n return 1;\n};\n\nexport const checkForCliUpdates = async (input: {\n packageName: string;\n currentVersion: string;\n argv: readonly string[];\n env: NodeJS.ProcessEnv;\n}): Promise<void> => {\n try {\n const nowMs = Date.now();\n const cache = await readCache();\n const shouldCheck = shouldRunUpdateCheck({\n argv: input.argv,\n env: input.env,\n isInteractive: Boolean(process.stdout.isTTY) && Boolean(process.stdin.isTTY),\n nowMs,\n lastCheckedAt: cache?.lastCheckedAt ?? null,\n });\n if (!shouldCheck) {\n return;\n }\n\n await writeCache({ lastCheckedAt: new Date(nowMs).toISOString() });\n\n const latestVersion = await fetchLatestVersion(input.packageName);\n if (latestVersion === null) {\n return;\n }\n\n const comparison = compareVersions(latestVersion, input.currentVersion);\n if (comparison === null || comparison <= 0) {\n return;\n }\n\n const choice = await promptInstall(input.packageName, latestVersion, input.currentVersion);\n if (choice !== \"install\") {\n return;\n }\n\n const installed = await installLatestVersion(input.packageName);\n if (installed) {\n stderr.write(renderUpdateSuccessMessage());\n process.exit(0);\n } else {\n stderr.write(\n \"CodeSentinel update failed. You can retry with: npm install -g @getcodesentinel/codesentinel@latest\\n\",\n );\n }\n } catch {\n // Update checks are best-effort and must never block the CLI command.\n }\n};\n","import { spawn } from \"node:child_process\";\nimport type { Readable } from \"node:stream\";\nimport { stderr, stdin, stdout } from \"node:process\";\nimport { clearScreenDown, cursorTo, emitKeypressEvents, moveCursor } from \"node:readline\";\nimport type { Interface as ReadlineInterface } from \"node:readline\";\nimport { createInterface as createPromisesInterface } from \"node:readline/promises\";\n\nconst ANSI = {\n reset: \"\\x1b[0m\",\n bold: \"\\x1b[1m\",\n dim: \"\\x1b[2m\",\n cyan: \"\\x1b[36m\",\n green: \"\\x1b[32m\",\n} as const;\nconst PROMPT_PADDING = \" \";\n\ntype MenuActionDefinition = {\n label: string;\n description: string;\n commandBuilder: () => MenuActionResult | Promise<MenuActionResult>;\n};\n\ntype MenuActionResult =\n | {\n kind: \"run\";\n args: readonly string[];\n }\n | {\n kind: \"cancel\";\n };\n\nconst isWhitespace = (value: string): boolean => /\\s/.test(value);\n\nexport const splitShellLikeArgs = (input: string): string[] => {\n const trimmed = input.trim();\n if (trimmed.length === 0) {\n return [];\n }\n\n const result: string[] = [];\n let current = \"\";\n let quote: '\"' | \"'\" | null = null;\n let escaping = false;\n\n for (const character of trimmed) {\n if (escaping) {\n current += character;\n escaping = false;\n continue;\n }\n\n if (character === \"\\\\\") {\n escaping = true;\n continue;\n }\n\n if (quote !== null) {\n if (character === quote) {\n quote = null;\n } else {\n current += character;\n }\n continue;\n }\n\n if (character === '\"' || character === \"'\") {\n quote = character;\n continue;\n }\n\n if (isWhitespace(character)) {\n if (current.length > 0) {\n result.push(current);\n current = \"\";\n }\n continue;\n }\n\n current += character;\n }\n\n if (escaping) {\n current += \"\\\\\";\n }\n if (quote !== null) {\n throw new Error(\"Unterminated quoted argument\");\n }\n if (current.length > 0) {\n result.push(current);\n }\n\n return result;\n};\n\nconst renderMenu = (\n currentVersion: string,\n actions: readonly MenuActionDefinition[],\n selectedIndex: number,\n): void => {\n const optionLabels = actions.map((action, index) => `${index + 1}. ${action.label}`);\n const labelWidth = optionLabels.reduce((max, label) => Math.max(max, label.length), 0);\n const lines = [\n ` ${ANSI.bold}${ANSI.cyan}CodeSentinel${ANSI.reset} ${ANSI.dim}v${currentVersion}${ANSI.reset}`,\n \"\",\n \" Choose an action:\",\n \"\",\n ...actions.map((action, index) => {\n const selected = index === selectedIndex;\n const prefix = selected ? `${ANSI.green}>${ANSI.reset}` : \" \";\n const label = optionLabels[index]?.padEnd(labelWidth, \" \") ?? \"\";\n const renderedLabel = selected ? `${ANSI.bold}${label}${ANSI.reset}` : label;\n return `${prefix} ${renderedLabel} ${ANSI.dim}${action.description}${ANSI.reset}`;\n }),\n \"\",\n ` ${ANSI.dim}Use ↑/↓ to choose. Press enter to continue. Press q or Ctrl+C to exit.${ANSI.reset}`,\n ];\n\n stderr.write(lines.join(\"\\n\"));\n};\n\nconst clearTerminal = (): void => {\n cursorTo(stderr, 0, 0);\n clearScreenDown(stderr);\n};\n\nconst hideCursor = (): void => {\n stderr.write(\"\\x1b[?25l\");\n};\n\nconst showCursor = (): void => {\n stderr.write(\"\\x1b[?25h\");\n};\n\nconst pipeWithPadding = (\n stream: Readable | null,\n target: NodeJS.WriteStream,\n padding: string,\n): void => {\n if (stream === null) {\n return;\n }\n\n stream.setEncoding(\"utf8\");\n\n let buffer = \"\";\n let needsPrefix = true;\n\n const writeChunk = (chunk: string): void => {\n let start = 0;\n while (start < chunk.length) {\n if (needsPrefix) {\n target.write(padding);\n needsPrefix = false;\n }\n\n const newlineIndex = chunk.indexOf(\"\\n\", start);\n if (newlineIndex === -1) {\n target.write(chunk.slice(start));\n return;\n }\n\n target.write(chunk.slice(start, newlineIndex + 1));\n needsPrefix = true;\n start = newlineIndex + 1;\n }\n };\n\n stream.on(\"data\", (chunk: string) => {\n buffer += chunk;\n const lastNewlineIndex = buffer.lastIndexOf(\"\\n\");\n\n if (lastNewlineIndex === -1) {\n return;\n }\n\n writeChunk(buffer.slice(0, lastNewlineIndex + 1));\n buffer = buffer.slice(lastNewlineIndex + 1);\n });\n\n stream.on(\"end\", () => {\n if (buffer.length > 0) {\n writeChunk(buffer);\n buffer = \"\";\n }\n });\n};\n\nconst promptSelection = async (\n currentVersion: string,\n actions: readonly MenuActionDefinition[],\n): Promise<number | \"exit\"> => {\n if (!stdin.isTTY || !stderr.isTTY || typeof stdin.setRawMode !== \"function\") {\n return \"exit\";\n }\n\n return await new Promise<number | \"exit\">((resolve) => {\n emitKeypressEvents(stdin);\n\n let selectedIndex = 0;\n const previousRawMode = stdin.isRaw;\n\n const redraw = (): void => {\n clearTerminal();\n renderMenu(currentVersion, actions, selectedIndex);\n moveCursor(stderr, -1, 0);\n };\n\n const cleanup = (selection: number | \"exit\"): void => {\n stdin.off(\"keypress\", onKeypress);\n stdin.pause();\n stdin.setRawMode(previousRawMode);\n clearTerminal();\n showCursor();\n resolve(selection);\n };\n\n const onKeypress = (_str: string, key: { name?: string; ctrl?: boolean }): void => {\n if (key.ctrl === true && key.name === \"c\") {\n cleanup(\"exit\");\n return;\n }\n\n if (key.name === \"q\") {\n cleanup(\"exit\");\n return;\n }\n\n if (key.name === \"up\") {\n selectedIndex = selectedIndex > 0 ? selectedIndex - 1 : actions.length - 1;\n redraw();\n return;\n }\n\n if (key.name === \"down\") {\n selectedIndex = selectedIndex < actions.length - 1 ? selectedIndex + 1 : 0;\n redraw();\n return;\n }\n\n if (key.name === \"return\" || key.name === \"enter\") {\n cleanup(selectedIndex);\n }\n };\n\n stdin.on(\"keypress\", onKeypress);\n hideCursor();\n stdin.setRawMode(true);\n stdin.resume();\n redraw();\n });\n};\n\nconst createPrompt = (): ReadlineInterface =>\n createPromisesInterface({\n input: stdin,\n output: stderr,\n }) as unknown as ReadlineInterface;\n\nconst promptText = async (\n prompt: ReadlineInterface,\n label: string,\n defaultValue?: string,\n): Promise<string | null> => {\n const suffix =\n defaultValue === undefined || defaultValue.length === 0 ? \"\" : ` [${defaultValue}]`;\n let answer: string;\n\n try {\n answer = await (prompt as unknown as ReturnType<typeof createPromisesInterface>).question(\n `${PROMPT_PADDING}${label}${suffix}: `,\n );\n } catch (error) {\n if (error instanceof Error && \"code\" in error && error.code === \"ABORT_ERR\") {\n stderr.write(\"\\n\");\n return null;\n }\n throw error;\n }\n\n const trimmed = answer.trim();\n return trimmed.length > 0 ? trimmed : (defaultValue ?? \"\");\n};\n\nconst renderDependencyRiskPrompt = (errorMessage?: string): void => {\n clearTerminal();\n stderr.write(`${PROMPT_PADDING}${ANSI.bold}Scan dependency risk${ANSI.reset}\\n`);\n if (errorMessage !== undefined) {\n stderr.write(`\\n${PROMPT_PADDING}${errorMessage}\\n`);\n }\n stderr.write(\"\\n\");\n};\n\nconst buildDependencyRiskArgs = async (): Promise<MenuActionResult> => {\n const prompt = createPrompt();\n\n try {\n let errorMessage: string | undefined;\n\n while (true) {\n renderDependencyRiskPrompt(errorMessage);\n const dependency = await promptText(prompt, \"Package name\");\n if (dependency === null) {\n return { kind: \"cancel\" };\n }\n\n if (dependency.length === 0) {\n errorMessage = \"A package name is required.\";\n continue;\n }\n\n return {\n kind: \"run\",\n args: [\"dependency-risk\", dependency],\n };\n }\n } finally {\n prompt.close();\n }\n};\n\nconst waitForReturnToMenu = async (): Promise<void> => {\n if (!stdin.isTTY || !stderr.isTTY || typeof stdin.setRawMode !== \"function\") {\n return;\n }\n\n stderr.write(`\\n${PROMPT_PADDING}Press enter to return to the menu...`);\n\n await new Promise<void>((resolve) => {\n emitKeypressEvents(stdin);\n const previousRawMode = stdin.isRaw;\n\n const cleanup = (): void => {\n stdin.off(\"keypress\", onKeypress);\n stdin.pause();\n stdin.setRawMode(previousRawMode);\n showCursor();\n stderr.write(\"\\n\");\n resolve();\n };\n\n const onKeypress = (_str: string, key: { name?: string; ctrl?: boolean }): void => {\n if (key.ctrl === true && key.name === \"c\") {\n cleanup();\n return;\n }\n\n if (key.name === \"return\" || key.name === \"enter\") {\n cleanup();\n }\n };\n\n hideCursor();\n stdin.on(\"keypress\", onKeypress);\n stdin.setRawMode(true);\n stdin.resume();\n });\n};\n\nconst runCliCommand = async (scriptPath: string, args: readonly string[]): Promise<number> => {\n return await new Promise((resolve, reject) => {\n const child = spawn(process.execPath, [...process.execArgv, scriptPath, ...args], {\n stdio: [\"inherit\", \"pipe\", \"pipe\"],\n env: {\n ...process.env,\n CODESENTINEL_NO_UPDATE_NOTIFIER: \"1\",\n },\n });\n\n pipeWithPadding(child.stdout, stdout, PROMPT_PADDING);\n pipeWithPadding(child.stderr, stderr, PROMPT_PADDING);\n\n child.on(\"error\", (error) => {\n reject(error);\n });\n child.on(\"close\", (code) => {\n resolve(code ?? 1);\n });\n });\n};\n\nexport const runInteractiveCliMenu = async (input: {\n currentVersion: string;\n scriptPath: string;\n}): Promise<number> => {\n if (!stdin.isTTY || !stderr.isTTY || !stdout.isTTY) {\n stderr.write(`${PROMPT_PADDING}Interactive menu requires a TTY.\\n`);\n return 1;\n }\n\n const actions: readonly MenuActionDefinition[] = [\n {\n label: \"Run overview\",\n description: \"combined analyze + explain + report\",\n commandBuilder: () => ({ kind: \"run\", args: [\"run\"] }),\n },\n {\n label: \"Analyze repository\",\n description: \"structural and health scoring summary\",\n commandBuilder: () => ({ kind: \"run\", args: [\"analyze\"] }),\n },\n {\n label: \"Explain hotspots\",\n description: \"top findings in markdown by default\",\n commandBuilder: () => ({ kind: \"run\", args: [\"explain\", \"--format\", \"md\"] }),\n },\n {\n label: \"Generate report\",\n description: \"create a full report for a repository\",\n commandBuilder: () => ({ kind: \"run\", args: [\"report\", \"--format\", \"md\"] }),\n },\n {\n label: \"Run policy check\",\n description: \"execute governance gates\",\n commandBuilder: () => ({ kind: \"run\", args: [\"check\"] }),\n },\n {\n label: \"Scan dependency risk\",\n description: \"inspect a package from the registry\",\n commandBuilder: buildDependencyRiskArgs,\n },\n ];\n\n while (true) {\n const selectedIndex = await promptSelection(input.currentVersion, actions);\n if (selectedIndex === \"exit\") {\n stderr.write(\"\\n\");\n return 0;\n }\n\n const selectedAction = actions[selectedIndex];\n if (selectedAction === undefined) {\n stderr.write(`\\n${PROMPT_PADDING}`);\n return 1;\n }\n\n const actionResult = await selectedAction.commandBuilder();\n if (actionResult.kind === \"cancel\") {\n continue;\n }\n\n const exitCode = await runCliCommand(input.scriptPath, actionResult.args);\n if (exitCode !== 0) {\n stderr.write(`\\n${PROMPT_PADDING}Command exited with code ${exitCode}.\\n`);\n } else {\n stderr.write(\"\\n\");\n }\n await waitForReturnToMenu();\n }\n};\n","import { resolve } from \"node:path\";\nimport type { AnalyzeSummary } from \"@codesentinel/core\";\nimport {\n buildProjectGraphSummary,\n type ParseTypescriptProjectProgressEvent,\n} from \"@codesentinel/code-graph\";\nimport {\n analyzeDependencyExposureFromProject,\n type DependencyExposureProgressEvent,\n} from \"@codesentinel/dependency-firewall\";\nimport {\n analyzeRepositoryEvolutionFromGit,\n enrichEvolutionSummaryWithWorkspaces,\n type EvolutionAnalysisProgressEvent,\n} from \"@codesentinel/git-analyzer\";\nimport {\n computeRepositoryHealthSummary,\n type HealthEngineConfig,\n} from \"@codesentinel/health-engine\";\nimport { computeRepositoryRiskSummary, type RiskEngineConfig } from \"@codesentinel/risk-engine\";\nimport { createSilentLogger, type Logger } from \"./logger.js\";\n\nexport type AuthorIdentityCliMode = \"likely_merge\" | \"strict_email\";\nexport type ScoringProfileCliMode = \"default\" | \"personal\";\nexport type AnalysisRuntimeOptions = {\n recentWindowDays?: number;\n scoringProfile?: ScoringProfileCliMode;\n};\n\nconst resolveTargetPath = (inputPath: string | undefined, cwd: string): string =>\n resolve(cwd, inputPath ?? \".\");\n\nexport type AnalysisInputs = {\n structural: AnalyzeSummary[\"structural\"];\n evolution: AnalyzeSummary[\"evolution\"];\n external: AnalyzeSummary[\"external\"];\n};\n\nconst scoringProfileConfig: Readonly<\n Record<ScoringProfileCliMode, Partial<RiskEngineConfig> | undefined>\n> = {\n default: undefined,\n personal: {\n evolutionFactorWeights: {\n frequency: 0.26,\n churn: 0.24,\n recentVolatility: 0.2,\n ownershipConcentration: 0.08,\n busFactorRisk: 0.04,\n },\n },\n};\n\nconst healthProfileConfig: Readonly<\n Record<ScoringProfileCliMode, Partial<HealthEngineConfig> | undefined>\n> = {\n default: undefined,\n personal: {\n ownershipPenaltyMultiplier: 0.25,\n },\n};\n\nexport const resolveRiskConfigForProfile = (\n scoringProfile: ScoringProfileCliMode | undefined,\n): Partial<RiskEngineConfig> | undefined => {\n return scoringProfileConfig[scoringProfile ?? \"default\"];\n};\n\nexport const resolveHealthConfigForProfile = (\n scoringProfile: ScoringProfileCliMode | undefined,\n): Partial<HealthEngineConfig> | undefined => {\n return healthProfileConfig[scoringProfile ?? \"default\"];\n};\n\nconst createExternalProgressReporter = (\n logger: Logger,\n): ((event: DependencyExposureProgressEvent) => void) => {\n let lastLoggedProgress = 0;\n\n return (event) => {\n switch (event.stage) {\n case \"package_json_loaded\":\n logger.debug(\"external: package.json loaded\");\n break;\n case \"lockfile_selected\":\n logger.info(`external: lockfile selected (${event.kind})`);\n break;\n case \"lockfile_parsed\":\n logger.info(\n `external: parsed ${event.dependencyNodes} locked dependencies (${event.directDependencies} direct)`,\n );\n break;\n case \"metadata_fetch_started\":\n logger.info(`external: fetching dependency metadata (${event.total} packages)`);\n break;\n case \"metadata_fetch_progress\": {\n const currentPercent =\n event.total === 0 ? 100 : Math.floor((event.completed / event.total) * 100);\n if (\n event.completed === event.total ||\n event.completed === 1 ||\n event.completed - lastLoggedProgress >= 25\n ) {\n lastLoggedProgress = event.completed;\n logger.info(\n `external: metadata progress ${event.completed}/${event.total} (${currentPercent}%)`,\n );\n logger.debug(`external: last package processed ${event.packageName}`);\n }\n break;\n }\n case \"metadata_fetch_completed\":\n logger.info(`external: metadata fetch completed (${event.total} packages)`);\n break;\n case \"summary_built\":\n logger.info(\n `external: summary built (${event.totalDependencies} total, ${event.directDependencies} direct)`,\n );\n break;\n }\n };\n};\n\nconst createStructuralProgressReporter = (\n logger: Logger,\n): ((event: ParseTypescriptProjectProgressEvent) => void) => {\n let lastProcessed = 0;\n\n return (event) => {\n switch (event.stage) {\n case \"config_resolved\":\n if (event.usedFallbackScan) {\n logger.info(\n `structural: using filesystem scan discovery (tsconfigs=${event.tsconfigCount})`,\n );\n } else {\n logger.info(`structural: discovered tsconfig graph (${event.tsconfigCount} configs)`);\n }\n break;\n case \"files_discovered\":\n logger.info(`structural: discovered ${event.totalSourceFiles} source files`);\n break;\n case \"program_created\":\n logger.debug(`structural: TypeScript program created (${event.totalSourceFiles} files)`);\n break;\n case \"file_processed\":\n if (\n event.processed === event.total ||\n event.processed === 1 ||\n event.processed - lastProcessed >= 50\n ) {\n lastProcessed = event.processed;\n logger.info(`structural: resolved ${event.processed}/${event.total} files`);\n logger.debug(`structural: last file processed ${event.filePath}`);\n }\n break;\n case \"edges_resolved\":\n logger.info(`structural: resolved ${event.totalEdges} dependency edges`);\n break;\n }\n };\n};\n\nconst createEvolutionProgressReporter = (\n logger: Logger,\n): ((event: EvolutionAnalysisProgressEvent) => void) => {\n let lastParsedRecords = 0;\n\n return (event) => {\n switch (event.stage) {\n case \"checking_git_repository\":\n logger.debug(\"evolution: checking git repository\");\n break;\n case \"not_git_repository\":\n logger.warn(\"evolution: target path is not a git repository\");\n break;\n case \"loading_commit_history\":\n logger.info(\"evolution: loading git history\");\n break;\n case \"history\":\n if (event.event.stage === \"git_log_received\") {\n logger.info(`evolution: git log loaded (${event.event.bytes} bytes)`);\n break;\n }\n\n if (event.event.stage === \"git_log_parsed\") {\n logger.info(`evolution: parsed ${event.event.commits} commits`);\n break;\n }\n\n if (\n event.event.stage === \"git_log_parse_progress\" &&\n (event.event.parsedRecords === event.event.totalRecords ||\n event.event.parsedRecords === 1 ||\n event.event.parsedRecords - lastParsedRecords >= 500)\n ) {\n lastParsedRecords = event.event.parsedRecords;\n const currentPercent =\n event.event.totalRecords === 0\n ? 100\n : Math.floor((event.event.parsedRecords / event.event.totalRecords) * 100);\n logger.info(\n `evolution: parse progress ${event.event.parsedRecords}/${event.event.totalRecords} (${currentPercent}%)`,\n );\n }\n break;\n case \"computing_metrics\":\n logger.info(\"evolution: computing metrics\");\n break;\n case \"analysis_completed\":\n logger.debug(`evolution: analysis completed (available=${event.available})`);\n break;\n }\n };\n};\n\nexport const collectAnalysisInputs = async (\n inputPath: string | undefined,\n authorIdentityMode: AuthorIdentityCliMode,\n options: AnalysisRuntimeOptions = {},\n logger: Logger = createSilentLogger(),\n): Promise<AnalysisInputs> => {\n const invocationCwd = process.env[\"INIT_CWD\"] ?? process.cwd();\n const targetPath = resolveTargetPath(inputPath, invocationCwd);\n logger.info(`analyzing repository: ${targetPath}`);\n\n logger.info(\"building structural graph\");\n const structural = buildProjectGraphSummary({\n projectPath: targetPath,\n onProgress: createStructuralProgressReporter(logger),\n });\n logger.debug(\n `structural metrics: nodes=${structural.metrics.nodeCount}, edges=${structural.metrics.edgeCount}, cycles=${structural.metrics.cycleCount}`,\n );\n\n logger.info(`analyzing git evolution (author identity: ${authorIdentityMode})`);\n const repositoryEvolution = analyzeRepositoryEvolutionFromGit(\n {\n repositoryPath: targetPath,\n config: {\n authorIdentityMode,\n ...(options.recentWindowDays === undefined\n ? {}\n : { recentWindowDays: options.recentWindowDays }),\n },\n },\n createEvolutionProgressReporter(logger),\n );\n const evolution = enrichEvolutionSummaryWithWorkspaces(structural, repositoryEvolution);\n if (evolution.available) {\n logger.debug(\n `evolution metrics: commits=${evolution.metrics.totalCommits}, files=${evolution.metrics.totalFiles}, hotspotThreshold=${evolution.metrics.hotspotThresholdCommitCount}`,\n );\n } else {\n logger.warn(`evolution analysis unavailable: ${evolution.reason}`);\n }\n\n logger.info(\"analyzing external dependencies\");\n const external = await analyzeDependencyExposureFromProject(\n { repositoryPath: targetPath },\n createExternalProgressReporter(logger),\n );\n if (external.available) {\n logger.debug(\n `external metrics: total=${external.metrics.totalDependencies}, direct=${external.metrics.directDependencies}, transitive=${external.metrics.transitiveDependencies}`,\n );\n } else {\n logger.warn(`external analysis unavailable: ${external.reason}`);\n }\n\n return {\n structural,\n evolution,\n external,\n };\n};\n\nexport const runAnalyzeCommand = async (\n inputPath: string | undefined,\n authorIdentityMode: AuthorIdentityCliMode,\n options: AnalysisRuntimeOptions = {},\n logger: Logger = createSilentLogger(),\n): Promise<AnalyzeSummary> => {\n const analysisInputs = await collectAnalysisInputs(\n inputPath,\n authorIdentityMode,\n options,\n logger,\n );\n logger.info(\"computing risk summary\");\n const riskConfig = resolveRiskConfigForProfile(options.scoringProfile);\n const healthConfig = resolveHealthConfigForProfile(options.scoringProfile);\n const risk = computeRepositoryRiskSummary({\n structural: analysisInputs.structural,\n evolution: analysisInputs.evolution,\n external: analysisInputs.external,\n ...(riskConfig === undefined ? {} : { config: riskConfig }),\n });\n const health = computeRepositoryHealthSummary({\n structural: analysisInputs.structural,\n evolution: analysisInputs.evolution,\n ...(healthConfig === undefined ? {} : { config: healthConfig }),\n });\n logger.info(\n `analysis completed (riskScore=${risk.riskScore}, healthScore=${health.healthScore})`,\n );\n\n return {\n structural: analysisInputs.structural,\n evolution: analysisInputs.evolution,\n external: analysisInputs.external,\n risk,\n health,\n };\n};\n","export type GraphNode = {\n id: string;\n absolutePath: string;\n relativePath: string;\n};\n\nexport type GraphEdge = {\n from: string;\n to: string;\n};\n\nexport type GraphCycle = {\n nodes: readonly string[];\n};\n\nexport type FileDependency = {\n id: string;\n relativePath: string;\n directDependencies: readonly string[];\n fanIn: number;\n fanOut: number;\n depth: number;\n};\n\nexport type GraphMetrics = {\n nodeCount: number;\n edgeCount: number;\n cycleCount: number;\n graphDepth: number;\n maxFanIn: number;\n maxFanOut: number;\n};\n\nexport type WorkspaceKind = \"app\" | \"package\" | \"docs\" | \"example\" | \"tooling\" | \"unknown\";\n\nexport type WorkspacePackage = {\n name: string;\n path: string;\n kind: WorkspaceKind;\n};\n\nexport type WorkspaceStructuralSummary = WorkspacePackage & {\n fileCount: number;\n internalEdgeCount: number;\n incomingEdgeCount: number;\n outgoingEdgeCount: number;\n};\n\nexport type CrossWorkspaceEdge = {\n fromWorkspace: string;\n toWorkspace: string;\n from: string;\n to: string;\n};\n\nexport type GraphAnalysisSummary = {\n targetPath: string;\n nodes: readonly GraphNode[];\n edges: readonly GraphEdge[];\n cycles: readonly GraphCycle[];\n files: readonly FileDependency[];\n metrics: GraphMetrics;\n workspaces?: readonly WorkspaceStructuralSummary[];\n crossWorkspaceEdges?: readonly CrossWorkspaceEdge[];\n};\n\nexport type FileAuthorShare = {\n authorId: string;\n commits: number;\n share: number;\n};\n\nexport type FileAuthorChurnShare = {\n authorId: string;\n churnAdded: number;\n churnDeleted: number;\n churnTotal: number;\n share: number;\n};\n\nexport type FileEvolutionMetrics = {\n filePath: string;\n commitCount: number;\n frequencyPer100Commits: number;\n churnAdded: number;\n churnDeleted: number;\n churnTotal: number;\n lastCommitTimestamp: number | null;\n recentCommitCount: number;\n recentVolatility: number;\n topAuthorShareByCommits: number;\n busFactorByCommits: number;\n authorDistributionByCommits: readonly FileAuthorShare[];\n topAuthorShareByChurn: number;\n busFactorByChurn: number;\n authorDistributionByChurn: readonly FileAuthorChurnShare[];\n};\n\nexport type Hotspot = {\n filePath: string;\n rank: number;\n commitCount: number;\n churnTotal: number;\n};\n\nexport type FileCoupling = {\n fileA: string;\n fileB: string;\n coChangeCommits: number;\n couplingScore: number;\n};\n\nexport type RecentActivityPoint = {\n bucketStartUtcDate: string;\n commitCount: number;\n fileTouchCount: number;\n churnTotal: number;\n activeAuthorCount: number;\n volatilityScore: number;\n};\n\nexport type CouplingMatrix = {\n pairs: readonly FileCoupling[];\n totalPairCount: number;\n consideredCommits: number;\n skippedLargeCommits: number;\n truncated: boolean;\n};\n\nexport type RepositoryEvolutionMetrics = {\n totalCommits: number;\n totalFiles: number;\n headCommitTimestamp: number | null;\n recentWindowDays: number;\n hotspotTopPercent: number;\n hotspotThresholdCommitCount: number;\n};\n\nexport type WorkspaceEvolutionSummary = WorkspacePackage & {\n fileCount: number;\n commitCount: number;\n churnAdded: number;\n churnDeleted: number;\n churnTotal: number;\n recentCommitCount: number;\n recentVolatility: number;\n topAuthorShareByCommits: number;\n busFactorByCommits: number;\n hotspotCount: number;\n topHotspots: readonly Hotspot[];\n internalCouplingPairCount: number;\n incomingCouplingPairCount: number;\n outgoingCouplingPairCount: number;\n};\n\nexport type RepositoryEvolutionAvailable = {\n targetPath: string;\n available: true;\n files: readonly FileEvolutionMetrics[];\n hotspots: readonly Hotspot[];\n coupling: CouplingMatrix;\n recentActivity?: readonly RecentActivityPoint[];\n workspaces?: readonly WorkspaceEvolutionSummary[];\n metrics: RepositoryEvolutionMetrics;\n};\n\nexport type RepositoryEvolutionUnavailable = {\n targetPath: string;\n available: false;\n reason: \"not_git_repository\";\n};\n\nexport type RepositoryEvolutionSummary =\n | RepositoryEvolutionAvailable\n | RepositoryEvolutionUnavailable;\n\nexport type DependencyRiskSignal =\n | \"single_maintainer\"\n | \"abandoned\"\n | \"high_centrality\"\n | \"deep_chain\"\n | \"high_fanout\"\n | \"metadata_unavailable\";\n\nexport type DependencyExposureRecord = {\n name: string;\n direct: boolean;\n dependencyScope: \"prod\" | \"dev\";\n requestedRange: string | null;\n resolvedVersion: string | null;\n transitiveDependencies: readonly string[];\n weeklyDownloads: number | null;\n dependencyDepth: number;\n fanOut: number;\n dependents: number;\n maintainerCount: number | null;\n releaseFrequencyDays: number | null;\n daysSinceLastRelease: number | null;\n repositoryActivity30d: number | null;\n busFactor: number | null;\n ownRiskSignals: readonly DependencyRiskSignal[];\n inheritedRiskSignals: readonly DependencyRiskSignal[];\n riskSignals: readonly DependencyRiskSignal[];\n};\n\nexport type CentralDependency = {\n name: string;\n dependents: number;\n fanOut: number;\n direct: boolean;\n};\n\nexport type ExternalAnalysisMetrics = {\n totalDependencies: number;\n directDependencies: number;\n directProductionDependencies: number;\n directDevelopmentDependencies: number;\n transitiveDependencies: number;\n dependencyDepth: number;\n lockfileKind: \"pnpm\" | \"npm\" | \"npm-shrinkwrap\" | \"yarn\" | \"bun\";\n metadataCoverage: number;\n};\n\nexport type ExternalAnalysisAvailable = {\n targetPath: string;\n available: true;\n metrics: ExternalAnalysisMetrics;\n dependencies: readonly DependencyExposureRecord[];\n workspaces?: readonly WorkspaceDependencyExposureSummary[];\n highRiskDependencies: readonly string[];\n highRiskDevelopmentDependencies: readonly string[];\n transitiveExposureDependencies: readonly string[];\n singleMaintainerDependencies: readonly string[];\n abandonedDependencies: readonly string[];\n centralityRanking: readonly CentralDependency[];\n};\n\nexport type WorkspaceDependencyExposureSummary = WorkspacePackage & {\n directDependencies: number;\n directProductionDependencies: number;\n directDevelopmentDependencies: number;\n unresolvedDependencies: readonly string[];\n dependencyNames: readonly string[];\n sharedDependencies: readonly string[];\n highRiskDependencies: readonly string[];\n highRiskDevelopmentDependencies: readonly string[];\n transitiveExposureDependencies: readonly string[];\n singleMaintainerDependencies: readonly string[];\n abandonedDependencies: readonly string[];\n};\n\nexport type ExternalAnalysisUnavailable = {\n targetPath: string;\n available: false;\n reason:\n | \"package_json_not_found\"\n | \"lockfile_not_found\"\n | \"unsupported_lockfile_format\"\n | \"invalid_lockfile\";\n};\n\nexport type ExternalAnalysisSummary = ExternalAnalysisAvailable | ExternalAnalysisUnavailable;\n\nexport type RiskFactors = {\n structural: number;\n evolution: number;\n external: number;\n};\n\nexport type FileRiskScore = {\n file: string;\n score: number;\n normalizedScore: number;\n factors: RiskFactors;\n};\n\nexport type ModuleRiskScore = {\n module: string;\n score: number;\n normalizedScore: number;\n fileCount: number;\n};\n\nexport type DependencyRiskScore = {\n dependency: string;\n score: number;\n normalizedScore: number;\n ownRiskSignals: readonly DependencyRiskSignal[];\n inheritedRiskSignals: readonly DependencyRiskSignal[];\n};\n\nexport type WorkspaceRiskScore = WorkspacePackage & {\n score: number;\n normalizedScore: number;\n fileCount: number;\n averageFileRisk: number;\n peakFileRisk: number;\n internalEdgeCount: number;\n incomingEdgeCount: number;\n outgoingEdgeCount: number;\n topFiles: readonly RiskHotspot[];\n};\n\nexport type RiskHotspot = {\n file: string;\n score: number;\n factors: RiskFactors;\n};\n\nexport type FragileCluster = {\n id: string;\n kind: \"structural_cycle\" | \"change_coupling\";\n files: readonly string[];\n score: number;\n};\n\nexport type DependencyAmplificationZone = {\n file: string;\n score: number;\n externalPressure: number;\n};\n\nexport type RiskFactorFamily = \"structural\" | \"evolution\" | \"external\" | \"composite\";\n\nexport type EvidenceRef =\n | {\n kind: \"file_metric\";\n target: string;\n metric: string;\n }\n | {\n kind: \"repository_metric\";\n metric: string;\n }\n | {\n kind: \"dependency_metric\";\n target: string;\n metric: string;\n }\n | {\n kind: \"graph_cycle\";\n cycleId: string;\n files: readonly string[];\n }\n | {\n kind: \"coupling_pair\";\n fileA: string;\n fileB: string;\n };\n\nexport type RiskFactorTrace = {\n factorId: string;\n family: RiskFactorFamily;\n contribution: number;\n rawMetrics: Readonly<Record<string, number | null>>;\n normalizedMetrics: Readonly<Record<string, number | null>>;\n weight: number | null;\n amplification: number | null;\n evidence: readonly EvidenceRef[];\n confidence: number;\n};\n\nexport type RiskReductionLever = {\n factorId: string;\n estimatedImpact: number;\n};\n\nexport type TargetTrace = {\n targetType: \"repository\" | \"file\" | \"module\" | \"dependency\";\n targetId: string;\n totalScore: number;\n normalizedScore: number;\n factors: readonly RiskFactorTrace[];\n dominantFactors: readonly string[];\n reductionLevers: readonly RiskReductionLever[];\n};\n\nexport type RiskTrace = {\n schemaVersion: \"1\";\n contributionTolerance: number;\n targets: readonly TargetTrace[];\n};\n\nexport type RepositoryRiskSummary = {\n riskScore: number;\n normalizedScore: number;\n percentileRank?: number;\n hotspots: readonly RiskHotspot[];\n fragileClusters: readonly FragileCluster[];\n dependencyAmplificationZones: readonly DependencyAmplificationZone[];\n fileScores: readonly FileRiskScore[];\n moduleScores: readonly ModuleRiskScore[];\n workspaceScores: readonly WorkspaceRiskScore[];\n dependencyScores: readonly DependencyRiskScore[];\n};\n\nexport type RepositoryRiskEvaluation = {\n summary: RepositoryRiskSummary;\n trace?: RiskTrace;\n};\n\nexport type HealthDimension =\n | \"modularity\"\n | \"changeHygiene\"\n | \"testHealth\"\n | \"ownershipDistribution\";\n\nexport type HealthIssueSeverity = \"warn\" | \"error\";\n\nexport type HealthIssue = {\n id: string;\n ruleId?: string;\n signal: string;\n severity: HealthIssueSeverity;\n target: string;\n message: string;\n dimension: HealthDimension;\n evidenceMetrics: Readonly<Record<string, number | null>>;\n};\n\nexport type RepositoryHealthDimensions = {\n modularity: number;\n changeHygiene: number;\n testHealth: number;\n ownershipDistribution: number;\n};\n\nexport type HealthEvidenceRef =\n | {\n kind: \"repository_metric\";\n metric: string;\n }\n | {\n kind: \"file_metric\";\n target: string;\n metric: string;\n }\n | {\n kind: \"lint_rule\";\n ruleId: string;\n };\n\nexport type HealthFactorTrace = {\n factorId: string;\n contribution: number;\n penalty: number;\n rawMetrics: Readonly<Record<string, number | null>>;\n normalizedMetrics: Readonly<Record<string, number | null>>;\n weight: number;\n evidence: readonly HealthEvidenceRef[];\n};\n\nexport type HealthDimensionTrace = {\n dimension: HealthDimension;\n normalizedScore: number;\n score: number;\n factors: readonly HealthFactorTrace[];\n};\n\nexport type HealthTrace = {\n schemaVersion: \"1\";\n dimensions: readonly HealthDimensionTrace[];\n};\n\nexport type RepositoryHealthSummary = {\n healthScore: number;\n normalizedScore: number;\n dimensions: RepositoryHealthDimensions;\n topIssues: readonly HealthIssue[];\n trace?: HealthTrace;\n};\n\nexport const normalizeWorkspacePath = (pathValue: string): string =>\n pathValue.replaceAll(\"\\\\\", \"/\");\n\nexport const fileBelongsToWorkspace = (filePath: string, workspace: WorkspacePackage): boolean => {\n const normalizedFilePath = normalizeWorkspacePath(filePath);\n const normalizedWorkspacePath = normalizeWorkspacePath(workspace.path);\n return (\n normalizedFilePath === normalizedWorkspacePath ||\n normalizedFilePath.startsWith(`${normalizedWorkspacePath}/`)\n );\n};\n\nexport const findWorkspaceForFile = (\n filePath: string,\n workspaces: readonly WorkspacePackage[],\n): WorkspacePackage | null => {\n let match: WorkspacePackage | null = null;\n for (const workspace of workspaces) {\n if (fileBelongsToWorkspace(filePath, workspace)) {\n if (match === null || workspace.path.length > match.path.length) {\n match = workspace;\n }\n }\n }\n\n return match;\n};\n\nexport const createWorkspaceByFile = (\n filePaths: readonly string[],\n workspaces: readonly WorkspacePackage[],\n): ReadonlyMap<string, WorkspacePackage> => {\n const workspaceByFile = new Map<string, WorkspacePackage>();\n\n for (const filePath of filePaths) {\n const workspace = findWorkspaceForFile(filePath, workspaces);\n if (workspace !== null) {\n workspaceByFile.set(filePath, workspace);\n }\n }\n\n return workspaceByFile;\n};\n\nexport type AnalyzeSummary = {\n structural: GraphAnalysisSummary;\n evolution: RepositoryEvolutionSummary;\n external: ExternalAnalysisSummary;\n risk: RepositoryRiskSummary;\n health: RepositoryHealthSummary;\n};\n","export type NodeRecord = {\n id: string;\n absolutePath: string;\n relativePath: string;\n};\n\nexport type EdgeRecord = {\n from: string;\n to: string;\n};\n\nexport type GraphData = {\n nodes: readonly NodeRecord[];\n edges: readonly EdgeRecord[];\n adjacencyById: ReadonlyMap<string, readonly string[]>;\n};\n\nconst edgeKey = (from: string, to: string): string => `${from}\\u0000${to}`;\n\nexport const createGraphData = (\n nodes: readonly NodeRecord[],\n rawEdges: readonly EdgeRecord[],\n): GraphData => {\n const sortedNodes = [...nodes].sort((a, b) => a.id.localeCompare(b.id));\n const knownNodeIds = new Set(sortedNodes.map((node) => node.id));\n\n const uniqueEdgeMap = new Map<string, EdgeRecord>();\n for (const edge of rawEdges) {\n if (edge.from === edge.to) {\n continue;\n }\n\n if (!knownNodeIds.has(edge.from) || !knownNodeIds.has(edge.to)) {\n continue;\n }\n\n uniqueEdgeMap.set(edgeKey(edge.from, edge.to), edge);\n }\n\n const sortedEdges = [...uniqueEdgeMap.values()].sort((a, b) => {\n const fromCompare = a.from.localeCompare(b.from);\n if (fromCompare !== 0) {\n return fromCompare;\n }\n\n return a.to.localeCompare(b.to);\n });\n\n const adjacency = new Map<string, string[]>();\n for (const node of sortedNodes) {\n adjacency.set(node.id, []);\n }\n\n for (const edge of sortedEdges) {\n adjacency.get(edge.from)?.push(edge.to);\n }\n\n const adjacencyById = new Map<string, readonly string[]>();\n for (const [nodeId, targets] of adjacency.entries()) {\n adjacencyById.set(nodeId, [...targets]);\n }\n\n return {\n nodes: sortedNodes,\n edges: sortedEdges,\n adjacencyById,\n };\n};\n","import type {\n CrossWorkspaceEdge,\n FileDependency,\n GraphAnalysisSummary,\n GraphCycle,\n GraphMetrics,\n WorkspacePackage,\n WorkspaceStructuralSummary,\n} from \"@codesentinel/core\";\nimport { createWorkspaceByFile as createWorkspaceMembershipByFile } from \"@codesentinel/core\";\nimport type { GraphData } from \"./graph-model.js\";\nimport { runTarjanScc } from \"./tarjan.js\";\n\ntype DepthComputation = {\n depthByNodeId: ReadonlyMap<string, number>;\n graphDepth: number;\n cycles: readonly GraphCycle[];\n};\n\nconst hasSelfLoop = (\n nodeId: string,\n adjacencyById: ReadonlyMap<string, readonly string[]>,\n): boolean => {\n const targets = adjacencyById.get(nodeId) ?? [];\n return targets.includes(nodeId);\n};\n\nconst computeCyclesAndDepth = (graph: GraphData): DepthComputation => {\n const { components } = runTarjanScc(graph.adjacencyById);\n\n const cycles: GraphCycle[] = [];\n const componentByNodeId = new Map<string, number>();\n components.forEach((component, index) => {\n for (const nodeId of component) {\n componentByNodeId.set(nodeId, index);\n }\n\n if (component.length > 1) {\n cycles.push({ nodes: [...component] });\n return;\n }\n\n const onlyNode = component[0];\n if (onlyNode !== undefined && hasSelfLoop(onlyNode, graph.adjacencyById)) {\n cycles.push({ nodes: [...component] });\n }\n });\n\n const dagOutgoing = new Map<number, Set<number>>();\n const inDegree = new Map<number, number>();\n\n for (let i = 0; i < components.length; i += 1) {\n dagOutgoing.set(i, new Set());\n inDegree.set(i, 0);\n }\n\n for (const edge of graph.edges) {\n const fromComponent = componentByNodeId.get(edge.from);\n const toComponent = componentByNodeId.get(edge.to);\n\n if (fromComponent === undefined || toComponent === undefined || fromComponent === toComponent) {\n continue;\n }\n\n const outgoing = dagOutgoing.get(fromComponent);\n if (outgoing?.has(toComponent) === true) {\n continue;\n }\n\n outgoing?.add(toComponent);\n inDegree.set(toComponent, (inDegree.get(toComponent) ?? 0) + 1);\n }\n\n const queue: number[] = [];\n const depthByComponent = new Map<number, number>();\n\n for (let i = 0; i < components.length; i += 1) {\n if ((inDegree.get(i) ?? 0) === 0) {\n queue.push(i);\n depthByComponent.set(i, 0);\n }\n }\n\n let cursor = 0;\n while (cursor < queue.length) {\n const componentId = queue[cursor];\n cursor += 1;\n\n if (componentId === undefined) {\n continue;\n }\n\n const currentDepth = depthByComponent.get(componentId) ?? 0;\n const outgoing = dagOutgoing.get(componentId) ?? new Set<number>();\n\n for (const nextComponent of outgoing) {\n const nextDepth = depthByComponent.get(nextComponent) ?? 0;\n if (currentDepth + 1 > nextDepth) {\n depthByComponent.set(nextComponent, currentDepth + 1);\n }\n\n const remainingIncoming = (inDegree.get(nextComponent) ?? 0) - 1;\n inDegree.set(nextComponent, remainingIncoming);\n if (remainingIncoming === 0) {\n queue.push(nextComponent);\n }\n }\n }\n\n const depthByNodeId = new Map<string, number>();\n let graphDepth = 0;\n\n components.forEach((component, componentId) => {\n const componentDepth = depthByComponent.get(componentId) ?? 0;\n if (componentDepth > graphDepth) {\n graphDepth = componentDepth;\n }\n\n for (const nodeId of component) {\n depthByNodeId.set(nodeId, componentDepth);\n }\n });\n\n cycles.sort((a, b) => {\n const firstA = a.nodes[0] ?? \"\";\n const firstB = b.nodes[0] ?? \"\";\n return firstA.localeCompare(firstB);\n });\n\n return {\n depthByNodeId,\n graphDepth,\n cycles,\n };\n};\n\nconst createWorkspaceByFile = (\n graph: GraphData,\n workspaces: readonly WorkspacePackage[],\n): ReadonlyMap<string, WorkspacePackage> => {\n return createWorkspaceMembershipByFile(\n graph.nodes.map((node) => node.id),\n workspaces,\n );\n};\n\nconst createCrossWorkspaceEdges = (\n graph: GraphData,\n workspaceByFile: ReadonlyMap<string, WorkspacePackage>,\n): readonly CrossWorkspaceEdge[] => {\n const edges: CrossWorkspaceEdge[] = [];\n\n for (const edge of graph.edges) {\n const fromWorkspace = workspaceByFile.get(edge.from);\n const toWorkspace = workspaceByFile.get(edge.to);\n if (\n fromWorkspace === undefined ||\n toWorkspace === undefined ||\n fromWorkspace.path === toWorkspace.path\n ) {\n continue;\n }\n\n edges.push({\n fromWorkspace: fromWorkspace.path,\n toWorkspace: toWorkspace.path,\n from: edge.from,\n to: edge.to,\n });\n }\n\n return edges;\n};\n\nconst createWorkspaceSummaries = (\n graph: GraphData,\n workspaces: readonly WorkspacePackage[],\n workspaceByFile: ReadonlyMap<string, WorkspacePackage>,\n): readonly WorkspaceStructuralSummary[] => {\n if (workspaces.length === 0) {\n return [];\n }\n\n const fileCountByWorkspacePath = new Map<string, number>();\n const internalEdgesByWorkspacePath = new Map<string, number>();\n const incomingEdgesByWorkspacePath = new Map<string, number>();\n const outgoingEdgesByWorkspacePath = new Map<string, number>();\n\n for (const workspace of workspaces) {\n fileCountByWorkspacePath.set(workspace.path, 0);\n internalEdgesByWorkspacePath.set(workspace.path, 0);\n incomingEdgesByWorkspacePath.set(workspace.path, 0);\n outgoingEdgesByWorkspacePath.set(workspace.path, 0);\n }\n\n for (const node of graph.nodes) {\n const workspace = workspaceByFile.get(node.id);\n if (workspace === undefined) {\n continue;\n }\n\n fileCountByWorkspacePath.set(\n workspace.path,\n (fileCountByWorkspacePath.get(workspace.path) ?? 0) + 1,\n );\n }\n\n for (const edge of graph.edges) {\n const fromWorkspace = workspaceByFile.get(edge.from) ?? null;\n const toWorkspace = workspaceByFile.get(edge.to) ?? null;\n\n if (fromWorkspace === null && toWorkspace === null) {\n continue;\n }\n\n if (fromWorkspace?.path === toWorkspace?.path && fromWorkspace !== null) {\n internalEdgesByWorkspacePath.set(\n fromWorkspace.path,\n (internalEdgesByWorkspacePath.get(fromWorkspace.path) ?? 0) + 1,\n );\n continue;\n }\n\n if (fromWorkspace !== null) {\n outgoingEdgesByWorkspacePath.set(\n fromWorkspace.path,\n (outgoingEdgesByWorkspacePath.get(fromWorkspace.path) ?? 0) + 1,\n );\n }\n\n if (toWorkspace !== null) {\n incomingEdgesByWorkspacePath.set(\n toWorkspace.path,\n (incomingEdgesByWorkspacePath.get(toWorkspace.path) ?? 0) + 1,\n );\n }\n }\n\n return workspaces.map((workspace) => ({\n ...workspace,\n fileCount: fileCountByWorkspacePath.get(workspace.path) ?? 0,\n internalEdgeCount: internalEdgesByWorkspacePath.get(workspace.path) ?? 0,\n incomingEdgeCount: incomingEdgesByWorkspacePath.get(workspace.path) ?? 0,\n outgoingEdgeCount: outgoingEdgesByWorkspacePath.get(workspace.path) ?? 0,\n }));\n};\n\nexport const createGraphAnalysisSummary = (\n targetPath: string,\n graph: GraphData,\n workspaces: readonly WorkspacePackage[] = [],\n): GraphAnalysisSummary => {\n const fanInById = new Map<string, number>();\n const fanOutById = new Map<string, number>();\n\n for (const node of graph.nodes) {\n fanInById.set(node.id, 0);\n fanOutById.set(node.id, graph.adjacencyById.get(node.id)?.length ?? 0);\n }\n\n for (const edge of graph.edges) {\n fanInById.set(edge.to, (fanInById.get(edge.to) ?? 0) + 1);\n }\n\n const { cycles, depthByNodeId, graphDepth } = computeCyclesAndDepth(graph);\n\n let maxFanIn = 0;\n let maxFanOut = 0;\n\n const files: FileDependency[] = graph.nodes.map((node) => {\n const fanIn = fanInById.get(node.id) ?? 0;\n const fanOut = fanOutById.get(node.id) ?? 0;\n\n if (fanIn > maxFanIn) {\n maxFanIn = fanIn;\n }\n\n if (fanOut > maxFanOut) {\n maxFanOut = fanOut;\n }\n\n return {\n id: node.id,\n relativePath: node.relativePath,\n directDependencies: graph.adjacencyById.get(node.id) ?? [],\n fanIn,\n fanOut,\n depth: depthByNodeId.get(node.id) ?? 0,\n };\n });\n\n const metrics: GraphMetrics = {\n nodeCount: graph.nodes.length,\n edgeCount: graph.edges.length,\n cycleCount: cycles.length,\n graphDepth,\n maxFanIn,\n maxFanOut,\n };\n const workspaceByFile = createWorkspaceByFile(graph, workspaces);\n\n return {\n targetPath,\n nodes: graph.nodes,\n edges: graph.edges,\n cycles,\n files,\n metrics,\n ...(workspaces.length === 0\n ? {}\n : {\n workspaces: createWorkspaceSummaries(graph, workspaces, workspaceByFile),\n crossWorkspaceEdges: createCrossWorkspaceEdges(graph, workspaceByFile),\n }),\n };\n};\n","type TarjanResult = {\n components: readonly (readonly string[])[];\n};\n\nexport const runTarjanScc = (\n adjacencyById: ReadonlyMap<string, readonly string[]>,\n): TarjanResult => {\n // SCC = group of nodes where every node can reach every other node through directed edges.\n // In this codebase, SCCs are used to detect dependency cycles before computing graph depth.\n let index = 0;\n const indices = new Map<string, number>();\n const lowLink = new Map<string, number>();\n const stack: string[] = [];\n const onStack = new Set<string>();\n const components: string[][] = [];\n\n const strongConnect = (nodeId: string): void => {\n indices.set(nodeId, index);\n lowLink.set(nodeId, index);\n index += 1;\n\n stack.push(nodeId);\n onStack.add(nodeId);\n\n const neighbors = adjacencyById.get(nodeId) ?? [];\n for (const nextId of neighbors) {\n if (!indices.has(nextId)) {\n strongConnect(nextId);\n const nodeLowLink = lowLink.get(nodeId);\n const nextLowLink = lowLink.get(nextId);\n if (nodeLowLink !== undefined && nextLowLink !== undefined && nextLowLink < nodeLowLink) {\n lowLink.set(nodeId, nextLowLink);\n }\n continue;\n }\n\n if (onStack.has(nextId)) {\n const nodeLowLink = lowLink.get(nodeId);\n const nextIndex = indices.get(nextId);\n if (nodeLowLink !== undefined && nextIndex !== undefined && nextIndex < nodeLowLink) {\n lowLink.set(nodeId, nextIndex);\n }\n }\n }\n\n const nodeLowLink = lowLink.get(nodeId);\n const nodeIndex = indices.get(nodeId);\n if (nodeLowLink === undefined || nodeIndex === undefined || nodeLowLink !== nodeIndex) {\n return;\n }\n\n const component: string[] = [];\n for (;;) {\n const popped = stack.pop();\n if (popped === undefined) {\n break;\n }\n\n onStack.delete(popped);\n component.push(popped);\n if (popped === nodeId) {\n break;\n }\n }\n\n component.sort((a, b) => a.localeCompare(b));\n components.push(component);\n };\n\n const nodeIds = [...adjacencyById.keys()].sort((a, b) => a.localeCompare(b));\n for (const nodeId of nodeIds) {\n if (!indices.has(nodeId)) {\n strongConnect(nodeId);\n }\n }\n\n components.sort((a, b) => {\n const firstA = a[0] ?? \"\";\n const firstB = b[0] ?? \"\";\n return firstA.localeCompare(firstB);\n });\n\n return { components };\n};\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { extname, isAbsolute, join, relative, resolve } from \"node:path\";\nimport * as ts from \"typescript\";\nimport type { WorkspacePackage } from \"@codesentinel/core\";\nimport type { EdgeRecord, NodeRecord } from \"../domain/graph-model.js\";\n\ntype ParsedProject = {\n nodes: readonly NodeRecord[];\n edges: readonly EdgeRecord[];\n};\n\ntype PackageJsonExportMap = {\n readonly [key: string]: PackageJsonExportValue | undefined;\n};\n\ntype PackageJsonExportValue = string | readonly PackageJsonExportValue[] | PackageJsonExportMap;\n\ntype PackageJsonEntryFields = {\n main?: string;\n module?: string;\n source?: string;\n types?: string;\n typings?: string;\n exports?: PackageJsonExportValue;\n};\n\nexport type ParseTypescriptProjectProgressEvent =\n | { stage: \"config_resolved\"; tsconfigCount: number; usedFallbackScan: boolean }\n | { stage: \"files_discovered\"; totalSourceFiles: number }\n | { stage: \"program_created\"; totalSourceFiles: number }\n | { stage: \"file_processed\"; processed: number; total: number; filePath: string }\n | { stage: \"edges_resolved\"; totalEdges: number };\n\nconst SOURCE_EXTENSIONS = new Set([\".ts\", \".tsx\", \".mts\", \".cts\", \".js\", \".jsx\", \".mjs\", \".cjs\"]);\nconst SCAN_EXCLUDES = [\n \"**/node_modules/**\",\n \"**/.git/**\",\n \"**/dist/**\",\n \"**/build/**\",\n \"**/.next/**\",\n \"**/coverage/**\",\n \"**/.turbo/**\",\n \"**/.cache/**\",\n \"**/out/**\",\n];\nconst SCAN_INCLUDES = [\"**/*\"];\nconst IGNORED_SEGMENTS = new Set([\n \"node_modules\",\n \".git\",\n \"dist\",\n \"build\",\n \".next\",\n \"coverage\",\n \".turbo\",\n \".cache\",\n \"out\",\n]);\n\nconst normalizePath = (pathValue: string): string => pathValue.replaceAll(\"\\\\\", \"/\");\n\nconst readPackageJson = (packageJsonPath: string): PackageJsonEntryFields | null => {\n try {\n return JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as PackageJsonEntryFields;\n } catch {\n return null;\n }\n};\n\nconst isProjectSourceFile = (filePath: string, projectRoot: string): boolean => {\n const extension = extname(filePath);\n if (!SOURCE_EXTENSIONS.has(extension)) {\n return false;\n }\n\n const relativePath = relative(projectRoot, filePath);\n if (relativePath.startsWith(\"..\")) {\n return false;\n }\n\n const normalizedRelativePath = normalizePath(relativePath);\n const segments = normalizedRelativePath.split(\"/\");\n return !segments.some((segment) => IGNORED_SEGMENTS.has(segment));\n};\n\nconst discoverSourceFilesByScan = (projectRoot: string): readonly string[] => {\n const files = ts.sys.readDirectory(\n projectRoot,\n [...SOURCE_EXTENSIONS],\n SCAN_EXCLUDES,\n SCAN_INCLUDES,\n );\n return files.map((filePath) => resolve(filePath));\n};\n\nconst parseTsConfigFile = (configPath: string): ts.ParsedCommandLine => {\n const parsedCommandLine = ts.getParsedCommandLineOfConfigFile(\n configPath,\n {},\n {\n ...ts.sys,\n onUnRecoverableConfigFileDiagnostic: () => {\n throw new Error(`Failed to parse TypeScript configuration at ${configPath}`);\n },\n },\n );\n\n if (parsedCommandLine === undefined) {\n throw new Error(`Failed to parse TypeScript configuration at ${configPath}`);\n }\n\n return parsedCommandLine;\n};\n\ntype CollectedTsConfigData = {\n fileNames: readonly string[];\n rootOptions: ts.CompilerOptions;\n visitedConfigCount: number;\n};\n\nconst collectFilesFromTsConfigGraph = (projectRoot: string): CollectedTsConfigData | null => {\n const rootConfigPath = ts.findConfigFile(\n projectRoot,\n (filePath) => ts.sys.fileExists(filePath),\n \"tsconfig.json\",\n );\n if (rootConfigPath === undefined) {\n return null;\n }\n\n const visitedConfigPaths = new Set<string>();\n const collectedFiles = new Set<string>();\n let rootOptions: ts.CompilerOptions | null = null;\n\n const visitConfig = (configPath: string): void => {\n const absoluteConfigPath = resolve(configPath);\n if (visitedConfigPaths.has(absoluteConfigPath)) {\n return;\n }\n\n visitedConfigPaths.add(absoluteConfigPath);\n const parsed = parseTsConfigFile(absoluteConfigPath);\n if (rootOptions === null) {\n rootOptions = parsed.options;\n }\n\n for (const filePath of parsed.fileNames) {\n collectedFiles.add(resolve(filePath));\n }\n\n for (const reference of parsed.projectReferences ?? []) {\n const referencePath = resolve(reference.path);\n const referenceConfigPath = ts.sys.directoryExists(referencePath)\n ? ts.findConfigFile(\n referencePath,\n (filePath) => ts.sys.fileExists(filePath),\n \"tsconfig.json\",\n )\n : referencePath;\n\n if (referenceConfigPath !== undefined && ts.sys.fileExists(referenceConfigPath)) {\n visitConfig(referenceConfigPath);\n }\n }\n };\n\n visitConfig(rootConfigPath);\n\n return {\n fileNames: [...collectedFiles],\n rootOptions: rootOptions ?? {\n moduleResolution: ts.ModuleResolutionKind.NodeNext,\n },\n visitedConfigCount: visitedConfigPaths.size,\n };\n};\n\nconst createCompilerOptions = (base: ts.CompilerOptions | undefined): ts.CompilerOptions => ({\n ...base,\n allowJs: true,\n moduleResolution: base?.moduleResolution ?? ts.ModuleResolutionKind.NodeNext,\n});\n\nconst parseTsConfig = (\n projectRoot: string,\n): {\n fileNames: readonly string[];\n options: ts.CompilerOptions;\n tsconfigCount: number;\n usedFallbackScan: boolean;\n} => {\n const collected = collectFilesFromTsConfigGraph(projectRoot);\n if (collected === null) {\n return {\n fileNames: discoverSourceFilesByScan(projectRoot),\n options: createCompilerOptions(undefined),\n tsconfigCount: 0,\n usedFallbackScan: true,\n };\n }\n\n if (collected.fileNames.length === 0) {\n return {\n fileNames: discoverSourceFilesByScan(projectRoot),\n options: createCompilerOptions(collected.rootOptions),\n tsconfigCount: collected.visitedConfigCount,\n usedFallbackScan: true,\n };\n }\n\n return {\n fileNames: collected.fileNames,\n options: createCompilerOptions(collected.rootOptions),\n tsconfigCount: collected.visitedConfigCount,\n usedFallbackScan: false,\n };\n};\n\nconst getSpecifierFromExpression = (expression: ts.Expression): string | undefined => {\n if (ts.isStringLiteral(expression)) {\n return expression.text;\n }\n\n if (ts.isNoSubstitutionTemplateLiteral(expression)) {\n return expression.text;\n }\n\n return undefined;\n};\n\nconst hasRuntimeImport = (importDeclaration: ts.ImportDeclaration): boolean => {\n const importClause = importDeclaration.importClause;\n if (importClause === undefined) {\n return true;\n }\n\n if (importClause.isTypeOnly) {\n return false;\n }\n\n if (importClause.name !== undefined) {\n return true;\n }\n\n const namedBindings = importClause.namedBindings;\n if (namedBindings === undefined) {\n return false;\n }\n\n if (ts.isNamespaceImport(namedBindings)) {\n return true;\n }\n\n if (namedBindings.elements.length === 0) {\n return true;\n }\n\n return namedBindings.elements.some((element) => !element.isTypeOnly);\n};\n\nconst extractModuleSpecifiers = (sourceFile: ts.SourceFile): readonly string[] => {\n const specifiers = new Set<string>();\n\n const visit = (node: ts.Node): void => {\n if (ts.isImportDeclaration(node)) {\n if (hasRuntimeImport(node) && node.moduleSpecifier !== undefined) {\n const specifier = getSpecifierFromExpression(node.moduleSpecifier);\n if (specifier !== undefined) {\n specifiers.add(specifier);\n }\n }\n return;\n }\n\n if (ts.isExportDeclaration(node)) {\n if (!node.isTypeOnly && node.moduleSpecifier !== undefined) {\n const specifier = getSpecifierFromExpression(node.moduleSpecifier);\n if (specifier !== undefined) {\n specifiers.add(specifier);\n }\n }\n return;\n }\n\n if (ts.isCallExpression(node)) {\n if (node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments.length > 0) {\n const firstArgument = node.arguments[0];\n if (firstArgument !== undefined) {\n const specifier = getSpecifierFromExpression(firstArgument);\n if (specifier !== undefined) {\n specifiers.add(specifier);\n }\n }\n }\n\n if (\n ts.isIdentifier(node.expression) &&\n node.expression.text === \"require\" &&\n node.arguments.length > 0\n ) {\n const firstArgument = node.arguments[0];\n if (firstArgument !== undefined) {\n const specifier = getSpecifierFromExpression(firstArgument);\n if (specifier !== undefined) {\n specifiers.add(specifier);\n }\n }\n }\n }\n\n ts.forEachChild(node, visit);\n };\n\n visit(sourceFile);\n return [...specifiers];\n};\n\nconst parseWorkspaceSpecifier = (\n specifier: string,\n workspaceNames: ReadonlySet<string>,\n): { packageName: string; subpath: string | null } | null => {\n const parts = specifier.split(\"/\");\n const packageName = specifier.startsWith(\"@\") ? parts.slice(0, 2).join(\"/\") : (parts[0] ?? \"\");\n\n if (!workspaceNames.has(packageName)) {\n return null;\n }\n\n const subpath = specifier.slice(packageName.length).replace(/^\\//, \"\");\n return {\n packageName,\n subpath: subpath.length === 0 ? null : subpath,\n };\n};\n\nconst expandFileCandidates = (pathWithoutExtension: string): readonly string[] => [\n pathWithoutExtension,\n ...[...SOURCE_EXTENSIONS].map((extension) => `${pathWithoutExtension}${extension}`),\n ...[...SOURCE_EXTENSIONS].map((extension) => join(pathWithoutExtension, `index${extension}`)),\n];\n\nconst isExportArray = (value: PackageJsonExportValue): value is readonly PackageJsonExportValue[] =>\n Array.isArray(value);\n\nconst isExportMap = (value: PackageJsonExportValue): value is PackageJsonExportMap =>\n typeof value !== \"string\" && !isExportArray(value);\n\nconst collectExportTargetCandidates = (\n value: PackageJsonExportValue | undefined,\n): readonly string[] => {\n if (value === undefined) {\n return [];\n }\n\n if (typeof value === \"string\") {\n return [value];\n }\n\n if (isExportArray(value)) {\n return value.flatMap((entry) => collectExportTargetCandidates(entry));\n }\n\n if (!isExportMap(value)) {\n return [];\n }\n\n const candidates: string[] = [];\n for (const key of [\"source\", \"types\", \"typings\", \"import\", \"module\", \"require\", \"default\"]) {\n candidates.push(...collectExportTargetCandidates(value[key]));\n }\n\n return candidates;\n};\n\nconst collectPackageExportCandidates = (\n packageJson: PackageJsonEntryFields | null,\n subpath: string | null,\n): readonly string[] => {\n const exportsValue = packageJson?.exports;\n if (exportsValue === undefined) {\n return [];\n }\n\n if (subpath === null) {\n if (typeof exportsValue === \"string\" || isExportArray(exportsValue)) {\n return collectExportTargetCandidates(exportsValue);\n }\n\n return collectExportTargetCandidates(exportsValue[\".\"]);\n }\n\n if (typeof exportsValue === \"string\" || isExportArray(exportsValue)) {\n return [];\n }\n\n const exportKey = `./${subpath}`;\n const exactCandidates = collectExportTargetCandidates(exportsValue[exportKey]);\n if (exactCandidates.length > 0) {\n return exactCandidates;\n }\n\n const wildcardCandidates: string[] = [];\n for (const [key, value] of Object.entries(exportsValue)) {\n if (!key.includes(\"*\")) {\n continue;\n }\n\n const [prefix = \"\", suffix = \"\"] = key.split(\"*\");\n if (!exportKey.startsWith(prefix) || !exportKey.endsWith(suffix)) {\n continue;\n }\n\n const replacement = exportKey.slice(prefix.length, exportKey.length - suffix.length);\n for (const candidate of collectExportTargetCandidates(value)) {\n wildcardCandidates.push(candidate.replaceAll(\"*\", replacement));\n }\n }\n\n return wildcardCandidates;\n};\n\nconst resolveFirstAnalyzedCandidate = (\n candidates: readonly string[],\n sourceFilePathSet: ReadonlySet<string>,\n): string | undefined => {\n for (const candidate of candidates) {\n for (const expanded of expandFileCandidates(candidate)) {\n const normalized = normalizePath(expanded);\n if (sourceFilePathSet.has(normalized) && existsSync(normalized)) {\n return normalized;\n }\n }\n }\n\n return undefined;\n};\n\nconst createWorkspaceResolver = (\n projectRoot: string,\n workspaces: readonly WorkspacePackage[],\n sourceFilePathSet: ReadonlySet<string>,\n): ((specifier: string) => string | undefined) => {\n const workspaceByName = new Map(workspaces.map((workspace) => [workspace.name, workspace]));\n const workspaceNames = new Set(workspaceByName.keys());\n\n return (specifier) => {\n const parsed = parseWorkspaceSpecifier(specifier, workspaceNames);\n if (parsed === null) {\n return undefined;\n }\n\n const workspace = workspaceByName.get(parsed.packageName);\n if (workspace === undefined) {\n return undefined;\n }\n\n const workspaceRoot = resolve(projectRoot, workspace.path);\n const packageJson = readPackageJson(join(workspaceRoot, \"package.json\"));\n const candidates =\n parsed.subpath === null\n ? [\n ...collectPackageExportCandidates(packageJson, null),\n packageJson?.source,\n packageJson?.types,\n packageJson?.typings,\n packageJson?.module,\n packageJson?.main,\n \"src/index\",\n \"index\",\n ].filter((candidate): candidate is string => candidate !== undefined)\n : [\n ...collectPackageExportCandidates(packageJson, parsed.subpath),\n parsed.subpath,\n join(\"src\", parsed.subpath),\n ];\n\n return resolveFirstAnalyzedCandidate(\n candidates.map((candidate) => resolve(workspaceRoot, candidate)),\n sourceFilePathSet,\n );\n };\n};\n\nconst createTsPathAliasResolver = (\n projectRoot: string,\n options: ts.CompilerOptions,\n sourceFilePathSet: ReadonlySet<string>,\n): ((specifier: string) => string | undefined) => {\n const paths = options.paths;\n if (paths === undefined) {\n return () => undefined;\n }\n\n const baseUrl = options.baseUrl === undefined ? projectRoot : options.baseUrl;\n const pathEntries = Object.entries(paths).sort(([left], [right]) => {\n const leftPrefix = left.split(\"*\")[0]?.length ?? left.length;\n const rightPrefix = right.split(\"*\")[0]?.length ?? right.length;\n return rightPrefix - leftPrefix || left.localeCompare(right);\n });\n\n return (specifier) => {\n for (const [pattern, substitutions] of pathEntries) {\n const [prefix = \"\", suffix = \"\"] = pattern.split(\"*\");\n const hasWildcard = pattern.includes(\"*\");\n if (hasWildcard) {\n if (!specifier.startsWith(prefix) || !specifier.endsWith(suffix)) {\n continue;\n }\n } else if (specifier !== pattern) {\n continue;\n }\n\n const replacement = hasWildcard\n ? specifier.slice(prefix.length, specifier.length - suffix.length)\n : \"\";\n const candidates = substitutions.map((substitution) =>\n resolve(baseUrl, hasWildcard ? substitution.replaceAll(\"*\", replacement) : substitution),\n );\n const resolved = resolveFirstAnalyzedCandidate(candidates, sourceFilePathSet);\n if (resolved !== undefined) {\n return resolved;\n }\n }\n\n return undefined;\n };\n};\n\nexport const parseTypescriptProject = (\n projectPath: string,\n onProgress?: (event: ParseTypescriptProjectProgressEvent) => void,\n workspaces: readonly WorkspacePackage[] = [],\n): ParsedProject => {\n const projectRoot = isAbsolute(projectPath) ? projectPath : resolve(projectPath);\n const { fileNames, options, tsconfigCount, usedFallbackScan } = parseTsConfig(projectRoot);\n onProgress?.({ stage: \"config_resolved\", tsconfigCount, usedFallbackScan });\n\n const sourceFilePaths = fileNames\n .filter((filePath) => isProjectSourceFile(filePath, projectRoot))\n .map((filePath) => normalizePath(resolve(filePath)));\n\n const uniqueSourceFilePaths = [...new Set(sourceFilePaths)].sort((a, b) => a.localeCompare(b));\n const sourceFilePathSet = new Set(uniqueSourceFilePaths);\n onProgress?.({ stage: \"files_discovered\", totalSourceFiles: uniqueSourceFilePaths.length });\n\n const program = ts.createProgram({\n rootNames: uniqueSourceFilePaths,\n options,\n });\n onProgress?.({ stage: \"program_created\", totalSourceFiles: uniqueSourceFilePaths.length });\n\n const nodeByAbsolutePath = new Map<string, NodeRecord>();\n for (const sourcePath of uniqueSourceFilePaths) {\n const relativePath = normalizePath(relative(projectRoot, sourcePath));\n const nodeId = relativePath;\n nodeByAbsolutePath.set(sourcePath, {\n id: nodeId,\n absolutePath: sourcePath,\n relativePath,\n });\n }\n\n const resolverCache = new Map<string, string | undefined>();\n const resolveWorkspaceSpecifier = createWorkspaceResolver(\n projectRoot,\n workspaces,\n sourceFilePathSet,\n );\n const resolveTsPathAlias = createTsPathAliasResolver(projectRoot, options, sourceFilePathSet);\n const edges: EdgeRecord[] = [];\n\n for (const [index, sourcePath] of uniqueSourceFilePaths.entries()) {\n const sourceFile = program.getSourceFile(sourcePath);\n if (sourceFile === undefined) {\n continue;\n }\n\n const fromNode = nodeByAbsolutePath.get(sourcePath);\n if (fromNode === undefined) {\n continue;\n }\n\n const moduleSpecifiers = extractModuleSpecifiers(sourceFile);\n for (const specifier of moduleSpecifiers) {\n const cacheKey = `${sourcePath}\\u0000${specifier}`;\n let resolvedPath = resolverCache.get(cacheKey);\n\n if (resolvedPath === undefined && !resolverCache.has(cacheKey)) {\n const resolved = ts.resolveModuleName(\n specifier,\n sourcePath,\n options,\n ts.sys,\n ).resolvedModule;\n if (resolved !== undefined) {\n resolvedPath = normalizePath(resolve(resolved.resolvedFileName));\n }\n if (resolvedPath === undefined || !sourceFilePathSet.has(resolvedPath)) {\n resolvedPath = resolveTsPathAlias(specifier);\n }\n if (resolvedPath === undefined || !sourceFilePathSet.has(resolvedPath)) {\n resolvedPath = resolveWorkspaceSpecifier(specifier);\n }\n resolverCache.set(cacheKey, resolvedPath);\n }\n\n if (resolvedPath === undefined || !sourceFilePathSet.has(resolvedPath)) {\n continue;\n }\n\n const toNode = nodeByAbsolutePath.get(resolvedPath);\n if (toNode === undefined) {\n continue;\n }\n\n edges.push({ from: fromNode.id, to: toNode.id });\n }\n\n const processed = index + 1;\n if (processed === 1 || processed === uniqueSourceFilePaths.length || processed % 50 === 0) {\n onProgress?.({\n stage: \"file_processed\",\n processed,\n total: uniqueSourceFilePaths.length,\n filePath: fromNode.id,\n });\n }\n }\n onProgress?.({ stage: \"edges_resolved\", totalEdges: edges.length });\n\n return {\n nodes: [...nodeByAbsolutePath.values()],\n edges,\n };\n};\n","import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { basename, join, relative, resolve } from \"node:path\";\nimport type { WorkspaceKind, WorkspacePackage } from \"@codesentinel/core\";\n\ntype PackageJsonWorkspaceConfig = {\n name?: string;\n workspaces?: readonly string[] | { packages?: readonly string[] };\n};\n\nconst normalizePath = (pathValue: string): string => pathValue.replaceAll(\"\\\\\", \"/\");\n\nconst stripQuotes = (value: string): string => value.replace(/^['\"]|['\"]$/g, \"\");\n\nconst readPackageJson = (path: string): PackageJsonWorkspaceConfig | null => {\n try {\n return JSON.parse(readFileSync(path, \"utf8\")) as PackageJsonWorkspaceConfig;\n } catch {\n return null;\n }\n};\n\nconst inferWorkspaceKind = (workspacePath: string): WorkspaceKind => {\n const segments = workspacePath.split(\"/\");\n const first = segments[0] ?? \"\";\n\n if (first === \"apps\" || first === \"app\") {\n return \"app\";\n }\n\n if (first === \"packages\" || first === \"package\") {\n return \"package\";\n }\n\n if (first === \"docs\" || first === \"documentation\") {\n return \"docs\";\n }\n\n if (first === \"examples\" || first === \"example-apps\" || first === \"playground\") {\n return \"example\";\n }\n\n if (first === \"tooling\" || first === \"tools\") {\n return \"tooling\";\n }\n\n return \"unknown\";\n};\n\nconst readWorkspacePatternsFromPackageJson = (projectRoot: string): readonly string[] => {\n const packageJson = readPackageJson(join(projectRoot, \"package.json\"));\n if (packageJson?.workspaces === undefined) {\n return [];\n }\n\n const workspaces = packageJson.workspaces;\n if (Array.isArray(workspaces)) {\n const workspaceArray: readonly unknown[] = workspaces;\n return workspaceArray.filter((workspace): workspace is string => typeof workspace === \"string\");\n }\n\n const workspaceObject = workspaces as { packages?: readonly string[] };\n return workspaceObject.packages ?? [];\n};\n\nconst readWorkspacePatternsFromPnpmWorkspace = (projectRoot: string): readonly string[] => {\n const workspacePath = join(projectRoot, \"pnpm-workspace.yaml\");\n if (!existsSync(workspacePath)) {\n return [];\n }\n\n const patterns: string[] = [];\n const lines = readFileSync(workspacePath, \"utf8\").split(\"\\n\");\n let readingPackages = false;\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.length === 0 || trimmed.startsWith(\"#\")) {\n continue;\n }\n\n if (!line.startsWith(\" \") && !line.startsWith(\"-\")) {\n readingPackages = trimmed === \"packages:\";\n continue;\n }\n\n if (!readingPackages) {\n continue;\n }\n\n const match = trimmed.match(/^-\\s+(.+)$/);\n if (match?.[1] !== undefined) {\n patterns.push(stripQuotes(match[1].trim()));\n }\n }\n\n return patterns;\n};\n\nconst expandPattern = (projectRoot: string, pattern: string): readonly string[] => {\n const segments = normalizePath(pattern)\n .split(\"/\")\n .filter((segment) => segment.length > 0);\n let current = [projectRoot];\n\n for (const segment of segments) {\n const next: string[] = [];\n if (segment === \"*\") {\n for (const directory of current) {\n if (!existsSync(directory)) {\n continue;\n }\n\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n if (entry.isDirectory()) {\n next.push(join(directory, entry.name));\n }\n }\n }\n } else {\n for (const directory of current) {\n const candidate = join(directory, segment);\n if (existsSync(candidate) && statSync(candidate).isDirectory()) {\n next.push(candidate);\n }\n }\n }\n\n current = next;\n }\n\n return current;\n};\n\nexport const discoverWorkspacePackages = (projectRoot: string): readonly WorkspacePackage[] => {\n const absoluteRoot = resolve(projectRoot);\n const packageJsonPatterns = readWorkspacePatternsFromPackageJson(absoluteRoot);\n const pnpmPatterns = readWorkspacePatternsFromPnpmWorkspace(absoluteRoot);\n const patterns = packageJsonPatterns.length > 0 ? packageJsonPatterns : pnpmPatterns;\n const includePatterns = patterns.filter((pattern) => !pattern.startsWith(\"!\"));\n const excludePatterns = patterns\n .filter((pattern) => pattern.startsWith(\"!\"))\n .map((pattern) => pattern.slice(1));\n\n const excludedPaths = new Set(\n excludePatterns\n .flatMap((pattern) => expandPattern(absoluteRoot, pattern))\n .map((path) => normalizePath(relative(absoluteRoot, path))),\n );\n\n const packagesByPath = new Map<string, WorkspacePackage>();\n for (const pattern of includePatterns) {\n for (const absoluteWorkspacePath of expandPattern(absoluteRoot, pattern)) {\n const relativePath = normalizePath(relative(absoluteRoot, absoluteWorkspacePath));\n if (\n relativePath.length === 0 ||\n relativePath.startsWith(\"..\") ||\n excludedPaths.has(relativePath)\n ) {\n continue;\n }\n\n const packageJsonPath = join(absoluteWorkspacePath, \"package.json\");\n if (!existsSync(packageJsonPath)) {\n continue;\n }\n\n const packageJson = readPackageJson(packageJsonPath);\n packagesByPath.set(relativePath, {\n name: packageJson?.name ?? basename(absoluteWorkspacePath),\n path: relativePath,\n kind: inferWorkspaceKind(relativePath),\n });\n }\n }\n\n return [...packagesByPath.values()].sort((a, b) => a.path.localeCompare(b.path));\n};\n","import type { GraphAnalysisSummary } from \"@codesentinel/core\";\nimport { createGraphData } from \"../domain/graph-model.js\";\nimport { createGraphAnalysisSummary } from \"../domain/graph-metrics.js\";\nimport {\n parseTypescriptProject,\n type ParseTypescriptProjectProgressEvent,\n} from \"../infrastructure/typescript-project.js\";\nimport { discoverWorkspacePackages } from \"../infrastructure/workspace-discovery.js\";\n\nexport type BuildProjectGraphSummaryInput = {\n projectPath: string;\n onProgress?: (event: ParseTypescriptProjectProgressEvent) => void;\n};\n\nexport const buildProjectGraphSummary = (\n input: BuildProjectGraphSummaryInput,\n): GraphAnalysisSummary => {\n const workspaces = discoverWorkspacePackages(input.projectPath);\n const parsedProject = parseTypescriptProject(input.projectPath, input.onProgress, workspaces);\n const graphData = createGraphData(parsedProject.nodes, parsedProject.edges);\n return createGraphAnalysisSummary(input.projectPath, graphData, workspaces);\n};\n","import type {\n CouplingMatrix,\n FileAuthorShare,\n FileAuthorChurnShare,\n FileCoupling,\n FileEvolutionMetrics,\n Hotspot,\n RecentActivityPoint,\n RepositoryEvolutionSummary,\n} from \"@codesentinel/core\";\nimport type { EvolutionComputationConfig, GitCommitRecord } from \"./evolution-types.js\";\n\ntype FileAccumulator = {\n commitCount: number;\n recentCommitCount: number;\n lastCommitTimestamp: number | null;\n churnAdded: number;\n churnDeleted: number;\n authorsByCommits: Map<string, number>;\n authorsByChurn: Map<string, { churnAdded: number; churnDeleted: number }>;\n};\n\ntype AuthorProfile = {\n authorId: string;\n commitCount: number;\n primaryName: string;\n emailStem: string | null;\n isBot: boolean;\n};\n\nconst pairKey = (a: string, b: string): string => `${a}\\u0000${b}`;\n\nconst round4 = (value: number): number => Number(value.toFixed(4));\n\nconst dayBucketStart = (value: number): number => Math.floor(value / 86_400) * 86_400;\n\nconst utcDateStringFromBucket = (value: number): string =>\n new Date(value * 1000).toISOString().slice(0, 10);\n\nconst normalizeRatio = (value: number, max: number): number =>\n max <= 0 ? 0 : Math.max(0, Math.min(1, value / max));\n\nconst normalizeName = (value: string): string =>\n value\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim();\n\nconst extractEmailStem = (authorId: string): string | null => {\n const normalized = authorId.trim().toLowerCase();\n const githubNoReplyMatch = normalized.match(/^\\d+\\+([^@]+)@users\\.noreply\\.github\\.com$/);\n if (githubNoReplyMatch?.[1] !== undefined) {\n return githubNoReplyMatch[1].replace(/[._+-]/g, \"\");\n }\n\n const atIndex = normalized.indexOf(\"@\");\n if (atIndex <= 0) {\n return null;\n }\n\n return normalized.slice(0, atIndex).replace(/[._+-]/g, \"\");\n};\n\nconst areNamesCompatible = (left: string, right: string): boolean => {\n if (left.length === 0 || right.length === 0) {\n return false;\n }\n\n if (left === right) {\n return true;\n }\n\n if (left.startsWith(`${right} `) || right.startsWith(`${left} `)) {\n return true;\n }\n\n return false;\n};\n\nconst chooseCanonicalAuthorId = (profiles: readonly AuthorProfile[]): string => {\n const ordered = [...profiles].sort((a, b) => {\n const aIsNoReply = a.authorId.includes(\"@users.noreply.github.com\");\n const bIsNoReply = b.authorId.includes(\"@users.noreply.github.com\");\n if (aIsNoReply !== bIsNoReply) {\n return aIsNoReply ? 1 : -1;\n }\n\n if (a.commitCount !== b.commitCount) {\n return b.commitCount - a.commitCount;\n }\n\n return a.authorId.localeCompare(b.authorId);\n });\n\n return ordered[0]?.authorId ?? \"\";\n};\n\nconst buildAuthorAliasMap = (commits: readonly GitCommitRecord[]): ReadonlyMap<string, string> => {\n const nameCountsByAuthorId = new Map<string, Map<string, number>>();\n const commitCountByAuthorId = new Map<string, number>();\n\n for (const commit of commits) {\n commitCountByAuthorId.set(\n commit.authorId,\n (commitCountByAuthorId.get(commit.authorId) ?? 0) + 1,\n );\n\n const normalizedName = normalizeName(commit.authorName);\n const names = nameCountsByAuthorId.get(commit.authorId) ?? new Map<string, number>();\n if (normalizedName.length > 0) {\n names.set(normalizedName, (names.get(normalizedName) ?? 0) + 1);\n }\n nameCountsByAuthorId.set(commit.authorId, names);\n }\n\n const profiles: AuthorProfile[] = [...commitCountByAuthorId.entries()].map(\n ([authorId, commitCount]) => {\n const names = nameCountsByAuthorId.get(authorId);\n const primaryName =\n names === undefined\n ? \"\"\n : ([...names.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0]?.[0] ??\n \"\");\n const normalizedAuthorId = authorId.toLowerCase();\n const isBot = normalizedAuthorId.includes(\"[bot]\");\n\n return {\n authorId,\n commitCount,\n primaryName,\n emailStem: isBot ? null : extractEmailStem(authorId),\n isBot,\n };\n },\n );\n\n const groupsByStem = new Map<string, AuthorProfile[]>();\n for (const profile of profiles) {\n if (profile.emailStem === null || profile.emailStem.length < 4) {\n continue;\n }\n\n const current = groupsByStem.get(profile.emailStem) ?? [];\n current.push(profile);\n groupsByStem.set(profile.emailStem, current);\n }\n\n const aliasMap = new Map<string, string>();\n for (const profile of profiles) {\n aliasMap.set(profile.authorId, profile.authorId);\n }\n\n for (const group of groupsByStem.values()) {\n if (group.length < 2) {\n continue;\n }\n\n const compatible: AuthorProfile[] = [];\n for (const profile of group) {\n if (profile.isBot || profile.primaryName.length === 0) {\n continue;\n }\n\n compatible.push(profile);\n }\n\n if (compatible.length < 2) {\n continue;\n }\n\n const canonical = chooseCanonicalAuthorId(compatible);\n const canonicalProfile = compatible.find((candidate) => candidate.authorId === canonical);\n if (canonicalProfile === undefined) {\n continue;\n }\n\n for (const profile of compatible) {\n if (areNamesCompatible(profile.primaryName, canonicalProfile.primaryName)) {\n aliasMap.set(profile.authorId, canonical);\n }\n }\n }\n\n return aliasMap;\n};\n\nconst computeBusFactor = (\n authorDistribution: readonly { share: number }[],\n threshold: number,\n): number => {\n if (authorDistribution.length === 0) {\n return 0;\n }\n\n let coveredShare = 0;\n for (let i = 0; i < authorDistribution.length; i += 1) {\n const entry = authorDistribution[i];\n if (entry === undefined) {\n continue;\n }\n\n coveredShare += entry.share;\n if (coveredShare >= threshold) {\n return i + 1;\n }\n }\n\n return authorDistribution.length;\n};\n\nconst finalizeAuthorDistribution = (\n authorCommits: ReadonlyMap<string, number>,\n): readonly FileAuthorShare[] => {\n const totalCommits = [...authorCommits.values()].reduce((sum, value) => sum + value, 0);\n if (totalCommits === 0) {\n return [];\n }\n\n return [...authorCommits.entries()]\n .map(([authorId, commits]) => ({\n authorId,\n commits,\n share: round4(commits / totalCommits),\n }))\n .sort((a, b) => b.commits - a.commits || a.authorId.localeCompare(b.authorId));\n};\n\nconst finalizeAuthorChurnDistribution = (\n authorChurn: ReadonlyMap<string, { churnAdded: number; churnDeleted: number }>,\n): readonly FileAuthorChurnShare[] => {\n const entries = [...authorChurn.entries()].map(([authorId, churn]) => {\n const churnAdded = churn.churnAdded;\n const churnDeleted = churn.churnDeleted;\n return {\n authorId,\n churnAdded,\n churnDeleted,\n churnTotal: churnAdded + churnDeleted,\n };\n });\n\n const totalChurn = entries.reduce((sum, entry) => sum + entry.churnTotal, 0);\n if (totalChurn === 0) {\n return [];\n }\n\n return entries\n .map((entry) => ({\n ...entry,\n share: round4(entry.churnTotal / totalChurn),\n }))\n .sort((a, b) => b.churnTotal - a.churnTotal || a.authorId.localeCompare(b.authorId));\n};\n\nconst buildCouplingMatrix = (\n coChangeByPair: ReadonlyMap<string, number>,\n fileCommitCount: ReadonlyMap<string, number>,\n consideredCommits: number,\n skippedLargeCommits: number,\n maxCouplingPairs: number,\n): CouplingMatrix => {\n const allPairs: FileCoupling[] = [];\n\n for (const [key, coChangeCommits] of coChangeByPair.entries()) {\n const [fileA, fileB] = key.split(\"\\u0000\");\n if (fileA === undefined || fileB === undefined) {\n continue;\n }\n\n const fileACommits = fileCommitCount.get(fileA) ?? 0;\n const fileBCommits = fileCommitCount.get(fileB) ?? 0;\n const denominator = fileACommits + fileBCommits - coChangeCommits;\n const couplingScore = denominator === 0 ? 0 : round4(coChangeCommits / denominator);\n\n allPairs.push({\n fileA,\n fileB,\n coChangeCommits,\n couplingScore,\n });\n }\n\n allPairs.sort(\n (a, b) =>\n b.coChangeCommits - a.coChangeCommits ||\n b.couplingScore - a.couplingScore ||\n a.fileA.localeCompare(b.fileA) ||\n a.fileB.localeCompare(b.fileB),\n );\n\n const truncated = allPairs.length > maxCouplingPairs;\n\n return {\n pairs: truncated ? allPairs.slice(0, maxCouplingPairs) : allPairs,\n totalPairCount: allPairs.length,\n consideredCommits,\n skippedLargeCommits,\n truncated,\n };\n};\n\nconst selectHotspots = (\n files: readonly FileEvolutionMetrics[],\n config: EvolutionComputationConfig,\n): { hotspots: readonly Hotspot[]; threshold: number } => {\n if (files.length === 0) {\n return { hotspots: [], threshold: 0 };\n }\n\n const sorted = [...files].sort(\n (a, b) =>\n b.commitCount - a.commitCount ||\n b.churnTotal - a.churnTotal ||\n a.filePath.localeCompare(b.filePath),\n );\n\n const hotspotCount = Math.max(\n config.hotspotMinFiles,\n Math.ceil(sorted.length * config.hotspotTopPercent),\n );\n const selected = sorted.slice(0, hotspotCount);\n\n const hotspots = selected.map((file, index) => ({\n filePath: file.filePath,\n rank: index + 1,\n commitCount: file.commitCount,\n churnTotal: file.churnTotal,\n }));\n\n const threshold = selected[selected.length - 1]?.commitCount ?? 0;\n return { hotspots, threshold };\n};\n\nexport const computeRepositoryEvolutionSummary = (\n targetPath: string,\n commits: readonly GitCommitRecord[],\n config: EvolutionComputationConfig,\n): RepositoryEvolutionSummary => {\n const authorAliasById =\n config.authorIdentityMode === \"likely_merge\"\n ? buildAuthorAliasMap(commits)\n : new Map<string, string>();\n const fileStats = new Map<string, FileAccumulator>();\n const coChangeByPair = new Map<string, number>();\n const recentActivityByDay = new Map<\n number,\n {\n commitCount: number;\n fileTouchCount: number;\n churnTotal: number;\n authors: Set<string>;\n }\n >();\n\n const headCommitTimestamp =\n commits.length === 0 ? null : (commits[commits.length - 1]?.authoredAtUnix ?? null);\n const recentWindowStart =\n headCommitTimestamp === null\n ? Number.NEGATIVE_INFINITY\n : headCommitTimestamp - config.recentWindowDays * 24 * 60 * 60;\n\n let consideredCommits = 0;\n let skippedLargeCommits = 0;\n\n for (const commit of commits) {\n const uniqueFiles = new Set<string>();\n\n for (const fileChange of commit.fileChanges) {\n uniqueFiles.add(fileChange.filePath);\n const current = fileStats.get(fileChange.filePath) ?? {\n commitCount: 0,\n recentCommitCount: 0,\n lastCommitTimestamp: null,\n churnAdded: 0,\n churnDeleted: 0,\n authorsByCommits: new Map<string, number>(),\n authorsByChurn: new Map<string, { churnAdded: number; churnDeleted: number }>(),\n };\n\n current.lastCommitTimestamp =\n current.lastCommitTimestamp === null\n ? commit.authoredAtUnix\n : Math.max(current.lastCommitTimestamp, commit.authoredAtUnix);\n\n current.churnAdded += fileChange.additions;\n current.churnDeleted += fileChange.deletions;\n\n const effectiveAuthorId = authorAliasById.get(commit.authorId) ?? commit.authorId;\n const authorChurn = current.authorsByChurn.get(effectiveAuthorId) ?? {\n churnAdded: 0,\n churnDeleted: 0,\n };\n authorChurn.churnAdded += fileChange.additions;\n authorChurn.churnDeleted += fileChange.deletions;\n current.authorsByChurn.set(effectiveAuthorId, authorChurn);\n\n fileStats.set(fileChange.filePath, current);\n }\n\n for (const filePath of uniqueFiles) {\n const current = fileStats.get(filePath);\n if (current === undefined) {\n continue;\n }\n\n current.commitCount += 1;\n if (commit.authoredAtUnix >= recentWindowStart) {\n current.recentCommitCount += 1;\n }\n\n const effectiveAuthorId = authorAliasById.get(commit.authorId) ?? commit.authorId;\n current.authorsByCommits.set(\n effectiveAuthorId,\n (current.authorsByCommits.get(effectiveAuthorId) ?? 0) + 1,\n );\n }\n\n const orderedFiles = [...uniqueFiles].sort((a, b) => a.localeCompare(b));\n if (commit.authoredAtUnix >= recentWindowStart) {\n const bucketStartTimestamp = dayBucketStart(commit.authoredAtUnix);\n const activity = recentActivityByDay.get(bucketStartTimestamp) ?? {\n commitCount: 0,\n fileTouchCount: 0,\n churnTotal: 0,\n authors: new Set<string>(),\n };\n const effectiveAuthorId = authorAliasById.get(commit.authorId) ?? commit.authorId;\n const commitChurn = commit.fileChanges.reduce(\n (sum, fileChange) => sum + fileChange.additions + fileChange.deletions,\n 0,\n );\n\n activity.commitCount += 1;\n activity.fileTouchCount += uniqueFiles.size;\n activity.churnTotal += commitChurn;\n activity.authors.add(effectiveAuthorId);\n recentActivityByDay.set(bucketStartTimestamp, activity);\n }\n\n if (orderedFiles.length > 1) {\n if (orderedFiles.length <= config.maxFilesPerCommitForCoupling) {\n consideredCommits += 1;\n for (let i = 0; i < orderedFiles.length - 1; i += 1) {\n for (let j = i + 1; j < orderedFiles.length; j += 1) {\n const fileA = orderedFiles[i];\n const fileB = orderedFiles[j];\n if (fileA === undefined || fileB === undefined) {\n continue;\n }\n\n const key = pairKey(fileA, fileB);\n coChangeByPair.set(key, (coChangeByPair.get(key) ?? 0) + 1);\n }\n }\n } else {\n skippedLargeCommits += 1;\n }\n }\n }\n\n const files: FileEvolutionMetrics[] = [...fileStats.entries()]\n .map(([filePath, stats]) => {\n const authorDistributionByCommits = finalizeAuthorDistribution(stats.authorsByCommits);\n const authorDistributionByChurn = finalizeAuthorChurnDistribution(stats.authorsByChurn);\n const topAuthorShareByCommits = authorDistributionByCommits[0]?.share ?? 0;\n const topAuthorShareByChurn = authorDistributionByChurn[0]?.share ?? 0;\n return {\n filePath,\n commitCount: stats.commitCount,\n frequencyPer100Commits:\n commits.length === 0 ? 0 : round4((stats.commitCount / commits.length) * 100),\n churnAdded: stats.churnAdded,\n churnDeleted: stats.churnDeleted,\n churnTotal: stats.churnAdded + stats.churnDeleted,\n lastCommitTimestamp: stats.lastCommitTimestamp,\n recentCommitCount: stats.recentCommitCount,\n recentVolatility:\n stats.commitCount === 0 ? 0 : round4(stats.recentCommitCount / stats.commitCount),\n topAuthorShareByCommits,\n busFactorByCommits: computeBusFactor(\n authorDistributionByCommits,\n config.busFactorCoverageThreshold,\n ),\n authorDistributionByCommits,\n topAuthorShareByChurn,\n busFactorByChurn: computeBusFactor(\n authorDistributionByChurn,\n config.busFactorCoverageThreshold,\n ),\n authorDistributionByChurn,\n };\n })\n .sort((a, b) => a.filePath.localeCompare(b.filePath));\n\n const fileCommitCount = new Map(files.map((file) => [file.filePath, file.commitCount]));\n const coupling = buildCouplingMatrix(\n coChangeByPair,\n fileCommitCount,\n consideredCommits,\n skippedLargeCommits,\n config.maxCouplingPairs,\n );\n\n const { hotspots, threshold } = selectHotspots(files, config);\n const recentActivityBase =\n headCommitTimestamp === null\n ? []\n : Array.from({ length: config.recentWindowDays }, (_, index) => {\n const bucketStartTimestamp =\n dayBucketStart(headCommitTimestamp) - (config.recentWindowDays - 1 - index) * 86_400;\n const activity = recentActivityByDay.get(bucketStartTimestamp);\n return {\n bucketStartUtcDate: utcDateStringFromBucket(bucketStartTimestamp),\n commitCount: activity?.commitCount ?? 0,\n fileTouchCount: activity?.fileTouchCount ?? 0,\n churnTotal: activity?.churnTotal ?? 0,\n activeAuthorCount: activity?.authors.size ?? 0,\n };\n });\n const maxRecentCommitCount = Math.max(1, ...recentActivityBase.map((point) => point.commitCount));\n const maxRecentFileTouches = Math.max(\n 1,\n ...recentActivityBase.map((point) => point.fileTouchCount),\n );\n const maxRecentChurn = Math.max(1, ...recentActivityBase.map((point) => point.churnTotal));\n const maxRecentChurnLog = Math.log1p(maxRecentChurn);\n const recentActivity: RecentActivityPoint[] = recentActivityBase.map((point) => {\n const commitIntensity = normalizeRatio(point.commitCount, maxRecentCommitCount);\n const fileTouchIntensity = normalizeRatio(point.fileTouchCount, maxRecentFileTouches);\n const churnIntensity =\n point.churnTotal <= 0 ? 0 : Math.log1p(point.churnTotal) / maxRecentChurnLog;\n\n return {\n ...point,\n volatilityScore: round4(\n commitIntensity * 0.35 + fileTouchIntensity * 0.2 + churnIntensity * 0.45,\n ),\n };\n });\n\n return {\n targetPath,\n available: true,\n files,\n hotspots,\n coupling,\n recentActivity,\n metrics: {\n totalCommits: commits.length,\n totalFiles: files.length,\n headCommitTimestamp,\n recentWindowDays: config.recentWindowDays,\n hotspotTopPercent: config.hotspotTopPercent,\n hotspotThresholdCommitCount: threshold,\n },\n };\n};\n","export type GitFileChange = {\n filePath: string;\n additions: number;\n deletions: number;\n};\n\nexport type GitCommitRecord = {\n hash: string;\n authorId: string;\n authorName: string;\n authoredAtUnix: number;\n fileChanges: readonly GitFileChange[];\n};\n\nexport type EvolutionComputationConfig = {\n authorIdentityMode: \"likely_merge\" | \"strict_email\";\n recentWindowDays: number;\n hotspotTopPercent: number;\n hotspotMinFiles: number;\n maxFilesPerCommitForCoupling: number;\n maxCouplingPairs: number;\n busFactorCoverageThreshold: number;\n};\n\nexport const DEFAULT_EVOLUTION_CONFIG: EvolutionComputationConfig = {\n authorIdentityMode: \"likely_merge\",\n recentWindowDays: 30,\n hotspotTopPercent: 0.1,\n hotspotMinFiles: 1,\n maxFilesPerCommitForCoupling: 200,\n maxCouplingPairs: 500,\n busFactorCoverageThreshold: 0.6,\n};\n","import type { RepositoryEvolutionSummary } from \"@codesentinel/core\";\nimport { computeRepositoryEvolutionSummary } from \"../domain/evolution-metrics.js\";\nimport {\n DEFAULT_EVOLUTION_CONFIG,\n type EvolutionComputationConfig,\n} from \"../domain/evolution-types.js\";\nimport type { GitHistoryProvider, GitHistoryProgressEvent } from \"./git-history-provider.js\";\n\nexport type AnalyzeRepositoryEvolutionInput = {\n repositoryPath: string;\n config?: Partial<EvolutionComputationConfig>;\n};\n\nexport type EvolutionAnalysisProgressEvent =\n | { stage: \"checking_git_repository\" }\n | { stage: \"not_git_repository\" }\n | { stage: \"loading_commit_history\" }\n | { stage: \"computing_metrics\" }\n | { stage: \"analysis_completed\"; available: boolean }\n | { stage: \"history\"; event: GitHistoryProgressEvent };\n\nconst createEffectiveConfig = (\n overrides: Partial<EvolutionComputationConfig> | undefined,\n): EvolutionComputationConfig => ({\n ...DEFAULT_EVOLUTION_CONFIG,\n ...overrides,\n});\n\nexport const analyzeRepositoryEvolution = (\n input: AnalyzeRepositoryEvolutionInput,\n historyProvider: GitHistoryProvider,\n onProgress?: (event: EvolutionAnalysisProgressEvent) => void,\n): RepositoryEvolutionSummary => {\n onProgress?.({ stage: \"checking_git_repository\" });\n if (!historyProvider.isGitRepository(input.repositoryPath)) {\n onProgress?.({ stage: \"not_git_repository\" });\n return {\n targetPath: input.repositoryPath,\n available: false,\n reason: \"not_git_repository\",\n };\n }\n\n onProgress?.({ stage: \"loading_commit_history\" });\n const commits = historyProvider.getCommitHistory(input.repositoryPath, (event) =>\n onProgress?.({ stage: \"history\", event }),\n );\n const config = createEffectiveConfig(input.config);\n onProgress?.({ stage: \"computing_metrics\" });\n\n const summary = computeRepositoryEvolutionSummary(input.repositoryPath, commits, config);\n onProgress?.({ stage: \"analysis_completed\", available: summary.available });\n return summary;\n};\n","import type {\n GraphAnalysisSummary,\n RepositoryEvolutionSummary,\n WorkspaceEvolutionSummary,\n} from \"@codesentinel/core\";\nimport { createWorkspaceByFile, normalizeWorkspacePath } from \"@codesentinel/core\";\n\nexport const enrichEvolutionSummaryWithWorkspaces = (\n structural: GraphAnalysisSummary,\n evolution: RepositoryEvolutionSummary,\n): RepositoryEvolutionSummary => {\n if (!evolution.available || structural.workspaces === undefined) {\n return evolution;\n }\n\n const workspaces = structural.workspaces;\n const workspaceByFile = createWorkspaceByFile(\n evolution.files.map((file) => normalizeWorkspacePath(file.filePath)),\n workspaces,\n );\n const structuralWorkspacePaths = new Set(workspaces.map((workspace) => workspace.path));\n\n const internalCouplingPairCountByWorkspace = new Map<string, number>();\n const incomingCouplingPairCountByWorkspace = new Map<string, number>();\n const outgoingCouplingPairCountByWorkspace = new Map<string, number>();\n\n for (const pair of evolution.coupling.pairs) {\n const fromWorkspace = workspaceByFile.get(normalizeWorkspacePath(pair.fileA));\n const toWorkspace = workspaceByFile.get(normalizeWorkspacePath(pair.fileB));\n if (fromWorkspace === undefined && toWorkspace === undefined) {\n continue;\n }\n\n if (fromWorkspace?.path === toWorkspace?.path && fromWorkspace !== undefined) {\n internalCouplingPairCountByWorkspace.set(\n fromWorkspace.path,\n (internalCouplingPairCountByWorkspace.get(fromWorkspace.path) ?? 0) + 1,\n );\n continue;\n }\n\n if (fromWorkspace !== undefined) {\n outgoingCouplingPairCountByWorkspace.set(\n fromWorkspace.path,\n (outgoingCouplingPairCountByWorkspace.get(fromWorkspace.path) ?? 0) + 1,\n );\n }\n\n if (toWorkspace !== undefined) {\n incomingCouplingPairCountByWorkspace.set(\n toWorkspace.path,\n (incomingCouplingPairCountByWorkspace.get(toWorkspace.path) ?? 0) + 1,\n );\n }\n }\n\n const workspaceSummaries: WorkspaceEvolutionSummary[] = workspaces\n .filter((workspace) => structuralWorkspacePaths.has(workspace.path))\n .map((workspace) => {\n const files = evolution.files\n .filter(\n (file) =>\n workspaceByFile.get(normalizeWorkspacePath(file.filePath))?.path === workspace.path,\n )\n .sort((a, b) => a.filePath.localeCompare(b.filePath));\n const commitCount = files.reduce((sum, file) => sum + file.commitCount, 0);\n const recentCommitCount = files.reduce((sum, file) => sum + file.recentCommitCount, 0);\n const churnAdded = files.reduce((sum, file) => sum + file.churnAdded, 0);\n const churnDeleted = files.reduce((sum, file) => sum + file.churnDeleted, 0);\n const churnTotal = churnAdded + churnDeleted;\n const topAuthorShareByCommits =\n files.length === 0 ? 0 : Math.max(...files.map((file) => file.topAuthorShareByCommits));\n const busFactorByCommits =\n files.length === 0 ? 0 : Math.min(...files.map((file) => file.busFactorByCommits));\n const topHotspots = evolution.hotspots.filter(\n (hotspot) =>\n workspaceByFile.get(normalizeWorkspacePath(hotspot.filePath))?.path === workspace.path,\n );\n\n return {\n name: workspace.name,\n path: workspace.path,\n kind: workspace.kind,\n fileCount: files.length,\n commitCount,\n churnAdded,\n churnDeleted,\n churnTotal,\n recentCommitCount,\n recentVolatility:\n commitCount === 0 ? 0 : Number((recentCommitCount / commitCount).toFixed(4)),\n topAuthorShareByCommits,\n busFactorByCommits,\n hotspotCount: topHotspots.length,\n topHotspots,\n internalCouplingPairCount: internalCouplingPairCountByWorkspace.get(workspace.path) ?? 0,\n incomingCouplingPairCount: incomingCouplingPairCountByWorkspace.get(workspace.path) ?? 0,\n outgoingCouplingPairCount: outgoingCouplingPairCountByWorkspace.get(workspace.path) ?? 0,\n };\n })\n .sort(\n (a, b) =>\n b.commitCount - a.commitCount ||\n b.churnTotal - a.churnTotal ||\n a.path.localeCompare(b.path),\n );\n\n return {\n ...evolution,\n workspaces: workspaceSummaries,\n };\n};\n","import { execFileSync } from \"node:child_process\";\n\nexport class GitCommandError extends Error {\n readonly args: readonly string[];\n\n constructor(message: string, args: readonly string[]) {\n super(message);\n this.name = \"GitCommandError\";\n this.args = args;\n }\n}\n\nexport interface GitCommandClient {\n run(repositoryPath: string, args: readonly string[]): string;\n}\n\nexport class ExecGitCommandClient implements GitCommandClient {\n run(repositoryPath: string, args: readonly string[]): string {\n try {\n return execFileSync(\"git\", [\"-C\", repositoryPath, ...args], {\n encoding: \"utf8\",\n maxBuffer: 1024 * 1024 * 64,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown git execution error\";\n throw new GitCommandError(message, args);\n }\n }\n}\n","export const COMMIT_RECORD_SEPARATOR = \"\\u001e\";\nexport const COMMIT_FIELD_SEPARATOR = \"\\u001f\";\n\nexport const GIT_LOG_FORMAT = `%x1e%H%x1f%at%x1f%an%x1f%ae`;\n","import type { GitCommitRecord } from \"../domain/evolution-types.js\";\nimport type { ParseGitLogProgressEvent } from \"../parsing/git-log-parser.js\";\n\nexport type GitHistoryProgressEvent =\n | { stage: \"git_log_received\"; bytes: number }\n | { stage: \"git_log_parsed\"; commits: number }\n | { stage: \"git_log_parse_progress\"; parsedRecords: number; totalRecords: number };\n\nexport interface GitHistoryProvider {\n isGitRepository(repositoryPath: string): boolean;\n getCommitHistory(\n repositoryPath: string,\n onProgress?: (event: GitHistoryProgressEvent) => void,\n ): readonly GitCommitRecord[];\n}\n\nexport const mapParseProgressToHistoryProgress = (\n event: ParseGitLogProgressEvent,\n): GitHistoryProgressEvent => ({\n stage: \"git_log_parse_progress\",\n parsedRecords: event.parsedRecords,\n totalRecords: event.totalRecords,\n});\n","import { COMMIT_FIELD_SEPARATOR, COMMIT_RECORD_SEPARATOR } from \"../domain/git-log-format.js\";\nimport type { GitCommitRecord, GitFileChange } from \"../domain/evolution-types.js\";\n\nexport type ParseGitLogProgressEvent = {\n parsedRecords: number;\n totalRecords: number;\n};\n\nconst parseInteger = (value: string): number | null => {\n if (value.length === 0) {\n return null;\n }\n\n const parsed = Number.parseInt(value, 10);\n if (Number.isNaN(parsed)) {\n return null;\n }\n\n return parsed;\n};\n\nconst normalizeAuthorIdentity = (authorName: string, authorEmail: string): string => {\n const normalizedName = authorName.trim().replace(/\\s+/g, \" \").toLowerCase();\n const normalizedEmail = authorEmail.trim().toLowerCase();\n\n if (/\\[bot\\]/i.test(normalizedName) || /\\[bot\\]/i.test(normalizedEmail)) {\n return normalizedEmail.length > 0 ? normalizedEmail : normalizedName;\n }\n\n const githubNoReplyMatch = normalizedEmail.match(/^\\d+\\+([^@]+)@users\\.noreply\\.github\\.com$/);\n const githubHandle = githubNoReplyMatch?.[1]?.trim().toLowerCase();\n if (githubHandle !== undefined && githubHandle.length > 0) {\n return `${githubHandle}@users.noreply.github.com`;\n }\n\n if (normalizedEmail.length > 0) {\n return normalizedEmail;\n }\n\n return normalizedName;\n};\n\nconst parseRenamedPath = (pathSpec: string): string => {\n if (!pathSpec.includes(\" => \")) {\n return pathSpec;\n }\n\n const braceRenameMatch = pathSpec.match(/^(.*)\\{(.+) => (.+)\\}(.*)$/);\n if (braceRenameMatch !== null) {\n const [, prefix, , renamedTo, suffix] = braceRenameMatch;\n return `${prefix}${renamedTo}${suffix}`;\n }\n\n const parts = pathSpec.split(\" => \");\n const finalPart = parts[parts.length - 1];\n return finalPart ?? pathSpec;\n};\n\nconst parseNumstatLine = (line: string): GitFileChange | null => {\n const parts = line.split(\"\\t\");\n if (parts.length < 3) {\n return null;\n }\n\n const additionsRaw = parts[0];\n const deletionsRaw = parts[1];\n const pathRaw = parts.slice(2).join(\"\\t\");\n\n if (additionsRaw === undefined || deletionsRaw === undefined) {\n return null;\n }\n\n const additions = additionsRaw === \"-\" ? 0 : parseInteger(additionsRaw);\n const deletions = deletionsRaw === \"-\" ? 0 : parseInteger(deletionsRaw);\n\n if (additions === null || deletions === null) {\n return null;\n }\n\n const filePath = parseRenamedPath(pathRaw);\n return {\n filePath,\n additions,\n deletions,\n };\n};\n\nexport const parseGitLog = (\n rawLog: string,\n onProgress?: (event: ParseGitLogProgressEvent) => void,\n): readonly GitCommitRecord[] => {\n const records = rawLog\n .split(COMMIT_RECORD_SEPARATOR)\n .map((record) => record.trim())\n .filter((record) => record.length > 0);\n\n const commits: GitCommitRecord[] = [];\n\n for (const [index, record] of records.entries()) {\n const lines = record\n .split(\"\\n\")\n .map((line) => line.trimEnd())\n .filter((line) => line.length > 0);\n\n if (lines.length === 0) {\n continue;\n }\n\n const headerParts = lines[0]?.split(COMMIT_FIELD_SEPARATOR) ?? [];\n if (headerParts.length !== 4) {\n continue;\n }\n\n const [hash, authoredAtRaw, authorName, authorEmail] = headerParts;\n if (\n hash === undefined ||\n authoredAtRaw === undefined ||\n authorName === undefined ||\n authorEmail === undefined\n ) {\n continue;\n }\n\n const authoredAtUnix = parseInteger(authoredAtRaw);\n if (authoredAtUnix === null) {\n continue;\n }\n\n const fileChanges: GitFileChange[] = [];\n for (const line of lines.slice(1)) {\n const parsedLine = parseNumstatLine(line);\n if (parsedLine !== null) {\n fileChanges.push(parsedLine);\n }\n }\n\n commits.push({\n hash,\n authorId: normalizeAuthorIdentity(authorName, authorEmail),\n authorName,\n authoredAtUnix,\n fileChanges,\n });\n\n const parsedRecords = index + 1;\n if (parsedRecords === 1 || parsedRecords === records.length || parsedRecords % 500 === 0) {\n onProgress?.({ parsedRecords, totalRecords: records.length });\n }\n }\n\n commits.sort((a, b) => a.authoredAtUnix - b.authoredAtUnix || a.hash.localeCompare(b.hash));\n return commits;\n};\n","import { GIT_LOG_FORMAT } from \"../domain/git-log-format.js\";\nimport type { GitCommitRecord } from \"../domain/evolution-types.js\";\nimport {\n mapParseProgressToHistoryProgress,\n type GitHistoryProvider,\n type GitHistoryProgressEvent,\n} from \"../application/git-history-provider.js\";\nimport { GitCommandError, type GitCommandClient } from \"./git-command-client.js\";\nimport { parseGitLog } from \"../parsing/git-log-parser.js\";\n\nconst NON_GIT_CODES = [\"not a git repository\", \"not in a git directory\"];\n\nconst isNotGitError = (error: GitCommandError): boolean => {\n const lower = error.message.toLowerCase();\n return NON_GIT_CODES.some((code) => lower.includes(code));\n};\n\nexport class GitCliHistoryProvider implements GitHistoryProvider {\n constructor(private readonly gitClient: GitCommandClient) {}\n\n isGitRepository(repositoryPath: string): boolean {\n try {\n const output = this.gitClient.run(repositoryPath, [\"rev-parse\", \"--is-inside-work-tree\"]);\n return output.trim() === \"true\";\n } catch (error) {\n if (error instanceof GitCommandError && isNotGitError(error)) {\n return false;\n }\n\n throw error;\n }\n }\n\n getCommitHistory(\n repositoryPath: string,\n onProgress?: (event: GitHistoryProgressEvent) => void,\n ): readonly GitCommitRecord[] {\n const output = this.gitClient.run(repositoryPath, [\n \"-c\",\n \"core.quotepath=false\",\n \"log\",\n \"--use-mailmap\",\n \"--no-merges\",\n \"--date=unix\",\n `--pretty=format:${GIT_LOG_FORMAT}`,\n \"--numstat\",\n \"--find-renames\",\n ]);\n onProgress?.({ stage: \"git_log_received\", bytes: Buffer.byteLength(output, \"utf8\") });\n const commits = parseGitLog(output, (event) =>\n onProgress?.(mapParseProgressToHistoryProgress(event)),\n );\n onProgress?.({ stage: \"git_log_parsed\", commits: commits.length });\n return commits;\n }\n}\n","import type { RepositoryEvolutionSummary } from \"@codesentinel/core\";\nimport {\n analyzeRepositoryEvolution,\n type EvolutionAnalysisProgressEvent,\n type AnalyzeRepositoryEvolutionInput,\n} from \"./application/analyze-repository-evolution.js\";\nexport { enrichEvolutionSummaryWithWorkspaces } from \"./application/enrich-evolution-with-workspaces.js\";\nimport { ExecGitCommandClient } from \"./infrastructure/git-command-client.js\";\nimport { GitCliHistoryProvider } from \"./infrastructure/git-history-provider.js\";\n\nexport type { AnalyzeRepositoryEvolutionInput } from \"./application/analyze-repository-evolution.js\";\nexport type { EvolutionAnalysisProgressEvent } from \"./application/analyze-repository-evolution.js\";\n\nexport const analyzeRepositoryEvolutionFromGit = (\n input: AnalyzeRepositoryEvolutionInput,\n onProgress?: (event: EvolutionAnalysisProgressEvent) => void,\n): RepositoryEvolutionSummary => {\n const historyProvider = new GitCliHistoryProvider(new ExecGitCommandClient());\n return analyzeRepositoryEvolution(input, historyProvider, onProgress);\n};\n","export const clamp01 = (value: number): number => {\n if (!Number.isFinite(value)) {\n return 0;\n }\n if (value <= 0) {\n return 0;\n }\n if (value >= 1) {\n return 1;\n }\n return value;\n};\n\nexport const round4 = (value: number): number => Number(value.toFixed(4));\n\nexport const average = (values: readonly number[]): number => {\n if (values.length === 0) {\n return 0;\n }\n\n const total = values.reduce((sum, value) => sum + value, 0);\n return total / values.length;\n};\n\nexport const concentration = (rawValues: readonly number[]): number => {\n const values = rawValues.filter((value) => value > 0);\n const count = values.length;\n if (count <= 1) {\n return 0;\n }\n\n const total = values.reduce((sum, value) => sum + value, 0);\n if (total <= 0) {\n return 0;\n }\n\n const hhi = values.reduce((sum, value) => {\n const share = value / total;\n return sum + share * share;\n }, 0);\n\n const minHhi = 1 / count;\n const normalized = (hhi - minHhi) / (1 - minHhi);\n return clamp01(normalized);\n};\n","import type {\n GraphAnalysisSummary,\n HealthDimension,\n HealthDimensionTrace,\n HealthEvidenceRef,\n HealthFactorTrace,\n HealthIssue,\n RepositoryEvolutionSummary,\n RepositoryHealthSummary,\n} from \"@codesentinel/core\";\nimport { average, clamp01, concentration, round4 } from \"../domain/math.js\";\n\nexport type ComputeRepositoryHealthSummaryInput = {\n structural: GraphAnalysisSummary;\n evolution: RepositoryEvolutionSummary;\n config?: HealthEngineConfig;\n};\n\nexport type HealthEngineConfig = {\n ownershipPenaltyMultiplier?: number;\n};\n\ntype HealthIssueWithImpact = HealthIssue & {\n impact: number;\n};\n\ntype FactorSpec = {\n factorId: string;\n penalty: number;\n rawMetrics: Readonly<Record<string, number | null>>;\n normalizedMetrics: Readonly<Record<string, number | null>>;\n weight: number;\n evidence: readonly HealthEvidenceRef[];\n};\n\nconst DIMENSION_WEIGHTS: Readonly<Record<HealthDimension, number>> = {\n modularity: 0.35,\n changeHygiene: 0.3,\n testHealth: 0.2,\n ownershipDistribution: 0.15,\n};\n\nconst HEALTH_TRACE_VERSION = \"1\" as const;\n\nconst toPercentage = (normalizedHealth: number): number => round4(clamp01(normalizedHealth) * 100);\n\nconst dampenForSmallSamples = (\n penalty: number,\n sampleSize: number,\n warmupSize: number,\n minimumWeight = 0.35,\n): number => {\n const reliability = clamp01(sampleSize / Math.max(1, warmupSize));\n const dampeningWeight = minimumWeight + (1 - minimumWeight) * reliability;\n return clamp01(penalty) * dampeningWeight;\n};\n\nconst topPercentShare = (values: readonly number[], fraction: number): number => {\n const positive = values.filter((value) => value > 0).sort((a, b) => b - a);\n if (positive.length === 0) {\n return 0;\n }\n\n const topCount = Math.max(1, Math.ceil(positive.length * clamp01(fraction)));\n const total = positive.reduce((sum, value) => sum + value, 0);\n const topTotal = positive.slice(0, topCount).reduce((sum, value) => sum + value, 0);\n if (total <= 0) {\n return 0;\n }\n\n return clamp01(topTotal / total);\n};\n\nconst normalizedEntropy = (weights: readonly number[]): number => {\n const positive = weights.filter((value) => value > 0);\n if (positive.length <= 1) {\n return 0;\n }\n\n const total = positive.reduce((sum, value) => sum + value, 0);\n if (total <= 0) {\n return 0;\n }\n\n const entropy = positive.reduce((sum, value) => {\n const p = value / total;\n return sum - p * Math.log(p);\n }, 0);\n return clamp01(entropy / Math.log(positive.length));\n};\n\nconst toFactorTrace = (spec: FactorSpec): HealthFactorTrace => ({\n factorId: spec.factorId,\n contribution: round4(spec.penalty * spec.weight * 100),\n penalty: round4(spec.penalty),\n rawMetrics: spec.rawMetrics,\n normalizedMetrics: spec.normalizedMetrics,\n weight: round4(spec.weight),\n evidence: spec.evidence,\n});\n\nconst createDimensionTrace = (\n dimension: HealthDimension,\n health: number,\n factors: readonly FactorSpec[],\n): HealthDimensionTrace => ({\n dimension,\n normalizedScore: round4(clamp01(health)),\n score: toPercentage(health),\n factors: factors.map((factor) => toFactorTrace(factor)),\n});\n\nconst filePaths = (structural: GraphAnalysisSummary): readonly string[] =>\n structural.files.map((file) => file.relativePath);\n\nconst normalizePath = (value: string): string => value.replaceAll(\"\\\\\", \"/\").toLowerCase();\n\nconst isTestPath = (path: string): boolean => {\n const normalized = normalizePath(path);\n return (\n normalized.includes(\"/__tests__/\") ||\n normalized.includes(\"/tests/\") ||\n normalized.includes(\"/test/\") ||\n normalized.includes(\".test.\") ||\n normalized.includes(\".spec.\")\n );\n};\n\nconst isSourcePath = (path: string): boolean => {\n if (path.endsWith(\".d.ts\")) {\n return false;\n }\n return !isTestPath(path);\n};\n\nconst hasTestDirectory = (paths: readonly string[]): boolean =>\n paths.some((path) => {\n const normalized = normalizePath(path);\n return (\n normalized.includes(\"/__tests__/\") ||\n normalized.includes(\"/tests/\") ||\n normalized.includes(\"/test/\")\n );\n });\n\nconst moduleNameFromPath = (path: string): string => {\n const normalized = path.replaceAll(\"\\\\\", \"/\");\n const firstSegment = normalized.split(\"/\")[0] ?? normalized;\n return firstSegment.length === 0 ? normalized : firstSegment;\n};\n\nconst pushIssue = (\n issues: HealthIssueWithImpact[],\n issue: Omit<HealthIssueWithImpact, \"severity\"> & { severity?: HealthIssue[\"severity\"] },\n): void => {\n issues.push({\n ...issue,\n severity: issue.severity ?? \"warn\",\n });\n};\n\nconst weightedPenalty = (factors: readonly FactorSpec[]): number =>\n clamp01(factors.reduce((sum, factor) => sum + factor.penalty * factor.weight, 0));\n\nexport const computeRepositoryHealthSummary = (\n input: ComputeRepositoryHealthSummaryInput,\n): RepositoryHealthSummary => {\n const ownershipPenaltyMultiplier = clamp01(input.config?.ownershipPenaltyMultiplier ?? 1);\n const issues: HealthIssueWithImpact[] = [];\n const sourceFileSet = new Set(input.structural.files.map((file) => file.relativePath));\n\n const sourceFileCount = Math.max(1, input.structural.files.length);\n const structuralEdges = input.structural.edges;\n\n const cycleSets = input.structural.cycles\n .map((cycle) => new Set(cycle.nodes))\n .filter((set) => set.size >= 2);\n\n const cycleNodeSet = new Set<string>();\n for (const cycleSet of cycleSets) {\n for (const node of cycleSet) {\n cycleNodeSet.add(node);\n }\n }\n\n const edgesInsideCycles = structuralEdges.filter((edge) =>\n cycleSets.some((cycleSet) => cycleSet.has(edge.from) && cycleSet.has(edge.to)),\n ).length;\n\n const cycleEdgeRatio =\n structuralEdges.length === 0 ? 0 : clamp01(edgesInsideCycles / structuralEdges.length);\n const cycleNodeRatio = clamp01(cycleNodeSet.size / sourceFileCount);\n const cycleDensityPenalty = clamp01(\n clamp01(cycleEdgeRatio / 0.2) * 0.75 + clamp01(cycleNodeRatio / 0.35) * 0.25,\n );\n\n const fanInConcentration = concentration(input.structural.files.map((file) => file.fanIn));\n const fanOutConcentration = concentration(input.structural.files.map((file) => file.fanOut));\n const fanConcentration = average([fanInConcentration, fanOutConcentration]);\n\n const centralityPressure = input.structural.files.map((file) => file.fanIn + file.fanOut);\n const centralityConcentration = concentration(centralityPressure);\n\n let structuralHotspotOverlap = 0;\n if (input.evolution.available) {\n const evolutionSourceFiles = input.evolution.files.filter((file) =>\n sourceFileSet.has(file.filePath),\n );\n const topStructuralCount = Math.max(1, Math.ceil(sourceFileCount * 0.1));\n const topChangeCount = Math.max(1, Math.ceil(Math.max(1, evolutionSourceFiles.length) * 0.1));\n\n const topStructural = new Set(\n [...input.structural.files]\n .map((file) => ({\n filePath: file.relativePath,\n pressure: file.fanIn + file.fanOut,\n }))\n .sort((a, b) => b.pressure - a.pressure || a.filePath.localeCompare(b.filePath))\n .slice(0, topStructuralCount)\n .map((item) => item.filePath),\n );\n\n const topChange = new Set(\n [...evolutionSourceFiles]\n .sort((a, b) => b.churnTotal - a.churnTotal || a.filePath.localeCompare(b.filePath))\n .slice(0, topChangeCount)\n .map((item) => item.filePath),\n );\n\n const overlapCount = [...topStructural].filter((filePath) => topChange.has(filePath)).length;\n structuralHotspotOverlap =\n topStructural.size === 0 || topChange.size === 0\n ? 0\n : clamp01(overlapCount / Math.min(topStructural.size, topChange.size));\n }\n\n const modularityFactors: readonly FactorSpec[] = [\n {\n factorId: \"health.modularity.cycle_density\",\n penalty: cycleDensityPenalty,\n rawMetrics: {\n cycleCount: input.structural.metrics.cycleCount,\n cycleEdgeRatio: round4(cycleEdgeRatio),\n cycleNodeRatio: round4(cycleNodeRatio),\n },\n normalizedMetrics: {\n cycleDensityPenalty: round4(cycleDensityPenalty),\n },\n weight: 0.4,\n evidence: [{ kind: \"repository_metric\", metric: \"structural.cycleEdgeRatio\" }],\n },\n {\n factorId: \"health.modularity.fan_concentration\",\n penalty: fanConcentration,\n rawMetrics: {\n fanInConcentration: round4(fanInConcentration),\n fanOutConcentration: round4(fanOutConcentration),\n },\n normalizedMetrics: {\n fanConcentration: round4(fanConcentration),\n },\n weight: 0.25,\n evidence: [{ kind: \"repository_metric\", metric: \"structural.files.fanIn/fanOut\" }],\n },\n {\n factorId: \"health.modularity.centrality_concentration\",\n penalty: centralityConcentration,\n rawMetrics: {\n centralityConcentration: round4(centralityConcentration),\n },\n normalizedMetrics: {\n centralityConcentration: round4(centralityConcentration),\n },\n weight: 0.2,\n evidence: [{ kind: \"repository_metric\", metric: \"structural.centralityPressure\" }],\n },\n {\n factorId: \"health.modularity.hotspot_overlap\",\n penalty: structuralHotspotOverlap,\n rawMetrics: {\n structuralHotspotOverlap: round4(structuralHotspotOverlap),\n },\n normalizedMetrics: {\n structuralHotspotOverlap: round4(structuralHotspotOverlap),\n },\n weight: 0.15,\n evidence: [{ kind: \"repository_metric\", metric: \"structural.evolution.hotspotOverlap\" }],\n },\n ];\n\n const modularityPenalty = dampenForSmallSamples(\n weightedPenalty(modularityFactors),\n sourceFileCount,\n 8,\n 0.45,\n );\n\n if (cycleDensityPenalty >= 0.35) {\n const firstCycle = input.structural.cycles[0];\n pushIssue(issues, {\n id: \"health.modularity.cycle_density\",\n ruleId: \"graph.cycle_density\",\n signal: \"structural.cycleEdgeRatio\",\n dimension: \"modularity\",\n target:\n firstCycle?.nodes\n .slice()\n .sort((a, b) => a.localeCompare(b))\n .join(\" -> \") ?? input.structural.targetPath,\n message:\n \"Dependencies inside cycles consume a high share of graph edges, reducing refactor flexibility.\",\n severity: cycleDensityPenalty >= 0.7 ? \"error\" : \"warn\",\n evidenceMetrics: {\n cycleCount: input.structural.metrics.cycleCount,\n cycleEdgeRatio: round4(cycleEdgeRatio),\n cycleNodeRatio: round4(cycleNodeRatio),\n },\n impact: round4(modularityPenalty * 0.35),\n });\n }\n\n if (centralityConcentration >= 0.5) {\n const hottest = [...input.structural.files]\n .map((file) => ({\n path: file.relativePath,\n pressure: file.fanIn + file.fanOut,\n }))\n .sort((a, b) => b.pressure - a.pressure || a.path.localeCompare(b.path))[0];\n\n pushIssue(issues, {\n id: \"health.modularity.centrality_concentration\",\n ruleId: \"graph.centrality_concentration\",\n signal: \"structural.centralityPressure\",\n dimension: \"modularity\",\n target: hottest?.path ?? input.structural.targetPath,\n message:\n \"Dependency flow is concentrated in a narrow set of files, creating architectural bottlenecks.\",\n evidenceMetrics: {\n fanConcentration: round4(fanConcentration),\n centralityConcentration: round4(centralityConcentration),\n },\n impact: round4(modularityPenalty * 0.25),\n });\n }\n\n if (structuralHotspotOverlap >= 0.5) {\n pushIssue(issues, {\n id: \"health.modularity.hotspot_overlap\",\n ruleId: \"graph.hotspot_overlap\",\n signal: \"structural.evolution.hotspotOverlap\",\n dimension: \"modularity\",\n target: input.structural.targetPath,\n message:\n \"Structural hubs overlap with top churn hotspots, making change pressure harder to isolate.\",\n evidenceMetrics: {\n structuralHotspotOverlap: round4(structuralHotspotOverlap),\n },\n impact: round4(modularityPenalty * 0.2),\n });\n }\n\n let churnConcentrationPenalty = 0;\n let volatilityConcentrationPenalty = 0;\n let coChangeClusterPenalty = 0;\n let top10PercentFilesChurnShare = 0;\n let top10PercentFilesVolatilityShare = 0;\n let denseCoChangePairRatio = 0;\n\n if (input.evolution.available) {\n const evolutionSourceFiles = input.evolution.files.filter((file) =>\n sourceFileSet.has(file.filePath),\n );\n const evolutionFileCount = evolutionSourceFiles.length;\n\n top10PercentFilesChurnShare = topPercentShare(\n evolutionSourceFiles.map((file) => file.churnTotal),\n 0.1,\n );\n top10PercentFilesVolatilityShare = topPercentShare(\n evolutionSourceFiles.map((file) => file.recentVolatility),\n 0.1,\n );\n\n const sourcePairs = input.evolution.coupling.pairs.filter(\n (pair) => sourceFileSet.has(pair.fileA) && sourceFileSet.has(pair.fileB),\n );\n const maxPairs = (evolutionFileCount * (evolutionFileCount - 1)) / 2;\n const densePairs = sourcePairs.filter((pair) => pair.couplingScore >= 0.55);\n denseCoChangePairRatio = maxPairs <= 0 ? 0 : clamp01(densePairs.length / maxPairs);\n const couplingScoreConcentration = concentration(sourcePairs.map((pair) => pair.couplingScore));\n\n churnConcentrationPenalty = dampenForSmallSamples(\n clamp01((top10PercentFilesChurnShare - 0.35) / 0.55),\n evolutionFileCount,\n 12,\n 0.3,\n );\n volatilityConcentrationPenalty = dampenForSmallSamples(\n clamp01((top10PercentFilesVolatilityShare - 0.35) / 0.55),\n evolutionFileCount,\n 12,\n 0.3,\n );\n\n const coChangeRaw = average([\n clamp01(denseCoChangePairRatio / 0.2),\n couplingScoreConcentration,\n ]);\n coChangeClusterPenalty = dampenForSmallSamples(coChangeRaw, sourcePairs.length, 20, 0.35);\n\n if (churnConcentrationPenalty >= 0.35) {\n const mostChurn = [...evolutionSourceFiles].sort(\n (a, b) => b.churnTotal - a.churnTotal || a.filePath.localeCompare(b.filePath),\n )[0];\n pushIssue(issues, {\n id: \"health.change_hygiene.churn_concentration\",\n ruleId: \"git.churn_distribution\",\n signal: \"evolution.top10PercentFilesChurnShare\",\n dimension: \"changeHygiene\",\n target: mostChurn?.filePath ?? input.structural.targetPath,\n message: \"A small slice of files carries most churn, reducing change predictability.\",\n evidenceMetrics: {\n top10PercentFilesChurnShare: round4(top10PercentFilesChurnShare),\n },\n impact: round4(churnConcentrationPenalty * 0.4),\n });\n }\n\n if (volatilityConcentrationPenalty >= 0.35) {\n const volatileFile = [...evolutionSourceFiles].sort(\n (a, b) => b.recentVolatility - a.recentVolatility || a.filePath.localeCompare(b.filePath),\n )[0];\n pushIssue(issues, {\n id: \"health.change_hygiene.volatility_concentration\",\n ruleId: \"git.volatility_distribution\",\n signal: \"evolution.top10PercentFilesVolatilityShare\",\n dimension: \"changeHygiene\",\n target: volatileFile?.filePath ?? input.structural.targetPath,\n message: \"Recent volatility is concentrated, increasing review and release uncertainty.\",\n evidenceMetrics: {\n top10PercentFilesVolatilityShare: round4(top10PercentFilesVolatilityShare),\n },\n impact: round4(volatilityConcentrationPenalty * 0.3),\n });\n }\n\n if (coChangeClusterPenalty >= 0.35) {\n const strongestPair = [...sourcePairs].sort(\n (a, b) =>\n b.couplingScore - a.couplingScore ||\n `${a.fileA}|${a.fileB}`.localeCompare(`${b.fileA}|${b.fileB}`),\n )[0];\n\n pushIssue(issues, {\n id: \"health.change_hygiene.dense_co_change_clusters\",\n ruleId: \"git.co_change_clusters\",\n signal: \"evolution.denseCoChangePairRatio\",\n dimension: \"changeHygiene\",\n target:\n strongestPair === undefined\n ? input.structural.targetPath\n : `${strongestPair.fileA}<->${strongestPair.fileB}`,\n message: \"Dense co-change clusters suggest wider coordination scope per change.\",\n evidenceMetrics: {\n denseCoChangePairRatio: round4(denseCoChangePairRatio),\n },\n impact: round4(coChangeClusterPenalty * 0.3),\n });\n }\n }\n\n const changeHygieneFactors: readonly FactorSpec[] = [\n {\n factorId: \"health.change_hygiene.churn_concentration\",\n penalty: churnConcentrationPenalty,\n rawMetrics: {\n top10PercentFilesChurnShare: round4(top10PercentFilesChurnShare),\n },\n normalizedMetrics: {\n churnConcentrationPenalty: round4(churnConcentrationPenalty),\n },\n weight: 0.4,\n evidence: [{ kind: \"repository_metric\", metric: \"evolution.top10PercentFilesChurnShare\" }],\n },\n {\n factorId: \"health.change_hygiene.volatility_concentration\",\n penalty: volatilityConcentrationPenalty,\n rawMetrics: {\n top10PercentFilesVolatilityShare: round4(top10PercentFilesVolatilityShare),\n },\n normalizedMetrics: {\n volatilityConcentrationPenalty: round4(volatilityConcentrationPenalty),\n },\n weight: 0.3,\n evidence: [\n {\n kind: \"repository_metric\",\n metric: \"evolution.top10PercentFilesVolatilityShare\",\n },\n ],\n },\n {\n factorId: \"health.change_hygiene.dense_co_change_clusters\",\n penalty: coChangeClusterPenalty,\n rawMetrics: {\n denseCoChangePairRatio: round4(denseCoChangePairRatio),\n },\n normalizedMetrics: {\n coChangeClusterPenalty: round4(coChangeClusterPenalty),\n },\n weight: 0.3,\n evidence: [{ kind: \"repository_metric\", metric: \"evolution.denseCoChangePairRatio\" }],\n },\n ];\n\n const changeHygienePenalty = input.evolution.available\n ? weightedPenalty(changeHygieneFactors)\n : 0.12;\n\n const paths = filePaths(input.structural);\n const testFiles = paths.filter((path) => isTestPath(path)).length;\n const sourceFiles = paths.filter((path) => isSourcePath(path)).length;\n const testRatio = sourceFiles <= 0 ? 1 : testFiles / sourceFiles;\n const testingDirectoryPresent = hasTestDirectory(paths);\n\n const testPresencePenalty = sourceFiles <= 0 ? 0 : testFiles === 0 ? 1 : 0;\n const testRatioPenalty = sourceFiles <= 0 ? 0 : 1 - clamp01(testRatio / 0.25);\n const testingDirectoryPenalty = sourceFiles <= 0 ? 0 : testingDirectoryPresent ? 0 : 0.35;\n\n const testHealthFactors: readonly FactorSpec[] = [\n {\n factorId: \"health.test_health.test_file_presence\",\n penalty: testPresencePenalty,\n rawMetrics: {\n sourceFiles,\n testFiles,\n },\n normalizedMetrics: {\n testPresencePenalty: round4(testPresencePenalty),\n },\n weight: 0.4,\n evidence: [{ kind: \"repository_metric\", metric: \"tests.filePresence\" }],\n },\n {\n factorId: \"health.test_health.test_to_source_ratio\",\n penalty: testRatioPenalty,\n rawMetrics: {\n testToSourceRatio: round4(testRatio),\n },\n normalizedMetrics: {\n testRatioPenalty: round4(testRatioPenalty),\n },\n weight: 0.45,\n evidence: [{ kind: \"repository_metric\", metric: \"tests.testToSourceRatio\" }],\n },\n {\n factorId: \"health.test_health.testing_directory_presence\",\n penalty: testingDirectoryPenalty,\n rawMetrics: {\n testingDirectoryPresent: testingDirectoryPresent ? 1 : 0,\n },\n normalizedMetrics: {\n testingDirectoryPenalty: round4(testingDirectoryPenalty),\n },\n weight: 0.15,\n evidence: [{ kind: \"repository_metric\", metric: \"tests.directoryPresence\" }],\n },\n ];\n\n const testHealthPenalty = dampenForSmallSamples(\n weightedPenalty(testHealthFactors),\n sourceFiles,\n 10,\n 0.3,\n );\n\n if (sourceFiles > 0 && testFiles === 0) {\n pushIssue(issues, {\n id: \"health.test_health.low_test_presence\",\n ruleId: \"tests.file_presence\",\n signal: \"tests.filePresence\",\n dimension: \"testHealth\",\n target: input.structural.targetPath,\n message: `No test files detected for ${sourceFiles} source file(s).`,\n severity: sourceFiles >= 12 ? \"error\" : \"warn\",\n evidenceMetrics: {\n sourceFiles,\n testFiles,\n testToSourceRatio: round4(testRatio),\n },\n impact: round4(testHealthPenalty * 0.45),\n });\n }\n\n if (sourceFiles > 0 && testRatio < 0.12) {\n pushIssue(issues, {\n id: \"health.test_health.low_test_ratio\",\n ruleId: \"tests.ratio\",\n signal: \"tests.testToSourceRatio\",\n dimension: \"testHealth\",\n target: input.structural.targetPath,\n message: \"Test-to-source ratio is low; long-term change confidence may degrade.\",\n evidenceMetrics: {\n sourceFiles,\n testFiles,\n testToSourceRatio: round4(testRatio),\n },\n impact: round4(testHealthPenalty * 0.35),\n });\n }\n\n if (input.evolution.available) {\n const evolutionSourceFiles = input.evolution.files.filter((file) =>\n sourceFileSet.has(file.filePath),\n );\n const authorTotals = new Map<string, number>();\n const moduleTotals = new Map<string, number>();\n const moduleAuthors = new Map<string, Map<string, number>>();\n\n let singleContributorFiles = 0;\n let trackedFiles = 0;\n\n for (const file of evolutionSourceFiles) {\n if (file.commitCount <= 0 || file.authorDistributionByCommits.length === 0) {\n continue;\n }\n\n trackedFiles += 1;\n const dominantShare = clamp01(file.authorDistributionByCommits[0]?.share ?? 0);\n if (file.authorDistributionByCommits.length === 1 || dominantShare >= 0.9) {\n singleContributorFiles += 1;\n }\n\n for (const author of file.authorDistributionByCommits) {\n const commits = Math.max(0, author.commits);\n if (commits <= 0) {\n continue;\n }\n\n const moduleName = moduleNameFromPath(file.filePath);\n const moduleAuthorTotals = moduleAuthors.get(moduleName) ?? new Map<string, number>();\n if (moduleAuthors.has(moduleName) === false) {\n moduleAuthors.set(moduleName, moduleAuthorTotals);\n }\n\n authorTotals.set(author.authorId, (authorTotals.get(author.authorId) ?? 0) + commits);\n moduleTotals.set(moduleName, (moduleTotals.get(moduleName) ?? 0) + commits);\n moduleAuthorTotals.set(\n author.authorId,\n (moduleAuthorTotals.get(author.authorId) ?? 0) + commits,\n );\n }\n }\n\n const totalAuthorCommits = [...authorTotals.values()].reduce((sum, value) => sum + value, 0);\n const highestAuthorCommits = [...authorTotals.values()].sort((a, b) => b - a)[0] ?? 0;\n const topAuthorCommitShare =\n totalAuthorCommits <= 0 ? 0 : clamp01(highestAuthorCommits / totalAuthorCommits);\n\n const filesWithSingleContributorRatio =\n trackedFiles === 0 ? 0 : clamp01(singleContributorFiles / trackedFiles);\n\n const authorEntropy = normalizedEntropy([...authorTotals.values()]);\n\n let dominatedModules = 0;\n let trackedModules = 0;\n for (const [moduleName, moduleCommitTotal] of moduleTotals.entries()) {\n if (moduleCommitTotal < 5) {\n continue;\n }\n\n const perModuleAuthors = moduleAuthors.get(moduleName);\n if (perModuleAuthors === undefined) {\n continue;\n }\n\n trackedModules += 1;\n const topAuthorModuleCommits = [...perModuleAuthors.values()].sort((a, b) => b - a)[0] ?? 0;\n const moduleTopShare =\n moduleCommitTotal <= 0 ? 0 : topAuthorModuleCommits / moduleCommitTotal;\n if (moduleTopShare >= 0.8) {\n dominatedModules += 1;\n }\n }\n\n const modulesDominatedBySingleContributorRatio =\n trackedModules === 0 ? 0 : clamp01(dominatedModules / trackedModules);\n\n const ownershipSampleSize = trackedFiles;\n const ownershipCommitVolume = totalAuthorCommits;\n\n const ownershipReliability = average([\n clamp01(ownershipSampleSize / 12),\n clamp01(ownershipCommitVolume / 180),\n ]);\n\n const topAuthorPenalty = clamp01((topAuthorCommitShare - 0.55) / 0.4);\n const singleContributorPenalty = clamp01((filesWithSingleContributorRatio - 0.35) / 0.6);\n const entropyPenalty = clamp01((0.75 - authorEntropy) / 0.75);\n const moduleDominancePenalty = clamp01((modulesDominatedBySingleContributorRatio - 0.4) / 0.6);\n\n const ownershipBasePenalty = weightedPenalty([\n {\n factorId: \"health.ownership.top_author_commit_share\",\n penalty: topAuthorPenalty,\n rawMetrics: {\n topAuthorCommitShare: round4(topAuthorCommitShare),\n },\n normalizedMetrics: {\n topAuthorPenalty: round4(topAuthorPenalty),\n },\n weight: 0.35,\n evidence: [{ kind: \"repository_metric\", metric: \"ownership.topAuthorCommitShare\" }],\n },\n {\n factorId: \"health.ownership.files_with_single_contributor_ratio\",\n penalty: singleContributorPenalty,\n rawMetrics: {\n filesWithSingleContributorRatio: round4(filesWithSingleContributorRatio),\n },\n normalizedMetrics: {\n singleContributorPenalty: round4(singleContributorPenalty),\n },\n weight: 0.25,\n evidence: [\n {\n kind: \"repository_metric\",\n metric: \"ownership.filesWithSingleContributorRatio\",\n },\n ],\n },\n {\n factorId: \"health.ownership.author_entropy\",\n penalty: entropyPenalty,\n rawMetrics: {\n authorEntropy: round4(authorEntropy),\n },\n normalizedMetrics: {\n authorEntropyPenalty: round4(entropyPenalty),\n },\n weight: 0.25,\n evidence: [{ kind: \"repository_metric\", metric: \"ownership.authorEntropy\" }],\n },\n {\n factorId: \"health.ownership.module_single_author_dominance\",\n penalty: moduleDominancePenalty,\n rawMetrics: {\n modulesDominatedBySingleContributorRatio: round4(\n modulesDominatedBySingleContributorRatio,\n ),\n },\n normalizedMetrics: {\n moduleDominancePenalty: round4(moduleDominancePenalty),\n },\n weight: 0.15,\n evidence: [{ kind: \"repository_metric\", metric: \"ownership.moduleDominance\" }],\n },\n ]);\n\n const ownershipDistributionPenalty = clamp01(\n ownershipBasePenalty * (0.3 + 0.7 * ownershipReliability) * ownershipPenaltyMultiplier,\n );\n\n const ownershipDistributionFactors: readonly FactorSpec[] = [\n {\n factorId: \"health.ownership.top_author_commit_share\",\n penalty: topAuthorPenalty,\n rawMetrics: {\n topAuthorCommitShare: round4(topAuthorCommitShare),\n },\n normalizedMetrics: {\n topAuthorPenalty: round4(topAuthorPenalty),\n ownershipPenaltyMultiplier: round4(ownershipPenaltyMultiplier),\n ownershipReliability: round4(ownershipReliability),\n },\n weight: 0.35,\n evidence: [{ kind: \"repository_metric\", metric: \"ownership.topAuthorCommitShare\" }],\n },\n {\n factorId: \"health.ownership.files_with_single_contributor_ratio\",\n penalty: singleContributorPenalty,\n rawMetrics: {\n filesWithSingleContributorRatio: round4(filesWithSingleContributorRatio),\n },\n normalizedMetrics: {\n singleContributorPenalty: round4(singleContributorPenalty),\n },\n weight: 0.25,\n evidence: [\n {\n kind: \"repository_metric\",\n metric: \"ownership.filesWithSingleContributorRatio\",\n },\n ],\n },\n {\n factorId: \"health.ownership.author_entropy\",\n penalty: entropyPenalty,\n rawMetrics: {\n authorEntropy: round4(authorEntropy),\n },\n normalizedMetrics: {\n authorEntropyPenalty: round4(entropyPenalty),\n },\n weight: 0.25,\n evidence: [{ kind: \"repository_metric\", metric: \"ownership.authorEntropy\" }],\n },\n {\n factorId: \"health.ownership.module_single_author_dominance\",\n penalty: moduleDominancePenalty,\n rawMetrics: {\n modulesDominatedBySingleContributorRatio: round4(\n modulesDominatedBySingleContributorRatio,\n ),\n },\n normalizedMetrics: {\n moduleDominancePenalty: round4(moduleDominancePenalty),\n },\n weight: 0.15,\n evidence: [{ kind: \"repository_metric\", metric: \"ownership.moduleDominance\" }],\n },\n ];\n\n if (topAuthorPenalty >= 0.35) {\n pushIssue(issues, {\n id: \"health.ownership.top_author_commit_share\",\n ruleId: \"ownership.top_author_share\",\n signal: \"ownership.topAuthorCommitShare\",\n dimension: \"ownershipDistribution\",\n target: input.structural.targetPath,\n message: \"A single contributor owns most commits, concentrating repository knowledge.\",\n severity: topAuthorPenalty >= 0.75 ? \"error\" : \"warn\",\n evidenceMetrics: {\n topAuthorCommitShare: round4(topAuthorCommitShare),\n authorEntropy: round4(authorEntropy),\n },\n impact: round4(ownershipDistributionPenalty * 0.4),\n });\n }\n\n if (singleContributorPenalty >= 0.35) {\n pushIssue(issues, {\n id: \"health.ownership.single_author_dominance\",\n ruleId: \"ownership.file_dominance\",\n signal: \"ownership.filesWithSingleContributorRatio\",\n dimension: \"ownershipDistribution\",\n target: input.structural.targetPath,\n message: \"Many files are dominated by a single contributor, reducing change resilience.\",\n evidenceMetrics: {\n filesWithSingleContributorRatio: round4(filesWithSingleContributorRatio),\n modulesDominatedBySingleContributorRatio: round4(\n modulesDominatedBySingleContributorRatio,\n ),\n },\n impact: round4(ownershipDistributionPenalty * 0.35),\n });\n }\n\n if (entropyPenalty >= 0.35) {\n pushIssue(issues, {\n id: \"health.ownership.low_author_entropy\",\n ruleId: \"ownership.author_entropy\",\n signal: \"ownership.authorEntropy\",\n dimension: \"ownershipDistribution\",\n target: input.structural.targetPath,\n message: \"Contributor distribution is narrow across the repository.\",\n evidenceMetrics: {\n authorEntropy: round4(authorEntropy),\n topAuthorCommitShare: round4(topAuthorCommitShare),\n },\n impact: round4(ownershipDistributionPenalty * 0.25),\n });\n }\n\n const modularityHealth = clamp01(1 - modularityPenalty);\n const changeHygieneHealth = clamp01(1 - changeHygienePenalty);\n const testHealthScore = clamp01(1 - testHealthPenalty);\n const ownershipDistributionHealth = clamp01(1 - ownershipDistributionPenalty);\n\n const normalizedScore = clamp01(\n modularityHealth * DIMENSION_WEIGHTS.modularity +\n changeHygieneHealth * DIMENSION_WEIGHTS.changeHygiene +\n testHealthScore * DIMENSION_WEIGHTS.testHealth +\n ownershipDistributionHealth * DIMENSION_WEIGHTS.ownershipDistribution,\n );\n\n const topIssues = [...issues]\n .sort(\n (a, b) =>\n b.impact - a.impact || a.id.localeCompare(b.id) || a.target.localeCompare(b.target),\n )\n .slice(0, 12)\n .map(({ impact: _impact, ...issue }) => issue);\n\n return {\n healthScore: toPercentage(normalizedScore),\n normalizedScore: round4(normalizedScore),\n dimensions: {\n modularity: toPercentage(modularityHealth),\n changeHygiene: toPercentage(changeHygieneHealth),\n testHealth: toPercentage(testHealthScore),\n ownershipDistribution: toPercentage(ownershipDistributionHealth),\n },\n topIssues,\n trace: {\n schemaVersion: HEALTH_TRACE_VERSION,\n dimensions: [\n createDimensionTrace(\"modularity\", modularityHealth, modularityFactors),\n createDimensionTrace(\"changeHygiene\", changeHygieneHealth, changeHygieneFactors),\n createDimensionTrace(\"testHealth\", testHealthScore, testHealthFactors),\n createDimensionTrace(\n \"ownershipDistribution\",\n ownershipDistributionHealth,\n ownershipDistributionFactors,\n ),\n ],\n },\n };\n }\n\n const ownershipDistributionPenalty = clamp01(0.12 * ownershipPenaltyMultiplier);\n const ownershipDistributionFactors: readonly FactorSpec[] = [\n {\n factorId: \"health.ownership.missing_git_history\",\n penalty: ownershipDistributionPenalty,\n rawMetrics: {\n gitHistoryAvailable: 0,\n },\n normalizedMetrics: {\n ownershipDistributionPenalty: round4(ownershipDistributionPenalty),\n },\n weight: 1,\n evidence: [{ kind: \"repository_metric\", metric: \"evolution.available\" }],\n },\n ];\n\n const modularityHealth = clamp01(1 - modularityPenalty);\n const changeHygieneHealth = clamp01(1 - changeHygienePenalty);\n const testHealthScore = clamp01(1 - testHealthPenalty);\n const ownershipDistributionHealth = clamp01(1 - ownershipDistributionPenalty);\n\n const normalizedScore = clamp01(\n modularityHealth * DIMENSION_WEIGHTS.modularity +\n changeHygieneHealth * DIMENSION_WEIGHTS.changeHygiene +\n testHealthScore * DIMENSION_WEIGHTS.testHealth +\n ownershipDistributionHealth * DIMENSION_WEIGHTS.ownershipDistribution,\n );\n\n const topIssues = [...issues]\n .sort(\n (a, b) => b.impact - a.impact || a.id.localeCompare(b.id) || a.target.localeCompare(b.target),\n )\n .slice(0, 12)\n .map(({ impact: _impact, ...issue }) => issue);\n\n return {\n healthScore: toPercentage(normalizedScore),\n normalizedScore: round4(normalizedScore),\n dimensions: {\n modularity: toPercentage(modularityHealth),\n changeHygiene: toPercentage(changeHygieneHealth),\n testHealth: toPercentage(testHealthScore),\n ownershipDistribution: toPercentage(ownershipDistributionHealth),\n },\n topIssues,\n trace: {\n schemaVersion: HEALTH_TRACE_VERSION,\n dimensions: [\n createDimensionTrace(\"modularity\", modularityHealth, modularityFactors),\n createDimensionTrace(\"changeHygiene\", changeHygieneHealth, changeHygieneFactors),\n createDimensionTrace(\"testHealth\", testHealthScore, testHealthFactors),\n createDimensionTrace(\n \"ownershipDistribution\",\n ownershipDistributionHealth,\n ownershipDistributionFactors,\n ),\n ],\n },\n };\n};\n","export type DimensionWeights = {\n structural: number;\n evolution: number;\n external: number;\n};\n\nexport type InteractionWeights = {\n structuralEvolution: number;\n centralInstability: number;\n dependencyAmplification: number;\n};\n\nexport type StructuralFactorWeights = {\n fanIn: number;\n fanOut: number;\n depth: number;\n cycleParticipation: number;\n};\n\nexport type EvolutionFactorWeights = {\n frequency: number;\n churn: number;\n recentVolatility: number;\n ownershipConcentration: number;\n busFactorRisk: number;\n};\n\nexport type DependencyFactorWeights = {\n signals: number;\n staleness: number;\n maintainerConcentration: number;\n transitiveBurden: number;\n centrality: number;\n chainDepth: number;\n busFactorRisk: number;\n};\n\nexport type RiskEngineConfig = {\n dimensionWeights: DimensionWeights;\n interactionWeights: InteractionWeights;\n structuralFactorWeights: StructuralFactorWeights;\n evolutionFactorWeights: EvolutionFactorWeights;\n dependencyFactorWeights: DependencyFactorWeights;\n quantileClamp: {\n lower: number;\n upper: number;\n };\n hotspotTopPercent: number;\n hotspotMinFiles: number;\n hotspotMaxFiles: number;\n couplingCluster: {\n minCoChangeCommits: number;\n percentileThreshold: number;\n floorScore: number;\n };\n amplificationZone: {\n pressureFloor: number;\n percentileThreshold: number;\n maxZones: number;\n };\n module: {\n maxPrefixSegments: number;\n rootLabel: string;\n commonSourceRoots: readonly string[];\n };\n dependencySignals: {\n inheritedSignalMultiplier: number;\n abandonedHalfLifeDays: number;\n missingMetadataPenalty: number;\n popularityHalfLifeDownloads: number;\n popularityMaxDampening: number;\n };\n externalDimension: {\n topDependencyPercentile: number;\n dependencyDepthHalfLife: number;\n };\n aggregatorAttenuation: {\n enabled: boolean;\n minFanIn: number;\n minFanOut: number;\n minCommitCount: number;\n maxChurnPerCommit: number;\n maxChurnPerDependency: number;\n maxStructuralReduction: number;\n };\n};\n\nexport const DEFAULT_RISK_ENGINE_CONFIG: RiskEngineConfig = {\n // Base dimensional influence. Risk is never dominated by a single dimension by default.\n dimensionWeights: {\n structural: 0.44,\n evolution: 0.36,\n external: 0.2,\n },\n // Interaction terms activate only when both related dimensions are high.\n interactionWeights: {\n structuralEvolution: 0.35,\n centralInstability: 0.25,\n dependencyAmplification: 0.2,\n },\n structuralFactorWeights: {\n fanIn: 0.3,\n fanOut: 0.25,\n depth: 0.2,\n cycleParticipation: 0.25,\n },\n evolutionFactorWeights: {\n frequency: 0.26,\n churn: 0.24,\n recentVolatility: 0.2,\n ownershipConcentration: 0.18,\n busFactorRisk: 0.12,\n },\n dependencyFactorWeights: {\n signals: 0.38,\n staleness: 0.16,\n maintainerConcentration: 0.16,\n transitiveBurden: 0.1,\n centrality: 0.08,\n chainDepth: 0.06,\n busFactorRisk: 0.06,\n },\n quantileClamp: {\n lower: 0.05,\n upper: 0.95,\n },\n hotspotTopPercent: 0.12,\n hotspotMinFiles: 3,\n hotspotMaxFiles: 30,\n couplingCluster: {\n minCoChangeCommits: 2,\n percentileThreshold: 0.9,\n floorScore: 0.35,\n },\n amplificationZone: {\n pressureFloor: 0.2,\n percentileThreshold: 0.85,\n maxZones: 20,\n },\n module: {\n maxPrefixSegments: 2,\n rootLabel: \"(root)\",\n commonSourceRoots: [\"src\", \"lib\", \"app\", \"packages\"],\n },\n dependencySignals: {\n inheritedSignalMultiplier: 0.45,\n // At this age, staleness reaches 50% risk.\n abandonedHalfLifeDays: 540,\n missingMetadataPenalty: 0.5,\n // At this download volume, popularity reaches 50% of its dampening effect.\n popularityHalfLifeDownloads: 100000,\n // Popularity can only reduce dependency risk by this fraction.\n popularityMaxDampening: 0.12,\n },\n externalDimension: {\n topDependencyPercentile: 0.85,\n dependencyDepthHalfLife: 6,\n },\n // Reduce false positives for thin aggregation hubs (for example, barrel/index re-export files)\n // that are structurally central but have low churn density and no cycle participation.\n aggregatorAttenuation: {\n enabled: true,\n minFanIn: 6,\n minFanOut: 4,\n minCommitCount: 4,\n maxChurnPerCommit: 24,\n maxChurnPerDependency: 10,\n maxStructuralReduction: 0.3,\n },\n};\n","import type {\n DependencyRiskScore,\n DependencyRiskSignal,\n EvidenceRef,\n ExternalAnalysisSummary,\n FileEvolutionMetrics,\n FileRiskScore,\n FragileCluster,\n GraphAnalysisSummary,\n ModuleRiskScore,\n RepositoryEvolutionSummary,\n RepositoryRiskSummary,\n RiskFactors,\n RiskFactorFamily,\n RiskFactorTrace,\n TargetTrace,\n WorkspaceRiskScore,\n} from \"@codesentinel/core\";\nimport { fileBelongsToWorkspace } from \"@codesentinel/core\";\nimport type { RiskEngineConfig } from \"../config.js\";\nimport {\n average,\n toUnitInterval,\n halfLifeRisk,\n normalizeWeights,\n percentile,\n round4,\n saturatingComposite,\n} from \"./math.js\";\nimport { buildQuantileScale, logScale, normalizeWithScale } from \"./normalization.js\";\nimport type { TraceCollector } from \"./trace-collector.js\";\n\ntype DependencyScoreComputation = {\n dependencyScores: readonly DependencyRiskScore[];\n repositoryExternalPressure: number;\n dependencyContexts: ReadonlyMap<\n string,\n {\n signalScore: number;\n stalenessRisk: number;\n maintainerConcentrationRisk: number;\n transitiveBurdenRisk: number;\n centralityRisk: number;\n chainDepthRisk: number;\n busFactorRisk: number;\n popularityDampener: number;\n rawMetrics: {\n daysSinceLastRelease: number | null;\n maintainerCount: number | null;\n transitiveCount: number;\n dependents: number;\n dependencyDepth: number;\n busFactor: number | null;\n weeklyDownloads: number | null;\n };\n confidence: number;\n }\n >;\n};\n\ntype FileRiskContext = {\n file: string;\n score: number;\n normalizedScore: number;\n factors: RiskFactors;\n structuralCentrality: number;\n traceTerms: {\n structuralBase: number;\n evolutionBase: number;\n externalBase: number;\n interactionStructuralEvolution: number;\n interactionCentralInstability: number;\n interactionDependencyAmplification: number;\n };\n rawMetrics: {\n fanIn: number;\n fanOut: number;\n depth: number;\n cycleParticipation: number;\n commitCount: number | null;\n churnTotal: number | null;\n recentVolatility: number | null;\n topAuthorShareByCommits: number | null;\n busFactorByCommits: number | null;\n dependencyAffinity: number;\n repositoryExternalPressure: number;\n structuralAttenuation: number;\n };\n normalizedMetrics: {\n fanInRisk: number;\n fanOutRisk: number;\n depthRisk: number;\n frequencyRisk: number;\n churnRisk: number;\n volatilityRisk: number;\n ownershipConcentrationRisk: number;\n busFactorRisk: number;\n };\n};\n\ntype MetricScales = {\n commitCount: ReturnType<typeof buildQuantileScale>;\n churnTotal: ReturnType<typeof buildQuantileScale>;\n busFactor: ReturnType<typeof buildQuantileScale>;\n};\n\ntype FactorTraceInput = {\n factorId: string;\n family: RiskFactorFamily;\n strength: number;\n rawMetrics: Readonly<Record<string, number | null>>;\n normalizedMetrics: Readonly<Record<string, number | null>>;\n weight: number | null;\n amplification: number | null;\n evidence: readonly EvidenceRef[];\n confidence: number;\n};\n\nconst normalizePath = (path: string): string => path.replaceAll(\"\\\\\", \"/\");\n\nconst computeAggregatorAttenuation = (input: {\n fanIn: number;\n fanOut: number;\n inCycle: number;\n evolutionMetrics: FileEvolutionMetrics | undefined;\n config: RiskEngineConfig[\"aggregatorAttenuation\"];\n}): number => {\n const { fanIn, fanOut, inCycle, evolutionMetrics, config } = input;\n if (!config.enabled || inCycle > 0) {\n return 1;\n }\n\n if (fanIn < config.minFanIn || fanOut < config.minFanOut) {\n return 1;\n }\n\n if (evolutionMetrics === undefined || evolutionMetrics.commitCount < config.minCommitCount) {\n return 1;\n }\n\n const churnPerCommit = evolutionMetrics.churnTotal / Math.max(1, evolutionMetrics.commitCount);\n const churnPerDependency = evolutionMetrics.churnTotal / Math.max(1, fanOut);\n\n if (\n churnPerCommit > config.maxChurnPerCommit ||\n churnPerDependency > config.maxChurnPerDependency\n ) {\n return 1;\n }\n\n const fanInSignal = toUnitInterval((fanIn - config.minFanIn) / Math.max(1, config.minFanIn));\n const fanOutSignal = toUnitInterval((fanOut - config.minFanOut) / Math.max(1, config.minFanOut));\n const lowChurnPerCommitSignal = 1 - toUnitInterval(churnPerCommit / config.maxChurnPerCommit);\n const lowChurnPerDependencySignal =\n 1 - toUnitInterval(churnPerDependency / config.maxChurnPerDependency);\n const attenuationConfidence = average([\n fanInSignal,\n fanOutSignal,\n lowChurnPerCommitSignal,\n lowChurnPerDependencySignal,\n ]);\n\n const reduction = toUnitInterval(config.maxStructuralReduction) * attenuationConfidence;\n return round4(toUnitInterval(1 - reduction));\n};\n\nconst dependencySignalWeights: Readonly<Record<DependencyRiskSignal, number>> = {\n single_maintainer: 0.3,\n abandoned: 0.3,\n high_centrality: 0.16,\n deep_chain: 0.14,\n high_fanout: 0.06,\n metadata_unavailable: 0.04,\n};\n\nconst dependencySignalWeightBudget = Object.values(dependencySignalWeights).reduce(\n (sum, value) => sum + value,\n 0,\n);\n\nconst computeDependencySignalScore = (\n ownSignals: readonly DependencyRiskSignal[],\n inheritedSignals: readonly DependencyRiskSignal[],\n inheritedSignalMultiplier: number,\n): number => {\n const ownWeight = ownSignals.reduce(\n (sum, signal) => sum + (dependencySignalWeights[signal] ?? 0),\n 0,\n );\n const inheritedWeight = inheritedSignals.reduce(\n (sum, signal) => sum + (dependencySignalWeights[signal] ?? 0),\n 0,\n );\n\n const weightedTotal = ownWeight + inheritedWeight * inheritedSignalMultiplier;\n const maxWeightedTotal = dependencySignalWeightBudget * (1 + inheritedSignalMultiplier);\n\n if (maxWeightedTotal <= 0) {\n return 0;\n }\n\n return toUnitInterval(weightedTotal / maxWeightedTotal);\n};\n\nconst clampConfidence = (value: number): number => round4(toUnitInterval(value));\n\nconst computeExternalMetadataConfidence = (external: ExternalAnalysisSummary): number => {\n if (!external.available) {\n return 0;\n }\n\n // Topology signals still exist without registry metadata, so keep a non-zero floor.\n return round4(toUnitInterval(0.35 + external.metrics.metadataCoverage * 0.65));\n};\n\nconst computeEvolutionHistoryConfidence = (\n structural: GraphAnalysisSummary,\n evolution: RepositoryEvolutionSummary,\n evolutionByFile: ReadonlyMap<string, FileEvolutionMetrics>,\n): number => {\n if (!evolution.available) {\n return 0;\n }\n\n const totalFiles = structural.files.length;\n if (totalFiles === 0) {\n return 1;\n }\n\n let coveredFiles = 0;\n for (const file of structural.files) {\n if (evolutionByFile.has(normalizePath(file.id))) {\n coveredFiles += 1;\n }\n }\n\n const coverage = coveredFiles / totalFiles;\n // Partial commit history still carries value, but confidence scales with coverage.\n return round4(toUnitInterval(0.3 + coverage * 0.7));\n};\n\nconst buildFactorTraces = (\n totalScore: number,\n inputs: readonly FactorTraceInput[],\n): readonly RiskFactorTrace[] => {\n const positiveInputs = inputs.filter((input) => input.strength > 0);\n const strengthTotal = positiveInputs.reduce((sum, input) => sum + input.strength, 0);\n\n const traces = inputs.map<RiskFactorTrace>((input) => ({\n factorId: input.factorId,\n family: input.family,\n contribution: 0,\n rawMetrics: input.rawMetrics,\n normalizedMetrics: input.normalizedMetrics,\n weight: input.weight,\n amplification: input.amplification,\n evidence: input.evidence,\n confidence: clampConfidence(input.confidence),\n }));\n\n if (strengthTotal <= 0 || totalScore <= 0) {\n return traces;\n }\n\n const scored = positiveInputs.map((input) => ({\n factorId: input.factorId,\n contribution: (totalScore * input.strength) / strengthTotal,\n }));\n\n let distributed = 0;\n for (let index = 0; index < scored.length; index += 1) {\n const current = scored[index];\n if (current === undefined) {\n continue;\n }\n\n const traceIndex = traces.findIndex((trace) => trace.factorId === current.factorId);\n if (traceIndex < 0) {\n continue;\n }\n const existing = traces[traceIndex];\n if (existing === undefined) {\n continue;\n }\n\n if (index === scored.length - 1) {\n const remaining = round4(totalScore - distributed);\n traces[traceIndex] = {\n ...existing,\n contribution: Math.max(0, remaining),\n };\n distributed += Math.max(0, remaining);\n continue;\n }\n\n const rounded = round4(current.contribution);\n traces[traceIndex] = {\n ...existing,\n contribution: rounded,\n };\n distributed += rounded;\n }\n\n return traces;\n};\n\nconst buildReductionLevers = (\n factors: readonly RiskFactorTrace[],\n): readonly { factorId: string; estimatedImpact: number }[] =>\n factors\n .filter((factor) => factor.contribution > 0)\n .sort((a, b) => b.contribution - a.contribution || a.factorId.localeCompare(b.factorId))\n .slice(0, 3)\n .map((factor) => ({\n factorId: factor.factorId,\n estimatedImpact: round4(factor.contribution),\n }));\n\nconst buildTargetTrace = (\n targetType: TargetTrace[\"targetType\"],\n targetId: string,\n totalScore: number,\n normalizedScore: number,\n factors: readonly RiskFactorTrace[],\n): TargetTrace => {\n const dominantFactors = [...factors]\n .filter((factor) => factor.contribution > 0)\n .sort((a, b) => b.contribution - a.contribution || a.factorId.localeCompare(b.factorId))\n .slice(0, 3)\n .map((factor) => factor.factorId);\n\n return {\n targetType,\n targetId,\n totalScore: round4(totalScore),\n normalizedScore: round4(normalizedScore),\n factors,\n dominantFactors,\n reductionLevers: buildReductionLevers(factors),\n };\n};\n\nconst computeDependencyScores = (\n external: ExternalAnalysisSummary,\n config: RiskEngineConfig,\n): DependencyScoreComputation => {\n if (!external.available) {\n return {\n dependencyScores: [],\n repositoryExternalPressure: 0,\n dependencyContexts: new Map(),\n };\n }\n\n const transitiveCounts = external.dependencies.map((dependency) =>\n logScale(dependency.transitiveDependencies.length),\n );\n const dependentCounts = external.dependencies.map((dependency) =>\n logScale(dependency.dependents),\n );\n const chainDepths = external.dependencies.map((dependency) => dependency.dependencyDepth);\n\n const transitiveScale = buildQuantileScale(\n transitiveCounts,\n config.quantileClamp.lower,\n config.quantileClamp.upper,\n );\n const dependentScale = buildQuantileScale(\n dependentCounts,\n config.quantileClamp.lower,\n config.quantileClamp.upper,\n );\n const chainDepthScale = buildQuantileScale(\n chainDepths,\n config.quantileClamp.lower,\n config.quantileClamp.upper,\n );\n\n const dependencyContexts = new Map<\n string,\n {\n signalScore: number;\n stalenessRisk: number;\n maintainerConcentrationRisk: number;\n transitiveBurdenRisk: number;\n centralityRisk: number;\n chainDepthRisk: number;\n busFactorRisk: number;\n popularityDampener: number;\n rawMetrics: {\n daysSinceLastRelease: number | null;\n maintainerCount: number | null;\n transitiveCount: number;\n dependents: number;\n dependencyDepth: number;\n busFactor: number | null;\n weeklyDownloads: number | null;\n };\n confidence: number;\n }\n >();\n\n const metadataConfidence = computeExternalMetadataConfidence(external);\n const dependencyScores = external.dependencies\n .map<DependencyRiskScore>((dependency) => {\n const signalScore = computeDependencySignalScore(\n dependency.ownRiskSignals,\n dependency.inheritedRiskSignals,\n config.dependencySignals.inheritedSignalMultiplier,\n );\n\n const maintainerConcentrationRisk =\n dependency.maintainerCount === null\n ? config.dependencySignals.missingMetadataPenalty\n : toUnitInterval(1 / Math.max(1, dependency.maintainerCount));\n\n const stalenessRisk =\n dependency.daysSinceLastRelease === null\n ? config.dependencySignals.missingMetadataPenalty\n : halfLifeRisk(\n dependency.daysSinceLastRelease,\n config.dependencySignals.abandonedHalfLifeDays,\n );\n\n const transitiveBurdenRisk = normalizeWithScale(\n logScale(dependency.transitiveDependencies.length),\n transitiveScale,\n );\n\n const centralityRisk = normalizeWithScale(logScale(dependency.dependents), dependentScale);\n const chainDepthRisk = normalizeWithScale(dependency.dependencyDepth, chainDepthScale);\n\n const busFactorRisk =\n dependency.busFactor === null\n ? config.dependencySignals.missingMetadataPenalty\n : toUnitInterval(1 / Math.max(1, dependency.busFactor));\n\n const weights = config.dependencyFactorWeights;\n const baseScore = toUnitInterval(\n signalScore * weights.signals +\n stalenessRisk * weights.staleness +\n maintainerConcentrationRisk * weights.maintainerConcentration +\n transitiveBurdenRisk * weights.transitiveBurden +\n centralityRisk * weights.centrality +\n chainDepthRisk * weights.chainDepth +\n busFactorRisk * weights.busFactorRisk,\n );\n\n const hasHardRiskSignal =\n dependency.ownRiskSignals.includes(\"abandoned\") ||\n dependency.ownRiskSignals.includes(\"metadata_unavailable\") ||\n dependency.ownRiskSignals.includes(\"single_maintainer\");\n\n const popularityDampener =\n dependency.weeklyDownloads === null || hasHardRiskSignal\n ? 1\n : 1 -\n halfLifeRisk(\n dependency.weeklyDownloads,\n config.dependencySignals.popularityHalfLifeDownloads,\n ) *\n config.dependencySignals.popularityMaxDampening;\n const normalizedScore = toUnitInterval(baseScore * popularityDampener);\n\n const availableMetricCount = [\n dependency.daysSinceLastRelease,\n dependency.maintainerCount,\n dependency.busFactor,\n dependency.weeklyDownloads,\n ].filter((value) => value !== null).length;\n const confidence = toUnitInterval((0.5 + availableMetricCount * 0.125) * metadataConfidence);\n\n dependencyContexts.set(dependency.name, {\n signalScore: round4(signalScore),\n stalenessRisk: round4(stalenessRisk),\n maintainerConcentrationRisk: round4(maintainerConcentrationRisk),\n transitiveBurdenRisk: round4(transitiveBurdenRisk),\n centralityRisk: round4(centralityRisk),\n chainDepthRisk: round4(chainDepthRisk),\n busFactorRisk: round4(busFactorRisk),\n popularityDampener: round4(popularityDampener),\n rawMetrics: {\n daysSinceLastRelease: dependency.daysSinceLastRelease,\n maintainerCount: dependency.maintainerCount,\n transitiveCount: dependency.transitiveDependencies.length,\n dependents: dependency.dependents,\n dependencyDepth: dependency.dependencyDepth,\n busFactor: dependency.busFactor,\n weeklyDownloads: dependency.weeklyDownloads,\n },\n confidence: round4(confidence),\n });\n\n return {\n dependency: dependency.name,\n score: round4(normalizedScore * 100),\n normalizedScore: round4(normalizedScore),\n ownRiskSignals: dependency.ownRiskSignals,\n inheritedRiskSignals: dependency.inheritedRiskSignals,\n };\n })\n .sort(\n (a, b) => b.normalizedScore - a.normalizedScore || a.dependency.localeCompare(b.dependency),\n );\n\n const normalizedValues = dependencyScores.map((score) => score.normalizedScore);\n const highDependencyRisk =\n dependencyScores.length === 0\n ? 0\n : percentile(normalizedValues, config.externalDimension.topDependencyPercentile);\n const averageDependencyRisk = average(normalizedValues);\n const depthRisk = halfLifeRisk(\n external.metrics.dependencyDepth,\n config.externalDimension.dependencyDepthHalfLife,\n );\n\n const repositoryExternalPressure = toUnitInterval(\n highDependencyRisk * 0.5 + averageDependencyRisk * 0.3 + depthRisk * 0.2,\n );\n\n return {\n dependencyScores,\n repositoryExternalPressure: round4(repositoryExternalPressure),\n dependencyContexts,\n };\n};\n\nconst mapEvolutionByFile = (\n evolution: RepositoryEvolutionSummary,\n): ReadonlyMap<string, FileEvolutionMetrics> => {\n if (!evolution.available) {\n return new Map<string, FileEvolutionMetrics>();\n }\n\n return new Map(\n evolution.files.map((fileMetrics) => [normalizePath(fileMetrics.filePath), fileMetrics]),\n );\n};\n\nconst computeEvolutionScales = (\n evolutionByFile: ReadonlyMap<string, FileEvolutionMetrics>,\n config: RiskEngineConfig,\n): MetricScales => {\n const evolutionFiles = [...evolutionByFile.values()];\n\n return {\n commitCount: buildQuantileScale(\n evolutionFiles.map((metrics) => logScale(metrics.commitCount)),\n config.quantileClamp.lower,\n config.quantileClamp.upper,\n ),\n churnTotal: buildQuantileScale(\n evolutionFiles.map((metrics) => logScale(metrics.churnTotal)),\n config.quantileClamp.lower,\n config.quantileClamp.upper,\n ),\n busFactor: buildQuantileScale(\n evolutionFiles.map((metrics) => metrics.busFactorByCommits),\n config.quantileClamp.lower,\n config.quantileClamp.upper,\n ),\n };\n};\n\nconst inferModuleName = (filePath: string, config: RiskEngineConfig): string => {\n const normalized = normalizePath(filePath);\n const parts = normalized.split(\"/\").filter((part) => part.length > 0);\n\n if (parts.length <= 1) {\n return config.module.rootLabel;\n }\n\n const first = parts[0];\n if (first === undefined) {\n return config.module.rootLabel;\n }\n\n if (!config.module.commonSourceRoots.includes(first)) {\n return first;\n }\n\n if (parts.length <= config.module.maxPrefixSegments) {\n return first;\n }\n\n return parts.slice(0, config.module.maxPrefixSegments).join(\"/\");\n};\n\nconst buildFragileClusters = (\n structural: GraphAnalysisSummary,\n evolution: RepositoryEvolutionSummary,\n fileScoresByFile: ReadonlyMap<string, FileRiskScore>,\n config: RiskEngineConfig,\n): readonly FragileCluster[] => {\n const clusters: FragileCluster[] = [];\n\n let cycleClusterCount = 0;\n for (const cycle of structural.cycles) {\n const files = [...new Set(cycle.nodes.map((node) => normalizePath(node)))].filter((filePath) =>\n fileScoresByFile.has(filePath),\n );\n\n if (files.length < 2) {\n continue;\n }\n\n files.sort((a, b) => a.localeCompare(b));\n\n const averageRisk = average(\n files.map((filePath) => fileScoresByFile.get(filePath)?.normalizedScore ?? 0),\n );\n\n const cycleSizeRisk = toUnitInterval((files.length - 1) / 5);\n const score = round4(toUnitInterval(averageRisk * 0.75 + cycleSizeRisk * 0.25) * 100);\n\n cycleClusterCount += 1;\n clusters.push({\n id: `cycle:${cycleClusterCount}`,\n kind: \"structural_cycle\",\n files,\n score,\n });\n }\n\n if (evolution.available && evolution.coupling.pairs.length > 0) {\n const candidates = evolution.coupling.pairs.filter(\n (pair) => pair.coChangeCommits >= config.couplingCluster.minCoChangeCommits,\n );\n\n const threshold = Math.max(\n config.couplingCluster.floorScore,\n percentile(\n candidates.map((pair) => pair.couplingScore),\n config.couplingCluster.percentileThreshold,\n ),\n );\n\n const selectedPairs = candidates\n .filter((pair) => pair.couplingScore >= threshold)\n .map((pair) => ({\n fileA: normalizePath(pair.fileA),\n fileB: normalizePath(pair.fileB),\n couplingScore: pair.couplingScore,\n }))\n .filter(\n (pair) =>\n pair.fileA !== pair.fileB &&\n fileScoresByFile.has(pair.fileA) &&\n fileScoresByFile.has(pair.fileB),\n );\n\n const adjacency = new Map<string, Set<string>>();\n for (const pair of selectedPairs) {\n const aNeighbors = adjacency.get(pair.fileA) ?? new Set<string>();\n aNeighbors.add(pair.fileB);\n adjacency.set(pair.fileA, aNeighbors);\n\n const bNeighbors = adjacency.get(pair.fileB) ?? new Set<string>();\n bNeighbors.add(pair.fileA);\n adjacency.set(pair.fileB, bNeighbors);\n }\n\n const visited = new Set<string>();\n let couplingClusterCount = 0;\n\n const orderedStarts = [...adjacency.keys()].sort((a, b) => a.localeCompare(b));\n for (const start of orderedStarts) {\n if (visited.has(start)) {\n continue;\n }\n\n const stack = [start];\n const files: string[] = [];\n\n while (stack.length > 0) {\n const current = stack.pop();\n if (current === undefined || visited.has(current)) {\n continue;\n }\n\n visited.add(current);\n files.push(current);\n\n const neighbors = adjacency.get(current);\n if (neighbors === undefined) {\n continue;\n }\n\n for (const neighbor of neighbors) {\n if (!visited.has(neighbor)) {\n stack.push(neighbor);\n }\n }\n }\n\n if (files.length < 2) {\n continue;\n }\n\n files.sort((a, b) => a.localeCompare(b));\n const fileSet = new Set(files);\n const componentPairs = selectedPairs.filter(\n (pair) => fileSet.has(pair.fileA) && fileSet.has(pair.fileB),\n );\n\n const meanFileRisk = average(\n files.map((filePath) => fileScoresByFile.get(filePath)?.normalizedScore ?? 0),\n );\n const meanCoupling = average(componentPairs.map((pair) => pair.couplingScore));\n\n const score = round4(toUnitInterval(meanFileRisk * 0.65 + meanCoupling * 0.35) * 100);\n\n couplingClusterCount += 1;\n clusters.push({\n id: `coupling:${couplingClusterCount}`,\n kind: \"change_coupling\",\n files,\n score,\n });\n }\n }\n\n return clusters.sort(\n (a, b) => b.score - a.score || a.kind.localeCompare(b.kind) || a.id.localeCompare(b.id),\n );\n};\n\nconst buildWorkspaceRiskScores = (\n structural: GraphAnalysisSummary,\n fileScoresByFile: ReadonlyMap<string, FileRiskScore>,\n): readonly WorkspaceRiskScore[] => {\n if (structural.workspaces === undefined || structural.workspaces.length === 0) {\n return [];\n }\n\n const maxIncomingEdges = structural.workspaces.reduce(\n (max, workspace) => Math.max(max, workspace.incomingEdgeCount),\n 0,\n );\n const maxOutgoingEdges = structural.workspaces.reduce(\n (max, workspace) => Math.max(max, workspace.outgoingEdgeCount),\n 0,\n );\n\n return structural.workspaces\n .map((workspace) => {\n const workspaceFileScores = [...fileScoresByFile.values()]\n .filter((fileScore) => fileBelongsToWorkspace(fileScore.file, workspace))\n .sort((a, b) => b.score - a.score || a.file.localeCompare(b.file));\n\n const averageFileRisk = average(\n workspaceFileScores.map((fileScore) => fileScore.normalizedScore),\n );\n const peakFileRisk = workspaceFileScores.reduce(\n (max, fileScore) => Math.max(max, fileScore.normalizedScore),\n 0,\n );\n const incomingPressure =\n maxIncomingEdges <= 0 ? 0 : toUnitInterval(workspace.incomingEdgeCount / maxIncomingEdges);\n const outgoingPressure =\n maxOutgoingEdges <= 0 ? 0 : toUnitInterval(workspace.outgoingEdgeCount / maxOutgoingEdges);\n const structuralPressure = toUnitInterval(incomingPressure * 0.7 + outgoingPressure * 0.3);\n const normalizedScore = toUnitInterval(\n averageFileRisk * 0.5 + peakFileRisk * 0.3 + structuralPressure * 0.2,\n );\n\n return {\n ...workspace,\n score: round4(normalizedScore * 100),\n normalizedScore: round4(normalizedScore),\n averageFileRisk: round4(averageFileRisk),\n peakFileRisk: round4(peakFileRisk),\n topFiles: workspaceFileScores.slice(0, 5).map((fileScore) => ({\n file: fileScore.file,\n score: fileScore.score,\n factors: fileScore.factors,\n })),\n };\n })\n .sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));\n};\n\nexport const computeRiskSummary = (\n structural: GraphAnalysisSummary,\n evolution: RepositoryEvolutionSummary,\n external: ExternalAnalysisSummary,\n config: RiskEngineConfig,\n traceCollector?: TraceCollector,\n): RepositoryRiskSummary => {\n const collector = traceCollector;\n const dependencyComputation = computeDependencyScores(external, config);\n const externalMetadataConfidence = computeExternalMetadataConfidence(external);\n const evolutionByFile = mapEvolutionByFile(evolution);\n const evolutionHistoryConfidence = computeEvolutionHistoryConfidence(\n structural,\n evolution,\n evolutionByFile,\n );\n const evolutionScales = computeEvolutionScales(evolutionByFile, config);\n\n const cycleFileSet = new Set(\n structural.cycles.flatMap((cycle) => cycle.nodes.map((node) => normalizePath(node))),\n );\n\n const fanInScale = buildQuantileScale(\n structural.files.map((file) => logScale(file.fanIn)),\n config.quantileClamp.lower,\n config.quantileClamp.upper,\n );\n const fanOutScale = buildQuantileScale(\n structural.files.map((file) => logScale(file.fanOut)),\n config.quantileClamp.lower,\n config.quantileClamp.upper,\n );\n const depthScale = buildQuantileScale(\n structural.files.map((file) => file.depth),\n config.quantileClamp.lower,\n config.quantileClamp.upper,\n );\n\n const dimensionWeights = normalizeWeights(config.dimensionWeights, {\n structural: true,\n evolution: evolution.available,\n external: external.available,\n });\n\n const fileRiskContexts = structural.files\n .map<FileRiskContext>((file) => {\n const filePath = normalizePath(file.id);\n const inCycle = cycleFileSet.has(filePath) ? 1 : 0;\n\n const fanInRisk = normalizeWithScale(logScale(file.fanIn), fanInScale);\n const fanOutRisk = normalizeWithScale(logScale(file.fanOut), fanOutScale);\n const depthRisk = normalizeWithScale(file.depth, depthScale);\n\n const structuralWeights = config.structuralFactorWeights;\n const structuralFactorRaw = toUnitInterval(\n fanInRisk * structuralWeights.fanIn +\n fanOutRisk * structuralWeights.fanOut +\n depthRisk * structuralWeights.depth +\n inCycle * structuralWeights.cycleParticipation,\n );\n\n const structuralCentralityRaw = toUnitInterval((fanInRisk + fanOutRisk) / 2);\n\n let evolutionFactor = 0;\n let frequencyRisk = 0;\n let churnRisk = 0;\n let volatilityRisk = 0;\n let ownershipConcentrationRisk = 0;\n let busFactorRisk = 0;\n const evolutionMetrics = evolutionByFile.get(filePath);\n if (evolution.available && evolutionMetrics !== undefined) {\n frequencyRisk = normalizeWithScale(\n logScale(evolutionMetrics.commitCount),\n evolutionScales.commitCount,\n );\n churnRisk = normalizeWithScale(\n logScale(evolutionMetrics.churnTotal),\n evolutionScales.churnTotal,\n );\n volatilityRisk = toUnitInterval(evolutionMetrics.recentVolatility);\n ownershipConcentrationRisk = toUnitInterval(evolutionMetrics.topAuthorShareByCommits);\n busFactorRisk = toUnitInterval(\n 1 - normalizeWithScale(evolutionMetrics.busFactorByCommits, evolutionScales.busFactor),\n );\n\n const evolutionWeights = config.evolutionFactorWeights;\n evolutionFactor = toUnitInterval(\n frequencyRisk * evolutionWeights.frequency +\n churnRisk * evolutionWeights.churn +\n volatilityRisk * evolutionWeights.recentVolatility +\n ownershipConcentrationRisk * evolutionWeights.ownershipConcentration +\n busFactorRisk * evolutionWeights.busFactorRisk,\n );\n }\n\n const structuralAttenuation = computeAggregatorAttenuation({\n fanIn: file.fanIn,\n fanOut: file.fanOut,\n inCycle,\n evolutionMetrics,\n config: config.aggregatorAttenuation,\n });\n const structuralFactor = toUnitInterval(structuralFactorRaw * structuralAttenuation);\n const structuralCentrality = toUnitInterval(structuralCentralityRaw * structuralAttenuation);\n\n const dependencyAffinity = toUnitInterval(structuralCentrality * 0.6 + evolutionFactor * 0.4);\n const externalFactor = external.available\n ? toUnitInterval(dependencyComputation.repositoryExternalPressure * dependencyAffinity)\n : 0;\n\n const structuralBase = structuralFactor * dimensionWeights.structural;\n const evolutionBase = evolutionFactor * dimensionWeights.evolution;\n const externalBase = externalFactor * dimensionWeights.external;\n const baseline = structuralBase + evolutionBase + externalBase;\n\n const interactionStructuralEvolution =\n structuralFactor * evolutionFactor * config.interactionWeights.structuralEvolution;\n const interactionCentralInstability =\n structuralCentrality * evolutionFactor * config.interactionWeights.centralInstability;\n const interactionDependencyAmplification =\n externalFactor *\n Math.max(structuralFactor, evolutionFactor) *\n config.interactionWeights.dependencyAmplification;\n\n const interactions = [\n interactionStructuralEvolution,\n interactionCentralInstability,\n interactionDependencyAmplification,\n ];\n\n const normalizedScore = saturatingComposite(baseline, interactions);\n\n return {\n file: filePath,\n score: round4(normalizedScore * 100),\n normalizedScore: round4(normalizedScore),\n factors: {\n structural: round4(structuralFactor),\n evolution: round4(evolutionFactor),\n external: round4(externalFactor),\n },\n structuralCentrality: round4(structuralCentrality),\n traceTerms: {\n structuralBase: round4(structuralBase),\n evolutionBase: round4(evolutionBase),\n externalBase: round4(externalBase),\n interactionStructuralEvolution: round4(interactionStructuralEvolution),\n interactionCentralInstability: round4(interactionCentralInstability),\n interactionDependencyAmplification: round4(interactionDependencyAmplification),\n },\n rawMetrics: {\n fanIn: file.fanIn,\n fanOut: file.fanOut,\n depth: file.depth,\n cycleParticipation: inCycle,\n commitCount: evolutionMetrics?.commitCount ?? null,\n churnTotal: evolutionMetrics?.churnTotal ?? null,\n recentVolatility: evolutionMetrics?.recentVolatility ?? null,\n topAuthorShareByCommits: evolutionMetrics?.topAuthorShareByCommits ?? null,\n busFactorByCommits: evolutionMetrics?.busFactorByCommits ?? null,\n dependencyAffinity: round4(dependencyAffinity),\n repositoryExternalPressure: round4(dependencyComputation.repositoryExternalPressure),\n structuralAttenuation: round4(structuralAttenuation),\n },\n normalizedMetrics: {\n fanInRisk: round4(fanInRisk),\n fanOutRisk: round4(fanOutRisk),\n depthRisk: round4(depthRisk),\n frequencyRisk: round4(frequencyRisk),\n churnRisk: round4(churnRisk),\n volatilityRisk: round4(volatilityRisk),\n ownershipConcentrationRisk: round4(ownershipConcentrationRisk),\n busFactorRisk: round4(busFactorRisk),\n },\n };\n })\n .sort((a, b) => b.score - a.score || a.file.localeCompare(b.file));\n\n const fileScores: FileRiskScore[] = fileRiskContexts.map((context) => ({\n file: context.file,\n score: context.score,\n normalizedScore: context.normalizedScore,\n factors: context.factors,\n }));\n\n if (collector !== undefined) {\n for (const context of fileRiskContexts) {\n const evidence: EvidenceRef[] = [\n { kind: \"file_metric\", target: context.file, metric: \"fanIn\" },\n { kind: \"file_metric\", target: context.file, metric: \"fanOut\" },\n { kind: \"file_metric\", target: context.file, metric: \"depth\" },\n ];\n\n if (context.rawMetrics.cycleParticipation > 0) {\n evidence.push({\n kind: \"graph_cycle\",\n cycleId: `file:${context.file}`,\n files: [context.file],\n });\n }\n\n const fileFactors = buildFactorTraces(context.score, [\n {\n factorId: \"file.structural\",\n family: \"structural\",\n strength: context.traceTerms.structuralBase,\n rawMetrics: {\n fanIn: context.rawMetrics.fanIn,\n fanOut: context.rawMetrics.fanOut,\n depth: context.rawMetrics.depth,\n cycleParticipation: context.rawMetrics.cycleParticipation,\n structuralAttenuation: context.rawMetrics.structuralAttenuation,\n },\n normalizedMetrics: {\n fanInRisk: context.normalizedMetrics.fanInRisk,\n fanOutRisk: context.normalizedMetrics.fanOutRisk,\n depthRisk: context.normalizedMetrics.depthRisk,\n structuralFactor: context.factors.structural,\n },\n weight: dimensionWeights.structural,\n amplification: null,\n evidence,\n confidence: 1,\n },\n {\n factorId: \"file.evolution\",\n family: \"evolution\",\n strength: context.traceTerms.evolutionBase,\n rawMetrics: {\n commitCount: context.rawMetrics.commitCount,\n churnTotal: context.rawMetrics.churnTotal,\n recentVolatility: context.rawMetrics.recentVolatility,\n topAuthorShareByCommits: context.rawMetrics.topAuthorShareByCommits,\n busFactorByCommits: context.rawMetrics.busFactorByCommits,\n },\n normalizedMetrics: {\n frequencyRisk: context.normalizedMetrics.frequencyRisk,\n churnRisk: context.normalizedMetrics.churnRisk,\n volatilityRisk: context.normalizedMetrics.volatilityRisk,\n ownershipConcentrationRisk: context.normalizedMetrics.ownershipConcentrationRisk,\n busFactorRisk: context.normalizedMetrics.busFactorRisk,\n evolutionFactor: context.factors.evolution,\n },\n weight: dimensionWeights.evolution,\n amplification: null,\n evidence: [{ kind: \"file_metric\", target: context.file, metric: \"commitCount\" }],\n confidence: evolution.available\n ? evolutionHistoryConfidence * (context.rawMetrics.commitCount === null ? 0.5 : 1)\n : 0,\n },\n {\n factorId: \"file.external\",\n family: \"external\",\n strength: context.traceTerms.externalBase,\n rawMetrics: {\n repositoryExternalPressure: context.rawMetrics.repositoryExternalPressure,\n dependencyAffinity: context.rawMetrics.dependencyAffinity,\n },\n normalizedMetrics: {\n externalFactor: context.factors.external,\n },\n weight: dimensionWeights.external,\n amplification: null,\n evidence: [{ kind: \"repository_metric\", metric: \"repositoryExternalPressure\" }],\n confidence: external.available ? 0.7 * externalMetadataConfidence : 0,\n },\n {\n factorId: \"file.composite.interactions\",\n family: \"composite\",\n strength:\n context.traceTerms.interactionStructuralEvolution +\n context.traceTerms.interactionCentralInstability +\n context.traceTerms.interactionDependencyAmplification,\n rawMetrics: {\n structuralEvolutionInteraction: context.traceTerms.interactionStructuralEvolution,\n centralInstabilityInteraction: context.traceTerms.interactionCentralInstability,\n dependencyAmplificationInteraction:\n context.traceTerms.interactionDependencyAmplification,\n },\n normalizedMetrics: {},\n weight: null,\n amplification:\n config.interactionWeights.structuralEvolution +\n config.interactionWeights.centralInstability +\n config.interactionWeights.dependencyAmplification,\n evidence: [{ kind: \"repository_metric\", metric: \"interactionWeights\" }],\n confidence: 0.9,\n },\n ]);\n\n collector.record(\n buildTargetTrace(\"file\", context.file, context.score, context.normalizedScore, fileFactors),\n );\n }\n }\n\n const fileScoresByFile = new Map(fileScores.map((fileScore) => [fileScore.file, fileScore]));\n\n const hotspotsCount = Math.min(\n config.hotspotMaxFiles,\n Math.max(config.hotspotMinFiles, Math.ceil(fileScores.length * config.hotspotTopPercent)),\n );\n\n const hotspots = fileScores.slice(0, hotspotsCount).map((fileScore) => ({\n file: fileScore.file,\n score: fileScore.score,\n factors: fileScore.factors,\n }));\n\n const moduleFiles = new Map<string, number[]>();\n for (const fileScore of fileScores) {\n const moduleName = inferModuleName(fileScore.file, config);\n const values = moduleFiles.get(moduleName) ?? [];\n values.push(fileScore.normalizedScore);\n moduleFiles.set(moduleName, values);\n }\n\n const moduleScores: ModuleRiskScore[] = [...moduleFiles.entries()]\n .map(([module, values]) => {\n const averageScore = average(values);\n const peakScore = values.reduce((max, value) => Math.max(max, value), 0);\n const normalizedScore = toUnitInterval(averageScore * 0.65 + peakScore * 0.35);\n\n return {\n module,\n score: round4(normalizedScore * 100),\n normalizedScore: round4(normalizedScore),\n fileCount: values.length,\n };\n })\n .sort((a, b) => b.score - a.score || a.module.localeCompare(b.module));\n\n if (collector !== undefined) {\n for (const [module, values] of moduleFiles.entries()) {\n const averageScore = average(values);\n const peakScore = values.reduce((max, value) => Math.max(max, value), 0);\n const normalizedScore = toUnitInterval(averageScore * 0.65 + peakScore * 0.35);\n const totalScore = round4(normalizedScore * 100);\n const factors = buildFactorTraces(totalScore, [\n {\n factorId: \"module.average_file_risk\",\n family: \"composite\",\n strength: averageScore * 0.65,\n rawMetrics: { averageFileRisk: round4(averageScore), fileCount: values.length },\n normalizedMetrics: { normalizedModuleRisk: round4(normalizedScore) },\n weight: 0.65,\n amplification: null,\n evidence: [{ kind: \"repository_metric\", metric: \"moduleAggregation.average\" }],\n confidence: 1,\n },\n {\n factorId: \"module.peak_file_risk\",\n family: \"composite\",\n strength: peakScore * 0.35,\n rawMetrics: { peakFileRisk: round4(peakScore), fileCount: values.length },\n normalizedMetrics: { normalizedModuleRisk: round4(normalizedScore) },\n weight: 0.35,\n amplification: null,\n evidence: [{ kind: \"repository_metric\", metric: \"moduleAggregation.peak\" }],\n confidence: 1,\n },\n ]);\n\n collector.record(buildTargetTrace(\"module\", module, totalScore, normalizedScore, factors));\n }\n }\n\n const workspaceScores = buildWorkspaceRiskScores(structural, fileScoresByFile);\n\n const fragileClusters = buildFragileClusters(structural, evolution, fileScoresByFile, config);\n\n const externalPressures = fileScores.map((fileScore) => fileScore.factors.external);\n const pressureThreshold = Math.max(\n config.amplificationZone.pressureFloor,\n percentile(externalPressures, config.amplificationZone.percentileThreshold),\n );\n\n const dependencyAmplificationZones = fileScores\n .map((fileScore) => {\n const intensity = toUnitInterval(\n fileScore.factors.external *\n Math.max(fileScore.factors.structural, fileScore.factors.evolution),\n );\n const normalizedZoneScore = toUnitInterval(intensity * 0.7 + fileScore.normalizedScore * 0.3);\n\n return {\n file: fileScore.file,\n score: round4(normalizedZoneScore * 100),\n externalPressure: fileScore.factors.external,\n };\n })\n .filter((zone) => external.available && zone.externalPressure >= pressureThreshold)\n .sort((a, b) => b.score - a.score || a.file.localeCompare(b.file))\n .slice(0, config.amplificationZone.maxZones)\n .map((zone) => ({\n ...zone,\n externalPressure: round4(zone.externalPressure),\n }));\n\n if (collector !== undefined && external.available) {\n const dependencyByName = new Map(\n external.dependencies.map((dependency) => [dependency.name, dependency]),\n );\n for (const dependencyScore of dependencyComputation.dependencyScores) {\n const dependency = dependencyByName.get(dependencyScore.dependency);\n const context = dependencyComputation.dependencyContexts.get(dependencyScore.dependency);\n if (dependency === undefined || context === undefined) {\n continue;\n }\n\n const hasMetadata =\n context.rawMetrics.daysSinceLastRelease !== null &&\n context.rawMetrics.maintainerCount !== null;\n const factors = buildFactorTraces(dependencyScore.score, [\n {\n factorId: \"dependency.signals\",\n family: \"external\",\n strength: context.signalScore * config.dependencyFactorWeights.signals,\n rawMetrics: {\n ownSignals: dependency.ownRiskSignals.length,\n inheritedSignals: dependency.inheritedRiskSignals.length,\n },\n normalizedMetrics: { signalScore: context.signalScore },\n weight: config.dependencyFactorWeights.signals,\n amplification: config.dependencySignals.inheritedSignalMultiplier,\n evidence: [{ kind: \"dependency_metric\", target: dependency.name, metric: \"riskSignals\" }],\n confidence: 0.95 * externalMetadataConfidence,\n },\n {\n factorId: \"dependency.staleness\",\n family: \"external\",\n strength: context.stalenessRisk * config.dependencyFactorWeights.staleness,\n rawMetrics: { daysSinceLastRelease: context.rawMetrics.daysSinceLastRelease },\n normalizedMetrics: { stalenessRisk: context.stalenessRisk },\n weight: config.dependencyFactorWeights.staleness,\n amplification: null,\n evidence: [\n { kind: \"dependency_metric\", target: dependency.name, metric: \"daysSinceLastRelease\" },\n ],\n confidence: (hasMetadata ? 0.9 : 0.5) * externalMetadataConfidence,\n },\n {\n factorId: \"dependency.maintainer_concentration\",\n family: \"external\",\n strength:\n context.maintainerConcentrationRisk *\n config.dependencyFactorWeights.maintainerConcentration,\n rawMetrics: { maintainerCount: context.rawMetrics.maintainerCount },\n normalizedMetrics: {\n maintainerConcentrationRisk: context.maintainerConcentrationRisk,\n },\n weight: config.dependencyFactorWeights.maintainerConcentration,\n amplification: null,\n evidence: [\n { kind: \"dependency_metric\", target: dependency.name, metric: \"maintainerCount\" },\n ],\n confidence: (hasMetadata ? 0.9 : 0.5) * externalMetadataConfidence,\n },\n {\n factorId: \"dependency.topology\",\n family: \"external\",\n strength:\n context.transitiveBurdenRisk * config.dependencyFactorWeights.transitiveBurden +\n context.centralityRisk * config.dependencyFactorWeights.centrality +\n context.chainDepthRisk * config.dependencyFactorWeights.chainDepth,\n rawMetrics: {\n transitiveCount: context.rawMetrics.transitiveCount,\n dependents: context.rawMetrics.dependents,\n dependencyDepth: context.rawMetrics.dependencyDepth,\n },\n normalizedMetrics: {\n transitiveBurdenRisk: context.transitiveBurdenRisk,\n centralityRisk: context.centralityRisk,\n chainDepthRisk: context.chainDepthRisk,\n },\n weight:\n config.dependencyFactorWeights.transitiveBurden +\n config.dependencyFactorWeights.centrality +\n config.dependencyFactorWeights.chainDepth,\n amplification: null,\n evidence: [\n { kind: \"dependency_metric\", target: dependency.name, metric: \"dependencyDepth\" },\n ],\n confidence: 1 * externalMetadataConfidence,\n },\n {\n factorId: \"dependency.bus_factor\",\n family: \"external\",\n strength: context.busFactorRisk * config.dependencyFactorWeights.busFactorRisk,\n rawMetrics: { busFactor: context.rawMetrics.busFactor },\n normalizedMetrics: { busFactorRisk: context.busFactorRisk },\n weight: config.dependencyFactorWeights.busFactorRisk,\n amplification: null,\n evidence: [{ kind: \"dependency_metric\", target: dependency.name, metric: \"busFactor\" }],\n confidence:\n (context.rawMetrics.busFactor === null ? 0.5 : 0.85) * externalMetadataConfidence,\n },\n {\n factorId: \"dependency.popularity_dampening\",\n family: \"composite\",\n strength: 1 - context.popularityDampener,\n rawMetrics: { weeklyDownloads: context.rawMetrics.weeklyDownloads },\n normalizedMetrics: { popularityDampener: context.popularityDampener },\n weight: config.dependencySignals.popularityMaxDampening,\n amplification: null,\n evidence: [\n { kind: \"dependency_metric\", target: dependency.name, metric: \"weeklyDownloads\" },\n ],\n confidence:\n (context.rawMetrics.weeklyDownloads === null ? 0.4 : 0.9) * externalMetadataConfidence,\n },\n ]);\n\n collector.record(\n buildTargetTrace(\n \"dependency\",\n dependencyScore.dependency,\n dependencyScore.score,\n dependencyScore.normalizedScore,\n factors,\n ),\n );\n }\n }\n\n const structuralDimension = average(fileScores.map((fileScore) => fileScore.factors.structural));\n const evolutionDimension = average(fileScores.map((fileScore) => fileScore.factors.evolution));\n const externalDimension = dependencyComputation.repositoryExternalPressure;\n\n const topCentralSlice = Math.max(1, Math.ceil(fileRiskContexts.length * 0.1));\n const criticalInstability = average(\n [...fileRiskContexts]\n .sort(\n (a, b) =>\n b.structuralCentrality * b.factors.evolution -\n a.structuralCentrality * a.factors.evolution || a.file.localeCompare(b.file),\n )\n .slice(0, topCentralSlice)\n .map((context) => context.structuralCentrality * context.factors.evolution),\n );\n\n const dependencyAmplification = average(\n dependencyAmplificationZones.map((zone) =>\n toUnitInterval((zone.externalPressure * zone.score) / 100),\n ),\n );\n\n const repositoryBaseline =\n structuralDimension * dimensionWeights.structural +\n evolutionDimension * dimensionWeights.evolution +\n externalDimension * dimensionWeights.external;\n\n const repositoryNormalizedScore = saturatingComposite(repositoryBaseline, [\n structuralDimension * evolutionDimension * config.interactionWeights.structuralEvolution,\n criticalInstability * config.interactionWeights.centralInstability,\n dependencyAmplification * config.interactionWeights.dependencyAmplification,\n ]);\n\n const riskScore = round4(repositoryNormalizedScore * 100);\n\n if (collector !== undefined) {\n const repositoryFactors = buildFactorTraces(riskScore, [\n {\n factorId: \"repository.structural\",\n family: \"structural\",\n strength: structuralDimension * dimensionWeights.structural,\n rawMetrics: { structuralDimension: round4(structuralDimension) },\n normalizedMetrics: { dimensionWeight: round4(dimensionWeights.structural) },\n weight: dimensionWeights.structural,\n amplification: null,\n evidence: [{ kind: \"repository_metric\", metric: \"structuralDimension\" }],\n confidence: 1,\n },\n {\n factorId: \"repository.evolution\",\n family: \"evolution\",\n strength: evolutionDimension * dimensionWeights.evolution,\n rawMetrics: { evolutionDimension: round4(evolutionDimension) },\n normalizedMetrics: { dimensionWeight: round4(dimensionWeights.evolution) },\n weight: dimensionWeights.evolution,\n amplification: null,\n evidence: [{ kind: \"repository_metric\", metric: \"evolutionDimension\" }],\n confidence: evolution.available ? evolutionHistoryConfidence : 0,\n },\n {\n factorId: \"repository.external\",\n family: \"external\",\n strength: externalDimension * dimensionWeights.external,\n rawMetrics: { externalDimension: round4(externalDimension) },\n normalizedMetrics: { dimensionWeight: round4(dimensionWeights.external) },\n weight: dimensionWeights.external,\n amplification: null,\n evidence: [{ kind: \"repository_metric\", metric: \"externalDimension\" }],\n confidence: external.available ? 0.8 * externalMetadataConfidence : 0,\n },\n {\n factorId: \"repository.composite.interactions\",\n family: \"composite\",\n strength:\n structuralDimension * evolutionDimension * config.interactionWeights.structuralEvolution +\n criticalInstability * config.interactionWeights.centralInstability +\n dependencyAmplification * config.interactionWeights.dependencyAmplification,\n rawMetrics: {\n structuralEvolution: round4(\n structuralDimension *\n evolutionDimension *\n config.interactionWeights.structuralEvolution,\n ),\n centralInstability: round4(\n criticalInstability * config.interactionWeights.centralInstability,\n ),\n dependencyAmplification: round4(\n dependencyAmplification * config.interactionWeights.dependencyAmplification,\n ),\n },\n normalizedMetrics: {\n criticalInstability: round4(criticalInstability),\n dependencyAmplification: round4(dependencyAmplification),\n },\n weight: null,\n amplification:\n config.interactionWeights.structuralEvolution +\n config.interactionWeights.centralInstability +\n config.interactionWeights.dependencyAmplification,\n evidence: [{ kind: \"repository_metric\", metric: \"interactionTerms\" }],\n confidence: 0.9,\n },\n ]);\n\n collector.record(\n buildTargetTrace(\n \"repository\",\n structural.targetPath,\n riskScore,\n repositoryNormalizedScore,\n repositoryFactors,\n ),\n );\n }\n\n return {\n riskScore,\n normalizedScore: round4(repositoryNormalizedScore),\n hotspots,\n fragileClusters,\n dependencyAmplificationZones,\n fileScores,\n moduleScores,\n workspaceScores,\n dependencyScores: dependencyComputation.dependencyScores,\n };\n};\n","export const toUnitInterval = (value: number): number =>\n Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : 0;\n\nexport const round4 = (value: number): number => Number(value.toFixed(4));\n\nexport const average = (values: readonly number[]): number => {\n if (values.length === 0) {\n return 0;\n }\n\n const total = values.reduce((sum, current) => sum + current, 0);\n return total / values.length;\n};\n\nexport const percentile = (values: readonly number[], p: number): number => {\n if (values.length === 0) {\n return 0;\n }\n\n if (values.length === 1) {\n return values[0] ?? 0;\n }\n\n const sorted = [...values].sort((a, b) => a - b);\n const position = toUnitInterval(p) * (sorted.length - 1);\n const lowerIndex = Math.floor(position);\n const upperIndex = Math.ceil(position);\n\n const lower = sorted[lowerIndex] ?? 0;\n const upper = sorted[upperIndex] ?? lower;\n\n if (lowerIndex === upperIndex) {\n return lower;\n }\n\n const ratio = position - lowerIndex;\n return lower + (upper - lower) * ratio;\n};\n\nexport const saturatingComposite = (\n baseline: number,\n amplifications: readonly number[],\n): number => {\n let value = toUnitInterval(baseline);\n\n for (const amplification of amplifications) {\n const boundedAmplification = toUnitInterval(amplification);\n value += (1 - value) * boundedAmplification;\n }\n\n return toUnitInterval(value);\n};\n\nexport const halfLifeRisk = (value: number, halfLife: number): number => {\n if (value <= 0 || halfLife <= 0) {\n return 0;\n }\n\n return toUnitInterval(value / (value + halfLife));\n};\n\nexport const normalizeWeights = <T extends string>(\n weights: Readonly<Record<T, number>>,\n enabled: Readonly<Record<T, boolean>>,\n): Readonly<Record<T, number>> => {\n let total = 0;\n const result: Record<T, number> = { ...weights };\n\n for (const key of Object.keys(result) as T[]) {\n const enabledValue = enabled[key];\n if (!enabledValue) {\n result[key] = 0;\n continue;\n }\n\n const value = Math.max(0, result[key]);\n result[key] = value;\n total += value;\n }\n\n if (total === 0) {\n const activeKeys = (Object.keys(result) as T[]).filter((key) => enabled[key]);\n if (activeKeys.length === 0) {\n return result;\n }\n\n const uniform = 1 / activeKeys.length;\n for (const key of activeKeys) {\n result[key] = uniform;\n }\n\n return result;\n }\n\n for (const key of Object.keys(result) as T[]) {\n if (enabled[key]) {\n result[key] = result[key] / total;\n }\n }\n\n return result;\n};\n","import { toUnitInterval, percentile } from \"./math.js\";\n\nexport type QuantileScale = {\n lower: number;\n upper: number;\n};\n\nexport const logScale = (value: number): number => Math.log1p(Math.max(0, value));\n\nexport const buildQuantileScale = (\n values: readonly number[],\n lowerPercentile: number,\n upperPercentile: number,\n): QuantileScale => {\n if (values.length === 0) {\n return { lower: 0, upper: 0 };\n }\n\n return {\n lower: percentile(values, lowerPercentile),\n upper: percentile(values, upperPercentile),\n };\n};\n\nexport const normalizeWithScale = (value: number, scale: QuantileScale): number => {\n if (scale.upper <= scale.lower) {\n return value > 0 ? 1 : 0;\n }\n\n return toUnitInterval((value - scale.lower) / (scale.upper - scale.lower));\n};\n","import type { RiskTrace, TargetTrace } from \"@codesentinel/core\";\n\nexport interface TraceCollector {\n record(target: TargetTrace): void;\n build(): RiskTrace | undefined;\n}\n\nclass NoopTraceCollector implements TraceCollector {\n record(_target: TargetTrace): void {}\n\n build(): undefined {\n return undefined;\n }\n}\n\nclass RecordingTraceCollector implements TraceCollector {\n private readonly targets: TargetTrace[] = [];\n\n record(target: TargetTrace): void {\n this.targets.push(target);\n }\n\n build(): RiskTrace {\n const orderedTargets = [...this.targets].sort((a, b) => {\n if (a.targetType !== b.targetType) {\n return a.targetType.localeCompare(b.targetType);\n }\n\n if (b.totalScore !== a.totalScore) {\n return b.totalScore - a.totalScore;\n }\n\n return a.targetId.localeCompare(b.targetId);\n });\n\n return {\n schemaVersion: \"1\",\n contributionTolerance: 0.0001,\n targets: orderedTargets,\n };\n }\n}\n\nconst noopCollectorSingleton = new NoopTraceCollector();\n\nexport const createTraceCollector = (enabled: boolean): TraceCollector =>\n enabled ? new RecordingTraceCollector() : noopCollectorSingleton;\n","import type {\n ExternalAnalysisSummary,\n GraphAnalysisSummary,\n RepositoryRiskEvaluation,\n RepositoryEvolutionSummary,\n RepositoryRiskSummary,\n} from \"@codesentinel/core\";\nimport { DEFAULT_RISK_ENGINE_CONFIG, type RiskEngineConfig } from \"../config.js\";\nimport { computeRiskSummary } from \"../domain/risk-model.js\";\nimport { createTraceCollector } from \"../domain/trace-collector.js\";\n\ntype DeepPartial<T> = {\n [K in keyof T]?: T[K] extends readonly unknown[]\n ? T[K]\n : T[K] extends object\n ? DeepPartial<T[K]>\n : T[K];\n};\n\nexport type ComputeRepositoryRiskSummaryInput = {\n structural: GraphAnalysisSummary;\n evolution: RepositoryEvolutionSummary;\n external: ExternalAnalysisSummary;\n config?: DeepPartial<RiskEngineConfig>;\n};\n\nexport type EvaluateRepositoryRiskOptions = {\n explain?: boolean;\n};\n\nconst mergeConfig = (overrides: DeepPartial<RiskEngineConfig> | undefined): RiskEngineConfig => {\n if (overrides === undefined) {\n return DEFAULT_RISK_ENGINE_CONFIG;\n }\n\n return {\n ...DEFAULT_RISK_ENGINE_CONFIG,\n ...overrides,\n dimensionWeights: {\n ...DEFAULT_RISK_ENGINE_CONFIG.dimensionWeights,\n ...overrides.dimensionWeights,\n },\n interactionWeights: {\n ...DEFAULT_RISK_ENGINE_CONFIG.interactionWeights,\n ...overrides.interactionWeights,\n },\n structuralFactorWeights: {\n ...DEFAULT_RISK_ENGINE_CONFIG.structuralFactorWeights,\n ...overrides.structuralFactorWeights,\n },\n evolutionFactorWeights: {\n ...DEFAULT_RISK_ENGINE_CONFIG.evolutionFactorWeights,\n ...overrides.evolutionFactorWeights,\n },\n dependencyFactorWeights: {\n ...DEFAULT_RISK_ENGINE_CONFIG.dependencyFactorWeights,\n ...overrides.dependencyFactorWeights,\n },\n quantileClamp: {\n ...DEFAULT_RISK_ENGINE_CONFIG.quantileClamp,\n ...overrides.quantileClamp,\n },\n couplingCluster: {\n ...DEFAULT_RISK_ENGINE_CONFIG.couplingCluster,\n ...overrides.couplingCluster,\n },\n amplificationZone: {\n ...DEFAULT_RISK_ENGINE_CONFIG.amplificationZone,\n ...overrides.amplificationZone,\n },\n module: {\n ...DEFAULT_RISK_ENGINE_CONFIG.module,\n ...overrides.module,\n },\n dependencySignals: {\n ...DEFAULT_RISK_ENGINE_CONFIG.dependencySignals,\n ...overrides.dependencySignals,\n },\n externalDimension: {\n ...DEFAULT_RISK_ENGINE_CONFIG.externalDimension,\n ...overrides.externalDimension,\n },\n aggregatorAttenuation: {\n ...DEFAULT_RISK_ENGINE_CONFIG.aggregatorAttenuation,\n ...overrides.aggregatorAttenuation,\n },\n };\n};\n\nexport const computeRepositoryRiskSummary = (\n input: ComputeRepositoryRiskSummaryInput,\n): RepositoryRiskSummary => {\n return evaluateRepositoryRisk(input, { explain: false }).summary;\n};\n\nexport const evaluateRepositoryRisk = (\n input: ComputeRepositoryRiskSummaryInput,\n options: EvaluateRepositoryRiskOptions = {},\n): RepositoryRiskEvaluation => {\n const config = mergeConfig(input.config);\n const collector = createTraceCollector(options.explain === true);\n const summary = computeRiskSummary(\n input.structural,\n input.evolution,\n input.external,\n config,\n collector,\n );\n\n const trace = collector.build();\n if (options.explain !== true) {\n return { summary };\n }\n\n if (trace === undefined) {\n return { summary };\n }\n\n return {\n summary,\n trace,\n };\n};\n","import { readFile, writeFile } from \"node:fs/promises\";\nimport {\n GovernanceConfigurationError,\n evaluateGates,\n renderCheckMarkdown,\n renderCheckText,\n type GateConfig,\n type GateEvaluationResult,\n} from \"@codesentinel/governance\";\nimport { compareSnapshots, parseSnapshot, type CodeSentinelSnapshot } from \"@codesentinel/reporter\";\nimport { buildAnalysisSnapshot } from \"./build-analysis-snapshot.js\";\nimport { createSilentLogger, type Logger } from \"./logger.js\";\nimport type { AuthorIdentityCliMode, ScoringProfileCliMode } from \"./run-analyze-command.js\";\n\nexport type CheckOutputFormat = \"json\" | \"text\" | \"md\";\n\nexport type RunCheckCommandOptions = {\n baselinePath?: string;\n includeTrace: boolean;\n recentWindowDays?: number;\n scoringProfile?: ScoringProfileCliMode;\n gateConfig: GateConfig;\n outputFormat: CheckOutputFormat;\n outputPath?: string;\n};\n\nexport type CheckCommandResult = {\n current: CodeSentinelSnapshot;\n baseline?: CodeSentinelSnapshot;\n diff?: ReturnType<typeof compareSnapshots>;\n gateResult: GateEvaluationResult;\n rendered: string;\n};\n\nconst formatCheckResult = (result: CheckCommandResult, format: CheckOutputFormat): string => {\n if (format === \"json\") {\n return JSON.stringify(\n {\n current: result.current,\n ...(result.baseline === undefined ? {} : { baseline: result.baseline }),\n ...(result.diff === undefined ? {} : { diff: result.diff }),\n violations: result.gateResult.violations,\n evaluatedGates: result.gateResult.evaluatedGates,\n highestSeverity: result.gateResult.highestSeverity,\n exitCode: result.gateResult.exitCode,\n },\n null,\n 2,\n );\n }\n\n if (format === \"md\") {\n return renderCheckMarkdown(result.current, result.gateResult);\n }\n\n return renderCheckText(result.current, result.gateResult);\n};\n\nexport const runCheckCommand = async (\n inputPath: string | undefined,\n authorIdentityMode: AuthorIdentityCliMode,\n options: RunCheckCommandOptions,\n logger: Logger = createSilentLogger(),\n): Promise<CheckCommandResult> => {\n logger.info(\"building current snapshot for check\");\n const current = await buildAnalysisSnapshot(\n inputPath,\n authorIdentityMode,\n {\n includeTrace: options.includeTrace,\n ...(options.scoringProfile === undefined ? {} : { scoringProfile: options.scoringProfile }),\n ...(options.recentWindowDays === undefined\n ? {}\n : { recentWindowDays: options.recentWindowDays }),\n },\n logger,\n );\n\n let baseline: CodeSentinelSnapshot | undefined;\n let diff: ReturnType<typeof compareSnapshots> | undefined;\n\n if (options.baselinePath !== undefined) {\n logger.info(`loading baseline snapshot: ${options.baselinePath}`);\n const baselineRaw = await readFile(options.baselinePath, \"utf8\");\n try {\n baseline = parseSnapshot(baselineRaw);\n } catch (error) {\n const message = error instanceof Error ? error.message : \"invalid baseline snapshot\";\n throw new GovernanceConfigurationError(`invalid baseline snapshot: ${message}`);\n }\n diff = compareSnapshots(current, baseline);\n }\n\n const gateResult = evaluateGates({\n current,\n ...(baseline === undefined ? {} : { baseline }),\n ...(diff === undefined ? {} : { diff }),\n gateConfig: options.gateConfig,\n });\n\n const rendered = formatCheckResult(\n {\n current,\n ...(baseline === undefined ? {} : { baseline }),\n ...(diff === undefined ? {} : { diff }),\n gateResult,\n rendered: \"\",\n },\n options.outputFormat,\n );\n\n if (options.outputPath !== undefined) {\n await writeFile(options.outputPath, rendered, \"utf8\");\n logger.info(`check output written: ${options.outputPath}`);\n }\n\n return {\n current,\n ...(baseline === undefined ? {} : { baseline }),\n ...(diff === undefined ? {} : { diff }),\n gateResult,\n rendered,\n };\n};\n\nexport { GovernanceConfigurationError };\n","import type { AnalyzeSummary } from \"@codesentinel/core\";\nimport { computeRepositoryHealthSummary } from \"@codesentinel/health-engine\";\nimport { evaluateRepositoryRisk } from \"@codesentinel/risk-engine\";\nimport { createSnapshot, type CodeSentinelSnapshot } from \"@codesentinel/reporter\";\nimport {\n collectAnalysisInputs,\n resolveHealthConfigForProfile,\n resolveRiskConfigForProfile,\n type AuthorIdentityCliMode,\n type ScoringProfileCliMode,\n} from \"./run-analyze-command.js\";\nimport type { Logger } from \"./logger.js\";\n\nexport type BuildAnalysisSnapshotOptions = {\n includeTrace: boolean;\n recentWindowDays?: number;\n scoringProfile?: ScoringProfileCliMode;\n};\n\nexport const buildAnalysisSnapshot = async (\n inputPath: string | undefined,\n authorIdentityMode: AuthorIdentityCliMode,\n options: BuildAnalysisSnapshotOptions,\n logger: Logger,\n): Promise<CodeSentinelSnapshot> => {\n const analysisInputs = await collectAnalysisInputs(\n inputPath,\n authorIdentityMode,\n {\n ...(options.recentWindowDays === undefined\n ? {}\n : { recentWindowDays: options.recentWindowDays }),\n },\n logger,\n );\n const riskConfig = resolveRiskConfigForProfile(options.scoringProfile);\n const healthConfig = resolveHealthConfigForProfile(options.scoringProfile);\n const evaluation = evaluateRepositoryRisk(\n {\n structural: analysisInputs.structural,\n evolution: analysisInputs.evolution,\n external: analysisInputs.external,\n ...(riskConfig === undefined ? {} : { config: riskConfig }),\n },\n { explain: options.includeTrace },\n );\n\n const summary: AnalyzeSummary = {\n structural: analysisInputs.structural,\n evolution: analysisInputs.evolution,\n external: analysisInputs.external,\n risk: evaluation.summary,\n health: computeRepositoryHealthSummary({\n structural: analysisInputs.structural,\n evolution: analysisInputs.evolution,\n ...(healthConfig === undefined ? {} : { config: healthConfig }),\n }),\n };\n\n return createSnapshot({\n analysis: summary,\n ...(evaluation.trace === undefined ? {} : { trace: evaluation.trace }),\n analysisConfig: {\n authorIdentityMode,\n includeTrace: options.includeTrace,\n scoringProfile: options.scoringProfile ?? \"default\",\n recentWindowDays: analysisInputs.evolution.available\n ? analysisInputs.evolution.metrics.recentWindowDays\n : (options.recentWindowDays ?? null),\n },\n });\n};\n","import { readFile, writeFile } from \"node:fs/promises\";\nimport {\n BaselineRefResolutionError,\n GovernanceConfigurationError,\n evaluateGates,\n renderCheckMarkdown,\n resolveAutoBaselineRef,\n resolveBaselineSnapshotFromRef,\n type GateConfig,\n type GateEvaluationResult,\n type OwnershipGateInput,\n type OwnershipGateMetrics,\n} from \"@codesentinel/governance\";\nimport { relative, resolve } from \"node:path\";\nimport type { OwnershipAudit } from \"@codesentinel/ownership\";\nimport {\n compareSnapshots,\n createReport,\n formatReport,\n parseSnapshot,\n type CodeSentinelSnapshot,\n} from \"@codesentinel/reporter\";\nimport { buildAnalysisSnapshot } from \"./build-analysis-snapshot.js\";\nimport { buildOwnershipAudit, OwnersConfigurationError } from \"./build-ownership-audit.js\";\nimport { createSilentLogger, type Logger } from \"./logger.js\";\nimport type { AuthorIdentityCliMode, ScoringProfileCliMode } from \"./run-analyze-command.js\";\n\nexport type RunCiCommandOptions = {\n baselinePath?: string;\n baselineRef?: string;\n baselineSha?: string;\n mainBranchCandidates?: readonly string[];\n snapshotPath?: string;\n reportPath?: string;\n jsonOutputPath?: string;\n includeTrace: boolean;\n recentWindowDays?: number;\n scoringProfile?: ScoringProfileCliMode;\n gateConfig: GateConfig;\n ownership?: { ref?: string; windowDays?: number; minCommits?: number };\n};\n\nexport type CiOwnershipSummary = {\n available: boolean;\n codeownersSource: string | null;\n metrics: OwnershipGateMetrics | null;\n warnings: readonly string[];\n};\n\nexport type CiCommandResult = {\n current: CodeSentinelSnapshot;\n baseline?: CodeSentinelSnapshot;\n diff?: ReturnType<typeof compareSnapshots>;\n gateResult: GateEvaluationResult;\n markdownSummary: string;\n ownership?: CiOwnershipSummary;\n machineReadable: {\n current: CodeSentinelSnapshot;\n baseline?: CodeSentinelSnapshot;\n diff?: ReturnType<typeof compareSnapshots>;\n violations: GateEvaluationResult[\"violations\"];\n highestSeverity: GateEvaluationResult[\"highestSeverity\"];\n exitCode: GateEvaluationResult[\"exitCode\"];\n ownership?: CiOwnershipSummary;\n };\n};\n\nconst isPathOutsideBase = (value: string): boolean => {\n return value === \"..\" || value.startsWith(\"../\") || value.startsWith(\"..\\\\\");\n};\n\nexport const runCiCommand = async (\n inputPath: string | undefined,\n authorIdentityMode: AuthorIdentityCliMode,\n options: RunCiCommandOptions,\n logger: Logger = createSilentLogger(),\n): Promise<CiCommandResult> => {\n if (options.baselinePath !== undefined && options.baselineRef !== undefined) {\n throw new GovernanceConfigurationError(\n \"baseline configuration is ambiguous: use either --baseline or --baseline-ref\",\n );\n }\n if (options.baselineSha !== undefined && options.baselineRef !== \"auto\") {\n throw new GovernanceConfigurationError(\"baseline-sha requires --baseline-ref auto\");\n }\n\n const resolvedTargetPath = resolve(inputPath ?? process.cwd());\n\n logger.info(\"building current snapshot\");\n const current = await buildAnalysisSnapshot(\n inputPath,\n authorIdentityMode,\n {\n includeTrace: options.includeTrace,\n ...(options.scoringProfile === undefined ? {} : { scoringProfile: options.scoringProfile }),\n ...(options.recentWindowDays === undefined\n ? {}\n : { recentWindowDays: options.recentWindowDays }),\n },\n logger,\n );\n\n if (options.snapshotPath !== undefined) {\n await writeFile(options.snapshotPath, JSON.stringify(current, null, 2), \"utf8\");\n logger.info(`snapshot written: ${options.snapshotPath}`);\n }\n\n let baseline: CodeSentinelSnapshot | undefined;\n let diff: ReturnType<typeof compareSnapshots> | undefined;\n\n if (options.baselineRef !== undefined) {\n let baselineRef = options.baselineRef;\n if (options.baselineRef === \"auto\") {\n logger.info(\"resolving baseline ref using auto strategy\");\n try {\n const autoResolved = await resolveAutoBaselineRef({\n repositoryPath: resolvedTargetPath,\n ...(options.baselineSha === undefined ? {} : { baselineSha: options.baselineSha }),\n ...(options.mainBranchCandidates === undefined\n ? {}\n : { mainBranchCandidates: options.mainBranchCandidates }),\n environment: process.env,\n });\n logger.info(\n `baseline auto strategy selected: ${autoResolved.strategy} (${autoResolved.resolvedRef} -> ${autoResolved.resolvedSha})`,\n );\n for (const attempt of autoResolved.attempts) {\n const detail = attempt.detail === undefined ? \"\" : ` (${attempt.detail})`;\n logger.debug(\n `baseline auto attempt: ${attempt.step} ${attempt.candidate} => ${attempt.outcome}${detail}`,\n );\n }\n baselineRef = autoResolved.resolvedRef;\n } catch (error) {\n if (error instanceof BaselineRefResolutionError) {\n throw new GovernanceConfigurationError(\n `unable to resolve baseline ref 'auto': ${error.message}`,\n );\n }\n throw error;\n }\n }\n\n logger.info(`resolving baseline from git ref: ${baselineRef}`);\n try {\n const resolved = await resolveBaselineSnapshotFromRef({\n repositoryPath: resolvedTargetPath,\n baselineRef,\n analyzeWorktree: async (worktreePath, repositoryRoot) => {\n const relativeTargetPath = relative(repositoryRoot, resolvedTargetPath);\n if (isPathOutsideBase(relativeTargetPath)) {\n throw new GovernanceConfigurationError(\n `target path is outside git repository root: ${resolvedTargetPath}`,\n );\n }\n\n const baselineTargetPath =\n relativeTargetPath.length === 0 || relativeTargetPath === \".\"\n ? worktreePath\n : resolve(worktreePath, relativeTargetPath);\n\n return buildAnalysisSnapshot(\n baselineTargetPath,\n authorIdentityMode,\n {\n includeTrace: options.includeTrace,\n ...(options.scoringProfile === undefined\n ? {}\n : { scoringProfile: options.scoringProfile }),\n ...(options.recentWindowDays === undefined\n ? {}\n : { recentWindowDays: options.recentWindowDays }),\n },\n logger,\n );\n },\n });\n baseline = resolved.baselineSnapshot;\n logger.info(`baseline ref resolved to ${resolved.resolvedSha}`);\n } catch (error) {\n if (error instanceof BaselineRefResolutionError) {\n throw new GovernanceConfigurationError(\n `unable to resolve baseline ref '${baselineRef}': ${error.message}`,\n );\n }\n throw error;\n }\n diff = compareSnapshots(current, baseline);\n } else if (options.baselinePath !== undefined) {\n logger.info(`loading baseline snapshot: ${options.baselinePath}`);\n const baselineRaw = await readFile(options.baselinePath, \"utf8\");\n try {\n baseline = parseSnapshot(baselineRaw);\n } catch (error) {\n const message = error instanceof Error ? error.message : \"invalid baseline snapshot\";\n throw new GovernanceConfigurationError(`invalid baseline snapshot: ${message}`);\n }\n diff = compareSnapshots(current, baseline);\n }\n\n const ownershipConfigured =\n options.gateConfig.maxUnownedCritical !== undefined ||\n options.gateConfig.maxGhostOwners !== undefined ||\n options.gateConfig.maxDrift !== undefined;\n\n let ownershipInput: OwnershipGateInput | undefined;\n let ownershipSummary: CiOwnershipSummary | undefined;\n\n if (ownershipConfigured) {\n logger.info(\"auditing declared ownership for ownership gates\");\n let audit: OwnershipAudit;\n try {\n ({ audit } = await buildOwnershipAudit(\n resolvedTargetPath,\n {\n ...(options.ownership?.ref === undefined ? {} : { ref: options.ownership.ref }),\n ...(options.ownership?.windowDays === undefined\n ? {}\n : { windowDays: options.ownership.windowDays }),\n ...(options.ownership?.minCommits === undefined\n ? {}\n : { minCommits: options.ownership.minCommits }),\n },\n logger,\n ));\n } catch (error) {\n if (error instanceof OwnersConfigurationError) {\n throw new GovernanceConfigurationError(error.message);\n }\n throw error;\n }\n\n if (audit.available) {\n const metrics: OwnershipGateMetrics = {\n declaredCoveragePercent: audit.metrics.declaredCoveragePercent,\n declaredCoverageCriticalPercent: audit.metrics.declaredCoverageCriticalPercent,\n driftPercent: audit.metrics.driftPercent,\n ghostOwnerCount: audit.metrics.ghostOwnerCount,\n unownedCriticalCount: audit.metrics.unownedCriticalCount,\n };\n ownershipInput = {\n available: true,\n source: audit.codeowners.source,\n metrics,\n };\n ownershipSummary = {\n available: true,\n codeownersSource: audit.codeowners.source,\n metrics,\n warnings: [...audit.warnings],\n };\n } else {\n ownershipInput = { available: false, warnings: [...audit.warnings] };\n ownershipSummary = {\n available: false,\n codeownersSource: null,\n metrics: null,\n warnings: [...audit.warnings],\n };\n }\n }\n\n const gateResult = evaluateGates({\n current,\n ...(baseline === undefined ? {} : { baseline }),\n ...(diff === undefined ? {} : { diff }),\n gateConfig: options.gateConfig,\n ...(ownershipInput === undefined ? {} : { ownership: ownershipInput }),\n });\n\n const report = createReport(current, diff);\n const reportMarkdown = formatReport(report, \"md\");\n const ciMarkdown = renderCheckMarkdown(current, gateResult);\n const markdownSummary = `${reportMarkdown}\\n\\n${ciMarkdown}`;\n\n if (options.reportPath !== undefined) {\n await writeFile(options.reportPath, markdownSummary, \"utf8\");\n logger.info(`report written: ${options.reportPath}`);\n }\n\n const machineReadable = {\n current,\n ...(baseline === undefined ? {} : { baseline }),\n ...(diff === undefined ? {} : { diff }),\n violations: gateResult.violations,\n highestSeverity: gateResult.highestSeverity,\n exitCode: gateResult.exitCode,\n ...(ownershipSummary === undefined ? {} : { ownership: ownershipSummary }),\n };\n\n if (options.jsonOutputPath !== undefined) {\n await writeFile(options.jsonOutputPath, JSON.stringify(machineReadable, null, 2), \"utf8\");\n logger.info(`ci machine output written: ${options.jsonOutputPath}`);\n }\n\n return {\n current,\n ...(baseline === undefined ? {} : { baseline }),\n ...(diff === undefined ? {} : { diff }),\n gateResult,\n markdownSummary,\n ...(ownershipSummary === undefined ? {} : { ownership: ownershipSummary }),\n machineReadable,\n };\n};\n\nexport { GovernanceConfigurationError };\n","import { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { buildProjectGraphSummary } from \"@codesentinel/code-graph\";\nimport {\n CODEOWNERS_CANDIDATE_PATHS,\n CodeownersError,\n DEFAULT_MIN_COMMITS,\n auditOwnership,\n discoverCodeowners,\n parseCodeowners,\n parseOwnerAliases,\n type OwnerAliases,\n type OwnershipAudit,\n type OwnershipFileEvidence,\n type ParsedCodeowners,\n} from \"@codesentinel/ownership\";\nimport {\n OwnersGitError,\n collectOwnershipEvidence,\n normalizeRepositoryPath,\n readRepositorySnapshot,\n readTextAtRef,\n type RepositorySnapshot,\n} from \"./owners-git.js\";\nimport type { Logger } from \"./logger.js\";\n\n/**\n * Shared ownership-audit pipeline for the `owners` and `report` commands.\n *\n * The command is offline by contract. The only inputs are the repository at `--ref`, the optional\n * versioned alias map and the structural analysis of the working tree.\n */\n\nexport const DEFAULT_OWNERS_WINDOW_DAYS = 90;\nexport const DEFAULT_OWNERS_REF = \"HEAD\";\nexport const DEFAULT_OWNERS_ALIASES_PATH = \".codesentinel/owners.json\";\n\nexport class OwnersConfigurationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"OwnersConfigurationError\";\n }\n}\n\nexport type BuildOwnershipAuditOptions = {\n codeownersPath?: string;\n ref?: string;\n windowDays?: number;\n minCommits?: number;\n aliasesPath?: string;\n warnings?: readonly string[];\n};\n\nexport type OwnershipAuditResult = {\n audit: OwnershipAudit;\n trackedFileCount: number;\n repositoryPath: string;\n};\n\nconst readSnapshot = (targetPath: string, ref: string): RepositorySnapshot => {\n try {\n return readRepositorySnapshot(targetPath, ref);\n } catch (error) {\n if (error instanceof OwnersGitError) {\n throw new OwnersConfigurationError(error.message);\n }\n throw error;\n }\n};\n\ntype ReadCodeownersInput = {\n snapshot: RepositorySnapshot;\n explicitPath: string | undefined;\n};\n\nconst readCodeowners = (input: ReadCodeownersInput): ParsedCodeowners | null => {\n const trackedFileSet = new Set(input.snapshot.trackedFiles);\n const explicitPath =\n input.explicitPath === undefined ? null : normalizeRepositoryPath(input.explicitPath);\n\n const selection =\n explicitPath === null\n ? discoverCodeowners(\n CODEOWNERS_CANDIDATE_PATHS.filter((candidate) => trackedFileSet.has(candidate)),\n )\n : { source: explicitPath, ignoredSources: [] as readonly string[] };\n\n if (selection === null) {\n return null;\n }\n if (!trackedFileSet.has(selection.source)) {\n throw new OwnersConfigurationError(\n `CODEOWNERS file \"${selection.source}\" is not tracked at ref \"${input.snapshot.ref}\".`,\n );\n }\n\n const text = readTextAtRef(input.snapshot.repositoryPath, input.snapshot.ref, selection.source);\n return parseCodeowners(text, {\n source: selection.source,\n ignoredSources: selection.ignoredSources,\n });\n};\n\ntype OwnerAliasesSource = {\n aliases: OwnerAliases;\n warnings: readonly string[];\n};\n\n/**\n * The alias map is versioned, so it is read from the audited ref when it is tracked there.\n * Otherwise the working-tree copy is used and the degradation is reported, because an alias map\n * that silently changes identity results is exactly the kind of hidden input this command avoids.\n */\nconst readOwnerAliases = async (\n snapshot: RepositorySnapshot,\n aliasesPath: string,\n): Promise<OwnerAliasesSource> => {\n const normalized = normalizeRepositoryPath(aliasesPath);\n const tracked = snapshot.trackedFiles.includes(normalized);\n\n if (tracked) {\n const text = readTextAtRef(snapshot.repositoryPath, snapshot.ref, normalized);\n const parsed = parseOwnerAliases(text);\n return { aliases: parsed.aliases, warnings: parsed.warnings };\n }\n\n const workingTreePath = resolve(snapshot.repositoryPath, normalized);\n if (existsSync(workingTreePath)) {\n const text = await readFile(workingTreePath, \"utf8\");\n const parsed = parseOwnerAliases(text);\n return {\n aliases: parsed.aliases,\n warnings: [\n ...parsed.warnings,\n `Identity aliases were read from the working tree because \"${normalized}\" is not tracked at \"${snapshot.ref}\".`,\n ],\n };\n }\n\n return { aliases: {}, warnings: [] };\n};\n\n/**\n * Structural fan-in is optional enrichment: when the project cannot be parsed the audit degrades to\n * the churn fallback and says so in its warnings rather than inventing criticality.\n */\nconst collectFanInByPath = (\n projectPath: string,\n logger: Logger,\n): ReadonlyMap<string, number> | null => {\n try {\n const structural = buildProjectGraphSummary({ projectPath });\n const fanIn = new Map<string, number>();\n for (const file of structural.files) {\n fanIn.set(normalizeRepositoryPath(file.relativePath), file.fanIn);\n }\n return fanIn;\n } catch (error) {\n logger.warn(\n `structural analysis unavailable, criticality falls back to churn: ${error instanceof Error ? error.message : \"unknown error\"}`,\n );\n return null;\n }\n};\n\nconst withFanIn = (\n evidence: readonly OwnershipFileEvidence[],\n fanInByPath: ReadonlyMap<string, number> | null,\n): readonly OwnershipFileEvidence[] => {\n if (fanInByPath === null) {\n return evidence;\n }\n\n return evidence.map((item) => {\n const fanIn = fanInByPath.get(item.filePath);\n if (fanIn === undefined) {\n return item;\n }\n return { ...item, criticality: { ...item.criticality, fanIn } };\n });\n};\n\nexport const buildOwnershipAudit = async (\n targetPath: string,\n options: BuildOwnershipAuditOptions,\n logger: Logger,\n): Promise<OwnershipAuditResult> => {\n const ref = options.ref ?? DEFAULT_OWNERS_REF;\n const windowDays = options.windowDays ?? DEFAULT_OWNERS_WINDOW_DAYS;\n const minCommits = options.minCommits ?? DEFAULT_MIN_COMMITS;\n\n const snapshot = readSnapshot(targetPath, ref);\n\n let parsedCodeowners: ParsedCodeowners | null;\n try {\n parsedCodeowners = readCodeowners({\n snapshot,\n explicitPath: options.codeownersPath,\n });\n } catch (error) {\n if (error instanceof CodeownersError) {\n throw new OwnersConfigurationError(error.message);\n }\n throw error;\n }\n\n const aliasSource = await readOwnerAliases(\n snapshot,\n options.aliasesPath ?? DEFAULT_OWNERS_ALIASES_PATH,\n );\n\n const collected = collectOwnershipEvidence(snapshot, windowDays);\n logger.debug(\n `ownership evidence: ${collected.files.length} files with history, window since ${collected.sinceUnix} of ${snapshot.trackedFiles.length} tracked`,\n );\n\n const fanInByPath = collectFanInByPath(snapshot.repositoryPath, logger);\n const evidence = withFanIn(collected.files, fanInByPath);\n\n const audit = auditOwnership({\n codeowners: parsedCodeowners,\n trackedFiles: snapshot.trackedFiles,\n evidence,\n aliases: aliasSource.aliases,\n minCommits,\n warnings: [...(options.warnings ?? []), ...aliasSource.warnings],\n });\n\n return {\n audit,\n trackedFileCount: snapshot.trackedFiles.length,\n repositoryPath: snapshot.repositoryPath,\n };\n};\n","export const CODEOWNERS_MAX_BYTES = 3 * 1024 * 1024;\n\nexport type CodeownersErrorCode = \"codeowners_too_large\" | \"codeowners_invalid_pattern\";\n\nexport class CodeownersError extends Error {\n readonly code: CodeownersErrorCode;\n\n constructor(code: CodeownersErrorCode, message: string) {\n super(message);\n this.name = \"CodeownersError\";\n this.code = code;\n }\n}\n\nexport type DeclaredOwner =\n | { kind: \"user\"; handle: string }\n | { kind: \"team\"; org: string; slug: string }\n | { kind: \"email\"; address: string };\n\n/**\n * Stable identity key for a declared owner, used to aggregate owners across files.\n * GitHub treats handles, team slugs and email addresses case-insensitively.\n */\nexport const declaredOwnerKey = (owner: DeclaredOwner): string => {\n if (owner.kind === \"user\") return `@${owner.handle.trim().toLowerCase()}`;\n if (owner.kind === \"team\")\n return `@${owner.org.trim().toLowerCase()}/${owner.slug.trim().toLowerCase()}`;\n return owner.address.trim().toLowerCase();\n};\n\nexport type CodeownersEntry = {\n pattern: string;\n owners: readonly DeclaredOwner[];\n /** 1-based line of the source file, so the report can link to it. */\n line: number;\n /**\n * Invalid lines are preserved for diagnostics but never take part in matching.\n * A line with a pattern and no owners is valid: it clears the ownership of the subtree.\n */\n ignored: boolean;\n};\n\nexport type CodeownersParseError = {\n line: number;\n reason: string;\n};\n\nexport type ParsedCodeowners = {\n source: string;\n entries: readonly CodeownersEntry[];\n errors: readonly CodeownersParseError[];\n ignoredSources: readonly string[];\n};\n\nexport type OwnershipStatus =\n | \"aligned\"\n | \"drifted\"\n | \"ghosted\"\n | \"unowned\"\n | \"unowned-critical\"\n | \"insufficient-evidence\"\n /** Degraded verdict: teams are opaque offline and aliases may be unresolved, so absence is not proof. */\n | \"unknown\";\n\nexport type FileOwnershipAudit = {\n filePath: string;\n declared: readonly DeclaredOwner[];\n matchLine: number | null;\n status: OwnershipStatus;\n observed: {\n /** Lifetime commits touching the file. */\n commits: number;\n /** Commits touching the file inside the activity window. */\n recentCommits: number;\n /** `recentCommits === 0 && commits > 0`: present in history, untouched in the window. */\n dormant: boolean;\n /** Distinct authors over the file's lifetime. */\n authors: number;\n topAuthorId: string | null;\n topAuthorShare: number | null;\n busFactor: number | null;\n lastCommitUnix: number | null;\n };\n criticality: {\n fanIn: number | null;\n isHotspot: boolean;\n riskScore: number | null;\n /**\n * Resolved criticality verdict. Stored so reporters do not have to re-apply the threshold\n * policy, and so `unowned-critical` is auditable from the output alone.\n */\n isCritical: boolean;\n };\n};\n\nexport type OwnershipAuditMetrics = {\n declaredCoveragePercent: number;\n declaredCoverageCriticalPercent: number;\n driftPercent: number;\n ghostOwnerCount: number;\n unownedCriticalCount: number;\n singleOwnerModuleCount: number;\n};\n\nexport type OwnershipAuditAvailable = {\n available: true;\n codeowners: ParsedCodeowners;\n metrics: OwnershipAuditMetrics;\n ghostOwners: readonly { owner: DeclaredOwner; samplePaths: readonly string[] }[];\n files: readonly FileOwnershipAudit[];\n warnings: readonly string[];\n};\n\nexport type OwnershipAuditUnavailable = {\n available: false;\n reason: \"codeowners_not_found\";\n warnings: readonly string[];\n};\n\nexport type OwnershipAudit = OwnershipAuditAvailable | OwnershipAuditUnavailable;\n","import { CodeownersError } from \"./codeowners.js\";\nimport type { CodeownersEntry } from \"./codeowners.js\";\n\nconst REGEX_METACHARACTERS = /[.*+?^${}()|[\\]\\\\]/g;\n\nconst ANY_DEPTH_PREFIX = \"(?:[^/]+/)*\";\n\nexport type CompiledCodeownersPattern = {\n pattern: string;\n regex: RegExp;\n};\n\nexport type CodeownersMatcher = (filePath: string) => CodeownersEntry | null;\n\nconst escapeLiteral = (value: string): string => value.replace(REGEX_METACHARACTERS, \"\\\\$&\");\n\nconst compileSegment = (segment: string): string =>\n [...segment]\n .map((character) => {\n if (character === \"*\") return \"[^/]*\";\n if (character === \"?\") return \"[^/]\";\n return escapeLiteral(character);\n })\n .join(\"\");\n\nconst compileBody = (segments: readonly string[]): string => {\n const parts: string[] = [];\n segments.forEach((segment, index) => {\n const isLast = index === segments.length - 1;\n if (segment === \"**\") {\n parts.push(isLast ? \".*\" : ANY_DEPTH_PREFIX);\n return;\n }\n parts.push(compileSegment(segment));\n if (!isLast) parts.push(\"/\");\n });\n return parts.join(\"\");\n};\n\nconst normalizeFilePath = (filePath: string): string => {\n let normalized = filePath;\n while (normalized.startsWith(\"./\")) normalized = normalized.slice(2);\n return normalized.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n};\n\n/**\n * Compiles a CODEOWNERS pattern into an anchored regular expression over repo-relative paths.\n *\n * Rules, matching GitHub's documented behaviour rather than full gitignore:\n * - A pattern with no internal `/` matches at any depth; `/`-prefixed patterns are root-anchored.\n * - `*` and `?` never cross a `/` separator; `**` crosses segments.\n * - A trailing `/` marks a directory pattern: it owns the directory subtree.\n * - A pattern whose last segment is literal also owns the subtree, so `/apps/github` covers\n * `apps/github/*`. A wildcarded last segment stays exact, so `docs/*` covers one level only.\n * - `!` and `[...]` are literal characters: GitHub does not implement negation or character classes.\n * - Matching is case-sensitive on every platform.\n */\nexport function compileCodeownersPattern(pattern: string): CompiledCodeownersPattern {\n const trimmed = pattern.trim();\n const directoryPattern = trimmed.endsWith(\"/\");\n const withoutTrailingSlashes = trimmed.replace(/\\/+$/, \"\");\n const anchored =\n withoutTrailingSlashes.startsWith(\"/\") || withoutTrailingSlashes.slice(1).includes(\"/\");\n const core = withoutTrailingSlashes.replace(/^\\/+/, \"\");\n\n if (core.length === 0) {\n throw new CodeownersError(\n \"codeowners_invalid_pattern\",\n `CODEOWNERS pattern \"${pattern}\" does not match any path.`,\n );\n }\n\n const segments = core.split(\"/\");\n const lastSegment = segments[segments.length - 1] ?? \"\";\n const lastSegmentIsLiteral =\n lastSegment !== \"**\" && !lastSegment.includes(\"*\") && !lastSegment.includes(\"?\");\n\n const prefix = anchored ? \"\" : ANY_DEPTH_PREFIX;\n const suffix = directoryPattern ? \"(?:/.*)\" : lastSegmentIsLiteral ? \"(?:/.*)?\" : \"\";\n const regex = new RegExp(`^${prefix}${compileBody(segments)}${suffix}$`);\n\n return { pattern: trimmed, regex };\n}\n\nexport function matchCodeownersPattern(pattern: string, filePath: string): boolean {\n const candidate = normalizeFilePath(filePath);\n if (candidate.length === 0) return false;\n return compileCodeownersPattern(pattern).regex.test(candidate);\n}\n\n/**\n * Precompiles every non-ignored entry once and returns a resolver with last-match-wins semantics.\n * A matching entry with no owners is a winner too: it means the subtree is deliberately unowned.\n */\nexport function createCodeownersMatcher(entries: readonly CodeownersEntry[]): CodeownersMatcher {\n const compiled = entries\n .filter((entry) => !entry.ignored)\n .map((entry) => ({ entry, regex: compileCodeownersPattern(entry.pattern).regex }));\n\n return (filePath: string): CodeownersEntry | null => {\n const candidate = normalizeFilePath(filePath);\n if (candidate.length === 0) return null;\n\n let winner: CodeownersEntry | null = null;\n for (const { entry, regex } of compiled) {\n if (regex.test(candidate)) winner = entry;\n }\n return winner;\n };\n}\n\n/** Convenience wrapper. Recompiles the entries on every call; use `createCodeownersMatcher` in loops. */\nexport function findOwningEntry(\n entries: readonly CodeownersEntry[],\n filePath: string,\n): CodeownersEntry | null {\n return createCodeownersMatcher(entries)(filePath);\n}\n","import type { DeclaredOwner } from \"./codeowners.js\";\n\n/**\n * Author evidence for a single file, already reduced to the observation window.\n *\n * `authorId` is expected to be the normalized identity produced by\n * `normalizeAuthorIdentity` in `@codesentinel/git-analyzer`: the numeric prefix of a GitHub\n * noreply address is already stripped, so `<handle>@users.noreply.github.com` is comparable\n * against a CODEOWNERS handle. An unnormalized `123+handle@users.noreply.github.com` will not\n * resolve, by design: the parser is the single place where that normalization happens.\n */\nexport type OwnershipAuthor = {\n authorId: string;\n /** Raw author name, when available. The evolution summary does not keep it. */\n authorName?: string | null;\n /** Commits by this author inside the observation window. */\n commits: number;\n};\n\n/**\n * Identity aliases: handle (with or without `@`) mapping to the author ids that belong to it.\n * The map is versioned in `.codesentinel/owners.json`; reading that file is the caller's job.\n */\nexport type OwnerAliases = Readonly<Record<string, readonly string[]>>;\n\n/**\n * How a declared owner related to the observed authors.\n *\n * - `github_noreply`, `email_local_part`, `author_name`, `alias`: the owner matched at least one\n * author, in cascade order.\n * - `email_owner`: an email owner matched an author id exactly.\n * - `team_unverified`: an unexpanded team. Offline it is opaque, so it is never a ghost.\n * - `no_activity`: no author matched and nothing external could hide the absence.\n * - `alias_unresolved`: no author matched, but the alias map declares identities for this handle\n * that were not observed. The map may be incomplete, so the absence is not proof.\n */\nexport type OwnerResolutionKind =\n | \"github_noreply\"\n | \"email_local_part\"\n | \"author_name\"\n | \"alias\"\n | \"email_owner\"\n | \"team_unverified\"\n | \"no_activity\"\n | \"alias_unresolved\";\n\nexport type OwnerResolution = {\n owner: DeclaredOwner;\n kind: OwnerResolutionKind;\n /** Author ids from the evidence covered by this owner, in evidence order. */\n activeAuthorIds: readonly string[];\n};\n\nexport const isActiveOwnerResolution = (resolution: OwnerResolution): boolean =>\n resolution.activeAuthorIds.length > 0;\n\n/**\n * Whether absence of activity for this owner is evidence: a team that was never expanded, or an\n * alias that never showed up in the window, both mean \"we do not know\" rather than \"ghost\".\n */\nexport const isVerifiableOwnerResolution = (resolution: OwnerResolution): boolean =>\n resolution.kind !== \"team_unverified\" && resolution.kind !== \"alias_unresolved\";\n","import type { OwnershipStatus } from \"./codeowners.js\";\nimport type { OwnerResolution } from \"./identity.js\";\nimport { isActiveOwnerResolution, isVerifiableOwnerResolution } from \"./identity.js\";\n\n/** Criticality defaults from the design: `fanIn >= 5` or hotspot. */\nexport const DEFAULT_FAN_IN_CRITICALITY_THRESHOLD = 5;\n\n/**\n * When no structural analysis exists, criticality falls back to hotspots plus churn. The cutoff is\n * the 90th percentile of the churn seen in the repository, computed with the nearest-rank method so\n * the result does not depend on input order.\n */\nexport const CHURN_CRITICALITY_PERCENTILE = 0.9;\n\n/** Risk score contributes through the upper quartile, as specified in the design. */\nexport const RISK_SCORE_CRITICALITY_PERCENTILE = 0.75;\n\n/** Below this many scores the quartile is noise, so the rule stays off. */\nexport const RISK_SCORE_CRITICALITY_MIN_SAMPLES = 4;\n\nexport type CriticalityEvidence = {\n fanIn?: number | null;\n isHotspot?: boolean | null;\n riskScore?: number | null;\n /** Churn is only used when structural data is missing. */\n churnTotal?: number | null;\n};\n\nexport type CriticalityPolicy = {\n fanInThreshold: number;\n /** Churn cutoff, enabled only when no file carries structural data. */\n churnThreshold: number | null;\n /** Risk score cutoff (upper quartile), `null` when the sample is too small. */\n riskScoreThreshold: number | null;\n structuralDataAvailable: boolean;\n};\n\nexport type CriticalityPolicyOptions = {\n fanInThreshold?: number;\n};\n\nconst finiteNumbers = (values: readonly (number | null | undefined)[]): number[] =>\n values\n .filter((value): value is number => typeof value === \"number\" && Number.isFinite(value))\n .sort((a, b) => a - b);\n\n/** Nearest-rank percentile over an ascending list: no interpolation, so no surprise decimals. */\nconst nearestRank = (sortedAscending: readonly number[], percentile: number): number | null => {\n if (sortedAscending.length === 0) return null;\n const rank = Math.ceil(percentile * sortedAscending.length);\n const index = Math.min(Math.max(rank, 1), sortedAscending.length) - 1;\n return sortedAscending[index] ?? null;\n};\n\n/**\n * Resolves the criticality cutoffs once for the whole audit.\n *\n * `structuralDataAvailable` is false when no file carries a `fanIn`, which is exactly the\n * \"git only, no structural analysis\" mode: criticality then degrades to hotspot + churn and the\n * audit must say so in `warnings` instead of pretending the result means the same thing.\n */\nexport const resolveCriticalityPolicy = (\n evidence: readonly CriticalityEvidence[],\n options: CriticalityPolicyOptions = {},\n): CriticalityPolicy => {\n const fanInThreshold = options.fanInThreshold ?? DEFAULT_FAN_IN_CRITICALITY_THRESHOLD;\n const fanInValues = finiteNumbers(evidence.map((item) => item.fanIn));\n const structuralDataAvailable = fanInValues.length > 0;\n\n const riskScores = finiteNumbers(evidence.map((item) => item.riskScore));\n const riskScoreThreshold =\n riskScores.length >= RISK_SCORE_CRITICALITY_MIN_SAMPLES\n ? nearestRank(riskScores, RISK_SCORE_CRITICALITY_PERCENTILE)\n : null;\n\n if (structuralDataAvailable) {\n return { fanInThreshold, churnThreshold: null, riskScoreThreshold, structuralDataAvailable };\n }\n\n const churnValues = finiteNumbers(evidence.map((item) => item.churnTotal));\n return {\n fanInThreshold,\n churnThreshold: nearestRank(churnValues, CHURN_CRITICALITY_PERCENTILE),\n riskScoreThreshold,\n structuralDataAvailable,\n };\n};\n\nexport const isCriticalFile = (\n evidence: CriticalityEvidence | undefined,\n policy: CriticalityPolicy,\n): boolean => {\n if (evidence === undefined) return false;\n\n const fanIn = typeof evidence.fanIn === \"number\" ? evidence.fanIn : null;\n if (fanIn !== null && Number.isFinite(fanIn) && fanIn >= policy.fanInThreshold) return true;\n if (evidence.isHotspot === true) return true;\n\n const riskScore = typeof evidence.riskScore === \"number\" ? evidence.riskScore : null;\n if (\n policy.riskScoreThreshold !== null &&\n riskScore !== null &&\n Number.isFinite(riskScore) &&\n riskScore >= policy.riskScoreThreshold\n ) {\n return true;\n }\n\n const churnTotal = typeof evidence.churnTotal === \"number\" ? evidence.churnTotal : null;\n return (\n policy.churnThreshold !== null &&\n churnTotal !== null &&\n Number.isFinite(churnTotal) &&\n churnTotal >= policy.churnThreshold\n );\n};\n\n/**\n * Fixed severity order for every report. It is part of the output contract: `files` is sorted by\n * this rank first, so two runs always emit the same bytes.\n *\n * Unowned critical and ghosted come first because they are the findings that need action;\n * `insufficient-evidence` sits near the end because it is the absence of data, not a finding.\n */\nexport const OWNERSHIP_STATUS_ORDER: Readonly<Record<OwnershipStatus, number>> = {\n \"unowned-critical\": 0,\n ghosted: 1,\n drifted: 2,\n unowned: 3,\n unknown: 4,\n \"insufficient-evidence\": 5,\n aligned: 6,\n};\n\nexport const ownershipStatusRank = (status: OwnershipStatus): number =>\n OWNERSHIP_STATUS_ORDER[status];\n\nexport type OwnershipClassificationInput = {\n /** Owners declared by the winning entry. Zero also covers \"no entry matched\" and a reset line. */\n declaredCount: number;\n isCritical: boolean;\n /** Lifetime commits touching the file, used for the evidence threshold. */\n commits: number;\n /** Commits touching the file inside the observation window, used for activity. */\n recentCommits: number;\n minCommits: number;\n /** Highest-commit author of the horizon that produced the verdict, bots excluded. */\n topAuthorId: string | null;\n /** False when the horizon that can produce a verdict has commits but no author breakdown. */\n hasAuthorEvidence: boolean;\n /** Declared owners resolved against the same horizon as `topAuthorId`. */\n resolutions: readonly OwnerResolution[];\n};\n\n/**\n * Classification with two horizons: lifetime history decides whether there is enough evidence,\n * window activity decides whether an owner is still around.\n *\n * Order: no declaration -> insufficient lifetime evidence -> no author evidence -> dormant ->\n * no declared owner active -> top author -> drift.\n *\n * A `ghosted` verdict needs *all* declared owners to be verifiable, so a team that was never\n * expanded or a stale alias map downgrades the file to `unknown` instead of inventing a ghost.\n * A dormant file (no commits in the window) can never be ghosted: it is compared against its\n * lifetime top author instead, because silence in the window is not owner inactivity.\n */\nexport const classifyOwnershipStatus = (input: OwnershipClassificationInput): OwnershipStatus => {\n if (input.declaredCount === 0) {\n return input.isCritical ? \"unowned-critical\" : \"unowned\";\n }\n if (input.commits < input.minCommits) {\n return \"insufficient-evidence\";\n }\n if (!input.hasAuthorEvidence) {\n return \"unknown\";\n }\n\n const topAuthorId = input.topAuthorId;\n\n if (input.recentCommits === 0) {\n return topAuthorId !== null &&\n input.resolutions.some((resolution) => resolution.activeAuthorIds.includes(topAuthorId))\n ? \"aligned\"\n : \"drifted\";\n }\n\n const active = input.resolutions.filter(isActiveOwnerResolution);\n if (active.length === 0) {\n return input.resolutions.every(isVerifiableOwnerResolution) ? \"ghosted\" : \"unknown\";\n }\n\n if (\n topAuthorId !== null &&\n active.some((resolution) => resolution.activeAuthorIds.includes(topAuthorId))\n ) {\n return \"aligned\";\n }\n return \"drifted\";\n};\n","import { declaredOwnerKey } from \"./codeowners.js\";\nimport type { DeclaredOwner, FileOwnershipAudit, OwnershipAuditMetrics } from \"./codeowners.js\";\nimport { ownershipStatusRank } from \"./classify.js\";\n\n/** At most three sample paths per ghost owner, as specified in the design. */\nexport const GHOST_OWNER_SAMPLE_PATHS = 3;\n\nconst roundTo = (value: number, decimals: number): number => {\n const factor = 10 ** decimals;\n return Math.round(value * factor) / factor;\n};\n\n/** Percentages are rounded to two decimals so the JSON stays stable and readable. */\nexport const percentOf = (part: number, total: number): number =>\n total === 0 ? 0 : roundTo((part / total) * 100, 2);\n\nconst compareText = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n\nconst compareNullableDescending = (a: number | null, b: number | null): number => {\n if (a === null && b === null) return 0;\n if (a === null) return 1;\n if (b === null) return -1;\n return b - a;\n};\n\n/**\n * Report order, part of the determinism contract: severity rank, then criticality descending,\n * then `fanIn`, then `riskScore`, then the path as the final tie-breaker.\n */\nexport const compareFileOwnershipAudits = (\n a: FileOwnershipAudit,\n b: FileOwnershipAudit,\n): number => {\n const byStatus = ownershipStatusRank(a.status) - ownershipStatusRank(b.status);\n if (byStatus !== 0) return byStatus;\n\n const byCritical = Number(b.criticality.isCritical) - Number(a.criticality.isCritical);\n if (byCritical !== 0) return byCritical;\n\n const byFanIn = compareNullableDescending(a.criticality.fanIn, b.criticality.fanIn);\n if (byFanIn !== 0) return byFanIn;\n\n const byRiskScore = compareNullableDescending(a.criticality.riskScore, b.criticality.riskScore);\n if (byRiskScore !== 0) return byRiskScore;\n\n return compareText(a.filePath, b.filePath);\n};\n\nexport const sortFileOwnershipAudits = (\n files: readonly FileOwnershipAudit[],\n): readonly FileOwnershipAudit[] => [...files].sort(compareFileOwnershipAudits);\n\n/** Module = first path segment; files at the repository root belong to the \".\" module. */\nexport const moduleOfPath = (filePath: string): string => {\n const separator = filePath.indexOf(\"/\");\n return separator === -1 ? \".\" : filePath.slice(0, separator);\n};\n\nconst countSingleOwnerModules = (files: readonly FileOwnershipAudit[]): number => {\n const ownersByModule = new Map<string, Set<string>>();\n for (const file of files) {\n const module = moduleOfPath(file.filePath);\n const owners = ownersByModule.get(module) ?? new Set<string>();\n for (const owner of file.declared) owners.add(declaredOwnerKey(owner));\n ownersByModule.set(module, owners);\n }\n\n let singleOwnerModules = 0;\n for (const owners of ownersByModule.values()) {\n if (owners.size === 1) singleOwnerModules += 1;\n }\n return singleOwnerModules;\n};\n\nexport type OwnershipMetricsInput = {\n files: readonly FileOwnershipAudit[];\n /** Universe of tracked files, including the ones no CODEOWNERS pattern matches. */\n trackedFileCount: number;\n /** Distinct owners with verified absence of activity. */\n ghostOwnerCount: number;\n};\n\n/**\n * Aggregate metrics. `declaredCoveragePercent` is the headline that GitHub inflates with a single\n * `* @someone`; `declaredCoverageCriticalPercent` is the one that matters.\n *\n * `driftPercent` is measured over files with a declaration, so unowned files cannot hide drift.\n */\nexport const computeOwnershipMetrics = (input: OwnershipMetricsInput): OwnershipAuditMetrics => {\n const declaredFiles = input.files.filter((file) => file.declared.length > 0);\n const criticalFiles = input.files.filter((file) => file.criticality.isCritical);\n const coveredCriticalFiles = criticalFiles.filter((file) => file.declared.length > 0);\n const driftedFiles = declaredFiles.filter((file) => file.status === \"drifted\");\n\n return {\n declaredCoveragePercent: percentOf(declaredFiles.length, input.trackedFileCount),\n declaredCoverageCriticalPercent: percentOf(coveredCriticalFiles.length, criticalFiles.length),\n driftPercent: percentOf(driftedFiles.length, declaredFiles.length),\n ghostOwnerCount: input.ghostOwnerCount,\n unownedCriticalCount: input.files.filter((file) => file.status === \"unowned-critical\").length,\n singleOwnerModuleCount: countSingleOwnerModules(declaredFiles),\n };\n};\n\nexport type GhostOwnerCandidate = {\n owner: DeclaredOwner;\n filePath: string;\n};\n\nexport type GhostOwnerSummary = {\n owner: DeclaredOwner;\n samplePaths: readonly string[];\n};\n\n/**\n * Deduplicates ghost owners across files. Owners are ordered by their identity key and paths\n * ascending, so the list does not depend on traversal order.\n */\nexport const summarizeGhostOwners = (\n candidates: readonly GhostOwnerCandidate[],\n): readonly GhostOwnerSummary[] => {\n const owners = new Map<string, { owner: DeclaredOwner; paths: Set<string> }>();\n for (const candidate of candidates) {\n const key = declaredOwnerKey(candidate.owner);\n const entry = owners.get(key) ?? { owner: candidate.owner, paths: new Set<string>() };\n entry.paths.add(candidate.filePath);\n owners.set(key, entry);\n }\n\n return [...owners.entries()]\n .sort(([a], [b]) => compareText(a, b))\n .map(([, entry]) => ({\n owner: entry.owner,\n samplePaths: [...entry.paths].sort(compareText).slice(0, GHOST_OWNER_SAMPLE_PATHS),\n }));\n};\n","import { CODEOWNERS_MAX_BYTES, CodeownersError } from \"../domain/codeowners.js\";\nimport type {\n CodeownersEntry,\n CodeownersParseError,\n DeclaredOwner,\n ParsedCodeowners,\n} from \"../domain/codeowners.js\";\n\nexport const CODEOWNERS_CANDIDATE_PATHS = [\n \".github/CODEOWNERS\",\n \"CODEOWNERS\",\n \"docs/CODEOWNERS\",\n] as const;\n\nexport const DEFAULT_CODEOWNERS_SOURCE = \"CODEOWNERS\";\n\nexport type CodeownersSourceSelection = {\n source: string;\n ignoredSources: readonly string[];\n};\n\nexport type ParseCodeownersOptions = {\n source?: string;\n ignoredSources?: readonly string[];\n};\n\nconst EMAIL_PATTERN = /^[^@\\s]+@[^@\\s]+$/;\nconst WHITESPACE_PATTERN = /\\s/;\n\nconst hasControlCharacter = (value: string): boolean => {\n for (const character of value) {\n const codePoint = character.codePointAt(0) ?? 0;\n if (codePoint < 0x20 || codePoint === 0x7f) return true;\n }\n return false;\n};\n\nconst parseOwner = (token: string): DeclaredOwner | null => {\n if (!token.startsWith(\"@\")) {\n return EMAIL_PATTERN.test(token) ? { kind: \"email\", address: token } : null;\n }\n\n const reference = token.slice(1);\n if (reference.length === 0 || reference.includes(\"@\")) return null;\n\n const parts = reference.split(\"/\");\n if (parts.length === 1) {\n return { kind: \"user\", handle: reference };\n }\n if (parts.length !== 2) return null;\n\n const [org, slug] = parts;\n if (org === undefined || slug === undefined || org.length === 0 || slug.length === 0) return null;\n return { kind: \"team\", org, slug };\n};\n\nconst isValidPattern = (pattern: string): boolean => {\n if (hasControlCharacter(pattern)) return false;\n return pattern.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\").length > 0;\n};\n\n/**\n * GitHub starts a comment at `#` when it is the first character of the line or follows whitespace,\n * and escaping it is not supported. Any other `#` stays inside the pattern.\n */\nconst commentIndex = (line: string): number => {\n for (let index = 0; index < line.length; index += 1) {\n if (line[index] !== \"#\") continue;\n const previous = index === 0 ? \"\" : (line[index - 1] ?? \"\");\n if (index === 0 || WHITESPACE_PATTERN.test(previous)) return index;\n }\n return -1;\n};\n\nconst stripComment = (line: string): string => {\n const index = commentIndex(line);\n return index === -1 ? line : line.slice(0, index);\n};\n\n/**\n * Parses CODEOWNERS text into entries plus parse errors. Pure: no filesystem, no network.\n *\n * A pattern with no owners is a valid entry that clears ownership of its subtree. A line with an\n * invalid pattern or owner is preserved with `ignored: true` and reported in `errors`; the owners\n * that did parse are kept for diagnostics but never participate in matching.\n */\nexport function parseCodeowners(\n text: string,\n options: ParseCodeownersOptions = {},\n): ParsedCodeowners {\n const byteLength = Buffer.byteLength(text, \"utf8\");\n if (byteLength > CODEOWNERS_MAX_BYTES) {\n throw new CodeownersError(\n \"codeowners_too_large\",\n `CODEOWNERS content is ${byteLength} bytes, above the ${CODEOWNERS_MAX_BYTES} byte limit GitHub accepts.`,\n );\n }\n\n const entries: CodeownersEntry[] = [];\n const errors: CodeownersParseError[] = [];\n const lines = text.replace(/^\\uFEFF/, \"\").split(\"\\n\");\n\n lines.forEach((rawLine, index) => {\n const lineNumber = index + 1;\n const line = rawLine.endsWith(\"\\r\") ? rawLine.slice(0, -1) : rawLine;\n const content = stripComment(line).trim();\n if (content.length === 0) return;\n\n const [pattern, ...ownerTokens] = content.split(/\\s+/);\n if (pattern === undefined) return;\n\n let ignored = !isValidPattern(pattern);\n if (ignored) {\n errors.push({ line: lineNumber, reason: `invalid pattern \"${pattern}\"` });\n }\n\n const owners: DeclaredOwner[] = [];\n for (const token of ownerTokens) {\n const owner = parseOwner(token);\n if (owner === null) {\n ignored = true;\n errors.push({ line: lineNumber, reason: `invalid owner \"${token}\"` });\n continue;\n }\n owners.push(owner);\n }\n\n entries.push({ pattern, owners, line: lineNumber, ignored });\n });\n\n return {\n source: options.source ?? DEFAULT_CODEOWNERS_SOURCE,\n entries,\n errors,\n ignoredSources: options.ignoredSources ?? [],\n };\n}\n\nconst normalizeSourcePath = (source: string): string => {\n let normalized = source;\n while (normalized.startsWith(\"./\")) normalized = normalized.slice(2);\n return normalized.replace(/^\\/+/, \"\");\n};\n\n/**\n * GitHub checks these locations in order and loads only the first one that exists.\n * `existingPaths` is whatever the caller found on disk; the rest become `ignoredSources`.\n */\nexport function discoverCodeowners(\n existingPaths: readonly string[],\n): CodeownersSourceSelection | null {\n const existing = new Set(existingPaths.map(normalizeSourcePath));\n const found = CODEOWNERS_CANDIDATE_PATHS.filter((candidate) => existing.has(candidate));\n const [source, ...ignoredSources] = found;\n if (source === undefined) return null;\n return { source, ignoredSources };\n}\n","import type { DeclaredOwner } from \"../domain/codeowners.js\";\nimport type { OwnerAliases, OwnerResolution, OwnershipAuthor } from \"../domain/identity.js\";\n\nconst BOT_MARKER = /\\[bot\\]/i;\nconst WHITESPACE_PATTERN = /\\s+/g;\n\n/**\n * Bots commit a lot and never own anything. `normalizeAuthorIdentity` keeps `[bot]` in the id,\n * so excluding them here prevents machine accounts from ever being attributed to a human handle.\n */\nexport const isBotAuthor = (author: OwnershipAuthor): boolean => {\n if (BOT_MARKER.test(author.authorId)) return true;\n return typeof author.authorName === \"string\" && BOT_MARKER.test(author.authorName);\n};\n\nconst normalizeHandle = (value: string): string =>\n value.trim().replace(/^@+/, \"\").toLowerCase().replace(WHITESPACE_PATTERN, \"\");\n\nconst normalizeAuthorName = (value: string): string =>\n value.toLowerCase().replace(WHITESPACE_PATTERN, \"\");\n\nconst localPartOf = (authorId: string): string | null => {\n const at = authorId.indexOf(\"@\");\n return at > 0 ? authorId.slice(0, at) : null;\n};\n\nconst uniquify = (values: readonly string[]): readonly string[] => [...new Set(values)];\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport type ParsedOwnerAliases = {\n aliases: OwnerAliases;\n warnings: readonly string[];\n};\n\n/**\n * Parses the versioned alias map (`.codesentinel/owners.json`) from text the caller read.\n *\n * Absence is not a problem: a missing or empty file yields no aliases and no warnings. Anything\n * that cannot be used is dropped with an explicit warning, because silently discarding identity\n * data would turn a configuration mistake into a false ghost-owner report.\n */\nexport const parseOwnerAliases = (raw: string | null | undefined): ParsedOwnerAliases => {\n const warnings: string[] = [];\n if (raw === null || raw === undefined || raw.trim().length === 0) {\n return { aliases: {}, warnings };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return {\n aliases: {},\n warnings: [\"owners.json is not valid JSON: identity aliases were ignored.\"],\n };\n }\n\n if (!isRecord(parsed)) {\n return {\n aliases: {},\n warnings: [\"owners.json must contain a JSON object: identity aliases were ignored.\"],\n };\n }\n\n const rawAliases = parsed[\"aliases\"];\n if (rawAliases === undefined || rawAliases === null) {\n return { aliases: {}, warnings };\n }\n\n if (!isRecord(rawAliases)) {\n return {\n aliases: {},\n warnings: ['owners.json \"aliases\" must be an object: identity aliases were ignored.'],\n };\n }\n\n const aliases: Record<string, readonly string[]> = {};\n for (const [handle, value] of Object.entries(rawAliases)) {\n const key = normalizeHandle(handle);\n if (key.length === 0) {\n warnings.push(\"An alias entry with an empty handle was ignored.\");\n continue;\n }\n if (!Array.isArray(value)) {\n warnings.push(`Alias entry \"${key}\" was ignored: expected an array of author ids.`);\n continue;\n }\n\n const targets = value\n .filter((target): target is string => typeof target === \"string\")\n .map((target) => target.trim().toLowerCase())\n .filter((target) => target.length > 0);\n\n if (targets.length === 0) {\n warnings.push(`Alias entry \"${key}\" was ignored: it contains no usable author id.`);\n continue;\n }\n\n aliases[key] = [...(aliases[key] ?? []), ...targets];\n }\n\n for (const key of Object.keys(aliases)) {\n aliases[key] = uniquify(aliases[key] ?? []);\n }\n\n return { aliases, warnings };\n};\n\nexport type IdentityResolver = (\n owner: DeclaredOwner,\n authors: readonly OwnershipAuthor[],\n) => OwnerResolution;\n\nconst resolveOwner = (\n owner: DeclaredOwner,\n authors: readonly OwnershipAuthor[],\n aliases: ReadonlyMap<string, readonly string[]>,\n): OwnerResolution => {\n if (owner.kind === \"team\") {\n return { owner, kind: \"team_unverified\", activeAuthorIds: [] };\n }\n\n const candidates = authors.filter((author) => !isBotAuthor(author));\n\n if (owner.kind === \"email\") {\n const target = owner.address.trim().toLowerCase();\n const active = candidates\n .filter((author) => author.authorId.trim().toLowerCase() === target)\n .map((author) => author.authorId);\n return { owner, kind: \"email_owner\", activeAuthorIds: uniquify(active) };\n }\n\n const handle = normalizeHandle(owner.handle);\n if (handle.length === 0) {\n return { owner, kind: \"no_activity\", activeAuthorIds: [] };\n }\n\n const noreplyId = `${handle}@users.noreply.github.com`;\n const aliasTargets = aliases.get(handle) ?? [];\n const byNoreply: string[] = [];\n const byLocalPart: string[] = [];\n const byName: string[] = [];\n const byAlias: string[] = [];\n\n for (const author of candidates) {\n const authorId = author.authorId.trim().toLowerCase();\n if (authorId === noreplyId) {\n byNoreply.push(author.authorId);\n continue;\n }\n\n const localPart = localPartOf(authorId);\n if (localPart !== null && localPart === handle) {\n byLocalPart.push(author.authorId);\n continue;\n }\n\n const authorName =\n typeof author.authorName === \"string\" ? normalizeAuthorName(author.authorName) : \"\";\n if (authorName.length > 0 && authorName === handle) {\n byName.push(author.authorId);\n continue;\n }\n\n if (aliasTargets.includes(authorId)) {\n byAlias.push(author.authorId);\n }\n }\n\n if (byNoreply.length > 0) {\n return { owner, kind: \"github_noreply\", activeAuthorIds: uniquify(byNoreply) };\n }\n if (byLocalPart.length > 0) {\n return { owner, kind: \"email_local_part\", activeAuthorIds: uniquify(byLocalPart) };\n }\n if (byName.length > 0) {\n return { owner, kind: \"author_name\", activeAuthorIds: uniquify(byName) };\n }\n if (byAlias.length > 0) {\n return { owner, kind: \"alias\", activeAuthorIds: uniquify(byAlias) };\n }\n if (aliasTargets.length > 0) {\n // The map claims identities for this handle and none of them were observed: the map may be\n // stale, so absence cannot be reported as a ghost.\n return { owner, kind: \"alias_unresolved\", activeAuthorIds: [] };\n }\n return { owner, kind: \"no_activity\", activeAuthorIds: [] };\n};\n\n/**\n * Builds an offline identity resolver from an alias map. Fully deterministic: no network, no clock,\n * and the cascade order is the one documented in the design (noreply, email local part, author\n * name, alias).\n */\nexport const createIdentityResolver = (aliases: OwnerAliases = {}): IdentityResolver => {\n const normalizedAliases = new Map<string, readonly string[]>();\n for (const [handle, targets] of Object.entries(aliases)) {\n const key = normalizeHandle(handle);\n if (key.length === 0) continue;\n normalizedAliases.set(\n key,\n targets.map((target) => target.trim().toLowerCase()).filter((target) => target.length > 0),\n );\n }\n\n return (owner, authors) => resolveOwner(owner, authors, normalizedAliases);\n};\n\nexport const resolveOwnerIdentities = (\n owners: readonly DeclaredOwner[],\n authors: readonly OwnershipAuthor[],\n aliases: OwnerAliases = {},\n): readonly OwnerResolution[] => {\n const resolve = createIdentityResolver(aliases);\n return owners.map((owner) => resolve(owner, authors));\n};\n","import type {\n DeclaredOwner,\n FileOwnershipAudit,\n OwnershipAudit,\n ParsedCodeowners,\n} from \"../domain/codeowners.js\";\nimport { declaredOwnerKey } from \"../domain/codeowners.js\";\nimport {\n classifyOwnershipStatus,\n isCriticalFile,\n resolveCriticalityPolicy,\n} from \"../domain/classify.js\";\nimport type { CriticalityEvidence, CriticalityPolicyOptions } from \"../domain/classify.js\";\nimport { isActiveOwnerResolution, isVerifiableOwnerResolution } from \"../domain/identity.js\";\nimport type { OwnerAliases, OwnershipAuthor } from \"../domain/identity.js\";\nimport {\n computeOwnershipMetrics,\n sortFileOwnershipAudits,\n summarizeGhostOwners,\n} from \"../domain/metrics.js\";\nimport type { GhostOwnerCandidate } from \"../domain/metrics.js\";\nimport { createCodeownersMatcher } from \"../domain/matcher.js\";\nimport { createIdentityResolver, isBotAuthor } from \"./resolve-identities.js\";\n\n/** Design default: at least two lifetime commits touching the file before a verdict is worth anything. */\nexport const DEFAULT_MIN_COMMITS = 2;\n\nconst NO_CODEOWNERS_WARNING = \"No CODEOWNERS file was found; the ownership audit is unavailable.\";\n\nexport type OwnershipFileEvidence = {\n filePath: string;\n /** Lifetime commits touching the file. */\n commits: number;\n /** Commits touching the file inside the activity window. */\n recentCommits: number;\n /** Lifetime commits per author. Bots never count as owner activity. */\n authors?: readonly OwnershipAuthor[];\n /** Commits per author inside the activity window. */\n recentAuthors?: readonly OwnershipAuthor[];\n lastCommitUnix?: number | null;\n busFactor?: number | null;\n /** Structural signals, already computed by the caller. Never imported from `code-graph`. */\n criticality?: CriticalityEvidence;\n};\n\nexport type AuditOwnershipInput = {\n /** `null` when no CODEOWNERS file was found; the audit degrades to `available: false`. */\n codeowners: ParsedCodeowners | null;\n /** Universe of files, from `git ls-files` on the audited ref. */\n trackedFiles: readonly string[];\n /** Per-file history projected onto the lifetime and activity-window horizons. */\n evidence?: readonly OwnershipFileEvidence[];\n /** Identity aliases from `.codesentinel/owners.json`, already parsed by the caller. */\n aliases?: OwnerAliases;\n /** Minimum commits per file before a verdict is emitted. Defaults to `DEFAULT_MIN_COMMITS`. */\n minCommits?: number;\n /** Fan-in threshold for criticality. Defaults to `DEFAULT_FAN_IN_CRITICALITY_THRESHOLD`. */\n fanInCriticalityThreshold?: number;\n /** Warnings produced by the caller (for example, alias file problems), appended as-is. */\n warnings?: readonly string[];\n};\n\nconst compareText = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n\nconst roundTo = (value: number, decimals: number): number => {\n const factor = 10 ** decimals;\n return Math.round(value * factor) / factor;\n};\n\n/** Commits per non-bot author id, so duplicated evidence rows cannot skew the top author. */\nconst aggregateAuthors = (authors: readonly OwnershipAuthor[]): Map<string, number> => {\n const commitsByAuthor = new Map<string, number>();\n for (const author of authors) {\n if (isBotAuthor(author)) continue;\n commitsByAuthor.set(\n author.authorId,\n (commitsByAuthor.get(author.authorId) ?? 0) + author.commits,\n );\n }\n return commitsByAuthor;\n};\n\nconst pickTopAuthor = (\n commitsByAuthor: ReadonlyMap<string, number>,\n): { topAuthorId: string; topAuthorShare: number } | null => {\n let best: { id: string; commits: number } | null = null;\n let total = 0;\n\n for (const [authorId, commits] of commitsByAuthor) {\n total += commits;\n if (\n best === null ||\n commits > best.commits ||\n (commits === best.commits && authorId < best.id)\n ) {\n best = { id: authorId, commits };\n }\n }\n\n if (best === null || total <= 0) return null;\n return { topAuthorId: best.id, topAuthorShare: roundTo(best.commits / total, 4) };\n};\n\nconst countDistinct = (values: readonly string[]): number => new Set(values).size;\n\nconst plural = (count: number, singular: string, pluralForm: string): string =>\n `${count} ${count === 1 ? singular : pluralForm}`;\n\n/**\n * Crosses declared ownership (CODEOWNERS) with observed ownership across two horizons.\n *\n * Lifetime history decides whether there is enough evidence and identifies the owner of a dormant\n * file. Window activity decides whether a declared owner is still active; a file untouched in the\n * window is never a ghost, because silence there is not proof of abandonment. Pure and offline: it\n * receives the tracked file list, per-file history and structural signals already computed\n * elsewhere, and returns a fully ordered, deterministic audit. No filesystem, no network, no clock.\n * Two runs over the same input produce byte-identical JSON.\n *\n * `ghosted` is only emitted for a file with window activity when every declared owner is\n * verifiable (no unexpanded team, no stale alias map) and none of them shows activity in the\n * window. Otherwise the file is `unknown` and the reason appears in `warnings`.\n */\nexport const auditOwnership = (input: AuditOwnershipInput): OwnershipAudit => {\n const callerWarnings = input.warnings ?? [];\n\n if (input.codeowners === null) {\n return {\n available: false,\n reason: \"codeowners_not_found\",\n warnings: [...callerWarnings, NO_CODEOWNERS_WARNING],\n };\n }\n\n const codeowners: ParsedCodeowners = input.codeowners;\n const minCommits = input.minCommits ?? DEFAULT_MIN_COMMITS;\n const criticalityOptions: CriticalityPolicyOptions =\n input.fanInCriticalityThreshold === undefined\n ? {}\n : { fanInThreshold: input.fanInCriticalityThreshold };\n\n const trackedFiles = [...new Set(input.trackedFiles)].sort(compareText);\n const trackedFileSet = new Set(trackedFiles);\n\n const evidenceByPath = new Map<string, OwnershipFileEvidence>();\n const warnings: string[] = [...callerWarnings];\n let duplicatedEvidence = 0;\n let evidenceOutsideUniverse = 0;\n\n for (const item of input.evidence ?? []) {\n if (!trackedFileSet.has(item.filePath)) {\n evidenceOutsideUniverse += 1;\n continue;\n }\n if (evidenceByPath.has(item.filePath)) {\n duplicatedEvidence += 1;\n continue;\n }\n evidenceByPath.set(item.filePath, item);\n }\n\n const evidenceItems = trackedFiles\n .map((filePath) => evidenceByPath.get(filePath))\n .filter((item): item is OwnershipFileEvidence => item !== undefined);\n\n const policy = resolveCriticalityPolicy(\n evidenceItems.map((item) => item.criticality ?? {}),\n criticalityOptions,\n );\n const matcher = createCodeownersMatcher(codeowners.entries);\n const resolveOwner = createIdentityResolver(input.aliases ?? {});\n\n const files: FileOwnershipAudit[] = [];\n const ghostCandidates: GhostOwnerCandidate[] = [];\n const teamKeys = new Set<string>();\n const unresolvedAliasKeys = new Set<string>();\n let filesWithoutAuthorEvidence = 0;\n\n for (const filePath of trackedFiles) {\n const item = evidenceByPath.get(filePath);\n const entry = matcher(filePath);\n const declared: readonly DeclaredOwner[] = entry?.owners ?? [];\n const authors = item?.authors ?? [];\n const recentAuthors = item?.recentAuthors ?? [];\n const commits = item?.commits ?? 0;\n const recentCommits = item?.recentCommits ?? 0;\n\n const lifetimeResolutions = declared.map((owner) => resolveOwner(owner, authors));\n const recentResolutions = declared.map((owner) => resolveOwner(owner, recentAuthors));\n const usesLifetimeHorizon = recentCommits === 0;\n const resolutions = usesLifetimeHorizon ? lifetimeResolutions : recentResolutions;\n const horizonAuthors = usesLifetimeHorizon ? authors : recentAuthors;\n const dormant = usesLifetimeHorizon && commits > 0;\n\n for (const resolution of resolutions) {\n if (resolution.kind === \"team_unverified\") teamKeys.add(declaredOwnerKey(resolution.owner));\n if (resolution.kind === \"alias_unresolved\") {\n unresolvedAliasKeys.add(declaredOwnerKey(resolution.owner));\n }\n }\n\n const commitsByAuthor = aggregateAuthors(horizonAuthors);\n const top = pickTopAuthor(commitsByAuthor);\n const hasAuthorEvidence = commitsByAuthor.size > 0;\n const isCritical = isCriticalFile(item?.criticality, policy);\n\n const status = classifyOwnershipStatus({\n declaredCount: declared.length,\n isCritical,\n commits,\n recentCommits,\n minCommits,\n topAuthorId: top?.topAuthorId ?? null,\n hasAuthorEvidence,\n resolutions,\n });\n\n if (declared.length > 0 && commits >= minCommits && !hasAuthorEvidence) {\n filesWithoutAuthorEvidence += 1;\n }\n\n if (declared.length > 0 && commits >= minCommits && recentCommits > 0) {\n for (const resolution of recentResolutions) {\n if (!isActiveOwnerResolution(resolution) && isVerifiableOwnerResolution(resolution)) {\n ghostCandidates.push({ owner: resolution.owner, filePath });\n }\n }\n }\n\n files.push({\n filePath,\n declared,\n matchLine: entry === null ? null : entry.line,\n status,\n observed: {\n commits,\n recentCommits,\n dormant,\n authors: countDistinct(authors.map((author) => author.authorId)),\n topAuthorId: top?.topAuthorId ?? null,\n topAuthorShare: top?.topAuthorShare ?? null,\n busFactor: item?.busFactor ?? null,\n lastCommitUnix: item?.lastCommitUnix ?? null,\n },\n criticality: {\n fanIn: item?.criticality?.fanIn ?? null,\n isHotspot: item?.criticality?.isHotspot === true,\n riskScore: item?.criticality?.riskScore ?? null,\n isCritical,\n },\n });\n }\n\n const sortedFiles = sortFileOwnershipAudits(files);\n const ghostOwners = summarizeGhostOwners(ghostCandidates);\n\n if (!policy.structuralDataAvailable) {\n warnings.push(\n \"No structural analysis available: criticality falls back to hotspots and churn (p90).\",\n );\n }\n if (teamKeys.size > 0) {\n warnings.push(\n `${plural(teamKeys.size, \"team owner\", \"team owners\")} cannot be verified offline; ` +\n \"teams are never reported as ghost owners.\",\n );\n }\n if (unresolvedAliasKeys.size > 0) {\n warnings.push(\n `${plural(unresolvedAliasKeys.size, \"declared owner has\", \"declared owners have\")} identity ` +\n \"aliases that were not observed in the relevant history; their files are never reported as ghost owners.\",\n );\n }\n if (filesWithoutAuthorEvidence > 0) {\n warnings.push(\n `${plural(filesWithoutAuthorEvidence, \"declared file has\", \"declared files have\")} commits ` +\n \"but no human author evidence; they are reported as unknown.\",\n );\n }\n if (duplicatedEvidence > 0) {\n warnings.push(\n `Ignored ${plural(duplicatedEvidence, \"duplicate file evidence entry\", \"duplicate file evidence entries\")}: ` +\n \"the first entry per path wins.\",\n );\n }\n if (evidenceOutsideUniverse > 0) {\n warnings.push(\n `Ignored ${plural(evidenceOutsideUniverse, \"file evidence entry\", \"file evidence entries\")} ` +\n \"outside the tracked universe.\",\n );\n }\n\n const metrics = computeOwnershipMetrics({\n files: sortedFiles,\n trackedFileCount: trackedFiles.length,\n ghostOwnerCount: ghostOwners.length,\n });\n\n return {\n available: true,\n codeowners,\n metrics,\n ghostOwners,\n files: sortedFiles,\n warnings,\n };\n};\n","import { execFileSync } from \"node:child_process\";\nimport type { OwnershipAuthor, OwnershipFileEvidence } from \"@codesentinel/ownership\";\n\n/**\n * Git access for the `owners` command. Everything read here is pinned to a ref, so the audit\n * measures the revision CI names and not whatever happens to be in the working tree.\n *\n * This is the only place in the command that shells out; the audit itself stays pure.\n */\n\nconst RECORD_SEPARATOR = \"\\u001e\";\nconst FIELD_SEPARATOR = \"\\u001f\";\nconst LOG_FORMAT = `%x1e%at${FIELD_SEPARATOR}%an${FIELD_SEPARATOR}%ae`;\nconst MAX_BUFFER_BYTES = 1024 * 1024 * 256;\n\nexport type OwnersGitErrorCode =\n \"not_a_git_repository\" | \"empty_repository\" | \"unknown_ref\" | \"git_failed\";\n\nexport class OwnersGitError extends Error {\n readonly code: OwnersGitErrorCode;\n\n constructor(code: OwnersGitErrorCode, message: string) {\n super(message);\n this.name = \"OwnersGitError\";\n this.code = code;\n }\n}\n\nexport type RepositorySnapshot = {\n /** Absolute path to the repository root, which is also the CODEOWNERS and path universe root. */\n repositoryPath: string;\n ref: string;\n /** Authored time of the ref commit. Anchors the observation window so runs are reproducible. */\n commitUnix: number;\n /** Tracked files at the ref, in ascending path order. */\n trackedFiles: readonly string[];\n};\n\nconst gitErrorMessage = (error: unknown): string => {\n if (error instanceof Error) {\n const stderr = \"stderr\" in error ? (error as { stderr?: unknown }).stderr : undefined;\n const trimmed = typeof stderr === \"string\" ? stderr.trim() : \"\";\n if (trimmed.length > 0) return trimmed;\n return error.message;\n }\n return \"unknown git execution error\";\n};\n\nconst runGit = (repositoryPath: string, args: readonly string[]): string => {\n try {\n return execFileSync(\"git\", [\"-C\", repositoryPath, ...args], {\n encoding: \"utf8\",\n maxBuffer: MAX_BUFFER_BYTES,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") {\n throw new OwnersGitError(\"git_failed\", \"git is not available on PATH.\");\n }\n throw new OwnersGitError(\"git_failed\", gitErrorMessage(error));\n }\n};\n\nconst splitLines = (value: string): string[] =>\n value\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n\n/**\n * Mirrors `normalizeAuthorIdentity` in `@codesentinel/git-analyzer` (not exported from that\n * package): numeric-prefixed GitHub noreply addresses collapse to `<handle>@users.noreply.github.com`\n * and bots keep their marker, so declared handles can be compared against history.\n */\nexport const normalizeGitAuthorIdentity = (authorName: string, authorEmail: string): string => {\n const normalizedName = authorName.trim().replace(/\\s+/g, \" \").toLowerCase();\n const normalizedEmail = authorEmail.trim().toLowerCase();\n\n if (/\\[bot\\]/i.test(normalizedName) || /\\[bot\\]/i.test(normalizedEmail)) {\n return normalizedEmail.length > 0 ? normalizedEmail : normalizedName;\n }\n\n const githubNoReplyMatch = normalizedEmail.match(/^\\d+\\+([^@]+)@users\\.noreply\\.github\\.com$/);\n const githubHandle = githubNoReplyMatch?.[1]?.trim().toLowerCase();\n if (githubHandle !== undefined && githubHandle.length > 0) {\n return `${githubHandle}@users.noreply.github.com`;\n }\n\n if (normalizedEmail.length > 0) {\n return normalizedEmail;\n }\n\n return normalizedName;\n};\n\nexport const normalizeRepositoryPath = (value: string): string => {\n let normalized = value.replace(/\\\\/g, \"/\").trim();\n while (normalized.startsWith(\"./\")) normalized = normalized.slice(2);\n return normalized.replace(/^\\/+/, \"\");\n};\n\nconst parseInteger = (value: string): number | null => {\n if (value.length === 0) return null;\n const parsed = Number.parseInt(value, 10);\n return Number.isNaN(parsed) ? null : parsed;\n};\n\n/**\n * A rename in `git log --numstat` arrives as `old => new` or `dir/{old => new}/file`. The\n * destination is what the current tree tracks, so that is the path the audit counts.\n */\nconst parseRenamedPath = (pathSpec: string): string => {\n if (!pathSpec.includes(\" => \")) return pathSpec;\n\n const braceRenameMatch = pathSpec.match(/^(.*)\\{(.+) => (.+)\\}(.*)$/);\n if (braceRenameMatch !== null) {\n const [, prefix, , renamedTo, suffix] = braceRenameMatch;\n return `${prefix}${renamedTo}${suffix}`;\n }\n\n const parts = pathSpec.split(\" => \");\n return parts[parts.length - 1] ?? pathSpec;\n};\n\n/**\n * Resolves the ref and lists the tracked tree at it. `git ls-tree -r` is the ref-pinned\n * equivalent of `git ls-files`: directories, binaries and untracked files are out of scope.\n */\nexport const readRepositorySnapshot = (targetPath: string, ref: string): RepositorySnapshot => {\n const inside = runGit(targetPath, [\"rev-parse\", \"--is-inside-work-tree\"]).trim();\n if (inside !== \"true\") {\n throw new OwnersGitError(\n \"not_a_git_repository\",\n `\"${targetPath}\" is not inside a git work tree.`,\n );\n }\n\n const repositoryPath = runGit(targetPath, [\"rev-parse\", \"--show-toplevel\"]).trim();\n if (repositoryPath.length === 0) {\n throw new OwnersGitError(\"not_a_git_repository\", `\"${targetPath}\" has no git work tree root.`);\n }\n\n const commitUnixRaw = runGit(repositoryPath, [\"log\", \"-1\", \"--format=%ct\", ref]).trim();\n const commitUnix = parseInteger(commitUnixRaw);\n if (commitUnix === null) {\n throw new OwnersGitError(\n \"unknown_ref\",\n `ref \"${ref}\" does not resolve to a commit in \"${repositoryPath}\".`,\n );\n }\n\n const trackedFiles = splitLines(\n runGit(repositoryPath, [\"ls-tree\", \"-r\", \"-z\", \"--name-only\", ref]).split(\"\\u0000\").join(\"\\n\"),\n ).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n\n if (trackedFiles.length === 0) {\n throw new OwnersGitError(\n \"empty_repository\",\n `ref \"${ref}\" has no tracked files, so there is nothing to audit.`,\n );\n }\n\n return { repositoryPath, ref, commitUnix, trackedFiles };\n};\n\n/** Reads one file exactly as the ref stores it. Callers must have seen the path in the tree. */\nexport const readTextAtRef = (repositoryPath: string, ref: string, filePath: string): string =>\n runGit(repositoryPath, [\"show\", `${ref}:${filePath}`]);\n\nexport type OwnershipEvidence = {\n /** One entry per file with at least one lifetime commit, ascending by path. */\n files: readonly OwnershipFileEvidence[];\n /** Epoch seconds the window starts at, derived from the ref commit. */\n sinceUnix: number;\n};\n\n/** Per-author accumulator for a single file: commits plus the raw name used for identity matching. */\ntype AuthorAccumulator = { authorName: string; commits: number };\n\ntype FileAccumulator = {\n commits: number;\n recentCommits: number;\n churnTotal: number;\n lastCommitUnix: number;\n authors: Map<string, AuthorAccumulator>;\n recentAuthors: Map<string, AuthorAccumulator>;\n};\n\nconst accumulateAuthor = (\n authors: Map<string, AuthorAccumulator>,\n authorId: string,\n authorName: string,\n): void => {\n const author = authors.get(authorId) ?? { authorName, commits: 0 };\n authors.set(authorId, { authorName: author.authorName, commits: author.commits + 1 });\n};\n\nconst toOwnershipAuthors = (\n authors: ReadonlyMap<string, AuthorAccumulator>,\n): readonly OwnershipAuthor[] =>\n [...authors.entries()]\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([authorId, value]) => ({\n authorId,\n authorName: value.authorName,\n commits: value.commits,\n }));\n\n/**\n * Builds per-file authorship evidence for both horizons in a single pass over full history.\n *\n * `commits` and `authors` cover the file's lifetime; `recentCommits` and `recentAuthors` cover\n * `[refCommit - windowDays, refCommit]`. The window is anchored to the ref commit and not to the\n * wall clock: two runs against the same ref therefore see the same commits, which is what makes\n * the JSON reproducible and lets a CI run and a local baseline agree.\n *\n * `criticality.churnTotal` deliberately keeps its window-only semantics, so the criticality\n * fallback still measures recent churn rather than the whole history.\n *\n * Rename detection is disabled so a rename shows up as a delete plus an add instead of a\n * brace-expanded path that would not resolve against the tracked tree.\n */\nexport const collectOwnershipEvidence = (\n snapshot: RepositorySnapshot,\n windowDays: number,\n): OwnershipEvidence => {\n const sinceUnix = snapshot.commitUnix - windowDays * 86_400;\n const rawLog = runGit(snapshot.repositoryPath, [\n \"-c\",\n \"core.quotepath=false\",\n \"log\",\n snapshot.ref,\n \"--no-merges\",\n \"--no-renames\",\n \"--numstat\",\n `--pretty=format:${LOG_FORMAT}`,\n ]);\n\n const trackedFileSet = new Set(snapshot.trackedFiles);\n const filesByPath = new Map<string, FileAccumulator>();\n\n const records = rawLog\n .split(RECORD_SEPARATOR)\n .map((record) => record.trim())\n .filter((record) => record.length > 0);\n\n for (const record of records) {\n const lines = record\n .split(\"\\n\")\n .map((line) => line.trimEnd())\n .filter((line) => line.length > 0);\n const header = lines[0];\n if (header === undefined) continue;\n\n const [authoredAtRaw, authorName, authorEmail] = header.split(FIELD_SEPARATOR);\n if (authoredAtRaw === undefined || authorName === undefined || authorEmail === undefined) {\n continue;\n }\n\n const authoredAtUnix = parseInteger(authoredAtRaw);\n if (authoredAtUnix === null) continue;\n\n const authorId = normalizeGitAuthorIdentity(authorName, authorEmail);\n const insideWindow = authoredAtUnix >= sinceUnix;\n\n for (const line of lines.slice(1)) {\n const parts = line.split(\"\\t\");\n if (parts.length < 3) continue;\n\n const [additionsRaw, deletionsRaw] = parts;\n if (additionsRaw === undefined || deletionsRaw === undefined) continue;\n\n const filePath = parseRenamedPath(parts.slice(2).join(\"\\t\"));\n if (!trackedFileSet.has(filePath)) continue;\n\n const accumulator = filesByPath.get(filePath) ?? {\n commits: 0,\n recentCommits: 0,\n churnTotal: 0,\n lastCommitUnix: authoredAtUnix,\n authors: new Map<string, AuthorAccumulator>(),\n recentAuthors: new Map<string, AuthorAccumulator>(),\n };\n\n accumulator.commits += 1;\n accumulator.lastCommitUnix = Math.max(accumulator.lastCommitUnix, authoredAtUnix);\n accumulateAuthor(accumulator.authors, authorId, authorName);\n\n if (insideWindow) {\n const additions = additionsRaw === \"-\" ? 0 : (parseInteger(additionsRaw) ?? 0);\n const deletions = deletionsRaw === \"-\" ? 0 : (parseInteger(deletionsRaw) ?? 0);\n\n accumulator.recentCommits += 1;\n accumulator.churnTotal += additions + deletions;\n accumulateAuthor(accumulator.recentAuthors, authorId, authorName);\n }\n\n filesByPath.set(filePath, accumulator);\n }\n }\n\n const files: OwnershipFileEvidence[] = [];\n for (const filePath of [...filesByPath.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))) {\n const accumulator = filesByPath.get(filePath);\n if (accumulator === undefined) continue;\n\n files.push({\n filePath,\n commits: accumulator.commits,\n recentCommits: accumulator.recentCommits,\n authors: toOwnershipAuthors(accumulator.authors),\n recentAuthors: toOwnershipAuthors(accumulator.recentAuthors),\n lastCommitUnix: accumulator.lastCommitUnix,\n criticality: { churnTotal: accumulator.churnTotal },\n });\n }\n\n return { files, sinceUnix };\n};\n","import { join } from \"node:path\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport {\n compareSnapshots,\n createReport,\n formatReport,\n parseSnapshot,\n type CodeSentinelReport,\n type ReportFormat,\n} from \"@codesentinel/reporter\";\nimport { type AuthorIdentityCliMode, type ScoringProfileCliMode } from \"./run-analyze-command.js\";\nimport { createSilentLogger, type Logger } from \"./logger.js\";\nimport { buildAnalysisSnapshot } from \"./build-analysis-snapshot.js\";\nimport { writeHtmlReportBundle } from \"./html-report.js\";\nimport { openPath } from \"./open-path.js\";\nimport { buildReportOwnership } from \"./report-ownership.js\";\n\nexport type ReportOutputFormat = ReportFormat | \"html\";\n\nexport type ReportCommandOptions = {\n format: ReportOutputFormat;\n comparePath?: string;\n outputPath?: string;\n snapshotPath?: string;\n open?: boolean;\n includeTrace: boolean;\n recentWindowDays?: number;\n scoringProfile?: ScoringProfileCliMode;\n};\n\nexport const runReportCommand = async (\n inputPath: string | undefined,\n authorIdentityMode: AuthorIdentityCliMode,\n options: ReportCommandOptions,\n logger: Logger = createSilentLogger(),\n): Promise<{ report: CodeSentinelReport; rendered: string; outputPath?: string }> => {\n logger.info(\"building analysis snapshot\");\n const current = await buildAnalysisSnapshot(\n inputPath,\n authorIdentityMode,\n {\n includeTrace: options.includeTrace,\n ...(options.scoringProfile === undefined ? {} : { scoringProfile: options.scoringProfile }),\n ...(options.recentWindowDays === undefined\n ? {}\n : { recentWindowDays: options.recentWindowDays }),\n },\n logger,\n );\n\n if (options.snapshotPath !== undefined) {\n await writeFile(options.snapshotPath, JSON.stringify(current, null, 2), \"utf8\");\n logger.info(`snapshot written: ${options.snapshotPath}`);\n }\n\n const { ownership, webUrl } = await buildReportOwnership(\n current.analysis.structural.targetPath,\n logger,\n );\n const extras = { ownership, repositoryWebUrl: webUrl };\n\n let report: CodeSentinelReport;\n if (options.comparePath === undefined) {\n report = createReport(current, undefined, extras);\n } else {\n logger.info(`loading baseline snapshot: ${options.comparePath}`);\n const baselineRaw = await readFile(options.comparePath, \"utf8\");\n const baseline = parseSnapshot(baselineRaw);\n const diff = compareSnapshots(current, baseline);\n report = createReport(current, diff, extras);\n }\n\n if (options.format === \"html\") {\n const bundlePath = await writeHtmlReportBundle(report, {\n repositoryPath: current.analysis.structural.targetPath,\n ...(options.outputPath === undefined ? {} : { outputPath: options.outputPath }),\n });\n if (options.open === true) {\n const opened = await openPath(join(bundlePath, \"index.html\"));\n if (!opened) {\n logger.warn(\"unable to open html report automatically on this platform\");\n }\n }\n logger.info(`html report written: ${bundlePath}`);\n return {\n report,\n rendered: bundlePath,\n outputPath: bundlePath,\n };\n }\n\n const rendered = formatReport(report, options.format);\n\n if (options.outputPath !== undefined) {\n await writeFile(options.outputPath, rendered, \"utf8\");\n logger.info(`report written: ${options.outputPath}`);\n }\n\n return {\n report,\n rendered,\n ...(options.outputPath === undefined ? {} : { outputPath: options.outputPath }),\n };\n};\n","import { mkdir, readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { CodeSentinelReport } from \"@codesentinel/reporter\";\n\nconst HTML_REPORT_DIR = \".codesentinel/report\";\n\nconst getBundledHtmlAppPath = (): string =>\n resolve(dirname(fileURLToPath(import.meta.url)), \"html-report-app\");\n\nconst serializeReportBootstrap = (report: CodeSentinelReport): string =>\n `window.__CODESENTINEL_REPORT__ = ${JSON.stringify(report).replaceAll(\"</\", \"<\\\\/\")};\\n`;\n\nconst escapeInlineScript = (script: string): string =>\n script\n .replaceAll(\"</script\", \"<\\\\/script\")\n .replaceAll(\"<script\", \"\\\\x3Cscript\")\n .replaceAll(\"<!--\", \"\\\\x3C!--\")\n .replaceAll(\"\\u2028\", \"\\\\u2028\")\n .replaceAll(\"\\u2029\", \"\\\\u2029\");\n\nconst ensureDirectory = async (directoryPath: string): Promise<void> => {\n await mkdir(directoryPath, { recursive: true });\n};\n\nconst readReferencedAssets = async (\n appPath: string,\n indexHtml: string,\n): Promise<{ styles: string[]; scripts: string[] }> => {\n const stylesheetPaths = [\n ...indexHtml.matchAll(/<link[^>]+rel=[\"']stylesheet[\"'][^>]+href=[\"']([^\"']+)[\"'][^>]*>/g),\n ]\n .map((match) => match[1])\n .filter(\n (value): value is string =>\n value !== undefined && !/^https?:\\/\\//.test(value) && !value.startsWith(\"//\"),\n );\n\n const styles = await Promise.all(\n stylesheetPaths.map(async (href) => readFile(resolve(appPath, href), \"utf8\")),\n );\n\n const scriptPaths = [...indexHtml.matchAll(/<script[^>]+src=[\"']([^\"']+)[\"'][^>]*><\\/script>/g)]\n .map((match) => match[1])\n .filter(\n (value): value is string =>\n value !== undefined && !/^https?:\\/\\//.test(value) && !value.startsWith(\"//\"),\n );\n\n const scripts = await Promise.all(\n scriptPaths.map(async (src) => readFile(resolve(appPath, src), \"utf8\")),\n );\n\n return { styles, scripts };\n};\n\nconst inlineBuiltHtml = async (appPath: string, report: CodeSentinelReport): Promise<string> => {\n const indexHtml = await readFile(resolve(appPath, \"index.html\"), \"utf8\");\n const { styles, scripts } = await readReferencedAssets(appPath, indexHtml);\n\n const htmlWithoutExternalAssets = indexHtml\n .replace(/\\s*<link[^>]+rel=[\"']stylesheet[\"'][^>]*>\\s*/g, (tag) =>\n /href=[\"'](https?:)?\\/\\//.test(tag) ? tag : \"\",\n )\n .replace(/\\s*<script[^>]+src=[\"'][^\"']+[\"'][^>]*><\\/script>\\s*/g, (tag) =>\n /src=[\"'](https?:)?\\/\\//.test(tag) ? tag : \"\",\n );\n\n const inlineStyles = styles.map((style) => `<style>\\n${style}\\n</style>`).join(\"\\n\");\n const bootstrapScript = `<script>\\n${serializeReportBootstrap(report)}</script>`;\n const inlineScripts = scripts\n .map((script) => `<script>\\n${escapeInlineScript(script)}\\n</script>`)\n .join(\"\\n\");\n\n return htmlWithoutExternalAssets\n .replace(\"</head>\", () => `${inlineStyles === \"\" ? \"\" : `${inlineStyles}\\n`}</head>`)\n .replace(\n \"</body>\",\n () => `${bootstrapScript}\\n${inlineScripts === \"\" ? \"\" : `${inlineScripts}\\n`}</body>`,\n );\n};\n\nconst assertHtmlAppAssets = async (assetPath: string): Promise<void> => {\n const assetStats = await stat(assetPath).catch(() => undefined);\n if (assetStats === undefined || !assetStats.isDirectory()) {\n throw new Error(\n `html_report_assets_missing: expected built app at ${assetPath}. Run the workspace build first.`,\n );\n }\n};\n\nexport type WriteHtmlReportBundleOptions = {\n repositoryPath: string;\n outputPath?: string;\n bundledAppPath?: string;\n};\n\nexport const resolveHtmlReportOutputPath = (\n repositoryPath: string,\n outputPath?: string,\n): string => {\n const invocationCwd = process.env[\"INIT_CWD\"] ?? process.cwd();\n return resolve(invocationCwd, outputPath ?? join(repositoryPath, HTML_REPORT_DIR));\n};\n\nexport const writeHtmlReportBundle = async (\n report: CodeSentinelReport,\n options: WriteHtmlReportBundleOptions,\n): Promise<string> => {\n const bundledAppPath = options.bundledAppPath ?? getBundledHtmlAppPath();\n await assertHtmlAppAssets(bundledAppPath);\n\n const outputPath = resolveHtmlReportOutputPath(options.repositoryPath, options.outputPath);\n await rm(outputPath, { recursive: true, force: true });\n await ensureDirectory(outputPath);\n await writeFile(\n resolve(outputPath, \"index.html\"),\n await inlineBuiltHtml(bundledAppPath, report),\n \"utf8\",\n );\n\n return outputPath;\n};\n","import { spawn } from \"node:child_process\";\nimport { platform } from \"node:os\";\n\nconst openCommandForPlatform = (\n targetPath: string,\n): { command: string; args: string[] } | undefined => {\n switch (platform()) {\n case \"darwin\":\n return { command: \"open\", args: [targetPath] };\n case \"win32\":\n return { command: \"cmd\", args: [\"/c\", \"start\", \"\", targetPath] };\n case \"linux\":\n return { command: \"xdg-open\", args: [targetPath] };\n default:\n return undefined;\n }\n};\n\nexport const openPath = async (targetPath: string): Promise<boolean> => {\n const command = openCommandForPlatform(targetPath);\n if (command === undefined) {\n return false;\n }\n\n return new Promise((resolve) => {\n const child = spawn(command.command, command.args, {\n detached: true,\n stdio: \"ignore\",\n });\n\n child.once(\"error\", () => resolve(false));\n child.once(\"spawn\", () => {\n child.unref();\n resolve(true);\n });\n });\n};\n","import { execFileSync } from \"node:child_process\";\nimport type { OwnershipAudit } from \"@codesentinel/ownership\";\nimport type { OwnershipAuditReport } from \"@codesentinel/reporter\";\nimport { buildOwnershipAudit } from \"./build-ownership-audit.js\";\nimport type { Logger } from \"./logger.js\";\n\nconst stripGitSuffix = (path: string): string => path.replace(/\\.git\\/?$/i, \"\").replace(/\\/+$/, \"\");\n\nexport const normalizeRepositoryWebUrl = (raw: string): string | null => {\n const value = raw.trim();\n if (value.length === 0) {\n return null;\n }\n\n if (!value.includes(\"://\")) {\n const scpMatch = value.match(/^(?:[^@\\s]+@)?([^:/\\s]+):(.+)$/);\n if (scpMatch === null) {\n return null;\n }\n\n const host = scpMatch[1];\n const path = stripGitSuffix(scpMatch[2] ?? \"\").replace(/^\\/+/, \"\");\n if (host === undefined || path.length === 0) {\n return null;\n }\n return `https://${host}/${path}`;\n }\n\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return null;\n }\n\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\" && url.protocol !== \"ssh:\") {\n return null;\n }\n\n const path = stripGitSuffix(url.pathname).replace(/^\\/+/, \"\");\n if (url.hostname.length === 0 || path.length === 0) {\n return null;\n }\n return `https://${url.hostname}/${path}`;\n};\n\nexport const readRepositoryWebUrl = (repositoryPath: string): string | null => {\n try {\n const raw = execFileSync(\n \"git\",\n [\"-C\", repositoryPath, \"config\", \"--get\", \"remote.origin.url\"],\n {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n },\n );\n return normalizeRepositoryWebUrl(raw);\n } catch {\n return null;\n }\n};\n\nexport const toOwnershipAuditReport = (audit: OwnershipAudit): OwnershipAuditReport => {\n if (!audit.available) {\n return {\n available: false,\n reason: audit.reason,\n warnings: audit.warnings,\n };\n }\n\n return {\n available: true,\n codeowners: {\n source: audit.codeowners.source,\n ignoredSources: audit.codeowners.ignoredSources,\n errors: audit.codeowners.errors,\n },\n metrics: audit.metrics,\n ghostOwners: audit.ghostOwners,\n files: audit.files,\n warnings: audit.warnings,\n };\n};\n\nexport const buildReportOwnership = async (\n repositoryPath: string,\n logger: Logger,\n): Promise<{ ownership: OwnershipAuditReport; webUrl: string | null }> => {\n const webUrl = readRepositoryWebUrl(repositoryPath);\n\n try {\n const { audit } = await buildOwnershipAudit(repositoryPath, {}, logger);\n return { ownership: toOwnershipAuditReport(audit), webUrl };\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown ownership audit error.\";\n logger.warn(`ownership audit unavailable: ${message}`);\n return {\n ownership: {\n available: false,\n reason: \"audit_unavailable\",\n warnings: [message],\n },\n webUrl,\n };\n }\n};\n","import type { AnalyzeSummary, RiskTrace, TargetTrace } from \"@codesentinel/core\";\nimport { computeRepositoryHealthSummary } from \"@codesentinel/health-engine\";\nimport { evaluateRepositoryRisk } from \"@codesentinel/risk-engine\";\nimport {\n collectAnalysisInputs,\n resolveHealthConfigForProfile,\n resolveRiskConfigForProfile,\n type AuthorIdentityCliMode,\n type ScoringProfileCliMode,\n} from \"./run-analyze-command.js\";\nimport { createSilentLogger, type Logger } from \"./logger.js\";\n\nexport type ExplainFormat = \"text\" | \"json\" | \"md\";\n\nexport type ExplainCommandOptions = {\n file?: string;\n module?: string;\n top: number;\n format: ExplainFormat;\n recentWindowDays?: number;\n scoringProfile?: ScoringProfileCliMode;\n};\n\nexport type ExplainResult = {\n summary: AnalyzeSummary;\n trace: RiskTrace;\n selectedTargets: readonly TargetTrace[];\n};\n\nconst selectTargets = (\n trace: RiskTrace,\n summary: AnalyzeSummary,\n options: ExplainCommandOptions,\n): readonly TargetTrace[] => {\n if (options.file !== undefined) {\n const normalized = options.file.replaceAll(\"\\\\\", \"/\");\n return trace.targets.filter(\n (target) => target.targetType === \"file\" && target.targetId === normalized,\n );\n }\n\n if (options.module !== undefined) {\n return trace.targets.filter(\n (target) => target.targetType === \"module\" && target.targetId === options.module,\n );\n }\n\n const top = Math.max(1, options.top);\n const topFiles = summary.risk.hotspots.slice(0, top).map((entry) => entry.file);\n const fileSet = new Set(topFiles);\n return trace.targets.filter(\n (target) =>\n target.targetType === \"repository\" ||\n (target.targetType === \"file\" && fileSet.has(target.targetId)),\n );\n};\n\nexport const runExplainCommand = async (\n inputPath: string | undefined,\n authorIdentityMode: AuthorIdentityCliMode,\n options: ExplainCommandOptions,\n logger: Logger = createSilentLogger(),\n): Promise<ExplainResult> => {\n const analysisInputs = await collectAnalysisInputs(\n inputPath,\n authorIdentityMode,\n {\n ...(options.recentWindowDays === undefined\n ? {}\n : { recentWindowDays: options.recentWindowDays }),\n },\n logger,\n );\n logger.info(\"computing explainable risk summary\");\n\n const riskConfig = resolveRiskConfigForProfile(options.scoringProfile);\n const healthConfig = resolveHealthConfigForProfile(options.scoringProfile);\n const evaluation = evaluateRepositoryRisk(\n {\n structural: analysisInputs.structural,\n evolution: analysisInputs.evolution,\n external: analysisInputs.external,\n ...(riskConfig === undefined ? {} : { config: riskConfig }),\n },\n { explain: true },\n );\n if (evaluation.trace === undefined) {\n throw new Error(\"risk trace unavailable\");\n }\n\n const summary: AnalyzeSummary = {\n structural: analysisInputs.structural,\n evolution: analysisInputs.evolution,\n external: analysisInputs.external,\n risk: evaluation.summary,\n health: computeRepositoryHealthSummary({\n structural: analysisInputs.structural,\n evolution: analysisInputs.evolution,\n ...(healthConfig === undefined ? {} : { config: healthConfig }),\n }),\n };\n logger.info(\n `explanation completed (riskScore=${summary.risk.riskScore}, healthScore=${summary.health.healthScore})`,\n );\n\n return {\n summary,\n trace: evaluation.trace,\n selectedTargets: selectTargets(evaluation.trace, summary, options),\n };\n};\n","import { writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { DEFAULT_MIN_COMMITS, type OwnershipAudit } from \"@codesentinel/ownership\";\nimport {\n buildOwnershipAudit,\n DEFAULT_OWNERS_REF,\n DEFAULT_OWNERS_WINDOW_DAYS,\n} from \"./build-ownership-audit.js\";\nimport {\n buildOwnersReport,\n evaluateOwnersThresholds,\n formatOwnersOutput,\n type OwnersOutputFormat,\n type OwnersReport,\n type OwnersThresholdConfig,\n} from \"./format-owners-output.js\";\nimport { createSilentLogger, type Logger } from \"./logger.js\";\n\nexport {\n DEFAULT_OWNERS_ALIASES_PATH,\n DEFAULT_OWNERS_REF,\n DEFAULT_OWNERS_WINDOW_DAYS,\n OwnersConfigurationError,\n} from \"./build-ownership-audit.js\";\n\n/**\n * Application layer for `codesentinel owners`: reads everything the audit needs from a git ref,\n * runs the pure audit and renders it.\n *\n * The command is offline by contract. The only inputs are the repository at `--ref`, the optional\n * versioned alias map and the structural analysis of the working tree.\n */\n\n/** ESLint-style exit codes fixed by the design, so a gate can tell \"problems\" from \"broken\". */\nexport const OWNERS_EXIT_CODES = {\n ok: 0,\n thresholdExceeded: 1,\n invalidConfiguration: 2,\n} as const;\n\nexport const DEFAULT_OWNERS_TOP = 10;\n\nexport type OwnersCommandOptions = {\n codeownersPath?: string;\n ref?: string;\n windowDays?: number;\n minCommits?: number;\n top?: number;\n format?: OwnersOutputFormat;\n outputPath?: string;\n aliasesPath?: string;\n resolveGithub?: boolean;\n thresholds?: Partial<OwnersThresholdConfig>;\n};\n\nexport type OwnersCommandResult = {\n audit: OwnershipAudit;\n report: OwnersReport;\n rendered: string;\n exitCode: number;\n trackedFileCount: number;\n outputPath?: string;\n};\n\nconst DEFAULT_THRESHOLDS: OwnersThresholdConfig = {\n failOn: \"none\",\n maxUnownedCritical: null,\n maxGhostOwners: null,\n maxDrift: null,\n};\n\nconst resolveTargetPath = (inputPath: string | undefined): string => {\n const invocationCwd = process.env[\"INIT_CWD\"] ?? process.cwd();\n return resolve(invocationCwd, inputPath ?? \".\");\n};\n\nconst normalizeThresholds = (\n input: Partial<OwnersThresholdConfig> | undefined,\n): OwnersThresholdConfig => ({\n failOn: input?.failOn ?? DEFAULT_THRESHOLDS.failOn,\n maxUnownedCritical: input?.maxUnownedCritical ?? DEFAULT_THRESHOLDS.maxUnownedCritical,\n maxGhostOwners: input?.maxGhostOwners ?? DEFAULT_THRESHOLDS.maxGhostOwners,\n maxDrift: input?.maxDrift ?? DEFAULT_THRESHOLDS.maxDrift,\n});\n\nconst resolveExitCode = (\n failOn: OwnersThresholdConfig[\"failOn\"],\n violationCount: number,\n): number => {\n if (failOn === \"none\" || violationCount === 0) {\n return OWNERS_EXIT_CODES.ok;\n }\n return failOn === \"error\" ? OWNERS_EXIT_CODES.thresholdExceeded : OWNERS_EXIT_CODES.ok;\n};\n\nexport const runOwnersCommand = async (\n inputPath: string | undefined,\n options: OwnersCommandOptions = {},\n logger: Logger = createSilentLogger(),\n): Promise<OwnersCommandResult> => {\n const targetPath = resolveTargetPath(inputPath);\n const ref = options.ref ?? DEFAULT_OWNERS_REF;\n const windowDays = options.windowDays ?? DEFAULT_OWNERS_WINDOW_DAYS;\n const minCommits = options.minCommits ?? DEFAULT_MIN_COMMITS;\n const top = options.top ?? DEFAULT_OWNERS_TOP;\n const format = options.format ?? \"console\";\n const thresholds = normalizeThresholds(options.thresholds);\n\n logger.info(`auditing declared ownership at ${ref} in ${targetPath}`);\n\n const callerWarnings: string[] = [];\n if (options.resolveGithub === true) {\n callerWarnings.push(\n \"--resolve-github is not implemented in this iteration; the audit stays offline and declared owners were resolved from local history only.\",\n );\n logger.warn(callerWarnings[callerWarnings.length - 1] ?? \"\");\n }\n\n const { audit, trackedFileCount } = await buildOwnershipAudit(\n targetPath,\n {\n ref,\n windowDays,\n minCommits,\n ...(options.codeownersPath === undefined ? {} : { codeownersPath: options.codeownersPath }),\n ...(options.aliasesPath === undefined ? {} : { aliasesPath: options.aliasesPath }),\n warnings: callerWarnings,\n },\n logger,\n );\n\n const metrics = audit.available ? audit.metrics : null;\n const violations = evaluateOwnersThresholds(metrics, thresholds);\n\n if (metrics === null && hasConfiguredThreshold(thresholds)) {\n logger.warn(\"no CODEOWNERS file was found; thresholds cannot be evaluated.\");\n }\n if (violations.length > 0) {\n for (const violation of violations) {\n logger.warn(`threshold exceeded (${thresholds.failOn}): ${violation.message}`);\n }\n }\n\n const report = buildOwnersReport({\n audit,\n ref,\n windowDays,\n minCommits,\n trackedFileCount,\n thresholds,\n violations,\n });\n const rendered = formatOwnersOutput(report, format, top);\n\n if (options.outputPath !== undefined) {\n await writeFile(options.outputPath, `${rendered}\\n`, \"utf8\");\n logger.info(`owners output written: ${options.outputPath}`);\n }\n\n return {\n audit,\n report,\n rendered,\n exitCode: resolveExitCode(thresholds.failOn, violations.length),\n trackedFileCount,\n ...(options.outputPath === undefined ? {} : { outputPath: options.outputPath }),\n };\n};\n\nconst hasConfiguredThreshold = (thresholds: OwnersThresholdConfig): boolean =>\n thresholds.maxUnownedCritical !== null ||\n thresholds.maxGhostOwners !== null ||\n thresholds.maxDrift !== null;\n","import type {\n DeclaredOwner,\n FileOwnershipAudit,\n OwnershipAudit,\n OwnershipAuditMetrics,\n OwnershipStatus,\n} from \"@codesentinel/ownership\";\n\n/**\n * Report payload and renderers for `codesentinel owners`.\n *\n * The payload is the JSON contract: fixed keys, fixed order, no timestamps, no clock. Console and\n * Markdown are rendered from the same object, so the three formats can never disagree.\n */\n\nexport const OWNERS_SCHEMA_VERSION = \"codesentinel.owners.v1\";\n\nexport type OwnersOutputFormat = \"console\" | \"json\" | \"md\";\n\nexport type OwnersFailOn = \"none\" | \"warn\" | \"error\";\n\nexport type OwnersThresholdConfig = {\n failOn: OwnersFailOn;\n maxUnownedCritical: number | null;\n maxGhostOwners: number | null;\n maxDrift: number | null;\n};\n\nexport type OwnersThresholdViolation = {\n threshold: \"max-unowned-critical\" | \"max-ghost-owners\" | \"max-drift\";\n limit: number;\n actual: number;\n message: string;\n};\n\nexport type OwnersReportCodeowners = {\n source: string;\n ignoredSources: readonly string[];\n entryCount: number;\n errorCount: number;\n errors: readonly { line: number; reason: string }[];\n};\n\nexport type OwnersReportFileCounts = {\n trackedFiles: number;\n declaredFiles: number;\n criticalFiles: number;\n declaredCriticalFiles: number;\n driftedFiles: number;\n};\n\nexport type OwnersReport = {\n schemaVersion: typeof OWNERS_SCHEMA_VERSION;\n available: boolean;\n ref: string;\n windowDays: number;\n minCommits: number;\n codeowners: OwnersReportCodeowners | null;\n fileCounts: OwnersReportFileCounts;\n metrics: OwnershipAuditMetrics | null;\n ghostOwners: readonly { owner: DeclaredOwner; samplePaths: readonly string[] }[];\n files: readonly FileOwnershipAudit[];\n warnings: readonly string[];\n thresholds: OwnersThresholdConfig & {\n violations: readonly OwnersThresholdViolation[];\n };\n};\n\nexport const formatDeclaredOwner = (owner: DeclaredOwner): string => {\n if (owner.kind === \"user\") return `@${owner.handle}`;\n if (owner.kind === \"team\") return `@${owner.org}/${owner.slug}`;\n return owner.address;\n};\n\nexport const formatDeclaredOwners = (owners: readonly DeclaredOwner[]): string =>\n owners.map(formatDeclaredOwner).join(\", \");\n\nconst compareText = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n\nconst countFileAudits = (\n files: readonly FileOwnershipAudit[],\n trackedFiles: number,\n): OwnersReportFileCounts => {\n const declaredFiles = files.filter((file) => file.declared.length > 0);\n return {\n trackedFiles,\n declaredFiles: declaredFiles.length,\n criticalFiles: files.filter((file) => file.criticality.isCritical).length,\n declaredCriticalFiles: files.filter(\n (file) => file.declared.length > 0 && file.criticality.isCritical,\n ).length,\n driftedFiles: declaredFiles.filter((file) => file.status === \"drifted\").length,\n };\n};\n\n/**\n * Thresholds are evaluated against the published metrics, never against a recomputed value, so\n * `--fail-on error` fails exactly what the output shows.\n */\nexport const evaluateOwnersThresholds = (\n metrics: OwnershipAuditMetrics | null,\n config: OwnersThresholdConfig,\n): readonly OwnersThresholdViolation[] => {\n if (metrics === null) {\n return [];\n }\n\n const violations: OwnersThresholdViolation[] = [];\n\n if (\n config.maxUnownedCritical !== null &&\n metrics.unownedCriticalCount > config.maxUnownedCritical\n ) {\n violations.push({\n threshold: \"max-unowned-critical\",\n limit: config.maxUnownedCritical,\n actual: metrics.unownedCriticalCount,\n message: `unowned critical files: ${metrics.unownedCriticalCount} (limit ${config.maxUnownedCritical})`,\n });\n }\n\n if (config.maxGhostOwners !== null && metrics.ghostOwnerCount > config.maxGhostOwners) {\n violations.push({\n threshold: \"max-ghost-owners\",\n limit: config.maxGhostOwners,\n actual: metrics.ghostOwnerCount,\n message: `ghost owners: ${metrics.ghostOwnerCount} (limit ${config.maxGhostOwners})`,\n });\n }\n\n if (config.maxDrift !== null) {\n const ratio = metrics.driftPercent / 100;\n if (ratio > config.maxDrift) {\n violations.push({\n threshold: \"max-drift\",\n limit: config.maxDrift,\n actual: ratio,\n message: `drift: ${metrics.driftPercent}% (limit ${formatRatio(config.maxDrift)})`,\n });\n }\n }\n\n return violations;\n};\n\nexport type BuildOwnersReportInput = {\n audit: OwnershipAudit;\n ref: string;\n windowDays: number;\n minCommits: number;\n trackedFileCount: number;\n thresholds: OwnersThresholdConfig;\n violations: readonly OwnersThresholdViolation[];\n};\n\nexport const buildOwnersReport = (input: BuildOwnersReportInput): OwnersReport => {\n const { audit } = input;\n const files = audit.available ? audit.files : [];\n const report: OwnersReport = {\n schemaVersion: OWNERS_SCHEMA_VERSION,\n available: audit.available,\n ref: input.ref,\n windowDays: input.windowDays,\n minCommits: input.minCommits,\n codeowners: audit.available\n ? {\n source: audit.codeowners.source,\n ignoredSources: [...audit.codeowners.ignoredSources].sort(compareText),\n entryCount: audit.codeowners.entries.length,\n errorCount: audit.codeowners.errors.length,\n errors: [...audit.codeowners.errors].sort((a, b) => a.line - b.line),\n }\n : null,\n fileCounts: countFileAudits(files, input.trackedFileCount),\n metrics: audit.available ? audit.metrics : null,\n ghostOwners: audit.available ? audit.ghostOwners : [],\n files,\n warnings: [...audit.warnings],\n thresholds: {\n ...input.thresholds,\n violations: [...input.violations],\n },\n };\n\n return report;\n};\n\nconst formatPercent = (value: number): string => {\n const rounded = Number.isInteger(value) ? value.toString() : value.toFixed(2);\n return `${rounded}%`;\n};\n\nconst formatRatio = (value: number): string => {\n const percent = Math.round(value * 100);\n return `${percent}%`;\n};\n\nconst formatShare = (share: number | null): string =>\n share === null ? \"n/a\" : `${Math.round(share * 100)}%`;\n\nconst plural = (count: number, singular: string, pluralForm: string): string =>\n `${count} ${count === 1 ? singular : pluralForm}`;\n\nconst padLabel = (label: string): string => `${label}:`.padEnd(26, \" \");\n\nconst topLimit = (value: number): number => (Number.isFinite(value) && value > 0 ? value : 0);\n\nconst renderConsoleSection = (\n title: string,\n lines: readonly string[],\n total: number,\n top: number,\n): string[] => {\n if (total === 0) {\n return [`${title}: none`];\n }\n\n const shown = lines.slice(0, topLimit(top));\n const remaining = total - shown.length;\n return [\n title,\n ...shown.map((line) => ` ${line}`),\n ...(remaining > 0 ? [` ... ${plural(remaining, \"more file\", \"more files\")}`] : []),\n ];\n};\n\nconst statusFiles = (\n files: readonly FileOwnershipAudit[],\n status: OwnershipStatus,\n): readonly FileOwnershipAudit[] => files.filter((file) => file.status === status);\n\nconst renderConsole = (report: OwnersReport, top: number): string => {\n const lines: string[] = [];\n lines.push(\n `Ownership audit — ${plural(report.fileCounts.trackedFiles, \"tracked file\", \"tracked files\")}, window ${report.windowDays}d, ref ${report.ref}`,\n );\n\n if (!report.available || report.metrics === null) {\n lines.push(\"\");\n lines.push(`No CODEOWNERS file was found at ${report.ref}.`);\n lines.push(\n \"Looked for .github/CODEOWNERS, CODEOWNERS and docs/CODEOWNERS. The ownership audit is unavailable.\",\n );\n appendWarnings(lines, report.warnings);\n return lines.join(\"\\n\");\n }\n\n const { metrics, fileCounts, codeowners } = report;\n const source = codeowners === null ? \"unknown\" : codeowners.source;\n const errors = codeowners === null ? 0 : codeowners.errorCount;\n lines.push(\n `CODEOWNERS ${source} · ${plural(codeowners?.entryCount ?? 0, \"entry\", \"entries\")} · ${plural(errors, \"invalid line\", \"invalid lines\")}`,\n );\n lines.push(\"\");\n lines.push(\n `${padLabel(\"Declared coverage\")}${formatPercent(metrics.declaredCoveragePercent)} (${fileCounts.declaredFiles}/${fileCounts.trackedFiles})`,\n );\n lines.push(\n `${padLabel(\"Critical coverage\")}${formatPercent(metrics.declaredCoverageCriticalPercent)} (${fileCounts.declaredCriticalFiles}/${fileCounts.criticalFiles})`,\n );\n lines.push(\n `${padLabel(\"Drift\")}${formatPercent(metrics.driftPercent)} (${fileCounts.driftedFiles}/${fileCounts.declaredFiles} declared files)`,\n );\n lines.push(\n `${padLabel(\"Owners without activity\")}${plural(metrics.ghostOwnerCount, \"owner\", \"owners\")}`,\n );\n lines.push(`${padLabel(\"Unowned critical\")}${metrics.unownedCriticalCount}`);\n lines.push(`${padLabel(\"Single-owner modules\")}${metrics.singleOwnerModuleCount}`);\n lines.push(\"\");\n\n const unownedCritical = statusFiles(report.files, \"unowned-critical\");\n lines.push(\n ...renderConsoleSection(\n \"Unowned critical\",\n unownedCritical.map(\n (file) =>\n `${file.filePath} fan-in ${file.criticality.fanIn ?? \"n/a\"} commits ${file.observed.commits} authors ${file.observed.authors}`,\n ),\n unownedCritical.length,\n top,\n ),\n );\n lines.push(\"\");\n\n const drifted = statusFiles(report.files, \"drifted\");\n lines.push(\n ...renderConsoleSection(\n \"Drift — declared owner is not the top recent author\",\n drifted.map(\n (file) =>\n `${file.filePath} declared ${formatDeclaredOwners(file.declared)} observed ${file.observed.topAuthorId ?? \"unknown\"} (${formatShare(file.observed.topAuthorShare)})`,\n ),\n drifted.length,\n top,\n ),\n );\n lines.push(\"\");\n\n const ghosts = report.ghostOwners;\n lines.push(\n ...renderConsoleSection(\n \"Ghost owners — declared, no commits in the window\",\n ghosts.map(\n (entry) =>\n `${formatDeclaredOwner(entry.owner)} ${entry.samplePaths.join(\", \") || \"no sample path\"}`,\n ),\n ghosts.length,\n top,\n ),\n );\n\n appendWarnings(lines, report.warnings);\n return lines.join(\"\\n\");\n};\n\nconst appendWarnings = (lines: string[], warnings: readonly string[]): void => {\n if (warnings.length === 0) return;\n lines.push(\"\");\n lines.push(\"Warnings\");\n for (const warning of warnings) {\n lines.push(` - ${warning}`);\n }\n};\n\nconst escapeTableCell = (value: string): string => value.replace(/\\|/g, \"\\\\|\");\n\nconst renderMarkdownTable = (header: readonly string[], rows: readonly string[][]): string[] => {\n const lines = [`| ${header.join(\" | \")} |`, `| ${header.map(() => \"---\").join(\" | \")} |`];\n for (const row of rows) {\n lines.push(`| ${row.map(escapeTableCell).join(\" | \")} |`);\n }\n return lines;\n};\n\nconst renderMarkdown = (report: OwnersReport, top: number): string => {\n const lines: string[] = [];\n lines.push(\"# Ownership audit\");\n lines.push(\"\");\n lines.push(`- ref: \\`${report.ref}\\``);\n lines.push(`- window: ${report.windowDays} days`);\n lines.push(`- tracked files: ${report.fileCounts.trackedFiles}`);\n lines.push(`- minimum commits per file: ${report.minCommits}`);\n\n if (!report.available || report.metrics === null) {\n lines.push(\"- CODEOWNERS: not found\");\n lines.push(\"\");\n lines.push(\n `No CODEOWNERS file was found at \\`${report.ref}\\` (looked for \\`.github/CODEOWNERS\\`, \\`CODEOWNERS\\` and \\`docs/CODEOWNERS\\`). The ownership audit is unavailable.`,\n );\n if (report.warnings.length > 0) {\n lines.push(\"\");\n lines.push(\"## Warnings\");\n lines.push(\"\");\n for (const warning of report.warnings) {\n lines.push(`- ${warning}`);\n }\n }\n return lines.join(\"\\n\");\n }\n\n const { metrics, fileCounts, codeowners } = report;\n const source = codeowners === null ? \"unknown\" : codeowners.source;\n lines.push(`- CODEOWNERS: \\`${source}\\``);\n if (codeowners !== null && codeowners.ignoredSources.length > 0) {\n lines.push(\n `- ignored sources: ${codeowners.ignoredSources.map((item) => `\\`${item}\\``).join(\", \")}`,\n );\n }\n lines.push(\"\");\n\n lines.push(\"## Metrics\");\n lines.push(\"\");\n lines.push(\n ...renderMarkdownTable(\n [\"Metric\", \"Value\"],\n [\n [\n \"Declared coverage\",\n `${formatPercent(metrics.declaredCoveragePercent)} (${fileCounts.declaredFiles}/${fileCounts.trackedFiles})`,\n ],\n [\n \"Critical coverage\",\n `${formatPercent(metrics.declaredCoverageCriticalPercent)} (${fileCounts.declaredCriticalFiles}/${fileCounts.criticalFiles})`,\n ],\n [\n \"Drift\",\n `${formatPercent(metrics.driftPercent)} (${fileCounts.driftedFiles}/${fileCounts.declaredFiles})`,\n ],\n [\"Owners without activity\", `${metrics.ghostOwnerCount}`],\n [\"Unowned critical\", `${metrics.unownedCriticalCount}`],\n [\"Single-owner modules\", `${metrics.singleOwnerModuleCount}`],\n ],\n ),\n );\n\n const unownedCritical = statusFiles(report.files, \"unowned-critical\").slice(0, topLimit(top));\n lines.push(\"\");\n lines.push(\"## Unowned critical\");\n lines.push(\"\");\n lines.push(\n ...(unownedCritical.length === 0\n ? [\"None.\"]\n : renderMarkdownTable(\n [\"Path\", \"Fan-in\", \"Commits\", \"Authors\"],\n unownedCritical.map((file) => [\n `\\`${file.filePath}\\``,\n `${file.criticality.fanIn ?? \"n/a\"}`,\n `${file.observed.commits}`,\n `${file.observed.authors}`,\n ]),\n )),\n );\n\n const drifted = statusFiles(report.files, \"drifted\").slice(0, topLimit(top));\n lines.push(\"\");\n lines.push(\"## Drift — declared owner is not the top recent author\");\n lines.push(\"\");\n lines.push(\n ...(drifted.length === 0\n ? [\"None.\"]\n : renderMarkdownTable(\n [\"Path\", \"Declared\", \"Observed\", \"Share\"],\n drifted.map((file) => [\n `\\`${file.filePath}\\``,\n formatDeclaredOwners(file.declared),\n file.observed.topAuthorId ?? \"unknown\",\n formatShare(file.observed.topAuthorShare),\n ]),\n )),\n );\n\n const ghosts = report.ghostOwners.slice(0, topLimit(top));\n lines.push(\"\");\n lines.push(\"## Ghost owners — declared, no commits in the window\");\n lines.push(\"\");\n lines.push(\n ...(ghosts.length === 0\n ? [\"None.\"]\n : renderMarkdownTable(\n [\"Owner\", \"Sample paths\"],\n ghosts.map((entry) => [\n formatDeclaredOwner(entry.owner),\n entry.samplePaths.join(\", \") || \"no sample path\",\n ]),\n )),\n );\n\n if (report.thresholds.violations.length > 0) {\n lines.push(\"\");\n lines.push(\"## Threshold violations\");\n lines.push(\"\");\n for (const violation of report.thresholds.violations) {\n lines.push(`- \\`${violation.threshold}\\`: ${violation.message}`);\n }\n }\n\n if (report.warnings.length > 0) {\n lines.push(\"\");\n lines.push(\"## Warnings\");\n lines.push(\"\");\n for (const warning of report.warnings) {\n lines.push(`- ${warning}`);\n }\n }\n\n return lines.join(\"\\n\");\n};\n\nexport const formatOwnersOutput = (\n report: OwnersReport,\n format: OwnersOutputFormat,\n top: number,\n): string => {\n if (format === \"json\") {\n return JSON.stringify(report, null, 2);\n }\n\n return format === \"md\" ? renderMarkdown(report, top) : renderConsole(report, top);\n};\n"],"mappings":";;;AAAA,SAAS,SAAS,gBAAgB,cAAc;;;AMAhD,SAAS,YAAY,oBAAoB;AACzC,SAAS,YAAY;AQDrB,SAAS,cAAc,aAAa;ACApC,SAAS,QAAAA,aAAY;ACArB,SAAS,eAAe;AACxB,SAAS,QAAAA,aAAY;ACDrB,SAAS,kBAAkB;AAC3B,SAAS,OAAO,SAAS,UAAU,QAAQ,MAAM,QAAQ,iBAAiB;AAC1E,SAAS,QAAAA,aAAY;AGFrB,SAAS,cAAAC,aAAY,aAAa,gBAAAC,eAAc,gBAAgB;AAChE,SAAS,UAAU,QAAAF,OAAM,UAAU,eAAe;AnByD3C,IAAM,mCAA2D;EACtE,wBAAwB;EACxB,oBAAoB;EACpB,qBAAqB;EACrB,gBAAgB;EAChB,yBAAyB;EACzB,4BAA4B;AAC9B;AClDA,IAAM,SAAS,CAAC,UAA0B,OAAO,MAAM,QAAQ,CAAC,CAAC;AASjE,IAAM,iBAAiB,CAAC,UAAsE;AAC5F,QAAM,SAAS,oBAAI,IAAoC;AAEvD,aAAW,QAAQ,OA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,WAAW,kBAAkB;AAAA,EACvC;AACF;","names":["join","existsSync","readFileSync","workspaceSummary","packageJsonPath","version","deletedAny","stripQuotes","withDefaults","splitIndex","name","requested","ONE_DAY_MS","MAX_RETRIES","RETRY_BASE_DELAY_MS","round4","basename","round4","basename","join","resolve","stdout","resolve","readFileSync","readFile","writeFile","dirname","resolve","fileURLToPath","toHealthTier","factorLabelById","repositoryDimensionScores","createSummaryShape","mkdir","readFile","writeFile","homedir","join","parseSemver","resolve","spawn","stderr","stdin","clearScreenDown","cursorTo","emitKeypressEvents","ANSI","ANSI","stderr","cursorTo","clearScreenDown","hideCursor","showCursor","stdin","resolve","emitKeypressEvents","scriptPath","spawn","resolve","filePaths","existsSync","readFileSync","join","relative","resolve","readdirSync","statSync","basename","nodeLowLink","createWorkspaceByFile","normalizePath","readPackageJson","packageJsonPath","program","stripQuotes","inferWorkspaceKind","readWorkspacePatternsFromPackageJson","readWorkspacePatternsFromPnpmWorkspace","expandPattern","round4","clamp01","round4","average","normalizePath","ownershipDistributionPenalty","ownershipDistributionFactors","modularityHealth","changeHygieneHealth","testHealthScore","ownershipDistributionHealth","normalizedScore","topIssues","round4","average","normalizePath","resolve","readFile","writeFile","readFile","writeFile","readFile","writeFile","relative","resolve","existsSync","readFile","resolve","percentile","WHITESPACE_PATTERN","compareText","roundTo","resolveOwner","execFileSync","stderr","runGit","parseInteger","parseRenamedPath","resolve","existsSync","readFile","resolve","writeFile","relative","readFile","join","readFile","writeFile","mkdir","readFile","stat","writeFile","dirname","join","resolve","spawn","resolve","execFileSync","path","execFileSync","writeFile","readFile","join","writeFile","resolve","compareText","plural","renderMarkdown","resolveTargetPath","resolve","writeFile","resolve","dirname","fileURLToPath","readFileSync","writeFile","readFile"]}
1
+ {"version":3,"sources":["../src/index.ts","../../dependency-firewall/src/domain/types.ts","../../dependency-firewall/src/domain/external-analysis.ts","../../dependency-firewall/src/application/map-with-concurrency.ts","../../dependency-firewall/src/application/collect-dependency-metadata.ts","../../dependency-firewall/src/application/dependency-exposure-pipeline.ts","../../dependency-firewall/src/infrastructure/fs-loader.ts","../../dependency-firewall/src/parsing/package-json-loader.ts","../../dependency-firewall/src/parsing/package-lock-parser.ts","../../dependency-firewall/src/parsing/pnpm-lock-parser.ts","../../dependency-firewall/src/parsing/yarn-lock-parser.ts","../../dependency-firewall/src/parsing/bun-lock-parser.ts","../../dependency-firewall/src/application/parse-lockfile-extraction.ts","../../dependency-firewall/src/infrastructure/cached-fetch.ts","../../dependency-firewall/src/infrastructure/fetch-json-with-retry.ts","../../dependency-firewall/src/infrastructure/npm-metadata-cache.ts","../../dependency-firewall/src/infrastructure/codesentinel-cache-dir.ts","../../dependency-firewall/src/infrastructure/file-cache-store.ts","../../dependency-firewall/src/application/resolve-registry-graph.ts","../../dependency-firewall/src/application/prepare-dependency-extraction.ts","../../dependency-firewall/src/infrastructure/workspace-package-manifests.ts","../../dependency-firewall/src/application/analyze-dependency-exposure.ts","../../dependency-firewall/src/application/analyze-dependency-candidate.ts","../../dependency-firewall/src/infrastructure/npm-registry-metadata-provider.ts","../../dependency-firewall/src/infrastructure/noop-metadata-provider.ts","../../dependency-firewall/src/index.ts","../../reporter/src/domain.ts","../../reporter/src/diff.ts","../../reporter/src/report.ts","../../reporter/src/renderers.ts","../../reporter/src/snapshot.ts","../../reporter/src/index.ts","../../governance/src/domain.ts","../../governance/src/evaluate-gates.ts","../../governance/src/render.ts","../../governance/src/baseline-ref.ts","../../governance/src/baseline-auto-resolver.ts","../src/application/format-analyze-output.ts","../src/application/format-explain-output.ts","../src/application/format-dependency-risk-output.ts","../src/application/logger.ts","../src/application/check-for-updates.ts","../src/application/interactive-menu.ts","../src/application/run-analyze-command.ts","../../core/src/index.ts","../../code-graph/src/domain/graph-model.ts","../../code-graph/src/domain/graph-metrics.ts","../../code-graph/src/domain/tarjan.ts","../../code-graph/src/infrastructure/typescript-project.ts","../../code-graph/src/infrastructure/workspace-discovery.ts","../../code-graph/src/application/build-project-graph-summary.ts","../../git-analyzer/src/domain/evolution-metrics.ts","../../git-analyzer/src/domain/evolution-types.ts","../../git-analyzer/src/application/analyze-repository-evolution.ts","../../git-analyzer/src/application/enrich-evolution-with-workspaces.ts","../../git-analyzer/src/infrastructure/git-command-client.ts","../../git-analyzer/src/domain/git-log-format.ts","../../git-analyzer/src/application/git-history-provider.ts","../../git-analyzer/src/parsing/git-log-parser.ts","../../git-analyzer/src/infrastructure/git-history-provider.ts","../../git-analyzer/src/index.ts","../../health-engine/src/domain/math.ts","../../health-engine/src/application/compute-repository-health-summary.ts","../../risk-engine/src/config.ts","../../risk-engine/src/domain/risk-model.ts","../../risk-engine/src/domain/math.ts","../../risk-engine/src/domain/normalization.ts","../../risk-engine/src/domain/trace-collector.ts","../../risk-engine/src/application/compute-repository-risk-summary.ts","../src/application/run-check-command.ts","../src/application/build-analysis-snapshot.ts","../src/application/run-ci-command.ts","../src/application/build-ownership-audit.ts","../../ownership/src/domain/codeowners.ts","../../ownership/src/domain/matcher.ts","../../ownership/src/domain/identity.ts","../../ownership/src/domain/classify.ts","../../ownership/src/domain/metrics.ts","../../ownership/src/application/parse-codeowners.ts","../../ownership/src/application/resolve-identities.ts","../../ownership/src/application/audit-ownership.ts","../src/application/owners-git.ts","../src/application/run-report-command.ts","../src/application/html-report.ts","../src/application/open-path.ts","../src/application/report-ownership.ts","../src/application/run-explain-command.ts","../src/application/run-owners-command.ts","../src/application/format-owners-output.ts","../src/application/run-init-command.ts"],"sourcesContent":["import { Command, CommanderError, Option } from \"commander\";\nimport { analyzeDependencyCandidateFromRegistry } from \"@codesentinel/dependency-firewall\";\nimport { EXIT_CODES, type GateConfig } from \"@codesentinel/governance\";\nimport {\n compareSnapshots,\n createReport,\n createSnapshot,\n formatReport,\n parseSnapshot,\n} from \"@codesentinel/reporter\";\nimport { readFileSync } from \"node:fs\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport {\n formatAnalyzeOutput,\n type AnalyzeOutputMode,\n} from \"./application/format-analyze-output.js\";\nimport { formatExplainOutput } from \"./application/format-explain-output.js\";\nimport {\n formatDependencyRiskOutput,\n type DependencyRiskOutputMode,\n} from \"./application/format-dependency-risk-output.js\";\nimport { createStderrLogger, parseLogLevel, type LogLevel } from \"./application/logger.js\";\nimport { checkForCliUpdates, runManualCliUpdate } from \"./application/check-for-updates.js\";\nimport { runInteractiveCliMenu } from \"./application/interactive-menu.js\";\nimport {\n runAnalyzeCommand,\n type AuthorIdentityCliMode,\n type ScoringProfileCliMode,\n} from \"./application/run-analyze-command.js\";\nimport {\n GovernanceConfigurationError as CheckConfigurationError,\n runCheckCommand,\n type CheckOutputFormat,\n} from \"./application/run-check-command.js\";\nimport {\n GovernanceConfigurationError as CiConfigurationError,\n runCiCommand,\n} from \"./application/run-ci-command.js\";\nimport { runReportCommand } from \"./application/run-report-command.js\";\nimport { runExplainCommand, type ExplainFormat } from \"./application/run-explain-command.js\";\nimport {\n OWNERS_EXIT_CODES,\n OwnersConfigurationError,\n runOwnersCommand,\n type OwnersCommandOptions,\n} from \"./application/run-owners-command.js\";\nimport type { OwnersFailOn, OwnersOutputFormat } from \"./application/format-owners-output.js\";\nimport { runInitCommand, type InitCiMode } from \"./application/run-init-command.js\";\nimport { writeHtmlReportBundle } from \"./application/html-report.js\";\nimport { openPath } from \"./application/open-path.js\";\n\nconst program = new Command();\nconst packageJsonPath = resolve(dirname(fileURLToPath(import.meta.url)), \"../package.json\");\nconst { version } = JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as { version: string };\n\nconst parseRecentWindowDays = (value: string): number => {\n const parsed = Number.parseInt(value, 10);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new Error(\"--recent-window-days must be a positive integer\");\n }\n return parsed;\n};\n\ntype RunDetail = \"compact\" | \"standard\" | \"full\";\n\nconst stripLeadingMarkdownHeading = (value: string, heading: string): string => {\n const prefix = `${heading}\\n`;\n if (value.startsWith(prefix)) {\n return value.slice(prefix.length).trimStart();\n }\n\n return value;\n};\n\nconst extractExplainTextSummary = (text: string): string => {\n const splitIndex = text.search(/\\n\\n(?:file|module|dependency|repository): /);\n if (splitIndex < 0) {\n return text.trim();\n }\n\n return text.slice(0, splitIndex).trim();\n};\n\nconst extractExplainMarkdownSummary = (markdown: string): string => {\n const splitIndex = markdown.search(/\\n\\n## (?:file|module|dependency|repository): /);\n if (splitIndex < 0) {\n return markdown.trim();\n }\n\n return markdown.slice(0, splitIndex).trim();\n};\n\nconst extractSummaryValue = (summary: string, key: string): string | undefined => {\n const prefix = `${key}: `;\n for (const rawLine of summary.split(\"\\n\")) {\n const line = rawLine.trimStart();\n if (line.startsWith(prefix)) {\n return line.slice(prefix.length).trim();\n }\n }\n\n return undefined;\n};\n\nconst renderReportHighlightsText = (\n report: Awaited<ReturnType<typeof runReportCommand>>[\"report\"],\n) => {\n const lines: string[] = [];\n lines.push(\"Repository Summary\");\n lines.push(` target: ${report.repository.targetPath}`);\n lines.push(` riskScore: ${report.repository.riskScore}`);\n lines.push(` healthScore: ${report.health.healthScore}`);\n lines.push(` normalizedScore: ${report.repository.normalizedScore}`);\n lines.push(` riskTier: ${report.repository.riskTier}`);\n lines.push(` healthTier: ${report.repository.healthTier}`);\n lines.push(\"\");\n lines.push(\"Top Hotspots\");\n for (const hotspot of report.hotspots.slice(0, 5)) {\n lines.push(` - ${hotspot.target} | score=${hotspot.score}`);\n lines.push(` priority actions: ${hotspot.suggestedActions.join(\" | \") || \"none\"}`);\n }\n\n return lines.join(\"\\n\");\n};\n\nconst renderReportHighlightsMarkdown = (\n report: Awaited<ReturnType<typeof runReportCommand>>[\"report\"],\n): string => {\n const lines: string[] = [];\n lines.push(\"## Repository Summary\");\n lines.push(`- target: \\`${report.repository.targetPath}\\``);\n lines.push(`- riskScore: \\`${report.repository.riskScore}\\``);\n lines.push(`- healthScore: \\`${report.health.healthScore}\\``);\n lines.push(`- normalizedScore: \\`${report.repository.normalizedScore}\\``);\n lines.push(`- riskTier: \\`${report.repository.riskTier}\\``);\n lines.push(`- healthTier: \\`${report.repository.healthTier}\\``);\n lines.push(\"\");\n lines.push(\"## Top Hotspots\");\n for (const hotspot of report.hotspots.slice(0, 5)) {\n lines.push(`- **${hotspot.target}** (score: \\`${hotspot.score}\\`)`);\n lines.push(` - priority actions: ${hotspot.suggestedActions.join(\" | \") || \"none\"}`);\n }\n\n return lines.join(\"\\n\");\n};\n\nconst renderCompactText = (\n report: Awaited<ReturnType<typeof runReportCommand>>[\"report\"],\n explainSummary: string,\n): string => {\n const lines: string[] = [];\n lines.push(\"CodeSentinel Run (compact)\");\n lines.push(\"\");\n lines.push(\"Repository\");\n lines.push(` target: ${report.repository.targetPath}`);\n lines.push(` riskScore: ${report.repository.riskScore}`);\n lines.push(` healthScore: ${report.health.healthScore}`);\n lines.push(` riskTier: ${report.repository.riskTier}`);\n lines.push(` healthTier: ${report.repository.healthTier}`);\n lines.push(\n ` dimensions: structural=${report.repository.dimensionScores.structural ?? \"n/a\"}, evolution=${report.repository.dimensionScores.evolution ?? \"n/a\"}, external=${report.repository.dimensionScores.external ?? \"n/a\"}, interactions=${report.repository.dimensionScores.interactions ?? \"n/a\"}`,\n );\n lines.push(\"\");\n lines.push(\n `Key Drivers: ${extractSummaryValue(explainSummary, \"key drivers\") ?? \"insufficient data\"}`,\n );\n lines.push(\n `Priority Actions: ${extractSummaryValue(explainSummary, \"priority actions\") ?? \"insufficient data\"}`,\n );\n lines.push(\"\");\n lines.push(\"Top Hotspots\");\n for (const hotspot of report.hotspots.slice(0, 3)) {\n lines.push(` - ${hotspot.target} | score=${hotspot.score}`);\n }\n\n return lines.join(\"\\n\");\n};\n\nconst renderCompactMarkdown = (\n report: Awaited<ReturnType<typeof runReportCommand>>[\"report\"],\n explainSummary: string,\n): string => {\n const lines: string[] = [];\n lines.push(\"# CodeSentinel Run (compact)\");\n lines.push(\"\");\n lines.push(\"## Repository\");\n lines.push(`- target: \\`${report.repository.targetPath}\\``);\n lines.push(`- riskScore: \\`${report.repository.riskScore}\\``);\n lines.push(`- healthScore: \\`${report.health.healthScore}\\``);\n lines.push(`- riskTier: \\`${report.repository.riskTier}\\``);\n lines.push(`- healthTier: \\`${report.repository.healthTier}\\``);\n lines.push(\n `- dimensions: structural=\\`${report.repository.dimensionScores.structural ?? \"n/a\"}\\`, evolution=\\`${report.repository.dimensionScores.evolution ?? \"n/a\"}\\`, external=\\`${report.repository.dimensionScores.external ?? \"n/a\"}\\`, interactions=\\`${report.repository.dimensionScores.interactions ?? \"n/a\"}\\``,\n );\n lines.push(\"\");\n lines.push(\n `- key drivers: ${extractSummaryValue(explainSummary, \"- key drivers\") ?? \"insufficient data\"}`,\n );\n lines.push(\n `- priority actions: ${extractSummaryValue(explainSummary, \"- priority actions\") ?? \"insufficient data\"}`,\n );\n lines.push(\"\");\n lines.push(\"## Top Hotspots\");\n for (const hotspot of report.hotspots.slice(0, 3)) {\n lines.push(`- \\`${hotspot.target}\\` (score: \\`${hotspot.score}\\`)`);\n }\n\n return lines.join(\"\\n\");\n};\n\nconst scoringProfileOption = (): Option =>\n new Option(\n \"--scoring-profile <profile>\",\n \"scoring profile: default (balanced) or personal (down-weights single-maintainer ownership penalties for risk and health ownership)\",\n )\n .choices([\"default\", \"personal\"])\n .default(\"default\");\n\nprogram\n .name(\"codesentinel\")\n .description(\"Structural and evolutionary risk analysis for TypeScript/JavaScript codebases\")\n .version(version);\n\nprogram\n .command(\"update\")\n .description(\"check for a newer CodeSentinel version and install it\")\n .action(async () => {\n process.exitCode = await runManualCliUpdate({\n packageName: \"@getcodesentinel/codesentinel\",\n currentVersion: version,\n });\n });\n\nprogram\n .command(\"analyze\")\n .argument(\"[path]\", \"path to the project to analyze\")\n .addOption(scoringProfileOption())\n .addOption(\n new Option(\n \"--author-identity <mode>\",\n \"author identity mode: likely_merge (heuristic) or strict_email (deterministic)\",\n )\n .choices([\"likely_merge\", \"strict_email\"])\n .default(\"likely_merge\"),\n )\n .addOption(\n new Option(\n \"--log-level <level>\",\n \"log verbosity: silent, error, warn, info, debug (logs are written to stderr)\",\n )\n .choices([\"silent\", \"error\", \"warn\", \"info\", \"debug\"])\n .default(parseLogLevel(process.env[\"CODESENTINEL_LOG_LEVEL\"])),\n )\n .addOption(\n new Option(\"--output <mode>\", \"output mode: summary (default) or json (full analysis object)\")\n .choices([\"summary\", \"json\"])\n .default(\"summary\"),\n )\n .option(\"--json\", \"shortcut for --output json\")\n .addOption(\n new Option(\n \"--recent-window-days <days>\",\n \"git recency window in days used for evolution volatility metrics\",\n )\n .argParser(parseRecentWindowDays)\n .default(30),\n )\n .action(\n async (\n path: string | undefined,\n options: {\n authorIdentity: AuthorIdentityCliMode;\n scoringProfile: ScoringProfileCliMode;\n logLevel: LogLevel;\n output: AnalyzeOutputMode;\n json?: boolean;\n recentWindowDays: number;\n },\n ) => {\n const logger = createStderrLogger(options.logLevel);\n const summary = await runAnalyzeCommand(\n path,\n options.authorIdentity,\n { recentWindowDays: options.recentWindowDays, scoringProfile: options.scoringProfile },\n logger,\n );\n const outputMode: AnalyzeOutputMode = options.json === true ? \"json\" : options.output;\n process.stdout.write(`${formatAnalyzeOutput(summary, outputMode)}\\n`);\n },\n );\n\nprogram\n .command(\"explain\")\n .argument(\"[path]\", \"path to the project to analyze\")\n .addOption(scoringProfileOption())\n .addOption(\n new Option(\n \"--author-identity <mode>\",\n \"author identity mode: likely_merge (heuristic) or strict_email (deterministic)\",\n )\n .choices([\"likely_merge\", \"strict_email\"])\n .default(\"likely_merge\"),\n )\n .addOption(\n new Option(\n \"--log-level <level>\",\n \"log verbosity: silent, error, warn, info, debug (logs are written to stderr)\",\n )\n .choices([\"silent\", \"error\", \"warn\", \"info\", \"debug\"])\n .default(parseLogLevel(process.env[\"CODESENTINEL_LOG_LEVEL\"])),\n )\n .option(\"--file <path>\", \"explain a specific file target\")\n .option(\"--module <name>\", \"explain a specific module target\")\n .option(\"--top <count>\", \"number of top hotspots to explain when no target is selected\", \"5\")\n .addOption(\n new Option(\n \"--recent-window-days <days>\",\n \"git recency window in days used for evolution volatility metrics\",\n )\n .argParser(parseRecentWindowDays)\n .default(30),\n )\n .addOption(\n new Option(\"--format <mode>\", \"output format: text, json, md\")\n .choices([\"text\", \"json\", \"md\"])\n .default(\"md\"),\n )\n .action(\n async (\n path: string | undefined,\n options: {\n authorIdentity: AuthorIdentityCliMode;\n scoringProfile: ScoringProfileCliMode;\n logLevel: LogLevel;\n file?: string;\n module?: string;\n top: string;\n recentWindowDays: number;\n format: ExplainFormat;\n },\n ) => {\n const logger = createStderrLogger(options.logLevel);\n const top = Number.parseInt(options.top, 10);\n const explainOptions = {\n ...(options.file === undefined ? {} : { file: options.file }),\n ...(options.module === undefined ? {} : { module: options.module }),\n top: Number.isFinite(top) ? top : 5,\n recentWindowDays: options.recentWindowDays,\n scoringProfile: options.scoringProfile,\n format: options.format,\n };\n const result = await runExplainCommand(path, options.authorIdentity, explainOptions, logger);\n process.stdout.write(`${formatExplainOutput(result, options.format)}\\n`);\n },\n );\n\nprogram\n .command(\"dependency-risk\")\n .argument(\"<dependency>\", \"dependency spec to evaluate (for example: react or react@19.0.0)\")\n .addOption(\n new Option(\n \"--log-level <level>\",\n \"log verbosity: silent, error, warn, info, debug (logs are written to stderr)\",\n )\n .choices([\"silent\", \"error\", \"warn\", \"info\", \"debug\"])\n .default(parseLogLevel(process.env[\"CODESENTINEL_LOG_LEVEL\"])),\n )\n .addOption(\n new Option(\"--output <mode>\", \"output mode: summary (default) or json (full analysis object)\")\n .choices([\"summary\", \"json\"])\n .default(\"summary\"),\n )\n .option(\"--json\", \"shortcut for --output json\")\n .option(\"--max-nodes <count>\", \"maximum dependency nodes to resolve\", \"250\")\n .option(\"--max-depth <count>\", \"maximum dependency depth to traverse\", \"6\")\n .action(\n async (\n dependency: string,\n options: {\n logLevel: LogLevel;\n output: DependencyRiskOutputMode;\n json?: boolean;\n maxNodes: string;\n maxDepth: string;\n },\n ) => {\n const logger = createStderrLogger(options.logLevel);\n const maxNodes = Number.parseInt(options.maxNodes, 10);\n const maxDepth = Number.parseInt(options.maxDepth, 10);\n\n logger.info(`analyzing dependency candidate: ${dependency}`);\n const result = await analyzeDependencyCandidateFromRegistry({\n dependency,\n maxNodes: Number.isFinite(maxNodes) ? maxNodes : 250,\n maxDepth: Number.isFinite(maxDepth) ? maxDepth : 6,\n });\n if (result.available) {\n logger.info(\n `dependency analysis completed (${result.dependency.name}@${result.dependency.resolvedVersion})`,\n );\n } else {\n logger.warn(`dependency analysis unavailable: ${result.reason}`);\n }\n\n const outputMode: DependencyRiskOutputMode = options.json === true ? \"json\" : options.output;\n process.stdout.write(`${formatDependencyRiskOutput(result, outputMode)}\\n`);\n },\n );\n\nprogram\n .command(\"report\")\n .argument(\"[path]\", \"path to the project to analyze\")\n .addOption(scoringProfileOption())\n .addOption(\n new Option(\n \"--author-identity <mode>\",\n \"author identity mode: likely_merge (heuristic) or strict_email (deterministic)\",\n )\n .choices([\"likely_merge\", \"strict_email\"])\n .default(\"likely_merge\"),\n )\n .addOption(\n new Option(\n \"--log-level <level>\",\n \"log verbosity: silent, error, warn, info, debug (logs are written to stderr)\",\n )\n .choices([\"silent\", \"error\", \"warn\", \"info\", \"debug\"])\n .default(parseLogLevel(process.env[\"CODESENTINEL_LOG_LEVEL\"])),\n )\n .addOption(\n new Option(\"--format <mode>\", \"output format: text, json, md, html\")\n .choices([\"text\", \"json\", \"md\", \"html\"])\n .default(\"md\"),\n )\n .option(\"--output <path>\", \"write rendered report to a file path\")\n .option(\"--open\", \"open the generated HTML report in the default browser\")\n .option(\"--compare <baseline>\", \"compare against a baseline snapshot JSON file\")\n .option(\"--snapshot <path>\", \"write current snapshot JSON artifact\")\n .option(\"--no-trace\", \"disable trace embedding in generated snapshot\")\n .addOption(\n new Option(\n \"--recent-window-days <days>\",\n \"git recency window in days used for evolution volatility metrics\",\n )\n .argParser(parseRecentWindowDays)\n .default(30),\n )\n .action(\n async (\n path: string | undefined,\n options: {\n authorIdentity: AuthorIdentityCliMode;\n scoringProfile: ScoringProfileCliMode;\n logLevel: LogLevel;\n format: \"text\" | \"json\" | \"md\" | \"html\";\n output?: string;\n open?: boolean;\n compare?: string;\n snapshot?: string;\n trace: boolean;\n recentWindowDays: number;\n },\n ) => {\n const logger = createStderrLogger(options.logLevel);\n const result = await runReportCommand(\n path,\n options.authorIdentity,\n {\n format: options.format,\n ...(options.output === undefined ? {} : { outputPath: options.output }),\n ...(options.compare === undefined ? {} : { comparePath: options.compare }),\n ...(options.snapshot === undefined ? {} : { snapshotPath: options.snapshot }),\n ...(options.open === undefined ? {} : { open: options.open }),\n includeTrace: options.trace,\n scoringProfile: options.scoringProfile,\n recentWindowDays: options.recentWindowDays,\n },\n logger,\n );\n\n if (options.output === undefined && options.format !== \"html\") {\n process.stdout.write(`${result.rendered}\\n`);\n return;\n }\n\n if (options.format === \"html\") {\n process.stdout.write(`${result.outputPath ?? result.rendered}\\n`);\n }\n },\n );\n\nprogram\n .command(\"run\")\n .argument(\"[path]\", \"path to the project to analyze\")\n .addOption(scoringProfileOption())\n .addOption(\n new Option(\n \"--author-identity <mode>\",\n \"author identity mode: likely_merge (heuristic) or strict_email (deterministic)\",\n )\n .choices([\"likely_merge\", \"strict_email\"])\n .default(\"likely_merge\"),\n )\n .addOption(\n new Option(\n \"--log-level <level>\",\n \"log verbosity: silent, error, warn, info, debug (logs are written to stderr)\",\n )\n .choices([\"silent\", \"error\", \"warn\", \"info\", \"debug\"])\n .default(parseLogLevel(process.env[\"CODESENTINEL_LOG_LEVEL\"])),\n )\n .addOption(\n new Option(\"--format <mode>\", \"combined output format: text, md, json\")\n .choices([\"text\", \"md\", \"json\"])\n .default(\"md\"),\n )\n .addOption(\n new Option(\"--detail <level>\", \"run detail level: compact (default), standard, full\")\n .choices([\"compact\", \"standard\", \"full\"])\n .default(\"compact\"),\n )\n .option(\"--file <path>\", \"explain a specific file target\")\n .option(\"--module <name>\", \"explain a specific module target\")\n .option(\"--top <count>\", \"number of top hotspots to explain when no target is selected\", \"5\")\n .option(\"--compare <baseline>\", \"compare against a baseline snapshot JSON file\")\n .option(\"--snapshot <path>\", \"write current snapshot JSON artifact\")\n .addOption(\n new Option(\"--report <format>\", \"write an additional report bundle during the run\")\n .choices([\"html\"])\n .default(undefined),\n )\n .option(\"--report-output <path>\", \"output path for the generated report bundle\")\n .option(\"--open\", \"open the generated HTML report in the default browser\")\n .option(\"--no-trace\", \"disable trace embedding in generated snapshot\")\n .addOption(\n new Option(\n \"--recent-window-days <days>\",\n \"git recency window in days used for evolution volatility metrics\",\n )\n .argParser(parseRecentWindowDays)\n .default(30),\n )\n .action(\n async (\n path: string | undefined,\n options: {\n authorIdentity: AuthorIdentityCliMode;\n scoringProfile: ScoringProfileCliMode;\n logLevel: LogLevel;\n format: \"text\" | \"md\" | \"json\";\n detail: RunDetail;\n file?: string;\n module?: string;\n top: string;\n compare?: string;\n snapshot?: string;\n report?: \"html\";\n reportOutput?: string;\n open?: boolean;\n trace: boolean;\n recentWindowDays: number;\n },\n ) => {\n const logger = createStderrLogger(options.logLevel);\n const top = Number.parseInt(options.top, 10);\n\n const explain = await runExplainCommand(\n path,\n options.authorIdentity,\n {\n ...(options.file === undefined ? {} : { file: options.file }),\n ...(options.module === undefined ? {} : { module: options.module }),\n top: Number.isFinite(top) ? top : 5,\n format: options.format,\n recentWindowDays: options.recentWindowDays,\n scoringProfile: options.scoringProfile,\n },\n logger,\n );\n\n const snapshot = createSnapshot({\n analysis: explain.summary,\n ...(options.trace === true ? { trace: explain.trace } : {}),\n });\n\n if (options.snapshot !== undefined) {\n await writeFile(options.snapshot, JSON.stringify(snapshot, null, 2), \"utf8\");\n logger.info(`snapshot written: ${options.snapshot}`);\n }\n\n const report =\n options.compare === undefined\n ? createReport(snapshot)\n : createReport(\n snapshot,\n compareSnapshots(snapshot, parseSnapshot(await readFile(options.compare, \"utf8\"))),\n );\n\n if (options.report === \"html\") {\n const htmlOutputPath = await writeHtmlReportBundle(report, {\n repositoryPath: explain.summary.structural.targetPath,\n ...(options.reportOutput === undefined ? {} : { outputPath: options.reportOutput }),\n });\n if (options.open === true) {\n const opened = await openPath(`${htmlOutputPath}/index.html`);\n if (!opened) {\n logger.warn(\"unable to open html report automatically on this platform\");\n }\n }\n logger.info(`html report written: ${htmlOutputPath}`);\n } else if (options.open === true) {\n logger.warn(\"--open has no effect unless --report html is set\");\n }\n\n if (options.format === \"json\") {\n const analyzeSummaryOutput = formatAnalyzeOutput(explain.summary, \"summary\");\n\n if (options.detail === \"compact\") {\n process.stdout.write(\n `${JSON.stringify(\n {\n schemaVersion: \"codesentinel.run.v1\",\n generatedAt: new Date().toISOString(),\n repository: report.repository,\n keyDrivers: extractSummaryValue(\n extractExplainTextSummary(formatExplainOutput(explain, \"text\")),\n \"key drivers\",\n ),\n priorityActions: extractSummaryValue(\n extractExplainTextSummary(formatExplainOutput(explain, \"text\")),\n \"priority actions\",\n ),\n topHotspots: report.hotspots.slice(0, 3).map((hotspot) => ({\n target: hotspot.target,\n score: hotspot.score,\n })),\n },\n null,\n 2,\n )}\\n`,\n );\n return;\n }\n\n if (options.detail === \"standard\") {\n const analyzeSummaryPayload: unknown = JSON.parse(analyzeSummaryOutput);\n\n process.stdout.write(\n `${JSON.stringify(\n {\n schemaVersion: \"codesentinel.run.v1\",\n generatedAt: new Date().toISOString(),\n analyze: analyzeSummaryPayload,\n explain: {\n summary: extractExplainTextSummary(formatExplainOutput(explain, \"text\")),\n },\n report: {\n repository: report.repository,\n health: report.health,\n hotspots: report.hotspots.slice(0, 5),\n structural: report.structural,\n external: report.external,\n },\n },\n null,\n 2,\n )}\\n`,\n );\n return;\n }\n\n process.stdout.write(\n `${JSON.stringify(\n {\n schemaVersion: \"codesentinel.run.v1\",\n generatedAt: new Date().toISOString(),\n analyze: explain.summary,\n explain,\n report,\n },\n null,\n 2,\n )}\\n`,\n );\n return;\n }\n\n const analyzeRendered = formatAnalyzeOutput(explain.summary, \"summary\");\n const explainRendered = formatExplainOutput(explain, options.format);\n\n if (options.detail === \"compact\") {\n if (options.format === \"md\") {\n process.stdout.write(\n `${renderCompactMarkdown(\n report,\n extractExplainMarkdownSummary(formatExplainOutput(explain, \"md\")),\n )}\\n`,\n );\n return;\n }\n\n process.stdout.write(\n `${renderCompactText(report, extractExplainTextSummary(formatExplainOutput(explain, \"text\")))}\\n`,\n );\n return;\n }\n\n if (options.detail === \"standard\") {\n if (options.format === \"md\") {\n process.stdout.write(\n `# CodeSentinel Run\\n\\n## Analyze\\n\\`\\`\\`json\\n${analyzeRendered}\\n\\`\\`\\`\\n\\n## Explain\\n${extractExplainMarkdownSummary(\n formatExplainOutput(explain, \"md\"),\n )}\\n\\n${renderReportHighlightsMarkdown(report)}\\n`,\n );\n return;\n }\n\n process.stdout.write(\n `CodeSentinel Run\\n\\nAnalyze\\n${analyzeRendered}\\n\\nExplain\\n${extractExplainTextSummary(\n formatExplainOutput(explain, \"text\"),\n )}\\n\\nReport\\n${renderReportHighlightsText(report)}\\n`,\n );\n return;\n }\n\n const reportRendered = formatReport(report, options.format);\n\n if (options.format === \"md\") {\n const explainSection = stripLeadingMarkdownHeading(\n explainRendered,\n \"# CodeSentinel Explanation\",\n );\n const reportSection = stripLeadingMarkdownHeading(reportRendered, \"# CodeSentinel Report\");\n\n process.stdout.write(\n `# CodeSentinel Run\\n\\n## Analyze\\n\\`\\`\\`json\\n${analyzeRendered}\\n\\`\\`\\`\\n\\n## Explain\\n${explainSection}\\n\\n## Report\\n${reportSection}\\n`,\n );\n return;\n }\n\n process.stdout.write(\n `CodeSentinel Run\\n\\nAnalyze\\n${analyzeRendered}\\n\\nExplain\\n${explainRendered}\\n\\nReport\\n${reportRendered}\\n`,\n );\n },\n );\n\nconst parseGateNumber = (value: string | undefined, optionName: string): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n\n const parsed = Number.parseFloat(value);\n if (!Number.isFinite(parsed)) {\n throw new CheckConfigurationError(`${optionName} must be numeric`);\n }\n\n return parsed;\n};\n\nconst collectOptionValues = (value: string, previous: string[] = []): string[] => {\n return [...previous, value];\n};\n\nconst parseMainBranches = (options: {\n mainBranch?: string[];\n mainBranches?: string;\n}): readonly string[] | undefined => {\n const fromRepeated = options.mainBranch ?? [];\n const fromCsv =\n options.mainBranches === undefined\n ? []\n : options.mainBranches\n .split(\",\")\n .map((value) => value.trim())\n .filter((value) => value.length > 0);\n\n const merged = [...fromRepeated, ...fromCsv];\n if (merged.length === 0) {\n return undefined;\n }\n\n const unique = Array.from(new Set(merged));\n return unique.length > 0 ? unique : undefined;\n};\n\nconst parseCiCount = (value: string | undefined, optionName: string): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n\n const trimmed = value.trim();\n const parsed = Number.parseInt(trimmed, 10);\n if (!/^\\d+$/.test(trimmed) || !Number.isInteger(parsed) || parsed < 0) {\n throw new CiConfigurationError(`${optionName} must be an integer >= 0`);\n }\n\n return parsed;\n};\n\nconst parseCiRatio = (value: string | undefined, optionName: string): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n\n const parsed = Number.parseFloat(value.trim());\n if (!Number.isFinite(parsed) || parsed < 0 || parsed > 1) {\n throw new CiConfigurationError(`${optionName} must be a number between 0 and 1`);\n }\n\n return parsed;\n};\n\nconst buildGateConfigFromOptions = (options: {\n maxRiskDelta?: string;\n maxHealthDelta?: string;\n noNewCycles?: boolean;\n noNewHighRiskDeps?: boolean;\n maxNewHotspots?: string;\n maxRiskScore?: string;\n minHealthScore?: string;\n newHotspotScoreThreshold?: string;\n maxUnownedCritical?: string;\n maxGhostOwners?: string;\n maxDrift?: string;\n failOn: \"error\" | \"warn\";\n}): GateConfig => {\n const maxRiskDelta = parseGateNumber(options.maxRiskDelta, \"--max-risk-delta\");\n const maxHealthDelta = parseGateNumber(options.maxHealthDelta, \"--max-health-delta\");\n const maxNewHotspots = parseGateNumber(options.maxNewHotspots, \"--max-new-hotspots\");\n const maxRiskScore = parseGateNumber(options.maxRiskScore, \"--max-risk-score\");\n const minHealthScore = parseGateNumber(options.minHealthScore, \"--min-health-score\");\n const newHotspotScoreThreshold = parseGateNumber(\n options.newHotspotScoreThreshold,\n \"--new-hotspot-score-threshold\",\n );\n const maxUnownedCritical = parseCiCount(options.maxUnownedCritical, \"--max-unowned-critical\");\n const maxGhostOwners = parseCiCount(options.maxGhostOwners, \"--max-ghost-owners\");\n const maxDrift = parseCiRatio(options.maxDrift, \"--max-drift\");\n\n return {\n ...(maxRiskDelta === undefined ? {} : { maxRiskDelta }),\n ...(maxHealthDelta === undefined ? {} : { maxHealthDelta }),\n ...(options.noNewCycles === true ? { noNewCycles: true } : {}),\n ...(options.noNewHighRiskDeps === true ? { noNewHighRiskDeps: true } : {}),\n ...(maxNewHotspots === undefined ? {} : { maxNewHotspots }),\n ...(maxRiskScore === undefined ? {} : { maxRiskScore }),\n ...(minHealthScore === undefined ? {} : { minHealthScore }),\n ...(newHotspotScoreThreshold === undefined ? {} : { newHotspotScoreThreshold }),\n ...(maxUnownedCritical === undefined ? {} : { maxUnownedCritical }),\n ...(maxGhostOwners === undefined ? {} : { maxGhostOwners }),\n ...(maxDrift === undefined ? {} : { maxDrift }),\n failOn: options.failOn,\n };\n};\n\nprogram\n .command(\"check\")\n .argument(\"[path]\", \"path to the project to analyze\")\n .addOption(scoringProfileOption())\n .addOption(\n new Option(\n \"--author-identity <mode>\",\n \"author identity mode: likely_merge (heuristic) or strict_email (deterministic)\",\n )\n .choices([\"likely_merge\", \"strict_email\"])\n .default(\"likely_merge\"),\n )\n .addOption(\n new Option(\n \"--log-level <level>\",\n \"log verbosity: silent, error, warn, info, debug (logs are written to stderr)\",\n )\n .choices([\"silent\", \"error\", \"warn\", \"info\", \"debug\"])\n .default(parseLogLevel(process.env[\"CODESENTINEL_LOG_LEVEL\"])),\n )\n .option(\"--compare <baseline>\", \"baseline snapshot path\")\n .option(\"--max-risk-delta <value>\", \"maximum allowed normalized risk score increase\")\n .option(\n \"--max-health-delta <value>\",\n \"maximum allowed normalized health score regression versus baseline (requires --compare)\",\n )\n .option(\"--no-new-cycles\", \"fail if new structural cycles are introduced\")\n .option(\"--no-new-high-risk-deps\", \"fail if new high-risk direct dependencies are introduced\")\n .option(\"--max-new-hotspots <count>\", \"maximum allowed number of new hotspots\")\n .option(\"--new-hotspot-score-threshold <score>\", \"minimum hotspot score to count as new hotspot\")\n .option(\"--max-risk-score <score>\", \"absolute risk score limit (0..100)\")\n .option(\"--min-health-score <score>\", \"minimum health score threshold (0..100)\")\n .addOption(\n new Option(\"--fail-on <level>\", \"failing severity threshold\")\n .choices([\"error\", \"warn\"])\n .default(\"error\"),\n )\n .addOption(\n new Option(\"--format <mode>\", \"output format: text, json, md\")\n .choices([\"text\", \"json\", \"md\"])\n .default(\"text\"),\n )\n .option(\"--output <path>\", \"write check output to a file path\")\n .option(\"--no-trace\", \"disable trace embedding in generated snapshot\")\n .addOption(\n new Option(\n \"--recent-window-days <days>\",\n \"git recency window in days used for evolution volatility metrics\",\n )\n .argParser(parseRecentWindowDays)\n .default(30),\n )\n .action(\n async (\n path: string | undefined,\n options: {\n authorIdentity: AuthorIdentityCliMode;\n scoringProfile: ScoringProfileCliMode;\n logLevel: LogLevel;\n compare?: string;\n maxRiskDelta?: string;\n maxHealthDelta?: string;\n noNewCycles?: boolean;\n noNewHighRiskDeps?: boolean;\n maxNewHotspots?: string;\n newHotspotScoreThreshold?: string;\n maxRiskScore?: string;\n minHealthScore?: string;\n failOn: \"error\" | \"warn\";\n format: CheckOutputFormat;\n output?: string;\n trace: boolean;\n recentWindowDays: number;\n },\n ) => {\n const logger = createStderrLogger(options.logLevel);\n\n try {\n const gateConfig = buildGateConfigFromOptions(options);\n const result = await runCheckCommand(\n path,\n options.authorIdentity,\n {\n ...(options.compare === undefined ? {} : { baselinePath: options.compare }),\n includeTrace: options.trace,\n scoringProfile: options.scoringProfile,\n recentWindowDays: options.recentWindowDays,\n gateConfig,\n outputFormat: options.format,\n ...(options.output === undefined ? {} : { outputPath: options.output }),\n },\n logger,\n );\n\n if (options.output === undefined) {\n process.stdout.write(`${result.rendered}\\n`);\n }\n\n process.exitCode = result.gateResult.exitCode;\n } catch (error) {\n if (error instanceof CheckConfigurationError) {\n logger.error(error.message);\n process.exitCode = EXIT_CODES.invalidConfiguration;\n return;\n }\n\n logger.error(error instanceof Error ? error.message : \"internal error\");\n process.exitCode = EXIT_CODES.internalError;\n }\n },\n );\n\nprogram\n .command(\"ci\")\n .argument(\"[path]\", \"path to the project to analyze\")\n .addOption(scoringProfileOption())\n .addOption(\n new Option(\n \"--author-identity <mode>\",\n \"author identity mode: likely_merge (heuristic) or strict_email (deterministic)\",\n )\n .choices([\"likely_merge\", \"strict_email\"])\n .default(\"likely_merge\"),\n )\n .addOption(\n new Option(\n \"--log-level <level>\",\n \"log verbosity: silent, error, warn, info, debug (logs are written to stderr)\",\n )\n .choices([\"silent\", \"error\", \"warn\", \"info\", \"debug\"])\n .default(parseLogLevel(process.env[\"CODESENTINEL_LOG_LEVEL\"])),\n )\n .option(\"--baseline <path>\", \"baseline snapshot path\")\n .option(\n \"--baseline-ref <gitRef>\",\n \"resolve baseline snapshot from a git reference (for example origin/main)\",\n )\n .option(\n \"--baseline-sha <sha>\",\n \"explicit baseline commit SHA (only valid with --baseline-ref auto)\",\n )\n .addOption(\n new Option(\n \"--main-branch <name>\",\n \"add a default branch candidate for auto baseline resolution (repeatable)\",\n ).argParser(collectOptionValues),\n )\n .option(\n \"--main-branches <names>\",\n \"comma-separated default branch candidates for auto baseline resolution (for example: main,master)\",\n )\n .option(\"--snapshot <path>\", \"write current snapshot JSON to path\")\n .option(\"--report <path>\", \"write markdown CI summary report\")\n .option(\"--json-output <path>\", \"write machine-readable CI JSON output\")\n .option(\"--max-risk-delta <value>\", \"maximum allowed normalized risk score increase\")\n .option(\n \"--max-health-delta <value>\",\n \"maximum allowed normalized health score regression versus baseline\",\n )\n .option(\"--no-new-cycles\", \"fail if new structural cycles are introduced\")\n .option(\"--no-new-high-risk-deps\", \"fail if new high-risk direct dependencies are introduced\")\n .option(\"--max-new-hotspots <count>\", \"maximum allowed number of new hotspots\")\n .option(\"--new-hotspot-score-threshold <score>\", \"minimum hotspot score to count as new hotspot\")\n .option(\"--max-risk-score <score>\", \"absolute risk score limit (0..100)\")\n .option(\"--min-health-score <score>\", \"minimum health score threshold (0..100)\")\n .option(\n \"--max-unowned-critical <count>\",\n \"maximum allowed unowned critical files (requires CODEOWNERS)\",\n )\n .option(\n \"--max-ghost-owners <count>\",\n \"maximum allowed owners without activity (requires CODEOWNERS)\",\n )\n .option(\n \"--max-drift <ratio>\",\n \"maximum allowed ownership drift ratio between 0 and 1 (requires CODEOWNERS)\",\n )\n .addOption(\n new Option(\"--fail-on <level>\", \"failing severity threshold\")\n .choices([\"error\", \"warn\"])\n .default(\"error\"),\n )\n .option(\"--no-trace\", \"disable trace embedding in generated snapshot\")\n .addOption(\n new Option(\n \"--recent-window-days <days>\",\n \"git recency window in days used for evolution volatility metrics\",\n )\n .argParser(parseRecentWindowDays)\n .default(30),\n )\n .action(\n async (\n path: string | undefined,\n options: {\n authorIdentity: AuthorIdentityCliMode;\n scoringProfile: ScoringProfileCliMode;\n logLevel: LogLevel;\n baseline?: string;\n baselineRef?: string;\n baselineSha?: string;\n mainBranch?: string[];\n mainBranches?: string;\n snapshot?: string;\n report?: string;\n jsonOutput?: string;\n maxRiskDelta?: string;\n maxHealthDelta?: string;\n noNewCycles?: boolean;\n noNewHighRiskDeps?: boolean;\n maxNewHotspots?: string;\n newHotspotScoreThreshold?: string;\n maxRiskScore?: string;\n minHealthScore?: string;\n maxUnownedCritical?: string;\n maxGhostOwners?: string;\n maxDrift?: string;\n failOn: \"error\" | \"warn\";\n trace: boolean;\n recentWindowDays: number;\n },\n ) => {\n const logger = createStderrLogger(options.logLevel);\n\n try {\n const gateConfig = buildGateConfigFromOptions(options);\n const mainBranchCandidates = parseMainBranches(options);\n const result = await runCiCommand(\n path,\n options.authorIdentity,\n {\n ...(options.baseline === undefined ? {} : { baselinePath: options.baseline }),\n ...(options.baselineRef === undefined ? {} : { baselineRef: options.baselineRef }),\n ...(options.baselineSha === undefined ? {} : { baselineSha: options.baselineSha }),\n ...(mainBranchCandidates === undefined ? {} : { mainBranchCandidates }),\n ...(options.snapshot === undefined ? {} : { snapshotPath: options.snapshot }),\n ...(options.report === undefined ? {} : { reportPath: options.report }),\n ...(options.jsonOutput === undefined ? {} : { jsonOutputPath: options.jsonOutput }),\n includeTrace: options.trace,\n scoringProfile: options.scoringProfile,\n recentWindowDays: options.recentWindowDays,\n gateConfig,\n },\n logger,\n );\n\n if (options.report === undefined) {\n process.stdout.write(`${result.markdownSummary}\\n`);\n }\n\n process.exitCode = result.gateResult.exitCode;\n } catch (error) {\n if (error instanceof CiConfigurationError) {\n logger.error(error.message);\n process.exitCode = EXIT_CODES.invalidConfiguration;\n return;\n }\n\n logger.error(error instanceof Error ? error.message : \"internal error\");\n process.exitCode = EXIT_CODES.internalError;\n }\n },\n );\n\nconst parseOwnersInteger = (\n value: string | undefined,\n optionName: string,\n minimum: number,\n): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n\n const trimmed = value.trim();\n const parsed = Number.parseInt(trimmed, 10);\n if (!/^\\d+$/.test(trimmed) || !Number.isInteger(parsed) || parsed < minimum) {\n throw new OwnersConfigurationError(\n `${optionName} must be an integer greater than or equal to ${minimum}`,\n );\n }\n\n return parsed;\n};\n\nconst parseOwnersRatio = (value: string | undefined, optionName: string): number | undefined => {\n if (value === undefined) {\n return undefined;\n }\n\n const parsed = Number.parseFloat(value.trim());\n if (!Number.isFinite(parsed) || parsed < 0 || parsed > 1) {\n throw new OwnersConfigurationError(`${optionName} must be a ratio between 0 and 1`);\n }\n\n return parsed;\n};\n\nprogram\n .command(\"owners\")\n .alias(\"ownership\")\n // The owners command owns the ESLint-style 0/1/2 contract, so a usage error has to surface as\n // the configuration exit code (2) instead of commander's default 1.\n .exitOverride()\n .argument(\"[path]\", \"path to the repository to audit\")\n .option(\n \"--codeowners <file>\",\n \"explicit CODEOWNERS path, relative to the repository root (default: auto-discovery)\",\n )\n .option(\"--ref <ref>\", \"git ref to read CODEOWNERS and the tracked tree from\", \"HEAD\")\n .option(\"--window-days <days>\", \"authorship observation window in days\", \"90\")\n .option(\"--min-commits <count>\", \"minimum per-file commits before a verdict is emitted\", \"2\")\n .option(\"--top <count>\", \"rows per console and markdown section\", \"10\")\n .addOption(\n new Option(\n \"--format <mode>\",\n \"output format: console (default), json (stable, sorted payload) or md (pastes into a PR)\",\n )\n .choices([\"console\", \"json\", \"md\"])\n .default(\"console\"),\n )\n .option(\"--output <file>\", \"write the rendered output to a file instead of stdout\")\n .option(\"--aliases <file>\", \"identity alias map\", \".codesentinel/owners.json\")\n .option(\n \"--resolve-github\",\n \"accepted for compatibility; not implemented in this iteration, the audit stays offline\",\n )\n .addOption(\n new Option(\"--fail-on <level>\", \"failing severity threshold: none, warn or error\")\n .choices([\"none\", \"warn\", \"error\"])\n .default(\"none\"),\n )\n .option(\"--max-unowned-critical <count>\", \"maximum allowed unowned critical files\")\n .option(\"--max-ghost-owners <count>\", \"maximum allowed owners without activity\")\n .option(\"--max-drift <ratio>\", \"maximum allowed drift ratio between 0 and 1\")\n .addOption(\n new Option(\n \"--log-level <level>\",\n \"log verbosity: silent, error, warn, info, debug (logs are written to stderr)\",\n )\n .choices([\"silent\", \"error\", \"warn\", \"info\", \"debug\"])\n .default(parseLogLevel(process.env[\"CODESENTINEL_LOG_LEVEL\"])),\n )\n .action(\n async (\n path: string | undefined,\n options: {\n codeowners?: string;\n ref: string;\n windowDays: string;\n minCommits: string;\n top: string;\n format: OwnersOutputFormat;\n output?: string;\n aliases: string;\n resolveGithub?: boolean;\n failOn: OwnersFailOn;\n maxUnownedCritical?: string;\n maxGhostOwners?: string;\n maxDrift?: string;\n logLevel: LogLevel;\n },\n ) => {\n const logger = createStderrLogger(options.logLevel);\n\n try {\n const windowDays = parseOwnersInteger(options.windowDays, \"--window-days\", 1) ?? 90;\n const minCommits = parseOwnersInteger(options.minCommits, \"--min-commits\", 0) ?? 2;\n const top = parseOwnersInteger(options.top, \"--top\", 1) ?? 10;\n const commandOptions: OwnersCommandOptions = {\n ...(options.codeowners === undefined ? {} : { codeownersPath: options.codeowners }),\n ref: options.ref,\n windowDays,\n minCommits,\n top,\n format: options.format,\n ...(options.output === undefined ? {} : { outputPath: options.output }),\n aliasesPath: options.aliases,\n ...(options.resolveGithub === true ? { resolveGithub: true } : {}),\n thresholds: {\n failOn: options.failOn,\n maxUnownedCritical:\n parseOwnersInteger(options.maxUnownedCritical, \"--max-unowned-critical\", 0) ?? null,\n maxGhostOwners:\n parseOwnersInteger(options.maxGhostOwners, \"--max-ghost-owners\", 0) ?? null,\n maxDrift: parseOwnersRatio(options.maxDrift, \"--max-drift\") ?? null,\n },\n };\n\n const result = await runOwnersCommand(path, commandOptions, logger);\n\n if (result.outputPath === undefined) {\n process.stdout.write(`${result.rendered}\\n`);\n }\n\n process.exitCode = result.exitCode;\n } catch (error) {\n if (error instanceof OwnersConfigurationError) {\n logger.error(error.message);\n process.exitCode = OWNERS_EXIT_CODES.invalidConfiguration;\n return;\n }\n\n logger.error(error instanceof Error ? error.message : \"internal error\");\n process.exitCode = OWNERS_EXIT_CODES.invalidConfiguration;\n }\n },\n );\n\nprogram\n .command(\"init\")\n .argument(\"[path]\", \"path to the repository to scaffold\")\n .option(\"--force\", \"overwrite generated files that already exist\")\n .addOption(\n new Option(\"--ci <mode>\", \"CI provider: github (default) or none\")\n .choices([\"github\", \"none\"])\n .default(\"github\"),\n )\n .option(\"--dry-run\", \"print what would be written without writing anything\")\n .action(\n async (\n path: string | undefined,\n options: { force?: boolean; ci: InitCiMode; dryRun?: boolean },\n ) => {\n const result = await runInitCommand(path, {\n ...(options.force === true ? { force: true } : {}),\n ci: options.ci,\n ...(options.dryRun === true ? { dryRun: true } : {}),\n });\n process.stdout.write(`${result.rendered}\\n`);\n process.exitCode = result.exitCode;\n },\n );\n\nconst executablePath = process.argv[0] ?? \"\";\nconst scriptPath = process.argv[1] ?? \"\";\n\nconst argv =\n process.argv[2] === \"--\" ? [executablePath, scriptPath, ...process.argv.slice(3)] : process.argv;\n\nif (argv.length <= 2) {\n if (process.stdin.isTTY && process.stdout.isTTY && process.stderr.isTTY) {\n process.exitCode = await runInteractiveCliMenu({\n currentVersion: version,\n scriptPath,\n });\n process.exit(process.exitCode ?? 0);\n }\n\n program.outputHelp();\n process.exit(0);\n}\n\nif (argv[2] !== \"update\") {\n await checkForCliUpdates({\n packageName: \"@getcodesentinel/codesentinel\",\n currentVersion: version,\n argv: process.argv,\n env: process.env,\n });\n}\n\ntry {\n await program.parseAsync(argv);\n} catch (error) {\n if (!(error instanceof CommanderError)) {\n throw error;\n }\n // `--help` and usage errors both travel through `exitOverride`; only real usage errors are\n // configuration failures for the command that opted into the ESLint-style exit codes.\n if (error.exitCode !== 0) {\n process.exitCode = OWNERS_EXIT_CODES.invalidConfiguration;\n }\n}\n","import type { WorkspacePackage } from \"@codesentinel/core\";\n\nexport type LockfileKind = \"pnpm\" | \"npm\" | \"npm-shrinkwrap\" | \"yarn\" | \"bun\";\n\nexport type DirectDependencySpec = {\n name: string;\n requestedRange: string;\n scope: \"prod\" | \"dev\";\n};\n\nexport type LockedDependencyNode = {\n name: string;\n version: string;\n dependencies: readonly string[];\n};\n\nexport type LockfileExtraction = {\n kind: LockfileKind;\n directDependencies: readonly DirectDependencySpec[];\n nodes: readonly LockedDependencyNode[];\n};\n\nexport type WorkspaceDependencyManifest = WorkspacePackage & {\n directDependencies: readonly DirectDependencySpec[];\n};\n\nexport type DependencyMetadata = {\n name: string;\n version: string;\n weeklyDownloads: number | null;\n maintainerCount: number | null;\n releaseFrequencyDays: number | null;\n daysSinceLastRelease: number | null;\n repositoryActivity30d: number | null;\n busFactor: number | null;\n};\n\nexport type DependencyMetadataRequestContext = {\n directDependency: boolean;\n};\n\nexport interface DependencyMetadataProvider {\n getMetadata(\n name: string,\n version: string,\n context: DependencyMetadataRequestContext,\n ): Promise<DependencyMetadata | null>;\n}\n\nexport type ExternalAnalysisConfig = {\n abandonedDaysThreshold: number;\n deepChainThreshold: number;\n fanOutHighThreshold: number;\n centralityTopN: number;\n maxHighRiskDependencies: number;\n metadataRequestConcurrency: number;\n};\n\nexport const DEFAULT_EXTERNAL_ANALYSIS_CONFIG: ExternalAnalysisConfig = {\n abandonedDaysThreshold: 540,\n deepChainThreshold: 6,\n fanOutHighThreshold: 25,\n centralityTopN: 20,\n maxHighRiskDependencies: 100,\n metadataRequestConcurrency: 8,\n};\n","import type {\n CentralDependency,\n DependencyExposureRecord,\n DependencyRiskSignal,\n ExternalAnalysisSummary,\n WorkspaceDependencyExposureSummary,\n} from \"@codesentinel/core\";\nimport type {\n DependencyMetadata,\n ExternalAnalysisConfig,\n LockfileExtraction,\n LockedDependencyNode,\n WorkspaceDependencyManifest,\n} from \"./types.js\";\n\nconst round4 = (value: number): number => Number(value.toFixed(4));\n\ntype NormalizedNode = {\n key: string;\n name: string;\n version: string;\n dependencies: readonly string[];\n};\n\nconst normalizeNodes = (nodes: readonly LockedDependencyNode[]): readonly NormalizedNode[] => {\n const byName = new Map<string, LockedDependencyNode[]>();\n\n for (const node of nodes) {\n const bucket = byName.get(node.name) ?? [];\n bucket.push(node);\n byName.set(node.name, bucket);\n }\n\n const normalized: NormalizedNode[] = [];\n\n for (const [name, candidates] of byName.entries()) {\n if (candidates.length === 0) {\n continue;\n }\n\n candidates.sort((a, b) => b.version.localeCompare(a.version));\n const selected = candidates[0];\n if (selected === undefined) {\n continue;\n }\n\n const deps = selected.dependencies\n .map((dep) => {\n const at = dep.lastIndexOf(\"@\");\n return at <= 0 ? dep : dep.slice(0, at);\n })\n .filter((depName) => depName.length > 0)\n .sort((a, b) => a.localeCompare(b));\n\n normalized.push({\n key: `${name}@${selected.version}`,\n name,\n version: selected.version,\n dependencies: deps,\n });\n }\n\n return normalized.sort((a, b) => a.name.localeCompare(b.name));\n};\n\nconst computeDepths = (\n nodeByName: ReadonlyMap<string, NormalizedNode>,\n directNames: ReadonlySet<string>,\n): { depthByName: ReadonlyMap<string, number>; maxDepth: number } => {\n const visiting = new Set<string>();\n const depthByName = new Map<string, number>();\n\n const compute = (name: string): number => {\n const known = depthByName.get(name);\n if (known !== undefined) {\n return known;\n }\n\n if (visiting.has(name)) {\n return 0;\n }\n\n visiting.add(name);\n\n const node = nodeByName.get(name);\n if (node === undefined) {\n visiting.delete(name);\n depthByName.set(name, 0);\n return 0;\n }\n\n let maxChildDepth = 0;\n for (const dependencyName of node.dependencies) {\n const childDepth = compute(dependencyName);\n if (childDepth > maxChildDepth) {\n maxChildDepth = childDepth;\n }\n }\n\n visiting.delete(name);\n const ownDepth = directNames.has(name) ? 0 : maxChildDepth + 1;\n depthByName.set(name, ownDepth);\n return ownDepth;\n };\n\n for (const name of nodeByName.keys()) {\n compute(name);\n }\n\n let maxDepth = 0;\n for (const depth of depthByName.values()) {\n if (depth > maxDepth) {\n maxDepth = depth;\n }\n }\n\n return { depthByName, maxDepth };\n};\n\nconst rankCentrality = (\n nodes: readonly NormalizedNode[],\n dependentsByName: ReadonlyMap<string, number>,\n directNames: ReadonlySet<string>,\n topN: number,\n): readonly CentralDependency[] =>\n [...nodes]\n .map((node) => ({\n name: node.name,\n dependents: dependentsByName.get(node.name) ?? 0,\n fanOut: node.dependencies.length,\n direct: directNames.has(node.name),\n }))\n .sort(\n (a, b) => b.dependents - a.dependents || b.fanOut - a.fanOut || a.name.localeCompare(b.name),\n )\n .slice(0, topN);\n\nconst canPropagateSignal = (signal: DependencyRiskSignal): boolean =>\n signal === \"abandoned\" ||\n signal === \"high_centrality\" ||\n signal === \"deep_chain\" ||\n signal === \"high_fanout\";\n\nconst collectTransitiveDependencies = (\n rootName: string,\n nodeByName: ReadonlyMap<string, NormalizedNode>,\n): readonly string[] => {\n const seen = new Set<string>();\n const stack = [...(nodeByName.get(rootName)?.dependencies ?? [])];\n\n while (stack.length > 0) {\n const current = stack.pop();\n if (current === undefined || seen.has(current) || current === rootName) {\n continue;\n }\n\n seen.add(current);\n const currentNode = nodeByName.get(current);\n if (currentNode === undefined) {\n continue;\n }\n\n for (const next of currentNode.dependencies) {\n if (!seen.has(next)) {\n stack.push(next);\n }\n }\n }\n\n return [...seen].sort((a, b) => a.localeCompare(b));\n};\n\nconst hasHighRiskSignals = (\n dependency: DependencyExposureRecord,\n config: ExternalAnalysisConfig,\n): boolean =>\n dependency.ownRiskSignals.includes(\"abandoned\") ||\n dependency.ownRiskSignals.filter(\n (signal) => signal === \"high_centrality\" || signal === \"deep_chain\" || signal === \"high_fanout\",\n ).length >= 2 ||\n (dependency.ownRiskSignals.includes(\"single_maintainer\") &&\n ((dependency.daysSinceLastRelease ?? 0) >= config.abandonedDaysThreshold / 2 ||\n (dependency.repositoryActivity30d ?? 1) <= 0));\n\nconst buildWorkspaceExposureSummaries = (\n workspaceManifests: readonly WorkspaceDependencyManifest[],\n allByName: ReadonlyMap<string, DependencyExposureRecord>,\n nodeByName: ReadonlyMap<string, NormalizedNode>,\n config: ExternalAnalysisConfig,\n): readonly WorkspaceDependencyExposureSummary[] => {\n if (workspaceManifests.length === 0) {\n return [];\n }\n\n const workspaceNames = new Set(workspaceManifests.map((workspace) => workspace.name));\n const externalDependencyNamesByWorkspace = new Map<string, readonly string[]>();\n const workspaceCountByDependency = new Map<string, number>();\n\n for (const workspace of workspaceManifests) {\n const dependencyNames = [\n ...new Set(\n workspace.directDependencies\n .map((dependency) => dependency.name)\n .filter((dependencyName) => !workspaceNames.has(dependencyName)),\n ),\n ].sort((a, b) => a.localeCompare(b));\n\n externalDependencyNamesByWorkspace.set(workspace.path, dependencyNames);\n\n for (const dependencyName of dependencyNames) {\n workspaceCountByDependency.set(\n dependencyName,\n (workspaceCountByDependency.get(dependencyName) ?? 0) + 1,\n );\n }\n }\n\n return [...workspaceManifests]\n .map((workspace) => {\n const dependencyNames = externalDependencyNamesByWorkspace.get(workspace.path) ?? [];\n const directSpecByName = new Map(\n workspace.directDependencies.map((dependency) => [dependency.name, dependency]),\n );\n const resolvedDependencies = dependencyNames\n .map((dependencyName) => allByName.get(dependencyName))\n .filter((dependency): dependency is DependencyExposureRecord => dependency !== undefined);\n const unresolvedDependencies = dependencyNames.filter(\n (dependencyName) => !allByName.has(dependencyName),\n );\n\n const highRiskDependencies = resolvedDependencies\n .filter(\n (dependency) =>\n (directSpecByName.get(dependency.name)?.scope ?? dependency.dependencyScope) ===\n \"prod\" && hasHighRiskSignals(dependency, config),\n )\n .map((dependency) => dependency.name)\n .sort((a, b) => a.localeCompare(b));\n\n const highRiskDevelopmentDependencies = resolvedDependencies\n .filter(\n (dependency) =>\n (directSpecByName.get(dependency.name)?.scope ?? dependency.dependencyScope) ===\n \"dev\" && hasHighRiskSignals(dependency, config),\n )\n .map((dependency) => dependency.name)\n .sort((a, b) => a.localeCompare(b));\n\n const transitiveExposureDependencies = resolvedDependencies\n .filter((dependency) => {\n const transitiveDependencies = collectTransitiveDependencies(dependency.name, nodeByName);\n return transitiveDependencies.some((transitiveName) => {\n const transitive = allByName.get(transitiveName);\n return transitive?.riskSignals.some(canPropagateSignal) ?? false;\n });\n })\n .map((dependency) => dependency.name)\n .sort((a, b) => a.localeCompare(b));\n\n const singleMaintainerDependencies = resolvedDependencies\n .filter((dependency) => dependency.ownRiskSignals.includes(\"single_maintainer\"))\n .map((dependency) => dependency.name)\n .sort((a, b) => a.localeCompare(b));\n\n const abandonedDependencies = resolvedDependencies\n .filter((dependency) => dependency.ownRiskSignals.includes(\"abandoned\"))\n .map((dependency) => dependency.name)\n .sort((a, b) => a.localeCompare(b));\n\n return {\n name: workspace.name,\n path: workspace.path,\n kind: workspace.kind,\n directDependencies: dependencyNames.length,\n directProductionDependencies: dependencyNames.filter(\n (dependencyName) => directSpecByName.get(dependencyName)?.scope === \"prod\",\n ).length,\n directDevelopmentDependencies: dependencyNames.filter(\n (dependencyName) => directSpecByName.get(dependencyName)?.scope === \"dev\",\n ).length,\n unresolvedDependencies,\n dependencyNames,\n sharedDependencies: dependencyNames.filter(\n (dependencyName) => (workspaceCountByDependency.get(dependencyName) ?? 0) > 1,\n ),\n highRiskDependencies,\n highRiskDevelopmentDependencies,\n transitiveExposureDependencies,\n singleMaintainerDependencies,\n abandonedDependencies,\n };\n })\n .sort(\n (a, b) =>\n b.highRiskDependencies.length - a.highRiskDependencies.length ||\n b.transitiveExposureDependencies.length - a.transitiveExposureDependencies.length ||\n b.directDependencies - a.directDependencies ||\n a.path.localeCompare(b.path),\n );\n};\n\nexport const buildExternalAnalysisSummary = (\n targetPath: string,\n extraction: LockfileExtraction,\n metadataByKey: ReadonlyMap<string, DependencyMetadata | null>,\n config: ExternalAnalysisConfig,\n workspaceManifests: readonly WorkspaceDependencyManifest[] = [],\n): ExternalAnalysisSummary => {\n const nodes = normalizeNodes(extraction.nodes);\n const directNames = new Set(extraction.directDependencies.map((dep) => dep.name));\n const directSpecByName = new Map(extraction.directDependencies.map((dep) => [dep.name, dep]));\n\n const nodeByName = new Map(nodes.map((node) => [node.name, node]));\n const dependentsByName = new Map<string, number>();\n\n for (const node of nodes) {\n dependentsByName.set(node.name, dependentsByName.get(node.name) ?? 0);\n }\n\n for (const node of nodes) {\n for (const dependencyName of node.dependencies) {\n if (!nodeByName.has(dependencyName)) {\n continue;\n }\n\n dependentsByName.set(dependencyName, (dependentsByName.get(dependencyName) ?? 0) + 1);\n }\n }\n\n const { depthByName, maxDepth } = computeDepths(nodeByName, directNames);\n const centralityRanking = rankCentrality(\n nodes,\n dependentsByName,\n directNames,\n config.centralityTopN,\n );\n\n const topCentralNames = new Set(\n centralityRanking\n .slice(0, Math.max(1, Math.ceil(centralityRanking.length * 0.25)))\n .map((entry) => entry.name),\n );\n\n const allDependencies: DependencyExposureRecord[] = [];\n let metadataAvailableCount = 0;\n\n for (const node of nodes) {\n const metadata = metadataByKey.get(node.key) ?? null;\n if (metadata !== null) {\n metadataAvailableCount += 1;\n }\n\n const dependencyDepth = depthByName.get(node.name) ?? 0;\n const dependents = dependentsByName.get(node.name) ?? 0;\n\n const riskSignals: DependencyRiskSignal[] = [];\n\n if ((metadata?.maintainerCount ?? 0) === 1) {\n riskSignals.push(\"single_maintainer\");\n }\n\n if ((metadata?.daysSinceLastRelease ?? 0) >= config.abandonedDaysThreshold) {\n riskSignals.push(\"abandoned\");\n }\n\n if (topCentralNames.has(node.name) && dependents > 0) {\n riskSignals.push(\"high_centrality\");\n }\n\n if (dependencyDepth >= config.deepChainThreshold) {\n riskSignals.push(\"deep_chain\");\n }\n\n if (node.dependencies.length >= config.fanOutHighThreshold) {\n riskSignals.push(\"high_fanout\");\n }\n\n if (metadata === null) {\n riskSignals.push(\"metadata_unavailable\");\n }\n\n allDependencies.push({\n name: node.name,\n direct: directNames.has(node.name),\n dependencyScope: directSpecByName.get(node.name)?.scope ?? \"prod\",\n requestedRange: directSpecByName.get(node.name)?.requestedRange ?? null,\n resolvedVersion: node.version,\n transitiveDependencies: [],\n weeklyDownloads: metadata?.weeklyDownloads ?? null,\n dependencyDepth,\n fanOut: node.dependencies.length,\n dependents,\n maintainerCount: metadata?.maintainerCount ?? null,\n releaseFrequencyDays: metadata?.releaseFrequencyDays ?? null,\n daysSinceLastRelease: metadata?.daysSinceLastRelease ?? null,\n repositoryActivity30d: metadata?.repositoryActivity30d ?? null,\n busFactor: metadata?.busFactor ?? null,\n ownRiskSignals: [...riskSignals].sort((a, b) => a.localeCompare(b)),\n inheritedRiskSignals: [],\n riskSignals,\n });\n }\n\n allDependencies.sort((a, b) => a.name.localeCompare(b.name));\n\n const allByName = new Map(allDependencies.map((dep) => [dep.name, dep]));\n\n const dependencies: DependencyExposureRecord[] = allDependencies\n .filter((dep) => dep.direct)\n .map((dep) => {\n const transitiveDependencies = collectTransitiveDependencies(dep.name, nodeByName);\n const inheritedSignals = new Set<DependencyRiskSignal>();\n const allSignals = new Set(dep.ownRiskSignals);\n\n for (const transitiveName of transitiveDependencies) {\n const transitive = allByName.get(transitiveName);\n if (transitive === undefined) {\n continue;\n }\n\n for (const signal of transitive.riskSignals) {\n if (canPropagateSignal(signal)) {\n inheritedSignals.add(signal);\n allSignals.add(signal);\n }\n }\n }\n\n return {\n ...dep,\n transitiveDependencies,\n inheritedRiskSignals: [...inheritedSignals].sort((a, b) => a.localeCompare(b)),\n riskSignals: [...allSignals].sort((a, b) => a.localeCompare(b)),\n };\n })\n .sort((a, b) => a.name.localeCompare(b.name));\n\n const highRiskDependencies = dependencies\n .filter(\n (dep) =>\n dep.ownRiskSignals.includes(\"abandoned\") ||\n dep.ownRiskSignals.filter(\n (signal) =>\n signal === \"high_centrality\" || signal === \"deep_chain\" || signal === \"high_fanout\",\n ).length >= 2 ||\n (dep.ownRiskSignals.includes(\"single_maintainer\") &&\n ((dep.daysSinceLastRelease ?? 0) >= config.abandonedDaysThreshold / 2 ||\n (dep.repositoryActivity30d ?? 1) <= 0)),\n )\n .filter((dep) => dep.dependencyScope === \"prod\")\n .sort(\n (a, b) => b.ownRiskSignals.length - a.ownRiskSignals.length || a.name.localeCompare(b.name),\n )\n .slice(0, config.maxHighRiskDependencies)\n .map((dep) => dep.name);\n\n const highRiskDevelopmentDependencies = dependencies\n .filter(\n (dep) =>\n dep.dependencyScope === \"dev\" &&\n (dep.ownRiskSignals.includes(\"abandoned\") ||\n dep.ownRiskSignals.filter(\n (signal) =>\n signal === \"high_centrality\" || signal === \"deep_chain\" || signal === \"high_fanout\",\n ).length >= 2 ||\n (dep.ownRiskSignals.includes(\"single_maintainer\") &&\n ((dep.daysSinceLastRelease ?? 0) >= config.abandonedDaysThreshold / 2 ||\n (dep.repositoryActivity30d ?? 1) <= 0))),\n )\n .sort(\n (a, b) => b.ownRiskSignals.length - a.ownRiskSignals.length || a.name.localeCompare(b.name),\n )\n .slice(0, config.maxHighRiskDependencies)\n .map((dep) => dep.name);\n\n const transitiveExposureDependencies = dependencies\n .filter((dep) => dep.inheritedRiskSignals.length > 0)\n .sort(\n (a, b) =>\n b.inheritedRiskSignals.length - a.inheritedRiskSignals.length ||\n a.name.localeCompare(b.name),\n )\n .map((dep) => dep.name);\n\n const singleMaintainerDependencies = dependencies\n .filter((dep) => dep.ownRiskSignals.includes(\"single_maintainer\"))\n .map((dep) => dep.name)\n .sort((a, b) => a.localeCompare(b));\n\n const abandonedDependencies = dependencies\n .filter((dep) => dep.ownRiskSignals.includes(\"abandoned\"))\n .map((dep) => dep.name)\n .sort((a, b) => a.localeCompare(b));\n\n const workspaces = buildWorkspaceExposureSummaries(\n workspaceManifests,\n allByName,\n nodeByName,\n config,\n );\n const workspaceSummary = workspaces.length > 0 ? { workspaces } : {};\n\n return {\n targetPath,\n available: true,\n metrics: {\n totalDependencies: allDependencies.length,\n directDependencies: dependencies.length,\n directProductionDependencies: dependencies.filter(\n (dependency) => dependency.dependencyScope === \"prod\",\n ).length,\n directDevelopmentDependencies: dependencies.filter(\n (dependency) => dependency.dependencyScope === \"dev\",\n ).length,\n transitiveDependencies: allDependencies.length - dependencies.length,\n dependencyDepth: maxDepth,\n lockfileKind: extraction.kind,\n metadataCoverage:\n allDependencies.length === 0 ? 0 : round4(metadataAvailableCount / allDependencies.length),\n },\n dependencies,\n ...workspaceSummary,\n highRiskDependencies,\n highRiskDevelopmentDependencies,\n transitiveExposureDependencies,\n singleMaintainerDependencies,\n abandonedDependencies,\n centralityRanking,\n };\n};\n","export const mapWithConcurrency = async <T, R>(\n values: readonly T[],\n limit: number,\n handler: (value: T) => Promise<R>,\n): Promise<readonly R[]> => {\n const effectiveLimit = Math.max(1, limit);\n const workerCount = Math.min(effectiveLimit, values.length);\n const UNSET = Symbol(\"map_with_concurrency_unset\");\n const results = new Array<R | typeof UNSET>(values.length).fill(UNSET);\n let index = 0;\n\n const workers: Promise<void>[] = Array.from({ length: workerCount }, async () => {\n // This loop always terminates: each iteration advances `index`,\n // and workers return once `index >= values.length`.\n while (true) {\n const current = index;\n index += 1;\n if (current >= values.length) {\n return;\n }\n\n const value = values[current] as T;\n results[current] = await handler(value);\n }\n });\n\n await Promise.all(workers);\n if (results.some((value) => value === UNSET)) {\n throw new Error(\"map_with_concurrency_incomplete_results\");\n }\n return results as R[];\n};\n","import type { LockfileExtraction, DependencyMetadataProvider } from \"../domain/types.js\";\nimport { mapWithConcurrency } from \"./map-with-concurrency.js\";\n\ntype MetadataEntry = {\n key: string;\n metadata: Awaited<ReturnType<DependencyMetadataProvider[\"getMetadata\"]>>;\n};\n\ntype MetadataProgressEvent = {\n completed: number;\n total: number;\n packageName: string;\n};\n\nexport const collectDependencyMetadata = async (\n extraction: LockfileExtraction,\n metadataProvider: DependencyMetadataProvider,\n concurrency: number,\n onProgress?: (event: MetadataProgressEvent) => void,\n): Promise<readonly MetadataEntry[]> => {\n const directNames = new Set(extraction.directDependencies.map((dependency) => dependency.name));\n let completed = 0;\n\n return mapWithConcurrency(extraction.nodes, concurrency, async (node) => {\n const result = {\n key: `${node.name}@${node.version}`,\n metadata: await metadataProvider.getMetadata(node.name, node.version, {\n directDependency: directNames.has(node.name),\n }),\n };\n completed += 1;\n onProgress?.({\n completed,\n total: extraction.nodes.length,\n packageName: node.name,\n });\n return result;\n });\n};\n","import type { ExternalAnalysisSummary } from \"@codesentinel/core\";\nimport { buildExternalAnalysisSummary } from \"../domain/external-analysis.js\";\nimport type {\n DependencyMetadata,\n DependencyMetadataProvider,\n ExternalAnalysisConfig,\n LockfileExtraction,\n WorkspaceDependencyManifest,\n} from \"../domain/types.js\";\nimport { collectDependencyMetadata } from \"./collect-dependency-metadata.js\";\n\nexport type DependencyExposureMetadataProgressEvent = {\n completed: number;\n total: number;\n packageName: string;\n};\n\nexport type BuildDependencyExposureSummaryInput = {\n targetPath: string;\n extraction: LockfileExtraction;\n metadataProvider: DependencyMetadataProvider;\n config: ExternalAnalysisConfig;\n workspaceManifests?: readonly WorkspaceDependencyManifest[];\n onMetadataProgress?: (event: DependencyExposureMetadataProgressEvent) => void;\n};\n\nexport const buildDependencyExposureSummary = async (\n input: BuildDependencyExposureSummaryInput,\n): Promise<ExternalAnalysisSummary> => {\n const metadataEntries = await collectDependencyMetadata(\n input.extraction,\n input.metadataProvider,\n input.config.metadataRequestConcurrency,\n input.onMetadataProgress,\n );\n\n const metadataByKey = new Map<string, DependencyMetadata | null>();\n for (const entry of metadataEntries) {\n metadataByKey.set(entry.key, entry.metadata);\n }\n\n return buildExternalAnalysisSummary(\n input.targetPath,\n input.extraction,\n metadataByKey,\n input.config,\n input.workspaceManifests ?? [],\n );\n};\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\n\nexport type RepositoryFiles = {\n packageJsonPath: string;\n packageJsonRaw: string;\n lockfilePath: string;\n lockfileRaw: string;\n};\n\nconst LOCKFILE_CANDIDATES: readonly {\n fileName: string;\n kind: \"pnpm\" | \"npm\" | \"npm-shrinkwrap\" | \"yarn\" | \"bun\";\n}[] = [\n { fileName: \"pnpm-lock.yaml\", kind: \"pnpm\" },\n { fileName: \"package-lock.json\", kind: \"npm\" },\n { fileName: \"npm-shrinkwrap.json\", kind: \"npm-shrinkwrap\" },\n { fileName: \"yarn.lock\", kind: \"yarn\" },\n { fileName: \"bun.lock\", kind: \"bun\" },\n { fileName: \"bun.lockb\", kind: \"bun\" },\n];\n\nexport type LockfileSelection = {\n path: string;\n kind: \"pnpm\" | \"npm\" | \"npm-shrinkwrap\" | \"yarn\" | \"bun\";\n raw: string;\n};\n\nexport const loadPackageJson = (repositoryPath: string): { path: string; raw: string } | null => {\n const packageJsonPath = join(repositoryPath, \"package.json\");\n if (!existsSync(packageJsonPath)) {\n return null;\n }\n\n return {\n path: packageJsonPath,\n raw: readFileSync(packageJsonPath, \"utf8\"),\n };\n};\n\nexport const selectLockfile = (repositoryPath: string): LockfileSelection | null => {\n for (const candidate of LOCKFILE_CANDIDATES) {\n const absolutePath = join(repositoryPath, candidate.fileName);\n if (!existsSync(absolutePath)) {\n continue;\n }\n\n return {\n path: absolutePath,\n kind: candidate.kind,\n raw: readFileSync(absolutePath, \"utf8\"),\n };\n }\n\n return null;\n};\n","import type { DirectDependencySpec } from \"../domain/types.js\";\n\ntype ParsedPackageJson = {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n optionalDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n};\n\nexport const parsePackageJson = (raw: string): readonly DirectDependencySpec[] => {\n const parsed = JSON.parse(raw) as ParsedPackageJson;\n const merged = new Map<string, DirectDependencySpec>();\n\n const addBlock = (block: Record<string, string> | undefined, scope: \"prod\" | \"dev\"): void => {\n if (block === undefined) {\n return;\n }\n\n for (const [name, versionRange] of Object.entries(block)) {\n const existing = merged.get(name);\n // Production scope wins when the same package appears in both scopes.\n if (existing?.scope === \"prod\" && scope === \"dev\") {\n continue;\n }\n\n merged.set(name, { name, requestedRange: versionRange, scope });\n }\n };\n\n addBlock(parsed.dependencies, \"prod\");\n addBlock(parsed.optionalDependencies, \"prod\");\n addBlock(parsed.peerDependencies, \"prod\");\n addBlock(parsed.devDependencies, \"dev\");\n\n return [...merged.values()].sort((a, b) => a.name.localeCompare(b.name));\n};\n","import type {\n DirectDependencySpec,\n LockfileExtraction,\n LockedDependencyNode,\n} from \"../domain/types.js\";\n\ntype PackageLockNode = {\n version?: string;\n dependencies?: Record<string, string>;\n};\n\ntype PackageLockShape = {\n lockfileVersion?: number;\n packages?: Record<string, PackageLockNode>;\n dependencies?: Record<string, { version?: string; dependencies?: Record<string, unknown> }>;\n};\n\nexport const parsePackageLock = (\n raw: string,\n directSpecs: readonly DirectDependencySpec[],\n): LockfileExtraction => {\n const parsed = JSON.parse(raw) as PackageLockShape;\n const nodes: LockedDependencyNode[] = [];\n\n if (parsed.packages !== undefined) {\n for (const [packagePath, packageData] of Object.entries(parsed.packages)) {\n if (packagePath.length === 0 || packageData.version === undefined) {\n continue;\n }\n\n const segments = packagePath.split(\"node_modules/\");\n const name = segments[segments.length - 1] ?? \"\";\n if (name.length === 0) {\n continue;\n }\n\n const dependencies = Object.entries(packageData.dependencies ?? {})\n .map(([depName, depRange]) => `${depName}@${String(depRange)}`)\n .sort((a, b) => a.localeCompare(b));\n\n nodes.push({\n name,\n version: packageData.version,\n dependencies,\n });\n }\n } else if (parsed.dependencies !== undefined) {\n for (const [name, dep] of Object.entries(parsed.dependencies)) {\n if (dep.version === undefined) {\n continue;\n }\n\n const dependencies = Object.entries(dep.dependencies ?? {})\n .map(([depName, depVersion]) => `${depName}@${String(depVersion)}`)\n .sort((a, b) => a.localeCompare(b));\n\n nodes.push({\n name,\n version: dep.version,\n dependencies,\n });\n }\n }\n\n nodes.sort((a, b) => a.name.localeCompare(b.name) || a.version.localeCompare(b.version));\n\n return {\n kind: \"npm\",\n directDependencies: directSpecs,\n nodes,\n };\n};\n","import type {\n DirectDependencySpec,\n LockfileExtraction,\n LockedDependencyNode,\n} from \"../domain/types.js\";\n\ntype ParserState = \"root\" | \"importers\" | \"packages\" | \"packageDeps\";\n\nconst sanitizeValue = (value: string): string => value.replace(/^['\"]|['\"]$/g, \"\").trim();\n\nconst parsePackageKey = (rawKey: string): { name: string; version: string } | null => {\n const key = sanitizeValue(rawKey.replace(/:$/, \"\"));\n const withoutSlash = key.startsWith(\"/\") ? key.slice(1) : key;\n\n const lastAt = withoutSlash.lastIndexOf(\"@\");\n if (lastAt <= 0) {\n return null;\n }\n\n const name = withoutSlash.slice(0, lastAt);\n const versionWithPeers = withoutSlash.slice(lastAt + 1);\n const version = versionWithPeers.split(\"(\")[0] ?? versionWithPeers;\n\n if (name.length === 0 || version.length === 0) {\n return null;\n }\n\n return { name, version };\n};\n\nexport const parsePnpmLockfile = (\n raw: string,\n directSpecs: readonly DirectDependencySpec[],\n): LockfileExtraction => {\n const lines = raw.split(\"\\n\");\n let state: ParserState = \"root\";\n let currentPackage: string | null = null;\n let currentDependencyName: string | null = null;\n const dependenciesByNode = new Map<string, Set<string>>();\n\n for (const line of lines) {\n if (line.trim().length === 0 || line.trimStart().startsWith(\"#\")) {\n continue;\n }\n\n if (line.startsWith(\"importers:\")) {\n state = \"importers\";\n continue;\n }\n\n if (line.startsWith(\"packages:\")) {\n state = \"packages\";\n continue;\n }\n\n if (state === \"packages\" || state === \"packageDeps\") {\n const packageMatch = line.match(/^\\s{2}([^\\s].+):\\s*$/);\n if (packageMatch !== null) {\n const parsedKey = parsePackageKey(packageMatch[1] ?? \"\");\n if (parsedKey !== null) {\n currentPackage = `${parsedKey.name}@${parsedKey.version}`;\n dependenciesByNode.set(currentPackage, new Set());\n state = \"packageDeps\";\n currentDependencyName = null;\n }\n continue;\n }\n }\n\n if (state === \"packageDeps\" && currentPackage !== null) {\n const depLine = line.match(/^\\s{6}([^:\\s]+):\\s*(.+)$/);\n if (depLine !== null) {\n const depName = sanitizeValue(depLine[1] ?? \"\");\n const depRef = sanitizeValue(depLine[2] ?? \"\");\n const depVersion = depRef.split(\"(\")[0] ?? depRef;\n\n if (depName.length > 0 && depVersion.length > 0) {\n dependenciesByNode.get(currentPackage)?.add(`${depName}@${depVersion}`);\n }\n currentDependencyName = null;\n continue;\n }\n\n const depBlockLine = line.match(/^\\s{6}([^:\\s]+):\\s*$/);\n if (depBlockLine !== null) {\n currentDependencyName = sanitizeValue(depBlockLine[1] ?? \"\");\n continue;\n }\n\n const depVersionLine = line.match(/^\\s{8}version:\\s*(.+)$/);\n if (depVersionLine !== null && currentDependencyName !== null) {\n const depRef = sanitizeValue(depVersionLine[1] ?? \"\");\n const depVersion = depRef.split(\"(\")[0] ?? depRef;\n if (depVersion.length > 0) {\n dependenciesByNode.get(currentPackage)?.add(`${currentDependencyName}@${depVersion}`);\n }\n currentDependencyName = null;\n continue;\n }\n\n if (line.match(/^\\s{4}(dependencies|optionalDependencies):\\s*$/) !== null) {\n continue;\n }\n }\n }\n\n const nodes: LockedDependencyNode[] = [...dependenciesByNode.entries()]\n .map(([nodeId, deps]) => {\n const at = nodeId.lastIndexOf(\"@\");\n return {\n name: nodeId.slice(0, at),\n version: nodeId.slice(at + 1),\n dependencies: [...deps].sort((a, b) => a.localeCompare(b)),\n };\n })\n .sort((a, b) => a.name.localeCompare(b.name) || a.version.localeCompare(b.version));\n\n return {\n kind: \"pnpm\",\n directDependencies: directSpecs,\n nodes,\n };\n};\n","import type {\n DirectDependencySpec,\n LockfileExtraction,\n LockedDependencyNode,\n} from \"../domain/types.js\";\n\nconst stripQuotes = (value: string): string => value.replace(/^['\"]|['\"]$/g, \"\");\n\nconst parseVersionSelector = (selector: string): string | null => {\n const npmIndex = selector.lastIndexOf(\"@npm:\");\n if (npmIndex >= 0) {\n return selector.slice(npmIndex + 5);\n }\n\n const lastAt = selector.lastIndexOf(\"@\");\n if (lastAt <= 0) {\n return null;\n }\n\n return selector.slice(lastAt + 1);\n};\n\nexport const parseYarnLock = (\n raw: string,\n directSpecs: readonly DirectDependencySpec[],\n): LockfileExtraction => {\n const lines = raw.split(\"\\n\");\n const nodes: LockedDependencyNode[] = [];\n\n let selectors: string[] = [];\n let version: string | null = null;\n let readingDependencies = false;\n let dependencies: string[] = [];\n\n const flushEntry = (): void => {\n if (selectors.length === 0 || version === null) {\n selectors = [];\n version = null;\n dependencies = [];\n readingDependencies = false;\n return;\n }\n\n for (const selector of selectors) {\n const parsedVersion = parseVersionSelector(selector);\n const at = selector.lastIndexOf(\"@\");\n const name = at <= 0 ? selector : selector.slice(0, at);\n if (name.length === 0) {\n continue;\n }\n\n nodes.push({\n name,\n version,\n dependencies: [...dependencies].sort((a, b) => a.localeCompare(b)),\n });\n\n if (parsedVersion !== null) {\n nodes.push({\n name,\n version: parsedVersion,\n dependencies: [...dependencies].sort((a, b) => a.localeCompare(b)),\n });\n }\n }\n\n selectors = [];\n version = null;\n dependencies = [];\n readingDependencies = false;\n };\n\n for (const line of lines) {\n if (line.trim().length === 0) {\n continue;\n }\n\n if (!line.startsWith(\" \") && line.endsWith(\":\")) {\n flushEntry();\n const keyText = line.slice(0, -1);\n selectors = keyText\n .split(\",\")\n .map((part) => stripQuotes(part.trim()))\n .filter((part) => part.length > 0);\n continue;\n }\n\n if (line.match(/^\\s{2}version\\s+/) !== null) {\n const value = line.replace(/^\\s{2}version\\s+/, \"\").trim();\n version = stripQuotes(value);\n readingDependencies = false;\n continue;\n }\n\n if (line.match(/^\\s{2}dependencies:\\s*$/) !== null) {\n readingDependencies = true;\n continue;\n }\n\n if (readingDependencies && line.match(/^\\s{4}[^\\s].+$/) !== null) {\n const depLine = line.trim();\n const firstSpace = depLine.indexOf(\" \");\n if (firstSpace <= 0) {\n continue;\n }\n\n const depName = stripQuotes(depLine.slice(0, firstSpace));\n const depRef = stripQuotes(depLine.slice(firstSpace + 1).trim());\n const depVersion = parseVersionSelector(depRef) ?? depRef;\n dependencies.push(`${depName}@${depVersion}`);\n continue;\n }\n\n readingDependencies = false;\n }\n\n flushEntry();\n\n const deduped = new Map<string, LockedDependencyNode>();\n for (const node of nodes) {\n const key = `${node.name}@${node.version}`;\n if (!deduped.has(key)) {\n deduped.set(key, node);\n }\n }\n\n return {\n kind: \"yarn\",\n directDependencies: directSpecs,\n nodes: [...deduped.values()].sort(\n (a, b) => a.name.localeCompare(b.name) || a.version.localeCompare(b.version),\n ),\n };\n};\n","import type { DirectDependencySpec, LockfileExtraction } from \"../domain/types.js\";\n\nexport const parseBunLock = (\n _raw: string,\n _directSpecs: readonly DirectDependencySpec[],\n): LockfileExtraction => {\n throw new Error(\"unsupported_lockfile_format\");\n};\n","import type { LockfileExtraction } from \"../domain/types.js\";\nimport type { parsePackageJson } from \"../parsing/package-json-loader.js\";\nimport { parsePackageLock } from \"../parsing/package-lock-parser.js\";\nimport { parsePnpmLockfile } from \"../parsing/pnpm-lock-parser.js\";\nimport { parseYarnLock } from \"../parsing/yarn-lock-parser.js\";\nimport { parseBunLock } from \"../parsing/bun-lock-parser.js\";\n\ntype SupportedLockfileKind = \"pnpm\" | \"npm\" | \"npm-shrinkwrap\" | \"yarn\" | \"bun\";\n\nexport const parseLockfileExtraction = (\n lockfileKind: SupportedLockfileKind,\n lockfileRaw: string,\n directSpecs: ReturnType<typeof parsePackageJson>,\n): LockfileExtraction => {\n switch (lockfileKind) {\n case \"pnpm\":\n return parsePnpmLockfile(lockfileRaw, directSpecs);\n case \"npm\":\n case \"npm-shrinkwrap\":\n return {\n ...parsePackageLock(lockfileRaw, directSpecs),\n kind: lockfileKind,\n };\n case \"yarn\":\n return parseYarnLock(lockfileRaw, directSpecs);\n case \"bun\":\n return parseBunLock(lockfileRaw, directSpecs);\n default:\n throw new Error(\"unsupported_lockfile_format\");\n }\n};\n","import type { CacheStore } from \"./cache-store.js\";\n\ntype CachedFetchOptions<T> = {\n key: string;\n ttlMs: number;\n cacheStore: CacheStore | null;\n fetchFresh: () => Promise<T | null>;\n nowMs?: number;\n};\n\nexport const cachedFetch = async <T>(options: CachedFetchOptions<T>): Promise<T | null> => {\n const nowMs = options.nowMs ?? Date.now();\n const cachedEntry =\n options.cacheStore === null ? null : await options.cacheStore.get<T>(options.key);\n\n if (cachedEntry !== null && nowMs - cachedEntry.fetchedAtMs <= options.ttlMs) {\n return cachedEntry.value;\n }\n\n try {\n const fresh = await options.fetchFresh();\n if (fresh !== null) {\n void options.cacheStore?.set(options.key, { value: fresh, fetchedAtMs: nowMs }).catch(() => {\n // Cache persistence failures should not impact the primary fetch path.\n });\n return fresh;\n }\n } catch {\n // Network failures should not block stale fallback.\n }\n\n return cachedEntry?.value ?? null;\n};\n","import { setTimeout as sleep } from \"node:timers/promises\";\n\nexport type FetchRetryOptions = {\n retries: number;\n baseDelayMs: number;\n};\n\nconst parseRetryAfterMs = (value: string | null): number | null => {\n if (value === null) {\n return null;\n }\n\n const seconds = Number.parseInt(value, 10);\n if (!Number.isFinite(seconds) || seconds <= 0) {\n return null;\n }\n\n return seconds * 1000;\n};\n\nconst shouldRetryStatus = (status: number): boolean => status === 429 || status >= 500;\n\nexport const fetchJsonWithRetry = async <T>(\n url: string,\n options: FetchRetryOptions,\n): Promise<T | null> => {\n for (let attempt = 0; attempt <= options.retries; attempt += 1) {\n const response = await fetch(url);\n if (response.ok) {\n return (await response.json()) as T;\n }\n\n if (!shouldRetryStatus(response.status) || attempt === options.retries) {\n return null;\n }\n\n const retryAfterMs = parseRetryAfterMs(response.headers.get(\"retry-after\"));\n const backoffMs = retryAfterMs ?? options.baseDelayMs * 2 ** attempt;\n await sleep(backoffMs);\n }\n\n return null;\n};\n","import { join } from \"node:path\";\nimport type { CacheStore } from \"./cache-store.js\";\nimport { resolveCodesentinelCacheDir } from \"./codesentinel-cache-dir.js\";\nimport { FileCacheStore } from \"./file-cache-store.js\";\n\nconst SIX_HOURS_MS = 6 * 60 * 60 * 1000;\nconst ONE_DAY_MS = 24 * 60 * 60 * 1000;\nconst DEFAULT_MAX_BYTES = 20 * 1024 * 1024;\nconst DEFAULT_MAX_ENTRY_BYTES = 4 * 1024 * 1024;\nconst DEFAULT_SWEEP_INTERVAL_WRITES = 25;\n\nlet cacheStoreSingleton: CacheStore | null | undefined;\n\nconst parsePositiveIntegerFromEnv = (value: string | undefined, fallback: number): number => {\n if (value === undefined) {\n return fallback;\n }\n const parsed = Number.parseInt(value, 10);\n if (!Number.isFinite(parsed) || parsed <= 0) {\n return fallback;\n }\n return parsed;\n};\n\nconst cacheDisabled = (env: NodeJS.ProcessEnv): boolean => {\n const mode = env[\"CODESENTINEL_CACHE_MODE\"]?.trim().toLowerCase();\n return mode === \"none\";\n};\n\nexport const getNpmMetadataCacheStore = (): CacheStore | null => {\n if (cacheStoreSingleton !== undefined) {\n return cacheStoreSingleton;\n }\n\n if (cacheDisabled(process.env)) {\n cacheStoreSingleton = null;\n return cacheStoreSingleton;\n }\n\n const path = join(resolveCodesentinelCacheDir(process.env), \"npm-metadata-v2\");\n const packumentTtlMs = getPackumentCacheTtlMs();\n const downloadsTtlMs = getWeeklyDownloadsCacheTtlMs();\n cacheStoreSingleton = new FileCacheStore(path, {\n maxBytes: parsePositiveIntegerFromEnv(\n process.env[\"CODESENTINEL_CACHE_MAX_BYTES\"],\n DEFAULT_MAX_BYTES,\n ),\n maxEntryBytes: parsePositiveIntegerFromEnv(\n process.env[\"CODESENTINEL_CACHE_MAX_ENTRY_BYTES\"],\n DEFAULT_MAX_ENTRY_BYTES,\n ),\n sweepIntervalWrites: parsePositiveIntegerFromEnv(\n process.env[\"CODESENTINEL_CACHE_SWEEP_INTERVAL_WRITES\"],\n DEFAULT_SWEEP_INTERVAL_WRITES,\n ),\n bucketForKey: (key) => {\n if (key.startsWith(\"npm:downloads:last-week:\")) {\n return \"downloads\";\n }\n if (key.startsWith(\"npm:packument:\")) {\n return \"packument\";\n }\n return \"default\";\n },\n maxAgeMsByBucket: {\n downloads: downloadsTtlMs,\n packument: packumentTtlMs,\n },\n });\n return cacheStoreSingleton;\n};\n\nexport const getPackumentCacheTtlMs = (): number =>\n parsePositiveIntegerFromEnv(process.env[\"CODESENTINEL_CACHE_TTL_PACKUMENT_MS\"], SIX_HOURS_MS);\n\nexport const getWeeklyDownloadsCacheTtlMs = (): number =>\n parsePositiveIntegerFromEnv(process.env[\"CODESENTINEL_CACHE_TTL_DOWNLOADS_MS\"], ONE_DAY_MS);\n\nexport const toMetadataPackumentCacheKey = (name: string): string =>\n `npm:packument:metadata:${name}`;\nexport const toGraphPackumentCacheKey = (name: string): string => `npm:packument:graph:${name}`;\nexport const toWeeklyDownloadsCacheKey = (name: string): string =>\n `npm:downloads:last-week:${name}`;\n","import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nexport const resolveCodesentinelCacheDir = (env: NodeJS.ProcessEnv = process.env): string => {\n const explicit = env[\"CODESENTINEL_CACHE_DIR\"]?.trim();\n if (explicit !== undefined && explicit.length > 0) {\n return explicit;\n }\n\n if (process.platform === \"win32\") {\n const localAppData = env[\"LOCALAPPDATA\"]?.trim();\n if (localAppData !== undefined && localAppData.length > 0) {\n return join(localAppData, \"codesentinel\", \"Cache\");\n }\n return join(homedir(), \"AppData\", \"Local\", \"codesentinel\", \"Cache\");\n }\n\n const xdgCacheHome = env[\"XDG_CACHE_HOME\"]?.trim();\n if (xdgCacheHome !== undefined && xdgCacheHome.length > 0) {\n return join(xdgCacheHome, \"codesentinel\");\n }\n\n return join(homedir(), \".cache\", \"codesentinel\");\n};\n","import { createHash } from \"node:crypto\";\nimport { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { CacheEntry, CacheStore } from \"./cache-store.js\";\n\ntype CacheEntryPayload = {\n key: string;\n fetchedAtMs: number;\n value: unknown;\n};\n\nconst parseCacheEntryPayload = (value: unknown): CacheEntryPayload | null => {\n if (typeof value !== \"object\" || value === null) {\n return null;\n }\n\n const payload = value as { key?: unknown; fetchedAtMs?: unknown; value?: unknown };\n if (typeof payload.key !== \"string\" || payload.key.length === 0) {\n return null;\n }\n if (typeof payload.fetchedAtMs !== \"number\" || !Number.isFinite(payload.fetchedAtMs)) {\n return null;\n }\n\n return {\n key: payload.key,\n fetchedAtMs: payload.fetchedAtMs,\n value: payload.value,\n };\n};\n\ntype FileCacheStoreOptions = {\n maxBytes: number;\n maxEntryBytes: number;\n sweepIntervalWrites: number;\n bucketForKey?: (key: string) => string;\n maxAgeMsByBucket?: Readonly<Record<string, number>>;\n};\n\nconst DEFAULT_OPTIONS: FileCacheStoreOptions = {\n maxBytes: 100 * 1024 * 1024,\n maxEntryBytes: 4 * 1024 * 1024,\n sweepIntervalWrites: 25,\n};\n\nconst DEFAULT_BUCKET = \"default\";\n\nconst normalizeBucket = (value: string): string => {\n const trimmed = value.trim().toLowerCase();\n if (trimmed.length === 0) {\n return DEFAULT_BUCKET;\n }\n return trimmed.replace(/[^a-z0-9_-]/g, \"_\");\n};\n\nexport class FileCacheStore implements CacheStore {\n private readonly byKey = new Map<string, CacheEntry<unknown> | null>();\n private readonly inFlightWrites = new Map<string, Promise<void>>();\n private writesSinceSweep = 0;\n private sweepPromise: Promise<void> = Promise.resolve();\n\n constructor(\n private readonly directoryPath: string,\n private readonly options: FileCacheStoreOptions = DEFAULT_OPTIONS,\n ) {}\n\n private bucketForKey(key: string): string {\n const configured = this.options.bucketForKey?.(key);\n if (configured === undefined) {\n return DEFAULT_BUCKET;\n }\n return normalizeBucket(configured);\n }\n\n private toEntryPath(key: string): string {\n const bucket = this.bucketForKey(key);\n const digest = createHash(\"sha256\").update(key).digest(\"hex\");\n return join(this.directoryPath, bucket, `${digest}.json`);\n }\n\n private async writeEntry(key: string, entry: CacheEntry<unknown>): Promise<void> {\n const filePath = this.toEntryPath(key);\n const bucketPath = join(this.directoryPath, this.bucketForKey(key));\n await mkdir(bucketPath, { recursive: true });\n const tempPath = `${filePath}.tmp`;\n const payload: CacheEntryPayload = {\n key,\n fetchedAtMs: entry.fetchedAtMs,\n value: entry.value,\n };\n const raw = JSON.stringify(payload);\n if (Buffer.byteLength(raw, \"utf8\") > this.options.maxEntryBytes) {\n return;\n }\n\n await writeFile(tempPath, raw, \"utf8\");\n await rename(tempPath, filePath);\n }\n\n private async sweepIfNeeded(): Promise<void> {\n this.writesSinceSweep += 1;\n if (this.writesSinceSweep < this.options.sweepIntervalWrites) {\n return;\n }\n this.writesSinceSweep = 0;\n\n this.sweepPromise = this.sweepPromise\n .catch(() => {\n // Keep sweep queue alive across failures.\n })\n .then(async () => {\n await this.evictToSizeLimit();\n });\n await this.sweepPromise;\n }\n\n private async evictToSizeLimit(): Promise<void> {\n const nowMs = Date.now();\n let entries: Array<{ path: string; size: number; mtimeMs: number; bucket: string }>;\n try {\n const bucketEntries = await readdir(this.directoryPath, { withFileTypes: true });\n const bucketNames = bucketEntries\n .filter((entry) => entry.isDirectory())\n .map((entry) => entry.name);\n entries = (\n await Promise.all(\n bucketNames.map(async (bucket) => {\n const bucketPath = join(this.directoryPath, bucket);\n const files = await readdir(bucketPath, { withFileTypes: true });\n return await Promise.all(\n files\n .filter((entry) => entry.isFile() && entry.name.endsWith(\".json\"))\n .map(async (entry) => {\n const path = join(bucketPath, entry.name);\n const info = await stat(path);\n return {\n path,\n size: info.size,\n mtimeMs: info.mtimeMs,\n bucket,\n };\n }),\n );\n }),\n )\n )\n .flat()\n .filter((entry) => Number.isFinite(entry.size) && entry.size > 0);\n } catch {\n return;\n }\n\n if (this.options.maxAgeMsByBucket !== undefined) {\n const retained: typeof entries = [];\n let deletedAny = false;\n for (const entry of entries) {\n const maxAgeMs = this.options.maxAgeMsByBucket[entry.bucket];\n const expired =\n typeof maxAgeMs === \"number\" &&\n Number.isFinite(maxAgeMs) &&\n nowMs - entry.mtimeMs > maxAgeMs;\n if (!expired) {\n retained.push(entry);\n continue;\n }\n\n try {\n await unlink(entry.path);\n deletedAny = true;\n } catch {\n retained.push(entry);\n }\n }\n entries = retained;\n if (deletedAny) {\n this.byKey.clear();\n }\n }\n\n let totalBytes = entries.reduce((sum, entry) => sum + entry.size, 0);\n if (totalBytes <= this.options.maxBytes) {\n return;\n }\n\n entries.sort((a, b) => a.mtimeMs - b.mtimeMs);\n let deletedAny = false;\n for (const entry of entries) {\n if (totalBytes <= this.options.maxBytes) {\n break;\n }\n try {\n await unlink(entry.path);\n deletedAny = true;\n totalBytes -= entry.size;\n } catch {\n // Ignore eviction failures for individual files.\n }\n }\n if (deletedAny) {\n this.byKey.clear();\n }\n }\n\n async get<T>(key: string): Promise<CacheEntry<T> | null> {\n if (this.byKey.has(key)) {\n return (this.byKey.get(key) as CacheEntry<T> | null) ?? null;\n }\n\n try {\n const raw = await readFile(this.toEntryPath(key), \"utf8\");\n const parsed = parseCacheEntryPayload(JSON.parse(raw));\n if (parsed === null || parsed.key !== key) {\n this.byKey.set(key, null);\n return null;\n }\n\n const value = { fetchedAtMs: parsed.fetchedAtMs, value: parsed.value as T };\n this.byKey.set(key, value as CacheEntry<unknown>);\n return value;\n } catch {\n this.byKey.set(key, null);\n return null;\n }\n }\n\n async set<T>(key: string, entry: CacheEntry<T>): Promise<void> {\n const normalized = entry as CacheEntry<unknown>;\n this.byKey.set(key, normalized);\n\n const previous = this.inFlightWrites.get(key) ?? Promise.resolve();\n const next = previous\n .catch(() => {\n // Keep write chain active even after previous failures.\n })\n .then(async () => {\n await this.writeEntry(key, normalized);\n await this.sweepIfNeeded();\n });\n this.inFlightWrites.set(key, next);\n await next;\n }\n}\n","import type { DirectDependencySpec, LockedDependencyNode } from \"../domain/types.js\";\nimport { cachedFetch } from \"../infrastructure/cached-fetch.js\";\nimport { fetchJsonWithRetry } from \"../infrastructure/fetch-json-with-retry.js\";\nimport {\n getNpmMetadataCacheStore,\n getPackumentCacheTtlMs,\n toGraphPackumentCacheKey,\n} from \"../infrastructure/npm-metadata-cache.js\";\n\ntype NpmPackageManifest = {\n dependencies?: Record<string, string>;\n};\n\ntype NpmPackumentRaw = {\n \"dist-tags\"?: Record<string, string>;\n versions?: Record<string, NpmPackageManifest>;\n};\n\ntype NpmPackumentGraph = {\n \"dist-tags\"?: Record<string, string>;\n versionNames: readonly string[];\n dependenciesByVersion: Readonly<Record<string, Record<string, string>>>;\n};\n\ntype ParsedSemver = {\n major: number;\n minor: number;\n patch: number;\n prerelease: readonly (string | number)[];\n};\n\ntype ResolvedVersion = {\n version: string;\n resolution: \"exact\" | \"tag\" | \"range\" | \"latest\";\n fallbackUsed: boolean;\n};\n\ntype QueueItem = {\n name: string;\n requested: string | null;\n depth: number;\n};\n\nexport type ResolvedDirectDependency = {\n name: string;\n requestedRange: string;\n resolvedVersion: string;\n resolution: \"exact\" | \"tag\" | \"range\" | \"latest\";\n scope: \"prod\" | \"dev\";\n};\n\nexport type ResolveRegistryGraphResult = {\n nodes: readonly LockedDependencyNode[];\n directDependencies: readonly ResolvedDirectDependency[];\n assumptions: readonly string[];\n truncated: boolean;\n};\n\nexport type ResolveRegistryGraphOptions = {\n maxNodes: number;\n maxDepth: number;\n};\n\nconst MAX_RETRIES = 3;\nconst RETRY_BASE_DELAY_MS = 500;\nconst PACKUMENT_CACHE_STORE = getNpmMetadataCacheStore();\n\nconst parsePrerelease = (value: string | undefined): readonly (string | number)[] => {\n if (value === undefined || value.length === 0) {\n return [];\n }\n\n return value.split(\".\").map((part) => {\n const asNumber = Number.parseInt(part, 10);\n if (!Number.isNaN(asNumber) && `${asNumber}` === part) {\n return asNumber;\n }\n\n return part;\n });\n};\n\nconst parseSemver = (value: string): ParsedSemver | null => {\n const trimmed = value.trim();\n const semverMatch = trimmed.match(\n /^v?(\\d+)\\.(\\d+)\\.(\\d+)(?:-([0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/,\n );\n if (semverMatch === null) {\n return null;\n }\n\n const major = Number.parseInt(semverMatch[1] ?? \"\", 10);\n const minor = Number.parseInt(semverMatch[2] ?? \"\", 10);\n const patch = Number.parseInt(semverMatch[3] ?? \"\", 10);\n if (!Number.isFinite(major) || !Number.isFinite(minor) || !Number.isFinite(patch)) {\n return null;\n }\n\n return {\n major,\n minor,\n patch,\n prerelease: parsePrerelease(semverMatch[4]),\n };\n};\n\nconst compareIdentifier = (left: string | number, right: string | number): number => {\n if (typeof left === \"number\" && typeof right === \"number\") {\n return left - right;\n }\n\n if (typeof left === \"number\") {\n return -1;\n }\n\n if (typeof right === \"number\") {\n return 1;\n }\n\n return left.localeCompare(right);\n};\n\nconst compareSemver = (left: ParsedSemver, right: ParsedSemver): number => {\n if (left.major !== right.major) {\n return left.major - right.major;\n }\n if (left.minor !== right.minor) {\n return left.minor - right.minor;\n }\n if (left.patch !== right.patch) {\n return left.patch - right.patch;\n }\n\n if (left.prerelease.length === 0 && right.prerelease.length === 0) {\n return 0;\n }\n if (left.prerelease.length === 0) {\n return 1;\n }\n if (right.prerelease.length === 0) {\n return -1;\n }\n\n const maxLength = Math.max(left.prerelease.length, right.prerelease.length);\n for (let i = 0; i < maxLength; i += 1) {\n const leftPart = left.prerelease[i];\n const rightPart = right.prerelease[i];\n\n if (leftPart === undefined && rightPart === undefined) {\n return 0;\n }\n if (leftPart === undefined) {\n return -1;\n }\n if (rightPart === undefined) {\n return 1;\n }\n\n const diff = compareIdentifier(leftPart, rightPart);\n if (diff !== 0) {\n return diff;\n }\n }\n\n return 0;\n};\n\nconst isWildcardPart = (value: string | undefined): boolean =>\n value === undefined || value === \"*\" || value.toLowerCase() === \"x\";\n\nconst matchesPartialVersion = (version: ParsedSemver, token: string): boolean => {\n const normalized = token.trim().replace(/^v/, \"\");\n if (normalized === \"*\" || normalized.length === 0) {\n return true;\n }\n\n const [majorPart, minorPart, patchPart] = normalized.split(\".\");\n if (majorPart !== undefined && !isWildcardPart(majorPart)) {\n const major = Number.parseInt(majorPart, 10);\n if (!Number.isFinite(major) || major !== version.major) {\n return false;\n }\n }\n\n if (minorPart !== undefined && !isWildcardPart(minorPart)) {\n const minor = Number.parseInt(minorPart, 10);\n if (!Number.isFinite(minor) || minor !== version.minor) {\n return false;\n }\n }\n\n if (patchPart !== undefined && !isWildcardPart(patchPart)) {\n const patch = Number.parseInt(patchPart, 10);\n if (!Number.isFinite(patch) || patch !== version.patch) {\n return false;\n }\n }\n\n return true;\n};\n\nconst parseComparatorToken = (token: string): { operator: string; versionToken: string } => {\n const operators = [\">=\", \"<=\", \">\", \"<\", \"=\"];\n for (const operator of operators) {\n if (token.startsWith(operator)) {\n return {\n operator,\n versionToken: token.slice(operator.length).trim(),\n };\n }\n }\n\n return {\n operator: \"=\",\n versionToken: token.trim(),\n };\n};\n\nconst satisfiesComparator = (version: ParsedSemver, token: string): boolean | null => {\n if (token.length === 0 || token === \"*\") {\n return true;\n }\n\n if (token.startsWith(\"^\")) {\n const base = parseSemver(token.slice(1));\n if (base === null) {\n return null;\n }\n\n let upper: ParsedSemver;\n if (base.major > 0) {\n upper = { major: base.major + 1, minor: 0, patch: 0, prerelease: [] };\n } else if (base.minor > 0) {\n upper = { major: 0, minor: base.minor + 1, patch: 0, prerelease: [] };\n } else {\n upper = { major: 0, minor: 0, patch: base.patch + 1, prerelease: [] };\n }\n\n return compareSemver(version, base) >= 0 && compareSemver(version, upper) < 0;\n }\n\n if (token.startsWith(\"~\")) {\n const base = parseSemver(token.slice(1));\n if (base === null) {\n return null;\n }\n\n const upper: ParsedSemver = {\n major: base.major,\n minor: base.minor + 1,\n patch: 0,\n prerelease: [],\n };\n\n return compareSemver(version, base) >= 0 && compareSemver(version, upper) < 0;\n }\n\n const parsedComparator = parseComparatorToken(token);\n const hasWildcard = /(^|[.])(?:x|X|\\*)($|[.])/.test(parsedComparator.versionToken);\n if (hasWildcard) {\n if (parsedComparator.operator !== \"=\") {\n return null;\n }\n return matchesPartialVersion(version, parsedComparator.versionToken);\n }\n\n const parsedVersion = parseSemver(parsedComparator.versionToken);\n if (parsedVersion === null) {\n if (parsedComparator.operator !== \"=\") {\n return null;\n }\n\n return matchesPartialVersion(version, parsedComparator.versionToken);\n }\n\n const comparison = compareSemver(version, parsedVersion);\n switch (parsedComparator.operator) {\n case \">\":\n return comparison > 0;\n case \">=\":\n return comparison >= 0;\n case \"<\":\n return comparison < 0;\n case \"<=\":\n return comparison <= 0;\n case \"=\":\n return comparison === 0;\n default:\n return null;\n }\n};\n\nconst satisfiesRangeClause = (version: ParsedSemver, clause: string): boolean | null => {\n const hyphenMatch = clause.match(/^\\s*(.+?)\\s+-\\s+(.+?)\\s*$/);\n if (hyphenMatch !== null) {\n const lower = hyphenMatch[1];\n const upper = hyphenMatch[2];\n if (lower === undefined || upper === undefined) {\n return null;\n }\n\n const lowerResult = satisfiesComparator(version, `>=${lower}`);\n const upperResult = satisfiesComparator(version, `<=${upper}`);\n if (lowerResult === null || upperResult === null) {\n return null;\n }\n\n return lowerResult && upperResult;\n }\n\n const tokens = clause\n .split(/\\s+/)\n .map((token) => token.trim())\n .filter((token) => token.length > 0);\n\n if (tokens.length === 0) {\n return true;\n }\n\n for (const token of tokens) {\n const matched = satisfiesComparator(version, token);\n if (matched === null) {\n return null;\n }\n\n if (!matched) {\n return false;\n }\n }\n\n return true;\n};\n\nconst resolveRangeVersion = (versions: readonly string[], requested: string): string | null => {\n const clauses = requested\n .split(\"||\")\n .map((clause) => clause.trim())\n .filter((clause) => clause.length > 0);\n\n if (clauses.length === 0) {\n return null;\n }\n\n const parsedVersions = versions\n .map((version) => ({ version, parsed: parseSemver(version) }))\n .filter(\n (candidate): candidate is { version: string; parsed: ParsedSemver } =>\n candidate.parsed !== null,\n )\n .sort((a, b) => compareSemver(b.parsed, a.parsed));\n\n for (const candidate of parsedVersions) {\n let clauseMatched = false;\n let clauseUnsupported = false;\n\n for (const clause of clauses) {\n const matched = satisfiesRangeClause(candidate.parsed, clause);\n if (matched === null) {\n clauseUnsupported = true;\n continue;\n }\n\n if (matched) {\n clauseMatched = true;\n break;\n }\n }\n\n if (clauseMatched) {\n return candidate.version;\n }\n\n if (clauseUnsupported && clauses.length === 1) {\n return null;\n }\n }\n\n return null;\n};\n\nconst slimPackumentForGraph = (payload: NpmPackumentRaw): NpmPackumentGraph => {\n const versions = payload.versions ?? {};\n const dependenciesByVersion: Record<string, Record<string, string>> = {};\n const versionNames = Object.keys(versions);\n\n for (const [version, manifest] of Object.entries(versions)) {\n const dependenciesRaw = manifest?.dependencies ?? {};\n const dependencies: Record<string, string> = {};\n for (const [dependencyName, dependencyRange] of Object.entries(dependenciesRaw)) {\n if (dependencyName.length > 0 && dependencyRange.length > 0) {\n dependencies[dependencyName] = dependencyRange;\n }\n }\n\n if (Object.keys(dependencies).length > 0) {\n dependenciesByVersion[version] = dependencies;\n }\n }\n\n const slim: NpmPackumentGraph = {\n versionNames,\n dependenciesByVersion,\n };\n if (payload[\"dist-tags\"] !== undefined) {\n slim[\"dist-tags\"] = payload[\"dist-tags\"];\n }\n return slim;\n};\n\nconst fetchPackument = async (name: string): Promise<NpmPackumentGraph | null> => {\n const encodedName = encodeURIComponent(name);\n try {\n return await cachedFetch<NpmPackumentGraph>({\n key: toGraphPackumentCacheKey(name),\n ttlMs: getPackumentCacheTtlMs(),\n cacheStore: PACKUMENT_CACHE_STORE,\n fetchFresh: async () => {\n const payload = await fetchJsonWithRetry<NpmPackumentRaw>(\n `https://registry.npmjs.org/${encodedName}`,\n {\n retries: MAX_RETRIES,\n baseDelayMs: RETRY_BASE_DELAY_MS,\n },\n );\n if (payload === null) {\n return null;\n }\n return slimPackumentForGraph(payload);\n },\n });\n } catch {\n return null;\n }\n};\n\nconst resolveRequestedVersion = (\n packument: NpmPackumentGraph,\n requested: string | null,\n): ResolvedVersion | null => {\n const versionKeys = [...packument.versionNames];\n const versionSet = new Set(versionKeys);\n const tags = packument[\"dist-tags\"] ?? {};\n const latest = tags[\"latest\"];\n\n if (requested !== null && versionSet.has(requested)) {\n return {\n version: requested,\n resolution: \"exact\",\n fallbackUsed: false,\n };\n }\n\n if (requested !== null) {\n const tagged = tags[requested];\n if (tagged !== undefined && versionSet.has(tagged)) {\n return {\n version: tagged,\n resolution: \"tag\",\n fallbackUsed: false,\n };\n }\n }\n\n if (requested !== null) {\n const matched = resolveRangeVersion(versionKeys, requested);\n if (matched !== null && versionSet.has(matched)) {\n return {\n version: matched,\n resolution: \"range\",\n fallbackUsed: false,\n };\n }\n }\n\n if (latest !== undefined && versionSet.has(latest)) {\n return {\n version: latest,\n resolution: \"latest\",\n fallbackUsed: requested !== null,\n };\n }\n\n const semverSorted = versionKeys\n .map((version) => ({ version, parsed: parseSemver(version) }))\n .filter(\n (candidate): candidate is { version: string; parsed: ParsedSemver } =>\n candidate.parsed !== null,\n )\n .sort((a, b) => compareSemver(b.parsed, a.parsed))\n .map((candidate) => candidate.version);\n const fallbackVersion = semverSorted[0] ?? versionKeys.sort((a, b) => b.localeCompare(a))[0];\n if (fallbackVersion === undefined) {\n return null;\n }\n\n return {\n version: fallbackVersion,\n resolution: \"latest\",\n fallbackUsed: requested !== null,\n };\n};\n\nexport const resolveRegistryGraphFromDirectSpecs = async (\n directSpecs: readonly DirectDependencySpec[],\n options: ResolveRegistryGraphOptions,\n): Promise<ResolveRegistryGraphResult> => {\n const maxNodes = Math.max(1, options.maxNodes);\n const maxDepth = Math.max(0, options.maxDepth);\n\n const queue: QueueItem[] = directSpecs.map((spec) => ({\n name: spec.name,\n requested: spec.requestedRange,\n depth: 0,\n }));\n const scopeByName = new Map(directSpecs.map((spec) => [spec.name, spec.scope]));\n const requestedByName = new Map(directSpecs.map((spec) => [spec.name, spec.requestedRange]));\n const packumentByName = new Map<string, NpmPackumentGraph | null>();\n const nodesByKey = new Map<string, LockedDependencyNode>();\n const directByName = new Map<string, ResolvedDirectDependency>();\n const assumptions = new Set<string>();\n let truncated = false;\n\n while (queue.length > 0) {\n if (nodesByKey.size >= maxNodes) {\n truncated = true;\n assumptions.add(`Dependency graph truncated at ${maxNodes} nodes.`);\n break;\n }\n\n const item = queue.shift();\n if (item === undefined) {\n break;\n }\n\n let packument = packumentByName.get(item.name) ?? null;\n if (!packumentByName.has(item.name)) {\n packument = await fetchPackument(item.name);\n packumentByName.set(item.name, packument);\n }\n\n if (packument === null) {\n if (scopeByName.has(item.name)) {\n assumptions.add(`Could not resolve direct dependency from registry: ${item.name}.`);\n }\n continue;\n }\n\n const resolved = resolveRequestedVersion(packument, item.requested);\n if (resolved === null) {\n if (scopeByName.has(item.name)) {\n assumptions.add(`Could not resolve direct dependency version: ${item.name}.`);\n }\n continue;\n }\n\n if (scopeByName.has(item.name) && !directByName.has(item.name)) {\n directByName.set(item.name, {\n name: item.name,\n requestedRange: requestedByName.get(item.name) ?? \"latest\",\n resolvedVersion: resolved.version,\n resolution: resolved.resolution,\n scope: scopeByName.get(item.name) ?? \"prod\",\n });\n }\n\n if (resolved.fallbackUsed && item.requested !== null) {\n assumptions.add(\n `Resolved ${item.name}@${item.requested} to latest (${resolved.version}) because exact/tag/range match was unavailable.`,\n );\n }\n\n const nodeKey = `${item.name}@${resolved.version}`;\n if (nodesByKey.has(nodeKey)) {\n continue;\n }\n\n const manifestDependencies = packument.dependenciesByVersion[resolved.version] ?? {};\n const dependencies = Object.entries(manifestDependencies)\n .filter(\n ([dependencyName, dependencyRange]) =>\n dependencyName.length > 0 && dependencyRange.length > 0,\n )\n .sort((a, b) => a[0].localeCompare(b[0]));\n\n nodesByKey.set(nodeKey, {\n name: item.name,\n version: resolved.version,\n dependencies: dependencies.map(\n ([dependencyName, dependencyRange]) => `${dependencyName}@${dependencyRange}`,\n ),\n });\n\n if (item.depth >= maxDepth && dependencies.length > 0) {\n truncated = true;\n assumptions.add(`Dependency graph truncated at depth ${maxDepth}.`);\n continue;\n }\n\n for (const [dependencyName, dependencyRange] of dependencies) {\n if (nodesByKey.size + queue.length >= maxNodes) {\n truncated = true;\n assumptions.add(`Dependency graph truncated at ${maxNodes} nodes.`);\n break;\n }\n\n queue.push({\n name: dependencyName,\n requested: dependencyRange,\n depth: item.depth + 1,\n });\n }\n }\n\n return {\n nodes: [...nodesByKey.values()].sort(\n (a, b) => a.name.localeCompare(b.name) || a.version.localeCompare(b.version),\n ),\n directDependencies: [...directByName.values()].sort((a, b) => a.name.localeCompare(b.name)),\n assumptions: [...assumptions].sort((a, b) => a.localeCompare(b)),\n truncated,\n };\n};\n","import type { LockfileExtraction } from \"../domain/types.js\";\nimport { loadPackageJson, selectLockfile } from \"../infrastructure/fs-loader.js\";\nimport { parsePackageJson } from \"../parsing/package-json-loader.js\";\nimport { parseLockfileExtraction } from \"./parse-lockfile-extraction.js\";\nimport { resolveRegistryGraphFromDirectSpecs } from \"./resolve-registry-graph.js\";\n\ntype LockfileKind = \"pnpm\" | \"npm\" | \"npm-shrinkwrap\" | \"yarn\" | \"bun\";\n\nexport type PreparedDependencyExtraction =\n | {\n available: false;\n reason: \"package_json_not_found\" | \"lockfile_not_found\";\n }\n | {\n available: true;\n lockfileKind: LockfileKind;\n extraction: LockfileExtraction;\n };\n\nexport const prepareDependencyExtraction = async (\n repositoryPath: string,\n): Promise<PreparedDependencyExtraction> => {\n const packageJson = loadPackageJson(repositoryPath);\n if (packageJson === null) {\n return {\n available: false,\n reason: \"package_json_not_found\",\n };\n }\n\n const directSpecs = parsePackageJson(packageJson.raw);\n const lockfile = selectLockfile(repositoryPath);\n\n if (lockfile === null) {\n const resolvedGraph = await resolveRegistryGraphFromDirectSpecs(directSpecs, {\n maxNodes: 500,\n maxDepth: 8,\n });\n if (resolvedGraph.nodes.length === 0) {\n return {\n available: false,\n reason: \"lockfile_not_found\",\n };\n }\n\n return {\n available: true,\n lockfileKind: \"npm\",\n extraction: {\n kind: \"npm\",\n directDependencies: resolvedGraph.directDependencies.map((dependency) => ({\n name: dependency.name,\n requestedRange: dependency.requestedRange,\n scope: dependency.scope,\n })),\n nodes: resolvedGraph.nodes,\n },\n };\n }\n\n return {\n available: true,\n lockfileKind: lockfile.kind,\n extraction: parseLockfileExtraction(lockfile.kind, lockfile.raw, directSpecs),\n };\n};\n","import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { basename, join, relative, resolve } from \"node:path\";\nimport type { WorkspaceKind } from \"@codesentinel/core\";\nimport type { WorkspaceDependencyManifest } from \"../domain/types.js\";\nimport { parsePackageJson } from \"../parsing/package-json-loader.js\";\n\ntype PackageJsonWorkspaceConfig = {\n name?: string;\n workspaces?: readonly string[] | { packages?: readonly string[] };\n};\n\nconst normalizePath = (pathValue: string): string => pathValue.replaceAll(\"\\\\\", \"/\");\n\nconst stripQuotes = (value: string): string => value.replace(/^['\"]|['\"]$/g, \"\");\n\nconst readPackageJson = (path: string): PackageJsonWorkspaceConfig | null => {\n try {\n return JSON.parse(readFileSync(path, \"utf8\")) as PackageJsonWorkspaceConfig;\n } catch {\n return null;\n }\n};\n\nconst inferWorkspaceKind = (workspacePath: string): WorkspaceKind => {\n const segments = workspacePath.split(\"/\");\n const first = segments[0] ?? \"\";\n\n if (first === \"apps\" || first === \"app\") {\n return \"app\";\n }\n\n if (first === \"packages\" || first === \"package\") {\n return \"package\";\n }\n\n if (first === \"docs\" || first === \"documentation\") {\n return \"docs\";\n }\n\n if (first === \"examples\" || first === \"example-apps\" || first === \"playground\") {\n return \"example\";\n }\n\n if (first === \"tooling\" || first === \"tools\") {\n return \"tooling\";\n }\n\n return \"unknown\";\n};\n\nconst readWorkspacePatternsFromPackageJson = (projectRoot: string): readonly string[] => {\n const packageJson = readPackageJson(join(projectRoot, \"package.json\"));\n if (packageJson?.workspaces === undefined) {\n return [];\n }\n\n const workspaces = packageJson.workspaces;\n if (Array.isArray(workspaces)) {\n const workspaceArray: readonly unknown[] = workspaces;\n return workspaceArray.filter((workspace): workspace is string => typeof workspace === \"string\");\n }\n\n const workspaceObject = workspaces as { packages?: readonly string[] };\n return workspaceObject.packages ?? [];\n};\n\nconst readWorkspacePatternsFromPnpmWorkspace = (projectRoot: string): readonly string[] => {\n const workspacePath = join(projectRoot, \"pnpm-workspace.yaml\");\n if (!existsSync(workspacePath)) {\n return [];\n }\n\n const patterns: string[] = [];\n const lines = readFileSync(workspacePath, \"utf8\").split(\"\\n\");\n let readingPackages = false;\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.length === 0 || trimmed.startsWith(\"#\")) {\n continue;\n }\n\n if (!line.startsWith(\" \") && !line.startsWith(\"-\")) {\n readingPackages = trimmed === \"packages:\";\n continue;\n }\n\n if (!readingPackages) {\n continue;\n }\n\n const match = trimmed.match(/^-\\s+(.+)$/);\n if (match?.[1] !== undefined) {\n patterns.push(stripQuotes(match[1].trim()));\n }\n }\n\n return patterns;\n};\n\nconst expandPattern = (projectRoot: string, pattern: string): readonly string[] => {\n const segments = normalizePath(pattern)\n .split(\"/\")\n .filter((segment) => segment.length > 0);\n let current = [projectRoot];\n\n for (const segment of segments) {\n const next: string[] = [];\n if (segment === \"*\") {\n for (const directory of current) {\n if (!existsSync(directory)) {\n continue;\n }\n\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n if (entry.isDirectory()) {\n next.push(join(directory, entry.name));\n }\n }\n }\n } else {\n for (const directory of current) {\n const candidate = join(directory, segment);\n if (existsSync(candidate) && statSync(candidate).isDirectory()) {\n next.push(candidate);\n }\n }\n }\n\n current = next;\n }\n\n return current;\n};\n\nexport const loadWorkspaceDependencyManifests = (\n projectRoot: string,\n): readonly WorkspaceDependencyManifest[] => {\n const absoluteRoot = resolve(projectRoot);\n const packageJsonPatterns = readWorkspacePatternsFromPackageJson(absoluteRoot);\n const pnpmPatterns = readWorkspacePatternsFromPnpmWorkspace(absoluteRoot);\n const patterns = packageJsonPatterns.length > 0 ? packageJsonPatterns : pnpmPatterns;\n const includePatterns = patterns.filter((pattern) => !pattern.startsWith(\"!\"));\n const excludePatterns = patterns\n .filter((pattern) => pattern.startsWith(\"!\"))\n .map((pattern) => pattern.slice(1));\n\n const excludedPaths = new Set(\n excludePatterns\n .flatMap((pattern) => expandPattern(absoluteRoot, pattern))\n .map((path) => normalizePath(relative(absoluteRoot, path))),\n );\n\n const manifestsByPath = new Map<string, WorkspaceDependencyManifest>();\n for (const pattern of includePatterns) {\n for (const absoluteWorkspacePath of expandPattern(absoluteRoot, pattern)) {\n const relativePath = normalizePath(relative(absoluteRoot, absoluteWorkspacePath));\n if (\n relativePath.length === 0 ||\n relativePath.startsWith(\"..\") ||\n excludedPaths.has(relativePath)\n ) {\n continue;\n }\n\n const packageJsonPath = join(absoluteWorkspacePath, \"package.json\");\n if (!existsSync(packageJsonPath)) {\n continue;\n }\n\n const rawPackageJson = readFileSync(packageJsonPath, \"utf8\");\n const packageJson = readPackageJson(packageJsonPath);\n manifestsByPath.set(relativePath, {\n name: packageJson?.name ?? basename(absoluteWorkspacePath),\n path: relativePath,\n kind: inferWorkspaceKind(relativePath),\n directDependencies: parsePackageJson(rawPackageJson),\n });\n }\n }\n\n return [...manifestsByPath.values()].sort((a, b) => a.path.localeCompare(b.path));\n};\n","import type { ExternalAnalysisSummary } from \"@codesentinel/core\";\nimport {\n DEFAULT_EXTERNAL_ANALYSIS_CONFIG,\n type DependencyMetadataProvider,\n type ExternalAnalysisConfig,\n type WorkspaceDependencyManifest,\n} from \"../domain/types.js\";\nimport { buildDependencyExposureSummary } from \"./dependency-exposure-pipeline.js\";\nimport { prepareDependencyExtraction } from \"./prepare-dependency-extraction.js\";\nimport { loadWorkspaceDependencyManifests } from \"../infrastructure/workspace-package-manifests.js\";\n\nexport type AnalyzeDependencyExposureInput = {\n repositoryPath: string;\n config?: Partial<ExternalAnalysisConfig>;\n};\n\nexport type DependencyExposureProgressEvent =\n | { stage: \"package_json_loaded\" }\n | { stage: \"lockfile_selected\"; kind: \"pnpm\" | \"npm\" | \"npm-shrinkwrap\" | \"yarn\" | \"bun\" }\n | { stage: \"lockfile_parsed\"; dependencyNodes: number; directDependencies: number }\n | { stage: \"metadata_fetch_started\"; total: number }\n | { stage: \"metadata_fetch_progress\"; completed: number; total: number; packageName: string }\n | { stage: \"metadata_fetch_completed\"; total: number }\n | { stage: \"summary_built\"; totalDependencies: number; directDependencies: number };\n\nexport type WorkspaceDependencyManifestLoader = (\n repositoryPath: string,\n) => readonly WorkspaceDependencyManifest[];\n\nconst withDefaults = (\n overrides: Partial<ExternalAnalysisConfig> | undefined,\n): ExternalAnalysisConfig => ({\n ...DEFAULT_EXTERNAL_ANALYSIS_CONFIG,\n ...overrides,\n});\n\nexport const analyzeDependencyExposure = async (\n input: AnalyzeDependencyExposureInput,\n metadataProvider: DependencyMetadataProvider,\n onProgress?: (event: DependencyExposureProgressEvent) => void,\n loadWorkspaceManifests: WorkspaceDependencyManifestLoader = loadWorkspaceDependencyManifests,\n): Promise<ExternalAnalysisSummary> => {\n const config = withDefaults(input.config);\n\n try {\n const prepared = await prepareDependencyExtraction(input.repositoryPath);\n if (!prepared.available) {\n return {\n targetPath: input.repositoryPath,\n available: false,\n reason: prepared.reason,\n };\n }\n\n onProgress?.({ stage: \"package_json_loaded\" });\n onProgress?.({ stage: \"lockfile_selected\", kind: prepared.lockfileKind });\n\n const { extraction } = prepared;\n\n onProgress?.({\n stage: \"lockfile_parsed\",\n dependencyNodes: extraction.nodes.length,\n directDependencies: extraction.directDependencies.length,\n });\n onProgress?.({ stage: \"metadata_fetch_started\", total: extraction.nodes.length });\n const summary = await buildDependencyExposureSummary({\n targetPath: input.repositoryPath,\n extraction,\n metadataProvider,\n config,\n workspaceManifests: loadWorkspaceManifests(input.repositoryPath),\n onMetadataProgress: (event) =>\n onProgress?.({\n stage: \"metadata_fetch_progress\",\n completed: event.completed,\n total: event.total,\n packageName: event.packageName,\n }),\n });\n onProgress?.({ stage: \"metadata_fetch_completed\", total: extraction.nodes.length });\n if (summary.available) {\n onProgress?.({\n stage: \"summary_built\",\n totalDependencies: summary.metrics.totalDependencies,\n directDependencies: summary.metrics.directDependencies,\n });\n }\n\n return summary;\n } catch (error) {\n const message = error instanceof Error ? error.message : \"unknown\";\n if (message.includes(\"unsupported_lockfile_format\")) {\n return {\n targetPath: input.repositoryPath,\n available: false,\n reason: \"unsupported_lockfile_format\",\n };\n }\n\n return {\n targetPath: input.repositoryPath,\n available: false,\n reason: \"invalid_lockfile\",\n };\n }\n};\n","import type { ExternalAnalysisSummary } from \"@codesentinel/core\";\nimport {\n DEFAULT_EXTERNAL_ANALYSIS_CONFIG,\n type DependencyMetadataProvider,\n type ExternalAnalysisConfig,\n type LockfileExtraction,\n} from \"../domain/types.js\";\nimport { buildDependencyExposureSummary } from \"./dependency-exposure-pipeline.js\";\nimport { resolveRegistryGraphFromDirectSpecs } from \"./resolve-registry-graph.js\";\n\nexport type AnalyzeDependencyCandidateInput = {\n dependency: string;\n config?: Partial<ExternalAnalysisConfig>;\n maxNodes?: number;\n maxDepth?: number;\n};\n\nexport type AnalyzeDependencyCandidateResult =\n | {\n available: false;\n reason: \"invalid_dependency_spec\" | \"package_not_found\";\n dependency: string;\n }\n | {\n available: true;\n dependency: {\n name: string;\n requested: string | null;\n resolvedVersion: string;\n resolution: \"exact\" | \"tag\" | \"range\" | \"latest\";\n };\n graph: {\n nodeCount: number;\n truncated: boolean;\n maxNodes: number;\n maxDepth: number;\n };\n assumptions: readonly string[];\n external: ExternalAnalysisSummary;\n };\n\nconst DEFAULT_MAX_NODES = 250;\nconst DEFAULT_MAX_DEPTH = 6;\n\nconst withDefaults = (\n overrides: Partial<ExternalAnalysisConfig> | undefined,\n): ExternalAnalysisConfig => ({\n ...DEFAULT_EXTERNAL_ANALYSIS_CONFIG,\n ...overrides,\n});\n\nconst parseDependencySpec = (value: string): { name: string; requested: string | null } | null => {\n const trimmed = value.trim();\n if (trimmed.length === 0 || /\\s/.test(trimmed)) {\n return null;\n }\n\n if (trimmed.startsWith(\"@\")) {\n const splitIndex = trimmed.lastIndexOf(\"@\");\n if (splitIndex <= 0) {\n return { name: trimmed, requested: null };\n }\n\n const name = trimmed.slice(0, splitIndex);\n const requested = trimmed.slice(splitIndex + 1);\n if (name.length === 0 || requested.length === 0) {\n return null;\n }\n\n return { name, requested };\n }\n\n const splitIndex = trimmed.lastIndexOf(\"@\");\n if (splitIndex <= 0) {\n return { name: trimmed, requested: null };\n }\n\n const name = trimmed.slice(0, splitIndex);\n const requested = trimmed.slice(splitIndex + 1);\n if (name.length === 0 || requested.length === 0) {\n return null;\n }\n\n return { name, requested };\n};\n\nexport const analyzeDependencyCandidate = async (\n input: AnalyzeDependencyCandidateInput,\n metadataProvider: DependencyMetadataProvider,\n): Promise<AnalyzeDependencyCandidateResult> => {\n const parsed = parseDependencySpec(input.dependency);\n if (parsed === null) {\n return {\n available: false,\n reason: \"invalid_dependency_spec\",\n dependency: input.dependency,\n };\n }\n\n const maxNodes = Math.max(1, input.maxNodes ?? DEFAULT_MAX_NODES);\n const maxDepth = Math.max(0, input.maxDepth ?? DEFAULT_MAX_DEPTH);\n const config = withDefaults(input.config);\n\n const graph = await resolveRegistryGraphFromDirectSpecs(\n [\n {\n name: parsed.name,\n requestedRange: parsed.requested ?? \"latest\",\n scope: \"prod\",\n },\n ],\n { maxNodes, maxDepth },\n );\n\n const direct = graph.directDependencies.find((dependency) => dependency.name === parsed.name);\n if (direct === undefined || graph.nodes.length === 0) {\n return {\n available: false,\n reason: \"package_not_found\",\n dependency: input.dependency,\n };\n }\n\n const extraction: LockfileExtraction = {\n kind: \"npm\",\n directDependencies: [\n {\n name: parsed.name,\n requestedRange: parsed.requested ?? \"latest\",\n scope: \"prod\",\n },\n ],\n nodes: graph.nodes,\n };\n\n const external = await buildDependencyExposureSummary({\n targetPath: `npm:${parsed.name}`,\n extraction,\n metadataProvider,\n config,\n });\n\n return {\n available: true,\n dependency: {\n name: parsed.name,\n requested: parsed.requested,\n resolvedVersion: direct.resolvedVersion,\n resolution: direct.resolution,\n },\n graph: {\n nodeCount: graph.nodes.length,\n truncated: graph.truncated,\n maxNodes,\n maxDepth,\n },\n assumptions: graph.assumptions,\n external,\n };\n};\n","import type {\n DependencyMetadata,\n DependencyMetadataProvider,\n DependencyMetadataRequestContext,\n} from \"../domain/types.js\";\nimport { cachedFetch } from \"./cached-fetch.js\";\nimport { fetchJsonWithRetry } from \"./fetch-json-with-retry.js\";\nimport {\n getNpmMetadataCacheStore,\n getPackumentCacheTtlMs,\n getWeeklyDownloadsCacheTtlMs,\n toMetadataPackumentCacheKey,\n toWeeklyDownloadsCacheKey,\n} from \"./npm-metadata-cache.js\";\n\ntype NpmPackagePayload = {\n time?: Record<string, string>;\n maintainers?: Array<{ name?: string; email?: string }>;\n};\n\ntype NpmDownloadsPayload = {\n downloads?: number;\n};\n\nconst ONE_DAY_MS = 24 * 60 * 60 * 1000;\nconst MAX_RETRIES = 3;\nconst RETRY_BASE_DELAY_MS = 500;\nconst round4 = (value: number): number => Number(value.toFixed(4));\n\nconst parseDate = (iso: string | undefined): number | null => {\n if (iso === undefined) {\n return null;\n }\n\n const value = Date.parse(iso);\n return Number.isNaN(value) ? null : value;\n};\n\nexport class NpmRegistryMetadataProvider implements DependencyMetadataProvider {\n private readonly cache = new Map<string, DependencyMetadata | null>();\n private readonly cacheStore = getNpmMetadataCacheStore();\n\n private async fetchWeeklyDownloads(name: string): Promise<number | null> {\n const encodedName = encodeURIComponent(name);\n const payload = await cachedFetch<NpmDownloadsPayload>({\n key: toWeeklyDownloadsCacheKey(name),\n ttlMs: getWeeklyDownloadsCacheTtlMs(),\n cacheStore: this.cacheStore,\n fetchFresh: async () =>\n await fetchJsonWithRetry<NpmDownloadsPayload>(\n `https://api.npmjs.org/downloads/point/last-week/${encodedName}`,\n { retries: MAX_RETRIES, baseDelayMs: RETRY_BASE_DELAY_MS },\n ),\n });\n if (payload === null) {\n return null;\n }\n\n const downloads = payload.downloads;\n if (typeof downloads !== \"number\" || Number.isNaN(downloads) || downloads < 0) {\n return null;\n }\n\n return Math.floor(downloads);\n }\n\n async getMetadata(\n name: string,\n version: string,\n context: DependencyMetadataRequestContext,\n ): Promise<DependencyMetadata | null> {\n const key = `${name}@${version}`;\n if (this.cache.has(key)) {\n return this.cache.get(key) ?? null;\n }\n\n try {\n const encodedName = encodeURIComponent(name);\n const payload = await cachedFetch<NpmPackagePayload>({\n key: toMetadataPackumentCacheKey(name),\n ttlMs: getPackumentCacheTtlMs(),\n cacheStore: this.cacheStore,\n fetchFresh: async () => {\n const fresh = await fetchJsonWithRetry<NpmPackagePayload>(\n `https://registry.npmjs.org/${encodedName}`,\n {\n retries: MAX_RETRIES,\n baseDelayMs: RETRY_BASE_DELAY_MS,\n },\n );\n if (fresh === null) {\n return null;\n }\n const slim: NpmPackagePayload = {};\n if (fresh.time !== undefined) {\n slim.time = fresh.time;\n }\n if (fresh.maintainers !== undefined) {\n slim.maintainers = fresh.maintainers;\n }\n return slim;\n },\n });\n if (payload === null) {\n this.cache.set(key, null);\n return null;\n }\n const timeEntries = payload.time ?? {};\n\n const publishDates = Object.entries(timeEntries)\n .filter(([tag]) => tag !== \"created\" && tag !== \"modified\")\n .map(([, date]) => parseDate(date))\n .filter((value): value is number => value !== null)\n .sort((a, b) => a - b);\n\n const modifiedAt = parseDate(timeEntries[\"modified\"]);\n const now = Date.now();\n const daysSinceLastRelease =\n modifiedAt === null ? null : Math.max(0, round4((now - modifiedAt) / ONE_DAY_MS));\n\n let releaseFrequencyDays: number | null = null;\n if (publishDates.length >= 2) {\n const totalIntervals = publishDates.length - 1;\n let sum = 0;\n for (let i = 1; i < publishDates.length; i += 1) {\n const current = publishDates[i];\n const previous = publishDates[i - 1];\n if (current !== undefined && previous !== undefined) {\n sum += current - previous;\n }\n }\n\n releaseFrequencyDays = round4(sum / totalIntervals / ONE_DAY_MS);\n }\n\n const maintainers = payload.maintainers ?? [];\n const maintainerCount = maintainers.length > 0 ? maintainers.length : null;\n const weeklyDownloads = context.directDependency\n ? await this.fetchWeeklyDownloads(name).catch(() => null)\n : null;\n\n const metadata: DependencyMetadata = {\n name,\n version,\n weeklyDownloads,\n maintainerCount,\n releaseFrequencyDays,\n daysSinceLastRelease,\n repositoryActivity30d: null,\n busFactor: null,\n };\n\n this.cache.set(key, metadata);\n return metadata;\n } catch {\n this.cache.set(key, null);\n return null;\n }\n }\n}\n","import type { DependencyMetadata, DependencyMetadataProvider } from \"../domain/types.js\";\n\nexport class NoopMetadataProvider implements DependencyMetadataProvider {\n getMetadata(\n _name: string,\n _version: string,\n _context: { directDependency: boolean },\n ): Promise<DependencyMetadata | null> {\n return Promise.resolve(null);\n }\n}\n","import type { ExternalAnalysisSummary } from \"@codesentinel/core\";\nimport {\n analyzeDependencyExposure,\n type DependencyExposureProgressEvent,\n type AnalyzeDependencyExposureInput,\n} from \"./application/analyze-dependency-exposure.js\";\nimport {\n analyzeDependencyCandidate,\n type AnalyzeDependencyCandidateInput,\n type AnalyzeDependencyCandidateResult,\n} from \"./application/analyze-dependency-candidate.js\";\nimport { NpmRegistryMetadataProvider } from \"./infrastructure/npm-registry-metadata-provider.js\";\nimport { NoopMetadataProvider } from \"./infrastructure/noop-metadata-provider.js\";\n\nexport type { AnalyzeDependencyExposureInput } from \"./application/analyze-dependency-exposure.js\";\nexport type { DependencyExposureProgressEvent } from \"./application/analyze-dependency-exposure.js\";\nexport type {\n AnalyzeDependencyCandidateInput,\n AnalyzeDependencyCandidateResult,\n} from \"./application/analyze-dependency-candidate.js\";\n\nexport const analyzeDependencyExposureFromProject = async (\n input: AnalyzeDependencyExposureInput,\n onProgress?: (event: DependencyExposureProgressEvent) => void,\n): Promise<ExternalAnalysisSummary> => {\n const metadataProvider =\n process.env[\"CODESENTINEL_EXTERNAL_METADATA\"] === \"none\"\n ? new NoopMetadataProvider()\n : new NpmRegistryMetadataProvider();\n\n return analyzeDependencyExposure(input, metadataProvider, onProgress);\n};\n\nexport const analyzeDependencyCandidateFromRegistry = async (\n input: AnalyzeDependencyCandidateInput,\n): Promise<AnalyzeDependencyCandidateResult> => {\n const metadataProvider =\n process.env[\"CODESENTINEL_EXTERNAL_METADATA\"] === \"none\"\n ? new NoopMetadataProvider()\n : new NpmRegistryMetadataProvider();\n\n return analyzeDependencyCandidate(input, metadataProvider);\n};\n","import type {\n AnalyzeSummary,\n FileAuthorChurnShare,\n FileAuthorShare,\n HealthIssue,\n RecentActivityPoint,\n RepositoryHealthSummary,\n RiskFactors,\n RiskFactorTrace,\n RiskTrace,\n} from \"@codesentinel/core\";\n\nexport type { HealthIssue };\n\nexport const SNAPSHOT_SCHEMA_VERSION = \"codesentinel.snapshot.v1\" as const;\nexport const REPORT_SCHEMA_VERSION = \"codesentinel.report.v1\" as const;\nexport const RISK_MODEL_VERSION = \"deterministic-v1\" as const;\n\nexport type SnapshotSchemaVersion = typeof SNAPSHOT_SCHEMA_VERSION;\nexport type ReportSchemaVersion = typeof REPORT_SCHEMA_VERSION;\n\nexport type RiskTier = \"low\" | \"moderate\" | \"elevated\" | \"high\" | \"very_high\";\nexport type HealthTier = \"critical\" | \"weak\" | \"fair\" | \"good\" | \"excellent\";\n\nexport type ReportFormat = \"json\" | \"text\" | \"md\";\n\nexport type CodeSentinelSnapshot = {\n schemaVersion: SnapshotSchemaVersion;\n generatedAt: string;\n riskModelVersion: string;\n source: {\n targetPath: string;\n };\n analysis: AnalyzeSummary;\n trace?: RiskTrace;\n analysisConfig?: Readonly<Record<string, string | number | boolean | null>>;\n};\n\nexport type RenderedFactor = {\n id: string;\n label: string;\n contribution: number;\n confidence: number;\n evidence: string;\n};\n\nexport type HotspotReportItem = {\n rank: number;\n target: string;\n module: string;\n score: number;\n normalizedScore: number;\n commitCount: number | null;\n recentCommitCount: number | null;\n recentVolatility: number | null;\n churnTotal: number | null;\n ownerCount: number | null;\n topAuthorShareByCommits: number | null;\n busFactorByCommits: number | null;\n authorDistributionByCommits: readonly FileAuthorShare[];\n riskContributions: RiskFactors;\n reason: string;\n topFactors: readonly RenderedFactor[];\n suggestedActions: readonly string[];\n biggestLevers: readonly string[];\n};\n\nexport type StructuralFileExtreme = {\n file: string;\n module: string;\n value: number;\n};\n\nexport type StructuralCycleDetail = {\n id: string;\n size: number;\n nodes: readonly string[];\n path: string;\n};\n\nexport type StructuralArchitectureMetrics = {\n nodeCount: number;\n edgeCount: number;\n graphDepth: number;\n maxFanIn: number;\n maxFanOut: number;\n couplingDensity: number;\n entryPointCount: number;\n};\n\nexport type StructuralModuleAnatomyItem = {\n module: string;\n dependencyCount: number;\n fanIn: number;\n fanOut: number;\n depth: number;\n};\n\nexport type ChangeOwnershipMetrics = {\n totalCommits: number;\n totalFiles: number;\n recentWindowDays: number;\n meanBusFactorByCommits: number | null;\n averageRecentVolatility: number | null;\n sharedOwnershipPercent: number | null;\n concentratedOwnershipPercent: number | null;\n singleMaintainerPercent: number | null;\n staleOwnedFilesPercent: number | null;\n};\n\nexport type OwnershipPostureStatus = \"balanced\" | \"concentrated\" | \"siloed\" | \"stale\";\n\nexport type OwnershipPostureReportItem = {\n status: OwnershipPostureStatus;\n title: string;\n summary: string;\n activeContributors: number;\n largestContributorSharePercent: number | null;\n singleOwnerModulesPercent: number | null;\n};\n\nexport type CoChangePairReportItem = {\n fileA: string;\n fileB: string;\n coChangeCommits: number;\n couplingScore: number;\n};\n\nexport type ModuleKnowledgeReportItem = {\n module: string;\n totalCommits: number;\n recentCommits: number;\n activeAuthors: number;\n topAuthorShareByCommits: number;\n ownershipLabel: \"distributed\" | \"sparse\" | \"siloed\";\n};\n\nexport type FileOwnershipReportItem = {\n filePath: string;\n module: string;\n commitCount: number;\n churnTotal: number;\n ownershipLabel: \"shared\" | \"concentrated\" | \"singleMaintainer\";\n topAuthorShareByCommits: number;\n busFactorByCommits: number;\n authorDistributionByCommits: readonly FileAuthorShare[];\n topAuthorShareByChurn: number;\n busFactorByChurn: number;\n authorDistributionByChurn: readonly FileAuthorChurnShare[];\n};\n\nexport type OwnershipRiskAreaReportItem = {\n module: string;\n totalCommits: number;\n recentCommits: number;\n activeAuthors: number;\n topAuthorShareByCommits: number;\n ownershipLabel: \"distributed\" | \"sparse\" | \"siloed\";\n};\n\nexport type OwnershipContributorReportItem = {\n authorId: string;\n singleMaintainerFiles: number;\n concentratedFiles: number;\n ownedFiles: number;\n totalCommitTouches: number;\n totalCommitShare: number;\n ownedChurnShare: number;\n};\n\nexport type RecentActivityReportItem = RecentActivityPoint;\n\nexport type RiskyDependencyReportItem = {\n name: string;\n score: number;\n normalizedScore: number;\n dependencyScope: \"prod\" | \"dev\" | \"unknown\";\n direct: boolean;\n resolvedVersion: string | null;\n transitiveDependencyCount: number;\n dependentCount: number;\n fanOut: number;\n dependencyDepth: number;\n weeklyDownloads: number | null;\n maintainerCount: number | null;\n releaseFrequencyDays: number | null;\n daysSinceLastRelease: number | null;\n repositoryActivity30d: number | null;\n busFactor: number | null;\n ownRiskSignals: readonly string[];\n inheritedRiskSignals: readonly string[];\n riskSignals: readonly string[];\n reason: string;\n};\n\nexport type ExternalMetricsReportItem = {\n totalDependencies: number;\n directDependencies: number;\n directProductionDependencies: number;\n directDevelopmentDependencies: number;\n transitiveDependencies: number;\n dependencyDepth: number;\n lockfileKind: \"pnpm\" | \"npm\" | \"npm-shrinkwrap\" | \"yarn\" | \"bun\";\n metadataCoverage: number;\n};\n\nexport type ExternalCentralityReportItem = {\n name: string;\n dependents: number;\n fanOut: number;\n direct: boolean;\n};\n\nexport type WorkspaceStructuralReportItem = {\n name: string;\n path: string;\n kind: string;\n fileCount: number;\n internalEdgeCount: number;\n incomingEdgeCount: number;\n outgoingEdgeCount: number;\n};\n\nexport type WorkspaceRiskReportItem = {\n name: string;\n path: string;\n kind: string;\n score: number;\n normalizedScore: number;\n fileCount: number;\n averageFileRisk: number;\n peakFileRisk: number;\n internalEdgeCount: number;\n incomingEdgeCount: number;\n outgoingEdgeCount: number;\n topFiles: ReadonlyArray<{\n file: string;\n score: number;\n }>;\n};\n\nexport type WorkspaceEvolutionReportItem = {\n name: string;\n path: string;\n kind: string;\n fileCount: number;\n commitCount: number;\n churnTotal: number;\n recentCommitCount: number;\n recentVolatility: number;\n topAuthorShareByCommits: number;\n busFactorByCommits: number;\n hotspotCount: number;\n topHotspots: ReadonlyArray<{\n filePath: string;\n rank: number;\n commitCount: number;\n churnTotal: number;\n }>;\n internalCouplingPairCount: number;\n incomingCouplingPairCount: number;\n outgoingCouplingPairCount: number;\n};\n\nexport type WorkspaceDependencyExposureReportItem = {\n name: string;\n path: string;\n kind: string;\n directDependencies: number;\n directProductionDependencies: number;\n directDevelopmentDependencies: number;\n unresolvedDependencies: readonly string[];\n dependencyNames: readonly string[];\n sharedDependencies: readonly string[];\n highRiskDependencies: readonly string[];\n highRiskDevelopmentDependencies: readonly string[];\n transitiveExposureDependencies: readonly string[];\n singleMaintainerDependencies: readonly string[];\n abandonedDependencies: readonly string[];\n};\n\nexport type WorkspaceReportSummary = {\n structural: readonly WorkspaceStructuralReportItem[];\n risk: readonly WorkspaceRiskReportItem[];\n evolution: readonly WorkspaceEvolutionReportItem[];\n external: readonly WorkspaceDependencyExposureReportItem[];\n};\n\nexport type RepositoryDimensionScores = {\n structural: number | null;\n evolution: number | null;\n external: number | null;\n interactions: number | null;\n};\n\nexport type SnapshotDiff = {\n baselineGeneratedAt: string;\n riskScoreDelta: number;\n normalizedScoreDelta: number;\n externalDimensionDelta: number | null;\n fileRiskChanges: ReadonlyArray<{ target: string; before: number; after: number; delta: number }>;\n moduleRiskChanges: ReadonlyArray<{\n target: string;\n before: number;\n after: number;\n delta: number;\n }>;\n newHotspots: readonly string[];\n resolvedHotspots: readonly string[];\n newCycles: readonly string[];\n resolvedCycles: readonly string[];\n externalChanges: {\n highRiskAdded: readonly string[];\n highRiskRemoved: readonly string[];\n singleMaintainerAdded: readonly string[];\n singleMaintainerRemoved: readonly string[];\n abandonedAdded: readonly string[];\n abandonedRemoved: readonly string[];\n };\n};\n\n// Mirrors the audit shape from `@codesentinel/ownership` structurally. The reporter must not\n// depend on that package, so this duplication is deliberate and kept field-for-field.\nexport type DeclaredOwnerReportItem =\n | { kind: \"user\"; handle: string }\n | { kind: \"team\"; org: string; slug: string }\n | { kind: \"email\"; address: string };\n\nexport type OwnershipAuditStatus =\n | \"aligned\"\n | \"drifted\"\n | \"ghosted\"\n | \"unowned\"\n | \"unowned-critical\"\n | \"insufficient-evidence\"\n | \"unknown\";\n\nexport type OwnershipFileReportItem = {\n filePath: string;\n declared: readonly DeclaredOwnerReportItem[];\n matchLine: number | null;\n status: OwnershipAuditStatus;\n observed: {\n commits: number;\n authors: number;\n topAuthorId: string | null;\n topAuthorShare: number | null;\n busFactor: number | null;\n lastCommitUnix: number | null;\n };\n criticality: {\n fanIn: number | null;\n isHotspot: boolean;\n riskScore: number | null;\n isCritical: boolean;\n };\n};\n\nexport type OwnershipAuditReportMetrics = {\n declaredCoveragePercent: number;\n declaredCoverageCriticalPercent: number;\n driftPercent: number;\n ghostOwnerCount: number;\n unownedCriticalCount: number;\n singleOwnerModuleCount: number;\n};\n\nexport type OwnershipAuditReport =\n | {\n available: false;\n reason: \"codeowners_not_found\" | \"audit_unavailable\";\n warnings: readonly string[];\n }\n | {\n available: true;\n codeowners: {\n source: string;\n ignoredSources: readonly string[];\n errors: readonly { line: number; reason: string }[];\n };\n metrics: OwnershipAuditReportMetrics;\n ghostOwners: readonly {\n owner: DeclaredOwnerReportItem;\n samplePaths: readonly string[];\n }[];\n files: readonly OwnershipFileReportItem[];\n warnings: readonly string[];\n };\n\nexport type ReportExtras = {\n ownership?: OwnershipAuditReport;\n repositoryWebUrl?: string | null;\n};\n\nexport type CodeSentinelReport = {\n schemaVersion: ReportSchemaVersion;\n generatedAt: string;\n repository: {\n name: string;\n targetPath: string;\n riskScore: number;\n normalizedScore: number;\n riskTier: RiskTier;\n healthTier: HealthTier;\n confidence: number | null;\n dimensionScores: RepositoryDimensionScores;\n webUrl?: string | null;\n };\n health: RepositoryHealthSummary;\n workspaces: WorkspaceReportSummary;\n hotspots: readonly HotspotReportItem[];\n structural: {\n cycleCount: number;\n cycles: readonly string[];\n cycleDetails: readonly StructuralCycleDetail[];\n metrics: StructuralArchitectureMetrics;\n moduleAnatomy: readonly StructuralModuleAnatomyItem[];\n fanInOutExtremes: {\n highestFanIn: readonly StructuralFileExtreme[];\n highestFanOut: readonly StructuralFileExtreme[];\n deepestFiles: readonly StructuralFileExtreme[];\n };\n fragileClusters: ReadonlyArray<{\n id: string;\n kind: string;\n score: number;\n files: readonly string[];\n }>;\n };\n changeOwnership:\n | {\n available: false;\n reason: string;\n }\n | {\n available: true;\n metrics: ChangeOwnershipMetrics;\n posture: OwnershipPostureReportItem;\n recentActivity: readonly RecentActivityReportItem[];\n coChangePairs: readonly CoChangePairReportItem[];\n moduleKnowledge: readonly ModuleKnowledgeReportItem[];\n fragileAreas: readonly OwnershipRiskAreaReportItem[];\n contributorOwnership: readonly OwnershipContributorReportItem[];\n fileOwnership: readonly FileOwnershipReportItem[];\n };\n external:\n | {\n available: false;\n reason: string;\n }\n | {\n available: true;\n metrics: ExternalMetricsReportItem;\n highRiskDependencies: readonly string[];\n highRiskDevelopmentDependencies: readonly string[];\n transitiveExposureDependencies: readonly string[];\n singleMaintainerDependencies: readonly string[];\n abandonedDependencies: readonly string[];\n centralityRanking: readonly ExternalCentralityReportItem[];\n riskyDependencies: readonly RiskyDependencyReportItem[];\n };\n ownership?: OwnershipAuditReport;\n appendix: {\n snapshotSchemaVersion: string;\n riskModelVersion: string;\n timestamp: string;\n normalization: string;\n analysisConfig?: Readonly<Record<string, string | number | boolean | null>>;\n };\n diff?: SnapshotDiff;\n};\n\nexport const round4 = (value: number): number => Number(value.toFixed(4));\n\nexport const toRiskTier = (score: number): RiskTier => {\n if (score < 20) {\n return \"low\";\n }\n if (score < 40) {\n return \"moderate\";\n }\n if (score < 60) {\n return \"elevated\";\n }\n if (score < 80) {\n return \"high\";\n }\n return \"very_high\";\n};\n\nexport const toHealthTier = (score: number): HealthTier => {\n if (score < 20) {\n return \"critical\";\n }\n if (score < 40) {\n return \"weak\";\n }\n if (score < 60) {\n return \"fair\";\n }\n if (score < 80) {\n return \"good\";\n }\n return \"excellent\";\n};\n\nconst factorLabelById: Readonly<Record<string, string>> = {\n \"repository.structural\": \"Structural complexity\",\n \"repository.evolution\": \"Change volatility\",\n \"repository.external\": \"External dependency pressure\",\n \"repository.composite.interactions\": \"Intersection amplification\",\n \"file.structural\": \"File structural complexity\",\n \"file.evolution\": \"File change volatility\",\n \"file.external\": \"File external pressure\",\n \"file.composite.interactions\": \"File interaction amplification\",\n \"module.average_file_risk\": \"Average file risk\",\n \"module.peak_file_risk\": \"Peak file risk\",\n \"dependency.signals\": \"Dependency risk signals\",\n \"dependency.staleness\": \"Dependency staleness\",\n \"dependency.maintainer_concentration\": \"Maintainer concentration\",\n \"dependency.topology\": \"Dependency topology pressure\",\n \"dependency.bus_factor\": \"Dependency bus factor\",\n \"dependency.popularity_dampening\": \"Popularity dampening\",\n};\n\nexport const factorLabel = (factorId: string): string => factorLabelById[factorId] ?? factorId;\n\nexport const summarizeEvidence = (factor: RiskFactorTrace): string => {\n const entries = Object.entries(factor.rawMetrics)\n .filter(([, value]) => value !== null)\n .sort((a, b) => a[0].localeCompare(b[0]))\n .slice(0, 3)\n .map(([key, value]) => `${key}=${value}`);\n\n if (entries.length > 0) {\n return entries.join(\", \");\n }\n\n const evidence = [...factor.evidence]\n .map((entry) => {\n if (entry.kind === \"file_metric\") {\n return `${entry.target}:${entry.metric}`;\n }\n if (entry.kind === \"dependency_metric\") {\n return `${entry.target}:${entry.metric}`;\n }\n if (entry.kind === \"repository_metric\") {\n return entry.metric;\n }\n if (entry.kind === \"graph_cycle\") {\n return `cycle:${entry.cycleId}`;\n }\n return `${entry.fileA}<->${entry.fileB}`;\n })\n .sort((a, b) => a.localeCompare(b));\n\n return evidence.join(\", \");\n};\n","import type { CodeSentinelSnapshot, SnapshotDiff } from \"./domain.js\";\nimport { round4 } from \"./domain.js\";\n\ntype ScoreEntry = { target: string; before: number; after: number; delta: number };\n\nconst diffSets = (\n current: readonly string[],\n baseline: readonly string[],\n): { added: readonly string[]; removed: readonly string[] } => {\n const currentSet = new Set(current);\n const baselineSet = new Set(baseline);\n\n const added = [...currentSet]\n .filter((item) => !baselineSet.has(item))\n .sort((a, b) => a.localeCompare(b));\n const removed = [...baselineSet]\n .filter((item) => !currentSet.has(item))\n .sort((a, b) => a.localeCompare(b));\n\n return { added, removed };\n};\n\nconst diffScoreMap = (\n current: ReadonlyMap<string, number>,\n baseline: ReadonlyMap<string, number>,\n): readonly ScoreEntry[] => {\n const keys = [...new Set([...current.keys(), ...baseline.keys()])].sort((a, b) =>\n a.localeCompare(b),\n );\n\n return keys\n .map((key) => {\n const before = baseline.get(key) ?? 0;\n const after = current.get(key) ?? 0;\n const delta = round4(after - before);\n return {\n target: key,\n before: round4(before),\n after: round4(after),\n delta,\n };\n })\n .filter((entry) => entry.delta !== 0)\n .sort((a, b) => Math.abs(b.delta) - Math.abs(a.delta) || a.target.localeCompare(b.target));\n};\n\nconst cycleKey = (nodes: readonly string[]): string =>\n [...nodes].sort((a, b) => a.localeCompare(b)).join(\" -> \");\n\nconst repositoryExternalDimension = (snapshot: CodeSentinelSnapshot): number | null => {\n const factor = snapshot.trace?.targets\n .find(\n (target) =>\n target.targetType === \"repository\" &&\n target.targetId === snapshot.analysis.structural.targetPath,\n )\n ?.factors.find((item) => item.factorId === \"repository.external\");\n\n const raw = factor?.rawMetrics[\"externalDimension\"];\n return typeof raw === \"number\" ? round4(raw * 100) : null;\n};\n\nexport const compareSnapshots = (\n current: CodeSentinelSnapshot,\n baseline: CodeSentinelSnapshot,\n): SnapshotDiff => {\n const currentFileScores = new Map(\n current.analysis.risk.fileScores.map((item) => [item.file, item.score]),\n );\n const baselineFileScores = new Map(\n baseline.analysis.risk.fileScores.map((item) => [item.file, item.score]),\n );\n\n const currentModuleScores = new Map(\n current.analysis.risk.moduleScores.map((item) => [item.module, item.score]),\n );\n const baselineModuleScores = new Map(\n baseline.analysis.risk.moduleScores.map((item) => [item.module, item.score]),\n );\n\n const currentHotspots = current.analysis.risk.hotspots.slice(0, 10).map((item) => item.file);\n const baselineHotspots = baseline.analysis.risk.hotspots.slice(0, 10).map((item) => item.file);\n\n const currentCycles = current.analysis.structural.cycles.map((cycle) => cycleKey(cycle.nodes));\n const baselineCycles = baseline.analysis.structural.cycles.map((cycle) => cycleKey(cycle.nodes));\n\n const currentExternal = current.analysis.external.available\n ? current.analysis.external\n : {\n highRiskDependencies: [] as string[],\n singleMaintainerDependencies: [] as string[],\n abandonedDependencies: [] as string[],\n };\n const baselineExternal = baseline.analysis.external.available\n ? baseline.analysis.external\n : {\n highRiskDependencies: [] as string[],\n singleMaintainerDependencies: [] as string[],\n abandonedDependencies: [] as string[],\n };\n\n const highRisk = diffSets(\n currentExternal.highRiskDependencies,\n baselineExternal.highRiskDependencies,\n );\n const singleMaintainer = diffSets(\n currentExternal.singleMaintainerDependencies,\n baselineExternal.singleMaintainerDependencies,\n );\n const abandoned = diffSets(\n currentExternal.abandonedDependencies,\n baselineExternal.abandonedDependencies,\n );\n\n const hotspots = diffSets(currentHotspots, baselineHotspots);\n const cycles = diffSets(currentCycles, baselineCycles);\n\n return {\n baselineGeneratedAt: baseline.generatedAt,\n riskScoreDelta: round4(current.analysis.risk.riskScore - baseline.analysis.risk.riskScore),\n normalizedScoreDelta: round4(\n current.analysis.risk.normalizedScore - baseline.analysis.risk.normalizedScore,\n ),\n externalDimensionDelta:\n repositoryExternalDimension(current) === null ||\n repositoryExternalDimension(baseline) === null\n ? null\n : round4(repositoryExternalDimension(current)! - repositoryExternalDimension(baseline)!),\n fileRiskChanges: diffScoreMap(currentFileScores, baselineFileScores),\n moduleRiskChanges: diffScoreMap(currentModuleScores, baselineModuleScores),\n newHotspots: hotspots.added,\n resolvedHotspots: hotspots.removed,\n newCycles: cycles.added,\n resolvedCycles: cycles.removed,\n externalChanges: {\n highRiskAdded: highRisk.added,\n highRiskRemoved: highRisk.removed,\n singleMaintainerAdded: singleMaintainer.added,\n singleMaintainerRemoved: singleMaintainer.removed,\n abandonedAdded: abandoned.added,\n abandonedRemoved: abandoned.removed,\n },\n };\n};\n","import { basename, posix } from \"node:path\";\nimport type { TargetTrace } from \"@codesentinel/core\";\nimport {\n REPORT_SCHEMA_VERSION,\n factorLabel,\n round4,\n toHealthTier,\n summarizeEvidence,\n toRiskTier,\n type CodeSentinelReport,\n type CodeSentinelSnapshot,\n type FileOwnershipReportItem,\n type HotspotReportItem,\n type ReportExtras,\n type RepositoryDimensionScores,\n type RenderedFactor,\n type RiskyDependencyReportItem,\n type SnapshotDiff,\n type StructuralCycleDetail,\n type StructuralFileExtreme,\n type WorkspaceReportSummary,\n} from \"./domain.js\";\n\nconst toPosixDirname = (value: string): string => {\n const normalized = value.replaceAll(\"\\\\\", \"/\");\n const directory = posix.dirname(normalized);\n return directory === \".\" ? \"root\" : directory;\n};\n\nconst findTraceTarget = (\n snapshot: CodeSentinelSnapshot,\n targetType: TargetTrace[\"targetType\"],\n targetId: string,\n): TargetTrace | undefined =>\n snapshot.trace?.targets.find(\n (target) => target.targetType === targetType && target.targetId === targetId,\n );\n\nconst toRenderedFactors = (target: TargetTrace | undefined): readonly RenderedFactor[] => {\n if (target === undefined) {\n return [];\n }\n\n return [...target.factors]\n .sort((a, b) => b.contribution - a.contribution || a.factorId.localeCompare(b.factorId))\n .slice(0, 4)\n .map((factor) => ({\n id: factor.factorId,\n label: factorLabel(factor.factorId),\n contribution: round4(factor.contribution),\n confidence: round4(factor.confidence),\n evidence: summarizeEvidence(factor),\n }));\n};\n\nconst suggestedActions = (target: TargetTrace | undefined): readonly string[] => {\n if (target === undefined) {\n return [];\n }\n\n const actions: string[] = [];\n for (const lever of target.reductionLevers) {\n switch (lever.factorId) {\n case \"file.evolution\":\n case \"repository.evolution\":\n actions.push(\"Reduce recent churn and volatile edit frequency in this area.\");\n break;\n case \"file.structural\":\n case \"repository.structural\":\n actions.push(\"Reduce fan-in/fan-out concentration and simplify deep dependency paths.\");\n break;\n case \"file.composite.interactions\":\n case \"repository.composite.interactions\":\n actions.push(\"Stabilize central files before concurrent structural changes.\");\n break;\n case \"file.external\":\n case \"repository.external\":\n actions.push(\"Review external dependency pressure for this hotspot.\");\n break;\n default:\n actions.push(`Reduce ${factorLabel(lever.factorId).toLowerCase()} influence.`);\n break;\n }\n }\n\n return [...new Set(actions)].slice(0, 3);\n};\n\nconst hotspotReason = (factors: readonly RenderedFactor[]): string => {\n if (factors.length === 0) {\n return \"Limited trace data available for this hotspot.\";\n }\n\n return factors\n .slice(0, 2)\n .map((factor) => `${factor.label} (${factor.contribution})`)\n .join(\" + \");\n};\n\nconst hotspotItems = (snapshot: CodeSentinelSnapshot): readonly HotspotReportItem[] =>\n snapshot.analysis.risk.hotspots.slice(0, 10).map((hotspot, index) => {\n const fileScore = snapshot.analysis.risk.fileScores.find((item) => item.file === hotspot.file);\n const evolutionMetrics = snapshot.analysis.evolution.available\n ? snapshot.analysis.evolution.files.find((item) => item.filePath === hotspot.file)\n : undefined;\n const traceTarget = findTraceTarget(snapshot, \"file\", hotspot.file);\n const factors = toRenderedFactors(traceTarget);\n\n return {\n rank: index + 1,\n target: hotspot.file,\n module: toPosixDirname(hotspot.file),\n score: hotspot.score,\n normalizedScore: fileScore?.normalizedScore ?? round4(hotspot.score / 100),\n commitCount: evolutionMetrics?.commitCount ?? null,\n recentCommitCount: evolutionMetrics?.recentCommitCount ?? null,\n recentVolatility: evolutionMetrics?.recentVolatility ?? null,\n churnTotal: evolutionMetrics?.churnTotal ?? null,\n ownerCount: evolutionMetrics?.authorDistributionByCommits.length ?? null,\n topAuthorShareByCommits: evolutionMetrics?.topAuthorShareByCommits ?? null,\n busFactorByCommits: evolutionMetrics?.busFactorByCommits ?? null,\n authorDistributionByCommits: evolutionMetrics?.authorDistributionByCommits ?? [],\n riskContributions: hotspot.factors,\n reason: hotspotReason(factors),\n topFactors: factors,\n suggestedActions: suggestedActions(traceTarget),\n biggestLevers: (traceTarget?.reductionLevers ?? [])\n .slice(0, 3)\n .map((lever) => `${factorLabel(lever.factorId)} (${lever.estimatedImpact})`),\n };\n });\n\nconst repositoryConfidence = (snapshot: CodeSentinelSnapshot): number | null => {\n const target = findTraceTarget(snapshot, \"repository\", snapshot.analysis.structural.targetPath);\n if (target === undefined || target.factors.length === 0) {\n return null;\n }\n\n const weight = target.factors.reduce((sum, factor) => sum + factor.contribution, 0);\n if (weight <= 0) {\n return null;\n }\n\n const weighted = target.factors.reduce(\n (sum, factor) => sum + factor.confidence * factor.contribution,\n 0,\n );\n return round4(weighted / weight);\n};\n\nconst normalizeDependencyScope = (\n scope: string | undefined,\n): RiskyDependencyReportItem[\"dependencyScope\"] => {\n switch (scope) {\n case \"prod\":\n case \"dev\":\n return scope;\n default:\n return \"unknown\";\n }\n};\n\nconst topStructuralFiles = (\n snapshot: CodeSentinelSnapshot,\n selector: (value: (typeof snapshot.analysis.structural.files)[number]) => number,\n): readonly StructuralFileExtreme[] =>\n [...snapshot.analysis.structural.files]\n .sort((a, b) => selector(b) - selector(a) || a.relativePath.localeCompare(b.relativePath))\n .slice(0, 5)\n .map((file) => ({\n file: file.relativePath,\n module: toPosixDirname(file.relativePath),\n value: selector(file),\n }));\n\nconst cycleDetails = (snapshot: CodeSentinelSnapshot): readonly StructuralCycleDetail[] =>\n snapshot.analysis.structural.cycles.map((cycle, index) => {\n const nodes = [...cycle.nodes].sort((a, b) => a.localeCompare(b));\n return {\n id: `cycle-${index + 1}`,\n size: nodes.length,\n nodes,\n path: nodes.join(\" -> \"),\n };\n });\n\nconst structuralArchitectureMetrics = (snapshot: CodeSentinelSnapshot) => {\n const metrics = snapshot.analysis.structural.metrics;\n const nodeCount = metrics.nodeCount;\n const edgeCount = metrics.edgeCount;\n const maxPossibleEdges = nodeCount <= 1 ? 0 : nodeCount * (nodeCount - 1);\n const couplingDensity = maxPossibleEdges === 0 ? 0 : round4((edgeCount / maxPossibleEdges) * 100);\n const entryPointCount = snapshot.analysis.structural.files.filter(\n (file) => file.fanIn === 0 && file.fanOut > 0,\n ).length;\n\n return {\n nodeCount,\n edgeCount,\n graphDepth: metrics.graphDepth,\n maxFanIn: metrics.maxFanIn,\n maxFanOut: metrics.maxFanOut,\n couplingDensity,\n entryPointCount,\n };\n};\n\nconst structuralModuleAnatomy = (snapshot: CodeSentinelSnapshot) => {\n const moduleMap = new Map<\n string,\n { module: string; dependencyCount: number; fanIn: number; fanOut: number; depth: number }\n >();\n\n for (const file of snapshot.analysis.structural.files) {\n const module = toPosixDirname(file.relativePath);\n const current = moduleMap.get(module) ?? {\n module,\n dependencyCount: 0,\n fanIn: 0,\n fanOut: 0,\n depth: 0,\n };\n\n current.dependencyCount += file.directDependencies.length;\n current.fanIn = Math.max(current.fanIn, file.fanIn);\n current.fanOut = Math.max(current.fanOut, file.fanOut);\n current.depth = Math.max(current.depth, file.depth);\n moduleMap.set(module, current);\n }\n\n return [...moduleMap.values()]\n .sort(\n (a, b) =>\n b.dependencyCount - a.dependencyCount ||\n b.fanIn - a.fanIn ||\n b.depth - a.depth ||\n a.module.localeCompare(b.module),\n )\n .slice(0, 5);\n};\n\nconst average = (values: readonly number[]): number | null =>\n values.length === 0\n ? null\n : round4(values.reduce((sum, value) => sum + value, 0) / values.length);\n\nconst toPercent = (value: number): number => round4(value * 100);\nconst STALE_OWNED_FILE_DAYS = 180;\nconst MODULE_KNOWLEDGE_LABEL_PRIORITY = {\n siloed: 0,\n sparse: 1,\n distributed: 2,\n} as const;\n\nconst clamp01 = (value: number): number => Math.max(0, Math.min(1, value));\nconst MIN_FRAGILE_AREA_TOTAL_COMMITS = 3;\n\nconst fileOwnershipItems = (\n files: Extract<CodeSentinelSnapshot[\"analysis\"][\"evolution\"], { available: true }>[\"files\"],\n): Extract<CodeSentinelReport[\"changeOwnership\"], { available: true }>[\"fileOwnership\"] => {\n const labelPriority = {\n singleMaintainer: 0,\n concentrated: 1,\n shared: 2,\n } as const;\n\n return files\n .filter((file) => file.commitCount > 0 && file.authorDistributionByCommits.length > 0)\n .map((file) => {\n const ownershipLabel: FileOwnershipReportItem[\"ownershipLabel\"] =\n file.authorDistributionByCommits.length <= 1\n ? \"singleMaintainer\"\n : file.topAuthorShareByCommits > 0.6\n ? \"concentrated\"\n : \"shared\";\n\n return {\n filePath: file.filePath,\n module: toPosixDirname(file.filePath),\n commitCount: file.commitCount,\n churnTotal: file.churnTotal,\n ownershipLabel,\n topAuthorShareByCommits: file.topAuthorShareByCommits,\n busFactorByCommits: file.busFactorByCommits,\n authorDistributionByCommits: file.authorDistributionByCommits,\n topAuthorShareByChurn: file.topAuthorShareByChurn,\n busFactorByChurn: file.busFactorByChurn,\n authorDistributionByChurn: file.authorDistributionByChurn,\n };\n })\n .sort(\n (a, b) =>\n labelPriority[a.ownershipLabel] - labelPriority[b.ownershipLabel] ||\n b.topAuthorShareByCommits - a.topAuthorShareByCommits ||\n b.commitCount - a.commitCount ||\n a.filePath.localeCompare(b.filePath),\n );\n};\n\ntype ChangeOwnershipAvailable = Extract<CodeSentinelReport[\"changeOwnership\"], { available: true }>;\ntype ChangeOwnershipFileOwnership = ChangeOwnershipAvailable[\"fileOwnership\"];\ntype ChangeOwnershipModuleKnowledge = ChangeOwnershipAvailable[\"moduleKnowledge\"];\ntype ChangeOwnershipMetrics = ChangeOwnershipAvailable[\"metrics\"];\ntype ChangeOwnershipPosture = ChangeOwnershipAvailable[\"posture\"];\ntype ChangeOwnershipContributorOwnership = ChangeOwnershipAvailable[\"contributorOwnership\"];\n\nconst moduleKnowledgeItems = (\n files: Extract<CodeSentinelSnapshot[\"analysis\"][\"evolution\"], { available: true }>[\"files\"],\n): readonly ChangeOwnershipModuleKnowledge[number][] => {\n const moduleKnowledgeMap = new Map<\n string,\n {\n module: string;\n totalCommits: number;\n recentCommits: number;\n authors: Set<string>;\n weightedTopAuthorShare: number;\n weight: number;\n }\n >();\n\n for (const file of files) {\n const module = toPosixDirname(file.filePath);\n const current = moduleKnowledgeMap.get(module) ?? {\n module,\n totalCommits: 0,\n recentCommits: 0,\n authors: new Set<string>(),\n weightedTopAuthorShare: 0,\n weight: 0,\n };\n\n current.totalCommits += file.commitCount;\n current.recentCommits += file.recentCommitCount;\n for (const author of file.authorDistributionByCommits) {\n current.authors.add(author.authorId);\n }\n\n current.weightedTopAuthorShare += file.topAuthorShareByCommits * Math.max(1, file.commitCount);\n current.weight += Math.max(1, file.commitCount);\n moduleKnowledgeMap.set(module, current);\n }\n\n return [...moduleKnowledgeMap.values()]\n .map((entry) => {\n const topAuthorShareByCommits =\n entry.weight <= 0 ? 0 : round4(entry.weightedTopAuthorShare / entry.weight);\n const activeAuthors = entry.authors.size;\n const ownershipLabel: \"distributed\" | \"sparse\" | \"siloed\" =\n activeAuthors <= 1 || topAuthorShareByCommits >= 0.85\n ? \"siloed\"\n : activeAuthors <= 2 || topAuthorShareByCommits >= 0.65\n ? \"sparse\"\n : \"distributed\";\n\n return {\n module: entry.module,\n totalCommits: entry.totalCommits,\n recentCommits: entry.recentCommits,\n activeAuthors,\n topAuthorShareByCommits,\n ownershipLabel,\n };\n })\n .sort(\n (a, b) =>\n MODULE_KNOWLEDGE_LABEL_PRIORITY[a.ownershipLabel] -\n MODULE_KNOWLEDGE_LABEL_PRIORITY[b.ownershipLabel] ||\n b.totalCommits - a.totalCommits ||\n a.module.localeCompare(b.module),\n );\n};\n\nconst ownershipPosture = (\n fileOwnership: ChangeOwnershipFileOwnership,\n moduleKnowledge: ChangeOwnershipModuleKnowledge,\n metrics: ChangeOwnershipMetrics,\n): ChangeOwnershipPosture => {\n const authorTouchCounts = new Map<string, number>();\n for (const file of fileOwnership) {\n for (const author of file.authorDistributionByCommits) {\n authorTouchCounts.set(\n author.authorId,\n (authorTouchCounts.get(author.authorId) ?? 0) + author.commits,\n );\n }\n }\n\n const totalTouches = [...authorTouchCounts.values()].reduce((sum, value) => sum + value, 0);\n const largestContributorSharePercent =\n totalTouches <= 0\n ? null\n : round4((Math.max(...authorTouchCounts.values()) / totalTouches) * 100);\n const activeContributors = authorTouchCounts.size;\n const dominatedModules = moduleKnowledge.filter(\n (module) => module.ownershipLabel === \"siloed\" || module.topAuthorShareByCommits >= 0.8,\n ).length;\n const singleOwnerModulesPercent =\n moduleKnowledge.length === 0 ? null : round4((dominatedModules / moduleKnowledge.length) * 100);\n const concentratedOrSingle =\n (metrics.concentratedOwnershipPercent ?? 0) + (metrics.singleMaintainerPercent ?? 0);\n const staleOwnedFilesPercent = metrics.staleOwnedFilesPercent ?? 0;\n const singleMaintainerPercent = metrics.singleMaintainerPercent ?? 0;\n\n let status: ChangeOwnershipPosture[\"status\"] = \"balanced\";\n\n if (staleOwnedFilesPercent >= 25) {\n status = \"stale\";\n } else if (\n singleMaintainerPercent >= 35 ||\n (singleOwnerModulesPercent ?? 0) >= 35 ||\n (largestContributorSharePercent ?? 0) >= 55\n ) {\n status = \"siloed\";\n } else if (concentratedOrSingle >= 45 || (largestContributorSharePercent ?? 0) >= 30) {\n status = \"concentrated\";\n }\n\n const titleByStatus = {\n balanced: \"Balanced Ownership\",\n concentrated: \"Concentrated Ownership\",\n siloed: \"Siloed Ownership\",\n stale: \"Stale Ownership\",\n } as const;\n\n const summaryByStatus = {\n balanced: `Knowledge is broadly distributed across the repository. ${metrics.sharedOwnershipPercent ?? 0}% of ownership-ready files are shared, with limited module concentration.`,\n concentrated: `The repository still depends on a narrow set of contributors in key paths. ${round4(concentratedOrSingle)}% of ownership-ready files are concentrated or single-maintainer.`,\n siloed: `Knowledge silos are material. Single-maintainer files or module dominance are high enough that handoff risk is no longer isolated.`,\n stale: `A meaningful slice of owned files has gone cold. Stale ownership areas are large enough to distort the repo's operating posture.`,\n } as const;\n\n return {\n status,\n title: titleByStatus[status],\n summary: summaryByStatus[status],\n activeContributors,\n largestContributorSharePercent,\n singleOwnerModulesPercent,\n };\n};\n\nconst ownershipContributors = (\n fileOwnership: ChangeOwnershipFileOwnership,\n): ChangeOwnershipContributorOwnership => {\n const commitTouchesByAuthor = new Map<string, number>();\n let totalCommitTouches = 0;\n let totalChurn = 0;\n\n const contributorMap = new Map<\n string,\n {\n authorId: string;\n singleMaintainerFiles: number;\n concentratedFiles: number;\n ownedFiles: number;\n totalCommitTouches: number;\n ownedChurnTotal: number;\n }\n >();\n\n for (const file of fileOwnership) {\n for (const author of file.authorDistributionByCommits) {\n commitTouchesByAuthor.set(\n author.authorId,\n (commitTouchesByAuthor.get(author.authorId) ?? 0) + author.commits,\n );\n totalCommitTouches += author.commits;\n }\n\n for (const author of file.authorDistributionByChurn) {\n totalChurn += author.churnTotal;\n }\n\n const dominantAuthor = file.authorDistributionByCommits[0];\n if (dominantAuthor === undefined) {\n continue;\n }\n\n const current = contributorMap.get(dominantAuthor.authorId) ?? {\n authorId: dominantAuthor.authorId,\n singleMaintainerFiles: 0,\n concentratedFiles: 0,\n ownedFiles: 0,\n totalCommitTouches: 0,\n ownedChurnTotal: 0,\n };\n\n current.ownedFiles += 1;\n current.totalCommitTouches += dominantAuthor.commits;\n\n const dominantChurnShare = file.authorDistributionByChurn.find(\n (entry) => entry.authorId === dominantAuthor.authorId,\n );\n current.ownedChurnTotal += dominantChurnShare?.churnTotal ?? 0;\n\n if (file.ownershipLabel === \"singleMaintainer\") {\n current.singleMaintainerFiles += 1;\n } else if (file.ownershipLabel === \"concentrated\") {\n current.concentratedFiles += 1;\n }\n\n contributorMap.set(dominantAuthor.authorId, current);\n }\n\n return [...contributorMap.values()]\n .map((entry) => ({\n authorId: entry.authorId,\n singleMaintainerFiles: entry.singleMaintainerFiles,\n concentratedFiles: entry.concentratedFiles,\n ownedFiles: entry.ownedFiles,\n totalCommitTouches: entry.totalCommitTouches,\n totalCommitShare:\n totalCommitTouches === 0\n ? 0\n : round4((entry.totalCommitTouches / totalCommitTouches) * 100),\n ownedChurnShare: totalChurn === 0 ? 0 : round4((entry.ownedChurnTotal / totalChurn) * 100),\n }))\n .sort(\n (a, b) =>\n b.singleMaintainerFiles - a.singleMaintainerFiles ||\n b.concentratedFiles - a.concentratedFiles ||\n b.ownedFiles - a.ownedFiles ||\n b.totalCommitShare - a.totalCommitShare ||\n a.authorId.localeCompare(b.authorId),\n )\n .slice(0, 8);\n};\n\nconst ownershipFragilityScore = (module: ChangeOwnershipModuleKnowledge[number]): number => {\n const severityBase =\n module.ownershipLabel === \"siloed\" ? 0.85 : module.ownershipLabel === \"sparse\" ? 0.55 : 0.2;\n const severity = clamp01(severityBase + Math.max(0, module.topAuthorShareByCommits - 0.6));\n const activityWeight =\n clamp01(module.recentCommits / 6) * 0.65 + clamp01(module.totalCommits / 20) * 0.35;\n\n return round4(severity * activityWeight);\n};\n\nconst changeOwnershipSummary = (\n snapshot: CodeSentinelSnapshot,\n): CodeSentinelReport[\"changeOwnership\"] => {\n if (!snapshot.analysis.evolution.available) {\n return {\n available: false,\n reason: snapshot.analysis.evolution.reason,\n };\n }\n\n const evolution = snapshot.analysis.evolution;\n const files = evolution.files;\n const ownershipReadyFiles = files.filter(\n (file) => file.topAuthorShareByCommits !== null && file.authorDistributionByCommits.length > 0,\n );\n\n const sharedOwnershipCount = ownershipReadyFiles.filter(\n (file) => file.authorDistributionByCommits.length >= 2 && file.topAuthorShareByCommits <= 0.6,\n ).length;\n const concentratedOwnershipCount = ownershipReadyFiles.filter(\n (file) => file.authorDistributionByCommits.length >= 2 && file.topAuthorShareByCommits > 0.6,\n ).length;\n const singleMaintainerCount = ownershipReadyFiles.filter(\n (file) => file.authorDistributionByCommits.length <= 1,\n ).length;\n const headCommitTimestamp = evolution.metrics.headCommitTimestamp;\n const staleOwnedFilesCount = ownershipReadyFiles.filter(\n (file) =>\n file.commitCount > 0 &&\n file.lastCommitTimestamp !== null &&\n headCommitTimestamp !== null &&\n headCommitTimestamp - file.lastCommitTimestamp >= STALE_OWNED_FILE_DAYS * 86_400,\n ).length;\n const ownershipDivisor = ownershipReadyFiles.length || 0;\n const metrics = {\n totalCommits: evolution.metrics.totalCommits,\n totalFiles: evolution.metrics.totalFiles,\n recentWindowDays: evolution.metrics.recentWindowDays,\n meanBusFactorByCommits: average(\n files.map((file) => file.busFactorByCommits).filter((value) => value !== null),\n ),\n averageRecentVolatility: average(files.map((file) => toPercent(file.recentVolatility))),\n sharedOwnershipPercent:\n ownershipDivisor === 0 ? null : round4((sharedOwnershipCount / ownershipDivisor) * 100),\n concentratedOwnershipPercent:\n ownershipDivisor === 0 ? null : round4((concentratedOwnershipCount / ownershipDivisor) * 100),\n singleMaintainerPercent:\n ownershipDivisor === 0 ? null : round4((singleMaintainerCount / ownershipDivisor) * 100),\n staleOwnedFilesPercent:\n ownershipDivisor === 0 ? null : round4((staleOwnedFilesCount / ownershipDivisor) * 100),\n } satisfies ChangeOwnershipMetrics;\n\n const fileOwnership = fileOwnershipItems(files);\n const allModuleKnowledge = moduleKnowledgeItems(files);\n const posture = ownershipPosture(fileOwnership, allModuleKnowledge, metrics);\n const contributorOwnership = ownershipContributors(fileOwnership);\n const moduleKnowledge = allModuleKnowledge.slice(0, 8);\n const fragileAreas = allModuleKnowledge\n .slice()\n .filter((module) => module.totalCommits >= MIN_FRAGILE_AREA_TOTAL_COMMITS)\n .sort(\n (a, b) =>\n ownershipFragilityScore(b) - ownershipFragilityScore(a) ||\n b.topAuthorShareByCommits - a.topAuthorShareByCommits ||\n b.recentCommits - a.recentCommits ||\n b.totalCommits - a.totalCommits ||\n a.module.localeCompare(b.module),\n )\n .slice(0, 5);\n\n const coChangePairs = [...evolution.coupling.pairs]\n .sort(\n (a, b) =>\n b.couplingScore - a.couplingScore ||\n b.coChangeCommits - a.coChangeCommits ||\n a.fileA.localeCompare(b.fileA) ||\n a.fileB.localeCompare(b.fileB),\n )\n .slice(0, 5)\n .map((pair) => ({\n fileA: pair.fileA,\n fileB: pair.fileB,\n coChangeCommits: pair.coChangeCommits,\n couplingScore: round4(pair.couplingScore),\n }));\n\n return {\n available: true,\n metrics,\n posture,\n recentActivity: evolution.recentActivity ?? [],\n coChangePairs,\n moduleKnowledge,\n fragileAreas,\n contributorOwnership,\n fileOwnership,\n };\n};\n\nconst riskyDependencies = (\n snapshot: CodeSentinelSnapshot,\n): readonly RiskyDependencyReportItem[] => {\n if (!snapshot.analysis.external.available) {\n return [];\n }\n\n const dependencyByName = new Map(\n snapshot.analysis.external.dependencies.map((dependency) => [dependency.name, dependency]),\n );\n\n return snapshot.analysis.risk.dependencyScores\n .map((score) => {\n const dependency = dependencyByName.get(score.dependency);\n const riskSignals = [...new Set([...score.ownRiskSignals, ...score.inheritedRiskSignals])];\n\n return {\n name: score.dependency,\n score: score.score,\n normalizedScore: score.normalizedScore,\n dependencyScope: normalizeDependencyScope(dependency?.dependencyScope),\n direct: dependency?.direct ?? false,\n resolvedVersion: dependency?.resolvedVersion ?? null,\n transitiveDependencyCount: dependency?.transitiveDependencies.length ?? 0,\n dependentCount: dependency?.dependents ?? 0,\n fanOut: dependency?.fanOut ?? 0,\n dependencyDepth: dependency?.dependencyDepth ?? 0,\n weeklyDownloads: dependency?.weeklyDownloads ?? null,\n maintainerCount: dependency?.maintainerCount ?? null,\n releaseFrequencyDays: dependency?.releaseFrequencyDays ?? null,\n daysSinceLastRelease: dependency?.daysSinceLastRelease ?? null,\n repositoryActivity30d: dependency?.repositoryActivity30d ?? null,\n busFactor: dependency?.busFactor ?? null,\n ownRiskSignals: dependency?.ownRiskSignals ?? [],\n inheritedRiskSignals: dependency?.inheritedRiskSignals ?? [],\n riskSignals,\n reason:\n riskSignals.length === 0\n ? \"Derived from aggregate dependency risk signals.\"\n : riskSignals.join(\", \"),\n };\n })\n .filter((dependency) => dependency.score > 0)\n .sort((a, b) => b.score - a.score || a.name.localeCompare(b.name))\n .slice(0, 20);\n};\n\nconst repositoryDimensionScores = (snapshot: CodeSentinelSnapshot): RepositoryDimensionScores => {\n const target = findTraceTarget(snapshot, \"repository\", snapshot.analysis.structural.targetPath);\n if (target === undefined) {\n return {\n structural: null,\n evolution: null,\n external: null,\n interactions: null,\n };\n }\n\n const structural = target.factors.find((factor) => factor.factorId === \"repository.structural\");\n const evolution = target.factors.find((factor) => factor.factorId === \"repository.evolution\");\n const external = target.factors.find((factor) => factor.factorId === \"repository.external\");\n const interactions = target.factors.find(\n (factor) => factor.factorId === \"repository.composite.interactions\",\n );\n\n const interactionScore =\n interactions === undefined\n ? null\n : round4(\n ((interactions.rawMetrics[\"structuralEvolution\"] ?? 0) +\n (interactions.rawMetrics[\"centralInstability\"] ?? 0) +\n (interactions.rawMetrics[\"dependencyAmplification\"] ?? 0)) *\n 100,\n );\n\n return {\n structural:\n structural === undefined\n ? null\n : round4((structural.rawMetrics[\"structuralDimension\"] ?? 0) * 100),\n evolution:\n evolution === undefined\n ? null\n : round4((evolution.rawMetrics[\"evolutionDimension\"] ?? 0) * 100),\n external:\n external === undefined ? null : round4((external.rawMetrics[\"externalDimension\"] ?? 0) * 100),\n interactions: interactionScore,\n };\n};\n\nconst workspaceSummary = (snapshot: CodeSentinelSnapshot): WorkspaceReportSummary => ({\n structural: [...(snapshot.analysis.structural.workspaces ?? [])]\n .sort(\n (a, b) =>\n b.incomingEdgeCount +\n b.outgoingEdgeCount +\n b.internalEdgeCount -\n (a.incomingEdgeCount + a.outgoingEdgeCount + a.internalEdgeCount) ||\n b.fileCount - a.fileCount ||\n a.path.localeCompare(b.path),\n )\n .map((workspace) => ({\n name: workspace.name,\n path: workspace.path,\n kind: workspace.kind,\n fileCount: workspace.fileCount,\n internalEdgeCount: workspace.internalEdgeCount,\n incomingEdgeCount: workspace.incomingEdgeCount,\n outgoingEdgeCount: workspace.outgoingEdgeCount,\n })),\n risk: [...snapshot.analysis.risk.workspaceScores]\n .sort((a, b) => b.score - a.score || a.path.localeCompare(b.path))\n .map((workspace) => ({\n name: workspace.name,\n path: workspace.path,\n kind: workspace.kind,\n score: workspace.score,\n normalizedScore: workspace.normalizedScore,\n fileCount: workspace.fileCount,\n averageFileRisk: workspace.averageFileRisk,\n peakFileRisk: workspace.peakFileRisk,\n internalEdgeCount: workspace.internalEdgeCount,\n incomingEdgeCount: workspace.incomingEdgeCount,\n outgoingEdgeCount: workspace.outgoingEdgeCount,\n topFiles: workspace.topFiles.slice(0, 5).map((file) => ({\n file: file.file,\n score: file.score,\n })),\n })),\n evolution: snapshot.analysis.evolution.available\n ? [...(snapshot.analysis.evolution.workspaces ?? [])]\n .sort(\n (a, b) =>\n b.recentVolatility - a.recentVolatility ||\n b.churnTotal - a.churnTotal ||\n b.commitCount - a.commitCount ||\n a.path.localeCompare(b.path),\n )\n .map((workspace) => ({\n name: workspace.name,\n path: workspace.path,\n kind: workspace.kind,\n fileCount: workspace.fileCount,\n commitCount: workspace.commitCount,\n churnTotal: workspace.churnTotal,\n recentCommitCount: workspace.recentCommitCount,\n recentVolatility: workspace.recentVolatility,\n topAuthorShareByCommits: workspace.topAuthorShareByCommits,\n busFactorByCommits: workspace.busFactorByCommits,\n hotspotCount: workspace.hotspotCount,\n topHotspots: workspace.topHotspots.slice(0, 5).map((hotspot) => ({\n filePath: hotspot.filePath,\n rank: hotspot.rank,\n commitCount: hotspot.commitCount,\n churnTotal: hotspot.churnTotal,\n })),\n internalCouplingPairCount: workspace.internalCouplingPairCount,\n incomingCouplingPairCount: workspace.incomingCouplingPairCount,\n outgoingCouplingPairCount: workspace.outgoingCouplingPairCount,\n }))\n : [],\n external: snapshot.analysis.external.available\n ? [...(snapshot.analysis.external.workspaces ?? [])]\n .sort(\n (a, b) =>\n b.highRiskDependencies.length - a.highRiskDependencies.length ||\n b.transitiveExposureDependencies.length - a.transitiveExposureDependencies.length ||\n b.directDependencies - a.directDependencies ||\n a.path.localeCompare(b.path),\n )\n .map((workspace) => ({\n name: workspace.name,\n path: workspace.path,\n kind: workspace.kind,\n directDependencies: workspace.directDependencies,\n directProductionDependencies: workspace.directProductionDependencies,\n directDevelopmentDependencies: workspace.directDevelopmentDependencies,\n unresolvedDependencies: [...workspace.unresolvedDependencies].sort((a, b) =>\n a.localeCompare(b),\n ),\n dependencyNames: [...workspace.dependencyNames].sort((a, b) => a.localeCompare(b)),\n sharedDependencies: [...workspace.sharedDependencies].sort((a, b) => a.localeCompare(b)),\n highRiskDependencies: [...workspace.highRiskDependencies].sort((a, b) =>\n a.localeCompare(b),\n ),\n highRiskDevelopmentDependencies: [...workspace.highRiskDevelopmentDependencies].sort(\n (a, b) => a.localeCompare(b),\n ),\n transitiveExposureDependencies: [...workspace.transitiveExposureDependencies].sort(\n (a, b) => a.localeCompare(b),\n ),\n singleMaintainerDependencies: [...workspace.singleMaintainerDependencies].sort((a, b) =>\n a.localeCompare(b),\n ),\n abandonedDependencies: [...workspace.abandonedDependencies].sort((a, b) =>\n a.localeCompare(b),\n ),\n }))\n : [],\n});\n\nexport const createReport = (\n snapshot: CodeSentinelSnapshot,\n diff?: SnapshotDiff,\n extras: ReportExtras = {},\n): CodeSentinelReport => {\n const external = snapshot.analysis.external;\n\n return {\n schemaVersion: REPORT_SCHEMA_VERSION,\n generatedAt: new Date().toISOString(),\n repository: {\n name:\n basename(snapshot.analysis.structural.targetPath) ||\n snapshot.analysis.structural.targetPath,\n targetPath: snapshot.analysis.structural.targetPath,\n riskScore: snapshot.analysis.risk.riskScore,\n normalizedScore: snapshot.analysis.risk.normalizedScore,\n riskTier: toRiskTier(snapshot.analysis.risk.riskScore),\n healthTier: toHealthTier(snapshot.analysis.health.healthScore),\n confidence: repositoryConfidence(snapshot),\n dimensionScores: repositoryDimensionScores(snapshot),\n webUrl: extras.repositoryWebUrl ?? null,\n },\n health: snapshot.analysis.health,\n workspaces: workspaceSummary(snapshot),\n hotspots: hotspotItems(snapshot),\n structural: {\n cycleCount: snapshot.analysis.structural.metrics.cycleCount,\n cycles: snapshot.analysis.structural.cycles.map((cycle) =>\n [...cycle.nodes].sort((a, b) => a.localeCompare(b)).join(\" -> \"),\n ),\n cycleDetails: cycleDetails(snapshot),\n metrics: structuralArchitectureMetrics(snapshot),\n moduleAnatomy: structuralModuleAnatomy(snapshot),\n fanInOutExtremes: {\n highestFanIn: topStructuralFiles(snapshot, (file) => file.fanIn),\n highestFanOut: topStructuralFiles(snapshot, (file) => file.fanOut),\n deepestFiles: topStructuralFiles(snapshot, (file) => file.depth),\n },\n fragileClusters: snapshot.analysis.risk.fragileClusters.map((cluster) => ({\n id: cluster.id,\n kind: cluster.kind,\n score: cluster.score,\n files: [...cluster.files].sort((a, b) => a.localeCompare(b)),\n })),\n },\n changeOwnership: changeOwnershipSummary(snapshot),\n external: !external.available\n ? {\n available: false,\n reason: external.reason,\n }\n : {\n available: true,\n metrics: external.metrics,\n highRiskDependencies: [...external.highRiskDependencies].sort((a, b) =>\n a.localeCompare(b),\n ),\n highRiskDevelopmentDependencies: [...external.highRiskDevelopmentDependencies].sort(\n (a, b) => a.localeCompare(b),\n ),\n transitiveExposureDependencies: [...external.transitiveExposureDependencies].sort(\n (a, b) => a.localeCompare(b),\n ),\n singleMaintainerDependencies: [...external.singleMaintainerDependencies].sort((a, b) =>\n a.localeCompare(b),\n ),\n abandonedDependencies: [...external.abandonedDependencies].sort((a, b) =>\n a.localeCompare(b),\n ),\n centralityRanking: [...external.centralityRanking].sort(\n (a, b) =>\n b.dependents - a.dependents || b.fanOut - a.fanOut || a.name.localeCompare(b.name),\n ),\n riskyDependencies: riskyDependencies(snapshot),\n },\n ...(extras.ownership === undefined ? {} : { ownership: extras.ownership }),\n appendix: {\n snapshotSchemaVersion: snapshot.schemaVersion,\n riskModelVersion: snapshot.riskModelVersion,\n timestamp: snapshot.generatedAt,\n normalization:\n \"Scores are deterministic 0-100 outputs from risk-engine normalized factors and interaction terms.\",\n ...(snapshot.analysisConfig === undefined ? {} : { analysisConfig: snapshot.analysisConfig }),\n },\n ...(diff === undefined ? {} : { diff }),\n };\n};\n","import type { CodeSentinelReport } from \"./domain.js\";\n\nconst renderTextDiff = (report: CodeSentinelReport): string[] => {\n if (report.diff === undefined) {\n return [];\n }\n\n return [\n \"\",\n \"Diff\",\n ` riskScoreDelta: ${report.diff.riskScoreDelta}`,\n ` normalizedScoreDelta: ${report.diff.normalizedScoreDelta}`,\n ` newHotspots: ${report.diff.newHotspots.join(\", \") || \"none\"}`,\n ` resolvedHotspots: ${report.diff.resolvedHotspots.join(\", \") || \"none\"}`,\n ` newCycles: ${report.diff.newCycles.join(\", \") || \"none\"}`,\n ` resolvedCycles: ${report.diff.resolvedCycles.join(\", \") || \"none\"}`,\n ];\n};\n\nconst renderTextWorkspaceSummary = (report: CodeSentinelReport): string[] => {\n const workspaceCount = Math.max(\n report.workspaces.structural.length,\n report.workspaces.risk.length,\n report.workspaces.evolution.length,\n report.workspaces.external.length,\n );\n\n if (workspaceCount === 0) {\n return [];\n }\n\n const lines = [\"\", \"Workspace Summary\"];\n lines.push(\" topRisk:\");\n for (const workspace of report.workspaces.risk.slice(0, 5)) {\n lines.push(\n ` - ${workspace.path} | score=${workspace.score} files=${workspace.fileCount} peakFileRisk=${workspace.peakFileRisk}`,\n );\n }\n if (report.workspaces.risk.length === 0) {\n lines.push(\" - none\");\n }\n\n lines.push(\" structuralCoupling:\");\n for (const workspace of report.workspaces.structural.slice(0, 5)) {\n lines.push(\n ` - ${workspace.path} | internal=${workspace.internalEdgeCount} incoming=${workspace.incomingEdgeCount} outgoing=${workspace.outgoingEdgeCount}`,\n );\n }\n if (report.workspaces.structural.length === 0) {\n lines.push(\" - none\");\n }\n\n lines.push(\" evolutionHotspots:\");\n for (const workspace of report.workspaces.evolution.slice(0, 5)) {\n lines.push(\n ` - ${workspace.path} | commits=${workspace.commitCount} churn=${workspace.churnTotal} recentVolatility=${workspace.recentVolatility}`,\n );\n }\n if (report.workspaces.evolution.length === 0) {\n lines.push(\" - none\");\n }\n\n lines.push(\" dependencyExposure:\");\n for (const workspace of report.workspaces.external.slice(0, 5)) {\n lines.push(\n ` - ${workspace.path} | direct=${workspace.directDependencies} shared=${workspace.sharedDependencies.length} highRisk=${workspace.highRiskDependencies.length} transitiveExposure=${workspace.transitiveExposureDependencies.length}`,\n );\n }\n if (report.workspaces.external.length === 0) {\n lines.push(\" - none\");\n }\n\n return lines;\n};\n\nexport const renderTextReport = (report: CodeSentinelReport): string => {\n const lines: string[] = [];\n lines.push(\"Repository Summary\");\n lines.push(` target: ${report.repository.targetPath}`);\n lines.push(` riskScore: ${report.repository.riskScore}`);\n lines.push(` normalizedScore: ${report.repository.normalizedScore}`);\n lines.push(` riskTier: ${report.repository.riskTier}`);\n lines.push(` healthTier: ${report.repository.healthTier}`);\n lines.push(` confidence: ${report.repository.confidence ?? \"n/a\"}`);\n\n lines.push(\"\");\n lines.push(\"Dimension Scores (0-100)\");\n lines.push(` structural: ${report.repository.dimensionScores.structural ?? \"n/a\"}`);\n lines.push(` evolution: ${report.repository.dimensionScores.evolution ?? \"n/a\"}`);\n lines.push(` external: ${report.repository.dimensionScores.external ?? \"n/a\"}`);\n lines.push(` interactions: ${report.repository.dimensionScores.interactions ?? \"n/a\"}`);\n\n lines.push(\"\");\n lines.push(\"Health Summary\");\n lines.push(` healthScore: ${report.health.healthScore}`);\n lines.push(` normalizedScore: ${report.health.normalizedScore}`);\n lines.push(` modularity: ${report.health.dimensions.modularity}`);\n lines.push(` changeHygiene: ${report.health.dimensions.changeHygiene}`);\n lines.push(` testHealth: ${report.health.dimensions.testHealth}`);\n lines.push(` ownershipDistribution: ${report.health.dimensions.ownershipDistribution}`);\n lines.push(\" topIssues:\");\n for (const issue of report.health.topIssues.slice(0, 5)) {\n const ruleSuffix = issue.ruleId === undefined ? \"\" : ` [rule=${issue.ruleId}]`;\n lines.push(\n ` - [${issue.severity}] (${issue.dimension}) ${issue.id}${ruleSuffix} @ ${issue.target}: ${issue.message}`,\n );\n }\n if (report.health.topIssues.length === 0) {\n lines.push(\" - none\");\n }\n\n lines.push(\"\");\n lines.push(\"Ownership Posture\");\n if (!report.changeOwnership.available) {\n lines.push(` unavailable: ${report.changeOwnership.reason}`);\n } else {\n lines.push(` status: ${report.changeOwnership.posture.title}`);\n lines.push(` summary: ${report.changeOwnership.posture.summary}`);\n lines.push(` activeContributors: ${report.changeOwnership.posture.activeContributors}`);\n lines.push(\n ` largestContributorSharePercent: ${report.changeOwnership.posture.largestContributorSharePercent ?? \"n/a\"}`,\n );\n lines.push(\n ` singleOwnerModulesPercent: ${report.changeOwnership.posture.singleOwnerModulesPercent ?? \"n/a\"}`,\n );\n }\n\n lines.push(\"\");\n lines.push(\"Top Hotspots\");\n for (const hotspot of report.hotspots) {\n lines.push(` - ${hotspot.target} | score=${hotspot.score}`);\n for (const factor of hotspot.topFactors) {\n lines.push(\n ` factor: ${factor.label} contribution=${factor.contribution} confidence=${factor.confidence}`,\n );\n lines.push(` evidence: ${factor.evidence}`);\n }\n lines.push(` priority actions: ${hotspot.suggestedActions.join(\" | \") || \"none\"}`);\n }\n\n lines.push(\"\");\n lines.push(\"Structural Observations\");\n lines.push(` cycleCount: ${report.structural.cycleCount}`);\n lines.push(` cycles: ${report.structural.cycles.join(\" ; \") || \"none\"}`);\n lines.push(` fragileClusters: ${report.structural.fragileClusters.length}`);\n\n lines.push(...renderTextWorkspaceSummary(report));\n\n lines.push(\"\");\n lines.push(\"External Exposure\");\n if (!report.external.available) {\n lines.push(` unavailable: ${report.external.reason}`);\n } else {\n lines.push(\n ` highRiskDependencies: ${report.external.highRiskDependencies.join(\", \") || \"none\"}`,\n );\n lines.push(\n ` highRiskDevelopmentDependencies: ${report.external.highRiskDevelopmentDependencies.join(\", \") || \"none\"}`,\n );\n lines.push(\n ` singleMaintainerDependencies: ${report.external.singleMaintainerDependencies.join(\", \") || \"none\"}`,\n );\n lines.push(\n ` abandonedDependencies: ${report.external.abandonedDependencies.join(\", \") || \"none\"}`,\n );\n }\n\n lines.push(\"\");\n lines.push(\"Appendix\");\n lines.push(` snapshotSchemaVersion: ${report.appendix.snapshotSchemaVersion}`);\n lines.push(` riskModelVersion: ${report.appendix.riskModelVersion}`);\n lines.push(` timestamp: ${report.appendix.timestamp}`);\n lines.push(` normalization: ${report.appendix.normalization}`);\n\n lines.push(...renderTextDiff(report));\n\n return lines.join(\"\\n\");\n};\n\nconst renderMarkdownDiff = (report: CodeSentinelReport): string[] => {\n if (report.diff === undefined) {\n return [];\n }\n\n return [\n \"\",\n \"## Diff\",\n `- riskScoreDelta: \\`${report.diff.riskScoreDelta}\\``,\n `- normalizedScoreDelta: \\`${report.diff.normalizedScoreDelta}\\``,\n `- newHotspots: ${report.diff.newHotspots.map((item) => `\\`${item}\\``).join(\", \") || \"none\"}`,\n `- resolvedHotspots: ${report.diff.resolvedHotspots.map((item) => `\\`${item}\\``).join(\", \") || \"none\"}`,\n `- newCycles: ${report.diff.newCycles.map((item) => `\\`${item}\\``).join(\", \") || \"none\"}`,\n `- resolvedCycles: ${report.diff.resolvedCycles.map((item) => `\\`${item}\\``).join(\", \") || \"none\"}`,\n ];\n};\n\nconst renderMarkdownWorkspaceSummary = (report: CodeSentinelReport): string[] => {\n const workspaceCount = Math.max(\n report.workspaces.structural.length,\n report.workspaces.risk.length,\n report.workspaces.evolution.length,\n report.workspaces.external.length,\n );\n\n if (workspaceCount === 0) {\n return [];\n }\n\n const lines = [\"\", \"## Workspace Summary\"];\n lines.push(\"- top risk:\");\n if (report.workspaces.risk.length === 0) {\n lines.push(\" - none\");\n } else {\n for (const workspace of report.workspaces.risk.slice(0, 5)) {\n lines.push(\n ` - \\`${workspace.path}\\`: score=\\`${workspace.score}\\`, files=\\`${workspace.fileCount}\\`, peak file risk=\\`${workspace.peakFileRisk}\\``,\n );\n }\n }\n\n lines.push(\"- structural coupling:\");\n if (report.workspaces.structural.length === 0) {\n lines.push(\" - none\");\n } else {\n for (const workspace of report.workspaces.structural.slice(0, 5)) {\n lines.push(\n ` - \\`${workspace.path}\\`: internal=\\`${workspace.internalEdgeCount}\\`, incoming=\\`${workspace.incomingEdgeCount}\\`, outgoing=\\`${workspace.outgoingEdgeCount}\\``,\n );\n }\n }\n\n lines.push(\"- evolution hotspots:\");\n if (report.workspaces.evolution.length === 0) {\n lines.push(\" - none\");\n } else {\n for (const workspace of report.workspaces.evolution.slice(0, 5)) {\n lines.push(\n ` - \\`${workspace.path}\\`: commits=\\`${workspace.commitCount}\\`, churn=\\`${workspace.churnTotal}\\`, recent volatility=\\`${workspace.recentVolatility}\\``,\n );\n }\n }\n\n lines.push(\"- dependency exposure:\");\n if (report.workspaces.external.length === 0) {\n lines.push(\" - none\");\n } else {\n for (const workspace of report.workspaces.external.slice(0, 5)) {\n lines.push(\n ` - \\`${workspace.path}\\`: direct=\\`${workspace.directDependencies}\\`, shared=\\`${workspace.sharedDependencies.length}\\`, high risk=\\`${workspace.highRiskDependencies.length}\\`, transitive exposure=\\`${workspace.transitiveExposureDependencies.length}\\``,\n );\n }\n }\n\n return lines;\n};\n\nexport const renderMarkdownReport = (report: CodeSentinelReport): string => {\n const lines: string[] = [];\n lines.push(\"# CodeSentinel Report\");\n lines.push(\"\");\n lines.push(\"## Repository Summary\");\n lines.push(`- target: \\`${report.repository.targetPath}\\``);\n lines.push(`- riskScore: \\`${report.repository.riskScore}\\``);\n lines.push(`- normalizedScore: \\`${report.repository.normalizedScore}\\``);\n lines.push(`- riskTier: \\`${report.repository.riskTier}\\``);\n lines.push(`- healthTier: \\`${report.repository.healthTier}\\``);\n lines.push(`- confidence: \\`${report.repository.confidence ?? \"n/a\"}\\``);\n\n lines.push(\"\");\n lines.push(\"## Dimension Scores (0-100)\");\n lines.push(`- structural: \\`${report.repository.dimensionScores.structural ?? \"n/a\"}\\``);\n lines.push(`- evolution: \\`${report.repository.dimensionScores.evolution ?? \"n/a\"}\\``);\n lines.push(`- external: \\`${report.repository.dimensionScores.external ?? \"n/a\"}\\``);\n lines.push(`- interactions: \\`${report.repository.dimensionScores.interactions ?? \"n/a\"}\\``);\n\n lines.push(\"\");\n lines.push(\"## Health Summary\");\n lines.push(`- healthScore: \\`${report.health.healthScore}\\``);\n lines.push(`- normalizedScore: \\`${report.health.normalizedScore}\\``);\n lines.push(`- modularity: \\`${report.health.dimensions.modularity}\\``);\n lines.push(`- changeHygiene: \\`${report.health.dimensions.changeHygiene}\\``);\n lines.push(`- testHealth: \\`${report.health.dimensions.testHealth}\\``);\n lines.push(`- ownershipDistribution: \\`${report.health.dimensions.ownershipDistribution}\\``);\n if (report.health.topIssues.length === 0) {\n lines.push(\"- top issues: none\");\n } else {\n lines.push(\"- top issues:\");\n for (const issue of report.health.topIssues.slice(0, 5)) {\n const ruleSuffix = issue.ruleId === undefined ? \"\" : ` [rule=${issue.ruleId}]`;\n lines.push(\n ` - [${issue.severity}] \\`${issue.id}\\`${ruleSuffix} (\\`${issue.dimension}\\`) @ \\`${issue.target}\\`: ${issue.message}`,\n );\n }\n }\n\n lines.push(\"\");\n lines.push(\"## Ownership Posture\");\n if (!report.changeOwnership.available) {\n lines.push(`- unavailable: \\`${report.changeOwnership.reason}\\``);\n } else {\n lines.push(`- status: \\`${report.changeOwnership.posture.title}\\``);\n lines.push(`- summary: ${report.changeOwnership.posture.summary}`);\n lines.push(`- active contributors: \\`${report.changeOwnership.posture.activeContributors}\\``);\n lines.push(\n `- largest contributor share percent: \\`${report.changeOwnership.posture.largestContributorSharePercent ?? \"n/a\"}\\``,\n );\n lines.push(\n `- single-owner modules percent: \\`${report.changeOwnership.posture.singleOwnerModulesPercent ?? \"n/a\"}\\``,\n );\n }\n\n lines.push(\"\");\n lines.push(\"## Top Hotspots\");\n for (const hotspot of report.hotspots) {\n lines.push(`- **${hotspot.target}** (score: \\`${hotspot.score}\\`)`);\n lines.push(` - Top factors:`);\n for (const factor of hotspot.topFactors) {\n lines.push(\n ` - ${factor.label}: contribution=\\`${factor.contribution}\\`, confidence=\\`${factor.confidence}\\``,\n );\n lines.push(` - evidence: \\`${factor.evidence}\\``);\n }\n lines.push(` - Priority actions: ${hotspot.suggestedActions.join(\" | \") || \"none\"}`);\n }\n\n lines.push(\"\");\n lines.push(\"## Structural Observations\");\n lines.push(`- cycles detected: \\`${report.structural.cycleCount}\\``);\n lines.push(\n `- cycles: ${report.structural.cycles.map((cycle) => `\\`${cycle}\\``).join(\", \") || \"none\"}`,\n );\n lines.push(`- fragile clusters: \\`${report.structural.fragileClusters.length}\\``);\n\n lines.push(...renderMarkdownWorkspaceSummary(report));\n\n lines.push(\"\");\n lines.push(\"## External Exposure Summary\");\n if (!report.external.available) {\n lines.push(`- unavailable: \\`${report.external.reason}\\``);\n } else {\n lines.push(\n `- high-risk dependencies: ${report.external.highRiskDependencies.map((item) => `\\`${item}\\``).join(\", \") || \"none\"}`,\n );\n lines.push(\n `- high-risk development dependencies: ${report.external.highRiskDevelopmentDependencies.map((item) => `\\`${item}\\``).join(\", \") || \"none\"}`,\n );\n lines.push(\n `- single maintainer dependencies: ${report.external.singleMaintainerDependencies.map((item) => `\\`${item}\\``).join(\", \") || \"none\"}`,\n );\n lines.push(\n `- abandoned dependencies: ${report.external.abandonedDependencies.map((item) => `\\`${item}\\``).join(\", \") || \"none\"}`,\n );\n }\n\n lines.push(\"\");\n lines.push(\"## Appendix\");\n lines.push(`- snapshot schema: \\`${report.appendix.snapshotSchemaVersion}\\``);\n lines.push(`- risk model version: \\`${report.appendix.riskModelVersion}\\``);\n lines.push(`- timestamp: \\`${report.appendix.timestamp}\\``);\n lines.push(`- normalization: ${report.appendix.normalization}`);\n\n lines.push(...renderMarkdownDiff(report));\n\n return lines.join(\"\\n\");\n};\n","import type { AnalyzeSummary, RiskTrace } from \"@codesentinel/core\";\nimport {\n RISK_MODEL_VERSION,\n SNAPSHOT_SCHEMA_VERSION,\n type CodeSentinelSnapshot,\n} from \"./domain.js\";\n\nexport type CreateSnapshotInput = {\n analysis: AnalyzeSummary;\n trace?: RiskTrace;\n generatedAt?: string;\n analysisConfig?: Readonly<Record<string, string | number | boolean | null>>;\n};\n\nexport const createSnapshot = (input: CreateSnapshotInput): CodeSentinelSnapshot => ({\n schemaVersion: SNAPSHOT_SCHEMA_VERSION,\n generatedAt: input.generatedAt ?? new Date().toISOString(),\n riskModelVersion: RISK_MODEL_VERSION,\n source: {\n targetPath: input.analysis.structural.targetPath,\n },\n analysis: input.analysis,\n ...(input.trace === undefined ? {} : { trace: input.trace }),\n ...(input.analysisConfig === undefined ? {} : { analysisConfig: input.analysisConfig }),\n});\n\nexport const parseSnapshot = (raw: string): CodeSentinelSnapshot => {\n const parsed = JSON.parse(raw) as Partial<CodeSentinelSnapshot>;\n if (parsed.schemaVersion !== SNAPSHOT_SCHEMA_VERSION) {\n throw new Error(\"unsupported_snapshot_schema\");\n }\n\n if (typeof parsed.generatedAt !== \"string\") {\n throw new Error(\"invalid_snapshot_generated_at\");\n }\n\n if (parsed.analysis === undefined || parsed.analysis === null) {\n throw new Error(\"invalid_snapshot_analysis\");\n }\n\n if (parsed.source === undefined || typeof parsed.source.targetPath !== \"string\") {\n throw new Error(\"invalid_snapshot_source\");\n }\n\n return parsed as CodeSentinelSnapshot;\n};\n","import type { CodeSentinelReport, ReportFormat } from \"./domain.js\";\nimport { compareSnapshots } from \"./diff.js\";\nimport { createReport } from \"./report.js\";\nimport { renderMarkdownReport, renderTextReport } from \"./renderers.js\";\nimport { createSnapshot, parseSnapshot } from \"./snapshot.js\";\n\nexport {\n SNAPSHOT_SCHEMA_VERSION,\n REPORT_SCHEMA_VERSION,\n RISK_MODEL_VERSION,\n factorLabel,\n summarizeEvidence,\n type CodeSentinelSnapshot,\n type CodeSentinelReport,\n type CoChangePairReportItem,\n type ChangeOwnershipMetrics,\n type DeclaredOwnerReportItem,\n type HealthIssue,\n type ExternalCentralityReportItem,\n type ExternalMetricsReportItem,\n type FileOwnershipReportItem,\n type HotspotReportItem,\n type OwnershipAuditReport,\n type OwnershipAuditReportMetrics,\n type OwnershipAuditStatus,\n type OwnershipFileReportItem,\n type ModuleKnowledgeReportItem,\n type OwnershipContributorReportItem,\n type OwnershipPostureReportItem,\n type OwnershipPostureStatus,\n type OwnershipRiskAreaReportItem,\n type RecentActivityReportItem,\n type SnapshotDiff,\n type RiskTier,\n type StructuralCycleDetail,\n type StructuralArchitectureMetrics,\n type StructuralFileExtreme,\n type RiskyDependencyReportItem,\n type WorkspaceDependencyExposureReportItem,\n type WorkspaceEvolutionReportItem,\n type WorkspaceReportSummary,\n type WorkspaceRiskReportItem,\n type WorkspaceStructuralReportItem,\n type ReportExtras,\n type ReportFormat,\n} from \"./domain.js\";\n\nexport { createSnapshot, parseSnapshot, compareSnapshots, createReport };\n\nexport const formatReport = (report: CodeSentinelReport, format: ReportFormat): string => {\n if (format === \"json\") {\n return JSON.stringify(report, null, 2);\n }\n\n if (format === \"md\") {\n return renderMarkdownReport(report);\n }\n\n return renderTextReport(report);\n};\n","import type { EvidenceRef } from \"@codesentinel/core\";\nimport type { CodeSentinelSnapshot, SnapshotDiff } from \"@codesentinel/reporter\";\n\nexport type ViolationSeverity = \"info\" | \"warn\" | \"error\";\n\nexport type Violation = {\n id: string;\n severity: ViolationSeverity;\n message: string;\n targets: readonly string[];\n evidenceRefs: readonly EvidenceRef[];\n};\n\nexport type FailOnLevel = \"error\" | \"warn\";\n\nexport type OwnershipGateMetrics = {\n declaredCoveragePercent: number;\n declaredCoverageCriticalPercent: number;\n driftPercent: number;\n ghostOwnerCount: number;\n unownedCriticalCount: number;\n};\n\nexport type OwnershipGateInput =\n | { available: true; source: string; metrics: OwnershipGateMetrics }\n | { available: false; warnings: readonly string[] };\n\nexport type OwnershipGateResult = {\n evaluated: boolean;\n source: string | null;\n metrics: OwnershipGateMetrics | null;\n};\n\nexport type GateConfig = {\n maxRiskDelta?: number;\n maxHealthDelta?: number;\n noNewCycles?: boolean;\n noNewHighRiskDeps?: boolean;\n maxNewHotspots?: number;\n maxRiskScore?: number;\n minHealthScore?: number;\n newHotspotScoreThreshold?: number;\n maxUnownedCritical?: number;\n maxGhostOwners?: number;\n maxDrift?: number;\n failOn: FailOnLevel;\n};\n\nexport type GateEvaluationInput = {\n current: CodeSentinelSnapshot;\n baseline?: CodeSentinelSnapshot;\n diff?: SnapshotDiff;\n gateConfig: GateConfig;\n ownership?: OwnershipGateInput;\n};\n\nexport type GateEvaluationResult = {\n violations: readonly Violation[];\n highestSeverity: ViolationSeverity | null;\n exitCode: 0 | 1 | 2;\n evaluatedGates: readonly string[];\n warnings: readonly string[];\n ownership?: OwnershipGateResult;\n};\n\nexport const EXIT_CODES = {\n ok: 0,\n errorViolation: 1,\n warnViolation: 2,\n invalidConfiguration: 3,\n internalError: 4,\n} as const;\n\nexport class GovernanceConfigurationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"GovernanceConfigurationError\";\n }\n}\n\nexport const DEFAULT_NEW_HOTSPOT_SCORE_THRESHOLD = 60;\n","import type { EvidenceRef } from \"@codesentinel/core\";\nimport {\n DEFAULT_NEW_HOTSPOT_SCORE_THRESHOLD,\n GovernanceConfigurationError,\n type GateEvaluationInput,\n type GateEvaluationResult,\n type OwnershipGateResult,\n type Violation,\n type ViolationSeverity,\n} from \"./domain.js\";\n\nconst severityRank: Readonly<Record<ViolationSeverity, number>> = {\n info: 0,\n warn: 1,\n error: 2,\n};\n\nconst compareSeverity = (\n left: ViolationSeverity | null,\n right: ViolationSeverity | null,\n): ViolationSeverity | null => {\n if (left === null) {\n return right;\n }\n if (right === null) {\n return left;\n }\n\n return severityRank[left] >= severityRank[right] ? left : right;\n};\n\nconst stableSortViolations = (violations: readonly Violation[]): readonly Violation[] =>\n [...violations].sort((a, b) => {\n const severity = severityRank[b.severity] - severityRank[a.severity];\n if (severity !== 0) {\n return severity;\n }\n\n if (a.id !== b.id) {\n return a.id.localeCompare(b.id);\n }\n\n const aTarget = a.targets[0] ?? \"\";\n const bTarget = b.targets[0] ?? \"\";\n if (aTarget !== bTarget) {\n return aTarget.localeCompare(bTarget);\n }\n\n return a.message.localeCompare(b.message);\n });\n\nconst makeViolation = (\n id: string,\n severity: ViolationSeverity,\n message: string,\n targets: readonly string[],\n evidenceRefs: readonly EvidenceRef[],\n): Violation => ({\n id,\n severity,\n message,\n targets: [...targets].sort((a, b) => a.localeCompare(b)),\n evidenceRefs,\n});\n\nconst requireDiff = (input: GateEvaluationInput, gateId: string): void => {\n if (input.baseline === undefined || input.diff === undefined) {\n throw new GovernanceConfigurationError(`${gateId} requires --compare <baseline.json>`);\n }\n};\n\nconst validateGateConfig = (input: GateEvaluationInput): void => {\n const config = input.gateConfig;\n\n if (\n config.maxRiskDelta !== undefined &&\n (!Number.isFinite(config.maxRiskDelta) || config.maxRiskDelta < 0)\n ) {\n throw new GovernanceConfigurationError(\"max-risk-delta must be a finite number >= 0\");\n }\n\n if (\n config.maxHealthDelta !== undefined &&\n (!Number.isFinite(config.maxHealthDelta) || config.maxHealthDelta < 0)\n ) {\n throw new GovernanceConfigurationError(\"max-health-delta must be a finite number >= 0\");\n }\n\n if (\n config.maxNewHotspots !== undefined &&\n (!Number.isInteger(config.maxNewHotspots) || config.maxNewHotspots < 0)\n ) {\n throw new GovernanceConfigurationError(\"max-new-hotspots must be an integer >= 0\");\n }\n\n if (\n config.maxRiskScore !== undefined &&\n (!Number.isFinite(config.maxRiskScore) || config.maxRiskScore < 0 || config.maxRiskScore > 100)\n ) {\n throw new GovernanceConfigurationError(\"max-risk-score must be a number in [0, 100]\");\n }\n\n if (\n config.minHealthScore !== undefined &&\n (!Number.isFinite(config.minHealthScore) ||\n config.minHealthScore < 0 ||\n config.minHealthScore > 100)\n ) {\n throw new GovernanceConfigurationError(\"min-health-score must be a number in [0, 100]\");\n }\n\n if (\n config.newHotspotScoreThreshold !== undefined &&\n (!Number.isFinite(config.newHotspotScoreThreshold) ||\n config.newHotspotScoreThreshold < 0 ||\n config.newHotspotScoreThreshold > 100)\n ) {\n throw new GovernanceConfigurationError(\n \"new-hotspot-score-threshold must be a number in [0, 100]\",\n );\n }\n\n if (\n config.maxUnownedCritical !== undefined &&\n (!Number.isInteger(config.maxUnownedCritical) || config.maxUnownedCritical < 0)\n ) {\n throw new GovernanceConfigurationError(\"max-unowned-critical must be an integer >= 0\");\n }\n\n if (\n config.maxGhostOwners !== undefined &&\n (!Number.isInteger(config.maxGhostOwners) || config.maxGhostOwners < 0)\n ) {\n throw new GovernanceConfigurationError(\"max-ghost-owners must be an integer >= 0\");\n }\n\n if (\n config.maxDrift !== undefined &&\n (!Number.isFinite(config.maxDrift) || config.maxDrift < 0 || config.maxDrift > 1)\n ) {\n throw new GovernanceConfigurationError(\"max-drift must be a ratio between 0 and 1\");\n }\n};\n\nexport const evaluateGates = (input: GateEvaluationInput): GateEvaluationResult => {\n validateGateConfig(input);\n\n const config = input.gateConfig;\n const violations: Violation[] = [];\n const evaluatedGates: string[] = [];\n const warnings: string[] = [];\n\n if (config.maxRiskScore !== undefined) {\n evaluatedGates.push(\"max-risk-score\");\n const current = input.current.analysis.risk.riskScore;\n if (current > config.maxRiskScore) {\n violations.push(\n makeViolation(\n \"max-risk-score\",\n \"error\",\n `Risk score ${current} exceeds configured max ${config.maxRiskScore}.`,\n [input.current.analysis.structural.targetPath],\n [{ kind: \"repository_metric\", metric: \"riskScore\" }],\n ),\n );\n }\n }\n\n if (config.minHealthScore !== undefined) {\n evaluatedGates.push(\"min-health-score\");\n const current = input.current.analysis.health.healthScore;\n if (current < config.minHealthScore) {\n violations.push(\n makeViolation(\n \"min-health-score\",\n \"error\",\n `Health score ${current} is below configured minimum ${config.minHealthScore}.`,\n [input.current.analysis.structural.targetPath],\n [{ kind: \"repository_metric\", metric: \"healthScore\" }],\n ),\n );\n }\n }\n\n if (config.maxRiskDelta !== undefined) {\n evaluatedGates.push(\"max-risk-delta\");\n requireDiff(input, \"max-risk-delta\");\n const baseline = input.baseline;\n if (baseline === undefined) {\n throw new GovernanceConfigurationError(\"max-risk-delta requires baseline snapshot\");\n }\n\n const delta =\n input.current.analysis.risk.normalizedScore - baseline.analysis.risk.normalizedScore;\n if (delta > config.maxRiskDelta) {\n violations.push(\n makeViolation(\n \"max-risk-delta\",\n \"error\",\n `Risk normalized score delta ${delta.toFixed(4)} exceeds allowed ${config.maxRiskDelta}.`,\n [input.current.analysis.structural.targetPath],\n [{ kind: \"repository_metric\", metric: \"normalizedScore\" }],\n ),\n );\n }\n }\n\n if (config.maxHealthDelta !== undefined) {\n evaluatedGates.push(\"max-health-delta\");\n requireDiff(input, \"max-health-delta\");\n const baseline = input.baseline;\n if (baseline === undefined) {\n throw new GovernanceConfigurationError(\"max-health-delta requires baseline snapshot\");\n }\n\n const delta =\n input.current.analysis.health.normalizedScore - baseline.analysis.health.normalizedScore;\n if (delta < -config.maxHealthDelta) {\n violations.push(\n makeViolation(\n \"max-health-delta\",\n \"error\",\n `Health normalized score delta ${delta.toFixed(4)} is below allowed minimum ${(-config.maxHealthDelta).toFixed(4)}.`,\n [input.current.analysis.structural.targetPath],\n [{ kind: \"repository_metric\", metric: \"healthNormalizedScore\" }],\n ),\n );\n }\n }\n\n if (config.noNewCycles === true) {\n evaluatedGates.push(\"no-new-cycles\");\n requireDiff(input, \"no-new-cycles\");\n const diff = input.diff;\n if (diff === undefined) {\n throw new GovernanceConfigurationError(\"no-new-cycles requires diff\");\n }\n if (diff.newCycles.length > 0) {\n violations.push(\n makeViolation(\n \"no-new-cycles\",\n \"error\",\n `Detected ${diff.newCycles.length} new structural cycle(s).`,\n diff.newCycles,\n [{ kind: \"repository_metric\", metric: \"cycleCount\" }],\n ),\n );\n }\n }\n\n if (config.noNewHighRiskDeps === true) {\n evaluatedGates.push(\"no-new-high-risk-deps\");\n requireDiff(input, \"no-new-high-risk-deps\");\n const diff = input.diff;\n if (diff === undefined) {\n throw new GovernanceConfigurationError(\"no-new-high-risk-deps requires diff\");\n }\n if (diff.externalChanges.highRiskAdded.length > 0) {\n violations.push(\n makeViolation(\n \"no-new-high-risk-deps\",\n \"error\",\n `Detected ${diff.externalChanges.highRiskAdded.length} new high-risk dependency(ies).`,\n diff.externalChanges.highRiskAdded,\n diff.externalChanges.highRiskAdded.map((name) => ({\n kind: \"dependency_metric\",\n target: name,\n metric: \"highRiskDependencies\",\n })),\n ),\n );\n }\n }\n\n if (config.maxNewHotspots !== undefined) {\n evaluatedGates.push(\"max-new-hotspots\");\n requireDiff(input, \"max-new-hotspots\");\n const diff = input.diff;\n if (diff === undefined) {\n throw new GovernanceConfigurationError(\"max-new-hotspots requires diff\");\n }\n\n const scoreByFile = new Map(\n input.current.analysis.risk.fileScores.map((item) => [item.file, item.score]),\n );\n const threshold = config.newHotspotScoreThreshold ?? DEFAULT_NEW_HOTSPOT_SCORE_THRESHOLD;\n const counted = diff.newHotspots.filter((file) => (scoreByFile.get(file) ?? 0) >= threshold);\n\n if (counted.length > config.maxNewHotspots) {\n violations.push(\n makeViolation(\n \"max-new-hotspots\",\n \"warn\",\n `Detected ${counted.length} new hotspot(s) above score ${threshold}; allowed max is ${config.maxNewHotspots}.`,\n counted,\n counted.map((file) => ({ kind: \"file_metric\", target: file, metric: \"score\" })),\n ),\n );\n }\n }\n\n const ownershipConfigured =\n config.maxUnownedCritical !== undefined ||\n config.maxGhostOwners !== undefined ||\n config.maxDrift !== undefined;\n\n let ownership: OwnershipGateResult | undefined;\n\n if (ownershipConfigured) {\n const ownershipInput = input.ownership;\n if (ownershipInput === undefined) {\n warnings.push(\"ownership gates were not evaluated: no ownership input was provided.\");\n ownership = { evaluated: false, source: null, metrics: null };\n } else if (!ownershipInput.available) {\n warnings.push(...ownershipInput.warnings);\n warnings.push(\"ownership gates were not evaluated: no CODEOWNERS file was found.\");\n ownership = { evaluated: false, source: null, metrics: null };\n } else {\n const metrics = ownershipInput.metrics;\n ownership = {\n evaluated: true,\n source: ownershipInput.source,\n metrics,\n };\n\n if (config.maxUnownedCritical !== undefined) {\n evaluatedGates.push(\"max-unowned-critical\");\n if (metrics.unownedCriticalCount > config.maxUnownedCritical) {\n violations.push(\n makeViolation(\n \"max-unowned-critical\",\n \"error\",\n `Unowned critical files ${metrics.unownedCriticalCount} exceeds configured max ${config.maxUnownedCritical}.`,\n [],\n [{ kind: \"repository_metric\", metric: \"unownedCriticalCount\" }],\n ),\n );\n }\n }\n\n if (config.maxGhostOwners !== undefined) {\n evaluatedGates.push(\"max-ghost-owners\");\n if (metrics.ghostOwnerCount > config.maxGhostOwners) {\n violations.push(\n makeViolation(\n \"max-ghost-owners\",\n \"error\",\n `Ghost owners ${metrics.ghostOwnerCount} exceeds configured max ${config.maxGhostOwners}.`,\n [],\n [{ kind: \"repository_metric\", metric: \"ghostOwnerCount\" }],\n ),\n );\n }\n }\n\n if (config.maxDrift !== undefined) {\n evaluatedGates.push(\"max-drift\");\n const ratio = metrics.driftPercent / 100;\n if (ratio > config.maxDrift) {\n violations.push(\n makeViolation(\n \"max-drift\",\n \"error\",\n `Ownership drift ratio ${ratio.toFixed(4)} exceeds configured max ${config.maxDrift}.`,\n [],\n [{ kind: \"repository_metric\", metric: \"driftPercent\" }],\n ),\n );\n }\n }\n }\n }\n\n const ordered = stableSortViolations(violations);\n const highestSeverity = ordered.reduce<ViolationSeverity | null>(\n (current, violation) => compareSeverity(current, violation.severity),\n null,\n );\n\n const exitCode: 0 | 1 | 2 =\n highestSeverity === \"error\"\n ? 1\n : highestSeverity === \"warn\" && config.failOn === \"warn\"\n ? 2\n : 0;\n\n return {\n violations: ordered,\n highestSeverity,\n exitCode,\n evaluatedGates: [...evaluatedGates].sort((a, b) => a.localeCompare(b)),\n warnings: [...warnings],\n ...(ownership === undefined ? {} : { ownership }),\n };\n};\n","import { factorLabel, summarizeEvidence, type CodeSentinelSnapshot } from \"@codesentinel/reporter\";\nimport type { GateEvaluationResult, Violation } from \"./domain.js\";\n\nconst renderViolationText = (violation: Violation): string => {\n const targets = violation.targets.join(\", \") || \"n/a\";\n return `- [${violation.severity}] ${violation.id}: ${violation.message} (targets: ${targets})`;\n};\n\nexport const renderCheckText = (\n snapshot: CodeSentinelSnapshot,\n result: GateEvaluationResult,\n): string => {\n const lines: string[] = [];\n lines.push(\"CodeSentinel Check\");\n lines.push(`target: ${snapshot.analysis.structural.targetPath}`);\n lines.push(`riskScore: ${snapshot.analysis.risk.riskScore}`);\n lines.push(`evaluatedGates: ${result.evaluatedGates.join(\", \") || \"none\"}`);\n lines.push(`violations: ${result.violations.length}`);\n lines.push(`exitCode: ${result.exitCode}`);\n lines.push(\"\");\n lines.push(\"Violations\");\n if (result.violations.length === 0) {\n lines.push(\"- none\");\n } else {\n for (const violation of result.violations) {\n lines.push(renderViolationText(violation));\n }\n }\n\n if (result.ownership !== undefined) {\n lines.push(\"\");\n lines.push(\"Ownership\");\n lines.push(`evaluated: ${result.ownership.evaluated}`);\n lines.push(`source: ${result.ownership.source ?? \"none\"}`);\n if (result.ownership.metrics !== null) {\n const metrics = result.ownership.metrics;\n lines.push(`declaredCoverage: ${metrics.declaredCoveragePercent}`);\n lines.push(`declaredCoverageCritical: ${metrics.declaredCoverageCriticalPercent}`);\n lines.push(`unownedCritical: ${metrics.unownedCriticalCount}`);\n lines.push(`ghostOwners: ${metrics.ghostOwnerCount}`);\n lines.push(`driftPercent: ${metrics.driftPercent}`);\n }\n }\n\n if (result.warnings.length > 0) {\n lines.push(\"\");\n lines.push(\"Warnings\");\n for (const warning of result.warnings) {\n lines.push(`- ${warning}`);\n }\n }\n\n return lines.join(\"\\n\");\n};\n\nexport const renderCheckMarkdown = (\n snapshot: CodeSentinelSnapshot,\n result: GateEvaluationResult,\n): string => {\n const lines: string[] = [];\n lines.push(\"## CodeSentinel CI Summary\");\n lines.push(`- target: \\`${snapshot.analysis.structural.targetPath}\\``);\n lines.push(`- riskScore: \\`${snapshot.analysis.risk.riskScore}\\``);\n lines.push(\n `- evaluatedGates: ${result.evaluatedGates.map((item) => `\\`${item}\\``).join(\", \") || \"none\"}`,\n );\n lines.push(`- violations: \\`${result.violations.length}\\``);\n lines.push(`- exitCode: \\`${result.exitCode}\\``);\n\n const repositoryTrace = snapshot.trace?.targets.find(\n (target) =>\n target.targetType === \"repository\" &&\n target.targetId === snapshot.analysis.structural.targetPath,\n );\n if (repositoryTrace !== undefined) {\n lines.push(\"\");\n lines.push(\"### Why\");\n const topFactors = [...repositoryTrace.factors]\n .sort((a, b) => b.contribution - a.contribution || a.factorId.localeCompare(b.factorId))\n .slice(0, 3);\n\n for (const factor of topFactors) {\n lines.push(\n `- ${factorLabel(factor.factorId)}: contribution=\\`${factor.contribution}\\`, evidence=\\`${summarizeEvidence(factor)}\\``,\n );\n }\n }\n\n if (result.ownership !== undefined) {\n lines.push(\"\");\n lines.push(\"### Ownership\");\n lines.push(\n `- codeowners: ${result.ownership.source === null ? \"none\" : `\\`${result.ownership.source}\\``}`,\n );\n lines.push(`- evaluated: \\`${result.ownership.evaluated}\\``);\n if (result.ownership.metrics !== null) {\n const metrics = result.ownership.metrics;\n lines.push(\n `- declared coverage: \\`${metrics.declaredCoveragePercent}%\\` (critical \\`${metrics.declaredCoverageCriticalPercent}%\\`)`,\n );\n lines.push(`- unowned critical: \\`${metrics.unownedCriticalCount}\\``);\n lines.push(`- ghost owners: \\`${metrics.ghostOwnerCount}\\``);\n lines.push(`- drift: \\`${metrics.driftPercent}%\\``);\n }\n }\n\n if (result.warnings.length > 0) {\n lines.push(\"\");\n lines.push(\"### Warnings\");\n for (const warning of result.warnings) {\n lines.push(`- ${warning}`);\n }\n }\n\n lines.push(\"\");\n lines.push(\"### Violations\");\n if (result.violations.length === 0) {\n lines.push(\"- none\");\n } else {\n for (const violation of result.violations) {\n lines.push(`- [${violation.severity}] **${violation.id}**: ${violation.message}`);\n if (violation.targets.length > 0) {\n lines.push(` - targets: ${violation.targets.map((target) => `\\`${target}\\``).join(\", \")}`);\n }\n }\n }\n\n return lines.join(\"\\n\");\n};\n","import { mkdirSync, rmSync } from \"node:fs\";\nimport { basename, join, resolve } from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport type { CodeSentinelSnapshot } from \"@codesentinel/reporter\";\nimport {\n BaselineAutoResolutionError,\n resolveAutoBaseline,\n type BaselineAutoResolution,\n type GitCommandResult,\n} from \"./baseline-auto-resolver.js\";\n\nconst execFileAsync = promisify(execFile);\n\nconst SENTINEL_TMP_DIR = \".codesentinel-tmp\";\nconst WORKTREE_DIR = \"worktrees\";\n\nexport class BaselineRefResolutionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"BaselineRefResolutionError\";\n }\n}\n\nconst runGit = async (repositoryPath: string, args: readonly string[]): Promise<string> => {\n const result = await tryRunGit(repositoryPath, args);\n if (result.ok) {\n return result.stdout;\n }\n throw new BaselineRefResolutionError(result.message);\n};\n\nconst tryRunGit = async (\n repositoryPath: string,\n args: readonly string[],\n): Promise<GitCommandResult> => {\n try {\n const { stdout } = await execFileAsync(\"git\", [\"-C\", repositoryPath, ...args], {\n encoding: \"utf8\",\n });\n return { ok: true, stdout: stdout.trim() };\n } catch (error) {\n const message = error instanceof Error ? error.message : \"unknown git error\";\n return { ok: false, message };\n }\n};\n\nconst buildWorktreePath = (repoRoot: string, sha: string): string => {\n const tmpRoot = join(repoRoot, SENTINEL_TMP_DIR, WORKTREE_DIR);\n mkdirSync(tmpRoot, { recursive: true });\n\n const baseName = `baseline-${sha.slice(0, 12)}-${process.pid}`;\n const candidate = resolve(tmpRoot, baseName);\n return candidate;\n};\n\nconst sanitizeSnapshotForWorktree = (\n snapshot: CodeSentinelSnapshot,\n worktreePath: string,\n canonicalPath: string,\n): CodeSentinelSnapshot => {\n const replacePrefix = (value: string): string =>\n value.startsWith(worktreePath) ? `${canonicalPath}${value.slice(worktreePath.length)}` : value;\n\n const structural = snapshot.analysis.structural;\n\n return {\n ...snapshot,\n source: {\n targetPath: replacePrefix(snapshot.source.targetPath),\n },\n analysis: {\n ...snapshot.analysis,\n structural: {\n ...structural,\n targetPath: replacePrefix(structural.targetPath),\n nodes: structural.nodes.map((node) => ({\n ...node,\n absolutePath: replacePrefix(node.absolutePath),\n })),\n },\n evolution: {\n ...snapshot.analysis.evolution,\n targetPath: replacePrefix(snapshot.analysis.evolution.targetPath),\n },\n external: {\n ...snapshot.analysis.external,\n targetPath: replacePrefix(snapshot.analysis.external.targetPath),\n },\n },\n };\n};\n\nexport type BaselineRefResolutionResult = {\n baselineSnapshot: CodeSentinelSnapshot;\n resolvedRef: string;\n resolvedSha: string;\n};\n\nexport type ResolveBaselineFromRefInput = {\n repositoryPath: string;\n baselineRef: string;\n analyzeWorktree: (worktreePath: string, repositoryRoot: string) => Promise<CodeSentinelSnapshot>;\n};\n\nexport type ResolveAutoBaselineRefInput = {\n repositoryPath: string;\n baselineSha?: string;\n mainBranchCandidates?: readonly string[];\n environment?: Readonly<Record<string, string | undefined>>;\n};\n\nexport const resolveBaselineSnapshotFromRef = async (\n input: ResolveBaselineFromRefInput,\n): Promise<BaselineRefResolutionResult> => {\n const repositoryPath = resolve(input.repositoryPath);\n const ref = input.baselineRef.trim();\n if (ref.length === 0) {\n throw new BaselineRefResolutionError(\"baseline-ref cannot be empty\");\n }\n\n const repoRoot = await runGit(repositoryPath, [\"rev-parse\", \"--show-toplevel\"]);\n const sha = await runGit(repositoryPath, [\"rev-parse\", \"--verify\", `${ref}^{commit}`]);\n\n const worktreePath = buildWorktreePath(repoRoot, sha);\n\n const cleanup = (): void => {\n try {\n rmSync(worktreePath, { recursive: true, force: true });\n } catch {\n // Best-effort fallback cleanup if worktree remove fails.\n }\n };\n\n try {\n await runGit(repoRoot, [\"worktree\", \"add\", \"--detach\", worktreePath, sha]);\n\n const snapshot = await input.analyzeWorktree(worktreePath, repoRoot);\n const sanitized = sanitizeSnapshotForWorktree(snapshot, worktreePath, repoRoot);\n\n return {\n baselineSnapshot: sanitized,\n resolvedRef: ref,\n resolvedSha: sha,\n };\n } finally {\n try {\n await runGit(repoRoot, [\"worktree\", \"remove\", \"--force\", worktreePath]);\n } catch {\n cleanup();\n }\n }\n};\n\nexport const baselineTempDirectoryName = (): string =>\n basename(join(SENTINEL_TMP_DIR, WORKTREE_DIR));\n\nexport const resolveAutoBaselineRef = async (\n input: ResolveAutoBaselineRefInput,\n): Promise<BaselineAutoResolution> => {\n const repositoryPath = resolve(input.repositoryPath);\n const repoRoot = await runGit(repositoryPath, [\"rev-parse\", \"--show-toplevel\"]);\n\n try {\n return await resolveAutoBaseline({\n ...(input.baselineSha === undefined ? {} : { baselineSha: input.baselineSha }),\n ...(input.environment === undefined ? {} : { environment: input.environment }),\n ...(input.mainBranchCandidates === undefined\n ? {}\n : { mainBranchCandidates: input.mainBranchCandidates }),\n git: {\n resolveCommit: async (ref: string): Promise<GitCommandResult> =>\n tryRunGit(repoRoot, [\"rev-parse\", \"--verify\", ref]),\n mergeBase: async (leftRef: string, rightRef: string): Promise<GitCommandResult> =>\n tryRunGit(repoRoot, [\"merge-base\", leftRef, rightRef]),\n currentBranch: async (): Promise<GitCommandResult> =>\n tryRunGit(repoRoot, [\"symbolic-ref\", \"--quiet\", \"--short\", \"HEAD\"]),\n isShallowRepository: async (): Promise<GitCommandResult> =>\n tryRunGit(repoRoot, [\"rev-parse\", \"--is-shallow-repository\"]),\n },\n });\n } catch (error) {\n if (error instanceof BaselineAutoResolutionError) {\n throw new BaselineRefResolutionError(error.message);\n }\n throw error;\n }\n};\n","export class BaselineAutoResolutionError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"BaselineAutoResolutionError\";\n }\n}\n\nexport type BaselineAutoResolutionStrategy =\n | \"explicit_sha\"\n | \"ci_base_branch\"\n | \"main_branch_previous_commit\"\n | \"feature_branch_merge_base\";\n\nexport type BaselineAutoResolutionAttempt = {\n step: string;\n candidate: string;\n outcome: \"resolved\" | \"failed\" | \"skipped\";\n detail?: string;\n};\n\nexport type BaselineAutoResolution = {\n strategy: BaselineAutoResolutionStrategy;\n resolvedRef: string;\n resolvedSha: string;\n attempts: readonly BaselineAutoResolutionAttempt[];\n baseBranch?: string;\n};\n\nexport type GitCommandResult = { ok: true; stdout: string } | { ok: false; message: string };\n\nexport type BaselineAutoGitAdapter = {\n resolveCommit: (ref: string) => Promise<GitCommandResult>;\n mergeBase: (leftRef: string, rightRef: string) => Promise<GitCommandResult>;\n currentBranch: () => Promise<GitCommandResult>;\n isShallowRepository: () => Promise<GitCommandResult>;\n};\n\nexport type ResolveAutoBaselineInput = {\n baselineSha?: string;\n environment?: Readonly<Record<string, string | undefined>>;\n mainBranchCandidates?: readonly string[];\n git: BaselineAutoGitAdapter;\n};\n\nconst DEFAULT_MAIN_BRANCH_CANDIDATES = [\"main\", \"master\"] as const;\n\nconst providerBaseBranchKeys = [\n \"GITHUB_BASE_REF\",\n \"CI_MERGE_REQUEST_TARGET_BRANCH_NAME\",\n \"BITBUCKET_PR_DESTINATION_BRANCH\",\n] as const;\n\nconst normalizeMainBranches = (input: readonly string[] | undefined): readonly string[] => {\n const source = input === undefined || input.length === 0 ? DEFAULT_MAIN_BRANCH_CANDIDATES : input;\n const seen = new Set<string>();\n const values: string[] = [];\n\n for (const candidate of source) {\n const trimmed = candidate.trim();\n if (trimmed.length === 0 || seen.has(trimmed)) {\n continue;\n }\n seen.add(trimmed);\n values.push(trimmed);\n }\n\n return values.length > 0 ? values : DEFAULT_MAIN_BRANCH_CANDIDATES;\n};\n\nconst firstNonEmptyEnv = (\n environment: Readonly<Record<string, string | undefined>>,\n): { key: string; value: string } | undefined => {\n for (const key of providerBaseBranchKeys) {\n const value = environment[key]?.trim();\n if (value !== undefined && value.length > 0) {\n return { key, value };\n }\n }\n return undefined;\n};\n\nconst asBoolean = (value: string): boolean => {\n return value.trim().toLowerCase() === \"true\";\n};\n\nconst buildNoBaselineMessage = (): string => {\n return \"unable to resolve auto baseline; set --baseline-ref <ref> explicitly or provide --baseline <snapshot.json>\";\n};\n\nexport const resolveAutoBaseline = async (\n input: ResolveAutoBaselineInput,\n): Promise<BaselineAutoResolution> => {\n const attempts: BaselineAutoResolutionAttempt[] = [];\n const mainBranches = normalizeMainBranches(input.mainBranchCandidates);\n const environment = input.environment ?? {};\n\n const baselineSha = input.baselineSha?.trim();\n if (baselineSha !== undefined && baselineSha.length > 0) {\n const result = await input.git.resolveCommit(`${baselineSha}^{commit}`);\n if (result.ok) {\n attempts.push({ step: \"explicit-sha\", candidate: baselineSha, outcome: \"resolved\" });\n return {\n strategy: \"explicit_sha\",\n resolvedRef: baselineSha,\n resolvedSha: result.stdout,\n attempts,\n };\n }\n\n attempts.push({\n step: \"explicit-sha\",\n candidate: baselineSha,\n outcome: \"failed\",\n detail: result.message,\n });\n throw new BaselineAutoResolutionError(\n `invalid --baseline-sha '${baselineSha}': ${result.message}`,\n );\n }\n\n const providerBaseBranch = firstNonEmptyEnv(environment);\n if (providerBaseBranch !== undefined) {\n const originRef = `origin/${providerBaseBranch.value}`;\n const originResult = await input.git.resolveCommit(`${originRef}^{commit}`);\n if (originResult.ok) {\n attempts.push({\n step: `ci-base-branch:${providerBaseBranch.key}`,\n candidate: originRef,\n outcome: \"resolved\",\n });\n return {\n strategy: \"ci_base_branch\",\n resolvedRef: originRef,\n resolvedSha: originResult.stdout,\n attempts,\n baseBranch: providerBaseBranch.value,\n };\n }\n attempts.push({\n step: `ci-base-branch:${providerBaseBranch.key}`,\n candidate: originRef,\n outcome: \"failed\",\n detail: originResult.message,\n });\n\n const localRef = providerBaseBranch.value;\n const localResult = await input.git.resolveCommit(`${localRef}^{commit}`);\n if (localResult.ok) {\n attempts.push({\n step: `ci-base-branch-local:${providerBaseBranch.key}`,\n candidate: localRef,\n outcome: \"resolved\",\n });\n return {\n strategy: \"ci_base_branch\",\n resolvedRef: localRef,\n resolvedSha: localResult.stdout,\n attempts,\n baseBranch: providerBaseBranch.value,\n };\n }\n attempts.push({\n step: `ci-base-branch-local:${providerBaseBranch.key}`,\n candidate: localRef,\n outcome: \"failed\",\n detail: localResult.message,\n });\n } else {\n attempts.push({\n step: \"ci-base-branch\",\n candidate: providerBaseBranchKeys.join(\",\"),\n outcome: \"skipped\",\n detail: \"no CI base branch environment variable found\",\n });\n }\n\n const branchResult = await input.git.currentBranch();\n const branchName = branchResult.ok ? branchResult.stdout.trim() : undefined;\n if (branchName !== undefined && mainBranches.includes(branchName)) {\n const headPrevious = await input.git.resolveCommit(\"HEAD~1^{commit}\");\n if (headPrevious.ok) {\n attempts.push({\n step: \"main-branch-head-previous\",\n candidate: \"HEAD~1\",\n outcome: \"resolved\",\n });\n return {\n strategy: \"main_branch_previous_commit\",\n resolvedRef: \"HEAD~1\",\n resolvedSha: headPrevious.stdout,\n attempts,\n };\n }\n attempts.push({\n step: \"main-branch-head-previous\",\n candidate: \"HEAD~1\",\n outcome: \"failed\",\n detail: headPrevious.message,\n });\n throw new BaselineAutoResolutionError(\n `unable to resolve baseline from HEAD~1 on branch '${branchName}': ${headPrevious.message}`,\n );\n }\n\n if (branchName === undefined) {\n attempts.push({\n step: \"current-branch\",\n candidate: \"HEAD\",\n outcome: \"skipped\",\n detail: \"detached HEAD or symbolic-ref unavailable\",\n });\n } else {\n attempts.push({\n step: \"current-branch\",\n candidate: branchName,\n outcome: \"resolved\",\n detail: \"feature branch detected\",\n });\n }\n\n const mergeBaseCandidates = [\n ...mainBranches.map((candidate) => `origin/${candidate}`),\n ...mainBranches,\n ];\n\n for (const candidate of mergeBaseCandidates) {\n const mergeBase = await input.git.mergeBase(\"HEAD\", candidate);\n if (mergeBase.ok) {\n attempts.push({\n step: \"merge-base\",\n candidate: `HEAD..${candidate}`,\n outcome: \"resolved\",\n });\n return {\n strategy: \"feature_branch_merge_base\",\n resolvedRef: mergeBase.stdout,\n resolvedSha: mergeBase.stdout,\n attempts,\n };\n }\n attempts.push({\n step: \"merge-base\",\n candidate: `HEAD..${candidate}`,\n outcome: \"failed\",\n detail: mergeBase.message,\n });\n }\n\n const shallowResult = await input.git.isShallowRepository();\n const shallowRepository = shallowResult.ok && asBoolean(shallowResult.stdout);\n if (shallowRepository) {\n throw new BaselineAutoResolutionError(\n `${buildNoBaselineMessage()}; repository appears shallow. Fetch full history (for example: git fetch --unshallow or fetch-depth: 0).`,\n );\n }\n\n throw new BaselineAutoResolutionError(buildNoBaselineMessage());\n};\n","import type { AnalyzeSummary } from \"@codesentinel/core\";\n\nexport type AnalyzeOutputMode = \"summary\" | \"json\";\n\ntype EvolutionAvailable = Extract<AnalyzeSummary[\"evolution\"], { available: true }>;\ntype ExternalAvailable = Extract<AnalyzeSummary[\"external\"], { available: true }>;\ntype WorkspaceSummaryShape = {\n structuralTop: ReadonlyArray<{\n path: string;\n fileCount: number;\n internalEdgeCount: number;\n incomingEdgeCount: number;\n outgoingEdgeCount: number;\n }>;\n riskTop: ReadonlyArray<{\n path: string;\n score: number;\n fileCount: number;\n peakFileRisk: number;\n }>;\n evolutionTop: ReadonlyArray<{\n path: string;\n commitCount: number;\n churnTotal: number;\n recentVolatility: number;\n }>;\n dependencyExposureTop: ReadonlyArray<{\n path: string;\n directDependencies: number;\n sharedDependencies: number;\n highRiskDependencies: number;\n transitiveExposureDependencies: number;\n }>;\n};\n\nconst toHealthTier = (score: number): \"critical\" | \"weak\" | \"fair\" | \"good\" | \"excellent\" => {\n if (score < 20) {\n return \"critical\";\n }\n if (score < 40) {\n return \"weak\";\n }\n if (score < 60) {\n return \"fair\";\n }\n if (score < 80) {\n return \"good\";\n }\n return \"excellent\";\n};\n\ntype SummaryShape = {\n targetPath: string;\n structural: AnalyzeSummary[\"structural\"][\"metrics\"];\n evolution:\n | {\n available: false;\n reason: \"not_git_repository\";\n }\n | {\n available: true;\n metrics: EvolutionAvailable[\"metrics\"];\n hotspotsTop: readonly string[];\n };\n external:\n | {\n available: false;\n reason:\n | \"package_json_not_found\"\n | \"lockfile_not_found\"\n | \"unsupported_lockfile_format\"\n | \"invalid_lockfile\";\n }\n | {\n available: true;\n metrics: ExternalAvailable[\"metrics\"];\n highRiskDependenciesTop: readonly string[];\n highRiskDevelopmentDependenciesTop: readonly string[];\n transitiveExposureDependenciesTop: readonly string[];\n };\n risk: {\n riskScore: number;\n normalizedScore: number;\n hotspotsTop: ReadonlyArray<{\n file: string;\n score: number;\n }>;\n fragileClusterCount: number;\n dependencyAmplificationZoneCount: number;\n };\n workspaces: WorkspaceSummaryShape;\n health: {\n healthScore: number;\n healthTier: \"critical\" | \"weak\" | \"fair\" | \"good\" | \"excellent\";\n normalizedScore: number;\n dimensions: AnalyzeSummary[\"health\"][\"dimensions\"];\n topIssues: AnalyzeSummary[\"health\"][\"topIssues\"];\n };\n};\n\nconst createWorkspaceSummaryShape = (summary: AnalyzeSummary): WorkspaceSummaryShape => ({\n structuralTop: [...(summary.structural.workspaces ?? [])]\n .sort(\n (a, b) =>\n b.incomingEdgeCount +\n b.outgoingEdgeCount +\n b.internalEdgeCount -\n (a.incomingEdgeCount + a.outgoingEdgeCount + a.internalEdgeCount) ||\n b.fileCount - a.fileCount ||\n a.path.localeCompare(b.path),\n )\n .slice(0, 5)\n .map((workspace) => ({\n path: workspace.path,\n fileCount: workspace.fileCount,\n internalEdgeCount: workspace.internalEdgeCount,\n incomingEdgeCount: workspace.incomingEdgeCount,\n outgoingEdgeCount: workspace.outgoingEdgeCount,\n })),\n riskTop: [...summary.risk.workspaceScores]\n .sort((a, b) => b.score - a.score || a.path.localeCompare(b.path))\n .slice(0, 5)\n .map((workspace) => ({\n path: workspace.path,\n score: workspace.score,\n fileCount: workspace.fileCount,\n peakFileRisk: workspace.peakFileRisk,\n })),\n evolutionTop: summary.evolution.available\n ? [...(summary.evolution.workspaces ?? [])]\n .sort(\n (a, b) =>\n b.recentVolatility - a.recentVolatility ||\n b.churnTotal - a.churnTotal ||\n b.commitCount - a.commitCount ||\n a.path.localeCompare(b.path),\n )\n .slice(0, 5)\n .map((workspace) => ({\n path: workspace.path,\n commitCount: workspace.commitCount,\n churnTotal: workspace.churnTotal,\n recentVolatility: workspace.recentVolatility,\n }))\n : [],\n dependencyExposureTop: summary.external.available\n ? [...(summary.external.workspaces ?? [])]\n .sort(\n (a, b) =>\n b.highRiskDependencies.length - a.highRiskDependencies.length ||\n b.transitiveExposureDependencies.length - a.transitiveExposureDependencies.length ||\n b.directDependencies - a.directDependencies ||\n a.path.localeCompare(b.path),\n )\n .slice(0, 5)\n .map((workspace) => ({\n path: workspace.path,\n directDependencies: workspace.directDependencies,\n sharedDependencies: workspace.sharedDependencies.length,\n highRiskDependencies: workspace.highRiskDependencies.length,\n transitiveExposureDependencies: workspace.transitiveExposureDependencies.length,\n }))\n : [],\n});\n\nconst createSummaryShape = (summary: AnalyzeSummary): SummaryShape => ({\n targetPath: summary.structural.targetPath,\n structural: summary.structural.metrics,\n evolution: summary.evolution.available\n ? {\n available: true,\n metrics: summary.evolution.metrics,\n hotspotsTop: summary.evolution.hotspots.slice(0, 5).map((hotspot) => hotspot.filePath),\n }\n : {\n available: false,\n reason: summary.evolution.reason,\n },\n external: summary.external.available\n ? {\n available: true,\n metrics: summary.external.metrics,\n highRiskDependenciesTop: summary.external.highRiskDependencies.slice(0, 10),\n highRiskDevelopmentDependenciesTop: summary.external.highRiskDevelopmentDependencies.slice(\n 0,\n 10,\n ),\n transitiveExposureDependenciesTop: summary.external.transitiveExposureDependencies.slice(\n 0,\n 10,\n ),\n }\n : {\n available: false,\n reason: summary.external.reason,\n },\n risk: {\n riskScore: summary.risk.riskScore,\n normalizedScore: summary.risk.normalizedScore,\n hotspotsTop: summary.risk.hotspots.slice(0, 5).map((hotspot) => ({\n file: hotspot.file,\n score: hotspot.score,\n })),\n fragileClusterCount: summary.risk.fragileClusters.length,\n dependencyAmplificationZoneCount: summary.risk.dependencyAmplificationZones.length,\n },\n workspaces: createWorkspaceSummaryShape(summary),\n health: {\n healthScore: summary.health.healthScore,\n healthTier: toHealthTier(summary.health.healthScore),\n normalizedScore: summary.health.normalizedScore,\n dimensions: summary.health.dimensions,\n topIssues: summary.health.topIssues.slice(0, 5),\n },\n});\n\nexport const formatAnalyzeOutput = (summary: AnalyzeSummary, mode: AnalyzeOutputMode): string =>\n mode === \"json\"\n ? JSON.stringify(summary, null, 2)\n : JSON.stringify(createSummaryShape(summary), null, 2);\n","import type { AnalyzeSummary, RiskFactorTrace, RiskTrace, TargetTrace } from \"@codesentinel/core\";\nimport type { ExplainFormat } from \"./run-explain-command.js\";\n\nexport type ExplainOutputPayload = {\n summary: AnalyzeSummary;\n trace: RiskTrace;\n selectedTargets: readonly TargetTrace[];\n};\n\nconst sortFactorByContribution = (left: RiskFactorTrace, right: RiskFactorTrace): number =>\n right.contribution - left.contribution || left.factorId.localeCompare(right.factorId);\n\nconst toRiskBand = (score: number): \"low\" | \"moderate\" | \"elevated\" | \"high\" | \"very_high\" => {\n if (score < 20) {\n return \"low\";\n }\n if (score < 40) {\n return \"moderate\";\n }\n if (score < 60) {\n return \"elevated\";\n }\n if (score < 80) {\n return \"high\";\n }\n return \"very_high\";\n};\n\nconst factorLabelById: Readonly<Record<string, string>> = {\n \"repository.structural\": \"Structural complexity\",\n \"repository.evolution\": \"Change volatility\",\n \"repository.external\": \"External dependency pressure\",\n \"repository.composite.interactions\": \"Intersection amplification\",\n \"file.structural\": \"File structural complexity\",\n \"file.evolution\": \"File change volatility\",\n \"file.external\": \"File external pressure\",\n \"file.composite.interactions\": \"File interaction amplification\",\n \"module.average_file_risk\": \"Average file risk\",\n \"module.peak_file_risk\": \"Peak file risk\",\n \"dependency.signals\": \"Dependency risk signals\",\n \"dependency.staleness\": \"Dependency staleness\",\n \"dependency.maintainer_concentration\": \"Maintainer concentration\",\n \"dependency.topology\": \"Dependency topology pressure\",\n \"dependency.bus_factor\": \"Dependency bus factor\",\n \"dependency.popularity_dampening\": \"Popularity dampening\",\n};\n\nconst formatFactorLabel = (factorId: string): string => factorLabelById[factorId] ?? factorId;\n\nconst formatNumber = (value: number | null | undefined): string =>\n value === null || value === undefined ? \"n/a\" : `${value}`;\n\nconst formatDimension = (value: number | null): string => (value === null ? \"n/a\" : `${value}`);\n\nconst formatFactorSummary = (factor: RiskFactorTrace): string =>\n `${formatFactorLabel(factor.factorId)} (+${factor.contribution}, confidence=${factor.confidence})`;\n\nconst formatFactorContribution = (factor: RiskFactorTrace): string =>\n `${formatFactorLabel(factor.factorId)}=${factor.contribution}`;\n\nconst formatFactorEvidence = (factor: RiskFactorTrace): string => {\n if (factor.factorId === \"repository.structural\") {\n return `structural dimension=${formatNumber(factor.rawMetrics[\"structuralDimension\"])}`;\n }\n\n if (factor.factorId === \"repository.evolution\") {\n return `evolution dimension=${formatNumber(factor.rawMetrics[\"evolutionDimension\"])}`;\n }\n\n if (factor.factorId === \"repository.external\") {\n return `external dimension=${formatNumber(factor.rawMetrics[\"externalDimension\"])}`;\n }\n\n if (factor.factorId === \"repository.composite.interactions\") {\n return `structural×evolution=${formatNumber(factor.rawMetrics[\"structuralEvolution\"])}, central instability=${formatNumber(factor.rawMetrics[\"centralInstability\"])}, dependency amplification=${formatNumber(factor.rawMetrics[\"dependencyAmplification\"])}`;\n }\n\n if (factor.factorId === \"file.structural\") {\n return `fanIn=${formatNumber(factor.rawMetrics[\"fanIn\"])}, fanOut=${formatNumber(factor.rawMetrics[\"fanOut\"])}, depth=${formatNumber(factor.rawMetrics[\"depth\"])}, inCycle=${formatNumber(factor.rawMetrics[\"cycleParticipation\"])}, structuralAttenuation=${formatNumber(factor.rawMetrics[\"structuralAttenuation\"])}`;\n }\n\n if (factor.factorId === \"file.evolution\") {\n return `commitCount=${formatNumber(factor.rawMetrics[\"commitCount\"])}, churnTotal=${formatNumber(factor.rawMetrics[\"churnTotal\"])}, recentVolatility=${formatNumber(factor.rawMetrics[\"recentVolatility\"])}`;\n }\n\n if (factor.factorId === \"file.external\") {\n return `repositoryExternalPressure=${formatNumber(factor.rawMetrics[\"repositoryExternalPressure\"])}, dependencyAffinity=${formatNumber(factor.rawMetrics[\"dependencyAffinity\"])}`;\n }\n\n if (factor.factorId === \"file.composite.interactions\") {\n return `structural×evolution=${formatNumber(factor.rawMetrics[\"structuralEvolutionInteraction\"])}, central instability=${formatNumber(factor.rawMetrics[\"centralInstabilityInteraction\"])}, dependency amplification=${formatNumber(factor.rawMetrics[\"dependencyAmplificationInteraction\"])}`;\n }\n\n return \"evidence available in trace\";\n};\n\nconst findRepositoryTarget = (targets: readonly TargetTrace[]): TargetTrace | undefined =>\n targets.find((target) => target.targetType === \"repository\");\n\nconst repositoryDimensionScores = (\n repositoryTarget: TargetTrace | undefined,\n): {\n structural: number | null;\n evolution: number | null;\n external: number | null;\n interactions: number | null;\n} => {\n if (repositoryTarget === undefined) {\n return {\n structural: null,\n evolution: null,\n external: null,\n interactions: null,\n };\n }\n\n const structural = repositoryTarget.factors.find(\n (factor) => factor.factorId === \"repository.structural\",\n );\n const evolution = repositoryTarget.factors.find(\n (factor) => factor.factorId === \"repository.evolution\",\n );\n const external = repositoryTarget.factors.find(\n (factor) => factor.factorId === \"repository.external\",\n );\n const interactions = repositoryTarget.factors.find(\n (factor) => factor.factorId === \"repository.composite.interactions\",\n );\n\n return {\n structural:\n structural === undefined\n ? null\n : Number(((structural.rawMetrics[\"structuralDimension\"] ?? 0) * 100).toFixed(4)),\n evolution:\n evolution === undefined\n ? null\n : Number(((evolution.rawMetrics[\"evolutionDimension\"] ?? 0) * 100).toFixed(4)),\n external:\n external === undefined\n ? null\n : Number(((external.rawMetrics[\"externalDimension\"] ?? 0) * 100).toFixed(4)),\n interactions:\n interactions === undefined\n ? null\n : Number(\n (\n ((interactions.rawMetrics[\"structuralEvolution\"] ?? 0) +\n (interactions.rawMetrics[\"centralInstability\"] ?? 0) +\n (interactions.rawMetrics[\"dependencyAmplification\"] ?? 0)) *\n 100\n ).toFixed(4),\n ),\n };\n};\n\nconst buildRepositoryActions = (\n payload: ExplainOutputPayload,\n repositoryTarget: TargetTrace | undefined,\n): readonly string[] => {\n if (repositoryTarget === undefined) {\n return [\"No repository trace available.\"];\n }\n\n const topHotspots = payload.summary.risk.hotspots.slice(0, 3).map((hotspot) => hotspot.file);\n const highRiskDependencies = payload.summary.external.available\n ? payload.summary.external.highRiskDependencies.slice(0, 3)\n : [];\n\n const actions: string[] = [];\n for (const lever of repositoryTarget.reductionLevers) {\n if (lever.factorId === \"repository.evolution\") {\n actions.push(\n `Reduce volatility/churn in top hotspots first: ${topHotspots.join(\", \") || \"no hotspots available\"}.`,\n );\n continue;\n }\n\n if (lever.factorId === \"repository.structural\") {\n actions.push(\n `Lower fan-in/fan-out and break cycles in central files: ${topHotspots.join(\", \") || \"no hotspots available\"}.`,\n );\n continue;\n }\n\n if (lever.factorId === \"repository.composite.interactions\") {\n actions.push(\n \"Stabilize central files before refactors; interaction effects are amplifying risk.\",\n );\n continue;\n }\n\n if (lever.factorId === \"repository.external\") {\n actions.push(\n `Review high-risk direct dependencies: ${highRiskDependencies.join(\", \") || \"none detected\"}.`,\n );\n continue;\n }\n }\n\n if (actions.length === 0) {\n actions.push(\"No clear reduction levers available from current trace.\");\n }\n\n return actions.slice(0, 3);\n};\n\nconst renderTargetText = (target: TargetTrace): string => {\n const lines: string[] = [];\n lines.push(`${target.targetType}: ${target.targetId}`);\n lines.push(` score: ${target.totalScore} (${target.normalizedScore})`);\n lines.push(\" top factors:\");\n\n const topFactors = [...target.factors].sort(sortFactorByContribution).slice(0, 5);\n for (const factor of topFactors) {\n lines.push(` - ${formatFactorSummary(factor)}`);\n lines.push(` evidence: ${formatFactorEvidence(factor)}`);\n }\n\n lines.push(\" reduction levers:\");\n for (const lever of target.reductionLevers) {\n lines.push(\n ` - ${formatFactorLabel(lever.factorId)} | estimatedImpact=${lever.estimatedImpact}`,\n );\n }\n\n return lines.join(\"\\n\");\n};\n\nconst renderText = (payload: ExplainOutputPayload): string => {\n const lines: string[] = [];\n const repositoryTarget =\n findRepositoryTarget(payload.selectedTargets) ?? findRepositoryTarget(payload.trace.targets);\n const repositoryTopFactors =\n repositoryTarget === undefined\n ? []\n : [...repositoryTarget.factors].sort(sortFactorByContribution).slice(0, 3);\n const dimensionScores = repositoryDimensionScores(repositoryTarget);\n const compositeFactors = repositoryTopFactors.filter((factor) => factor.family === \"composite\");\n\n lines.push(`target: ${payload.summary.structural.targetPath}`);\n lines.push(`riskScore: ${payload.summary.risk.riskScore}`);\n lines.push(`riskBand: ${toRiskBand(payload.summary.risk.riskScore)}`);\n lines.push(`selectedTargets: ${payload.selectedTargets.length}`);\n lines.push(\"dimensionScores:\");\n lines.push(` structural: ${formatDimension(dimensionScores.structural)}`);\n lines.push(` evolution: ${formatDimension(dimensionScores.evolution)}`);\n lines.push(` external: ${formatDimension(dimensionScores.external)}`);\n lines.push(` interactions: ${formatDimension(dimensionScores.interactions)}`);\n lines.push(\"\");\n lines.push(\"explanation:\");\n lines.push(\n ` key drivers: ${repositoryTopFactors.map(formatFactorSummary).join(\"; \") || \"insufficient data\"}`,\n );\n lines.push(\n ` contributions: ${repositoryTopFactors.map(formatFactorContribution).join(\", \") || \"insufficient data\"}`,\n );\n lines.push(\n ` interaction effects: ${compositeFactors.map((factor) => `${formatFactorLabel(factor.factorId)} [${formatFactorEvidence(factor)}]`).join(\"; \") || \"none\"}`,\n );\n lines.push(` priority actions: ${buildRepositoryActions(payload, repositoryTarget).join(\" \")}`);\n lines.push(\"\");\n\n for (const target of payload.selectedTargets) {\n lines.push(renderTargetText(target));\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\").trimEnd();\n};\n\nconst renderMarkdown = (payload: ExplainOutputPayload): string => {\n const lines: string[] = [];\n const repositoryTarget =\n findRepositoryTarget(payload.selectedTargets) ?? findRepositoryTarget(payload.trace.targets);\n const repositoryTopFactors =\n repositoryTarget === undefined\n ? []\n : [...repositoryTarget.factors].sort(sortFactorByContribution).slice(0, 3);\n const dimensionScores = repositoryDimensionScores(repositoryTarget);\n const compositeFactors = repositoryTopFactors.filter((factor) => factor.family === \"composite\");\n\n lines.push(`# CodeSentinel Explanation`);\n lines.push(`- target: \\`${payload.summary.structural.targetPath}\\``);\n lines.push(`- riskScore: \\`${payload.summary.risk.riskScore}\\``);\n lines.push(`- riskBand: \\`${toRiskBand(payload.summary.risk.riskScore)}\\``);\n lines.push(`- selectedTargets: \\`${payload.selectedTargets.length}\\``);\n lines.push(\"\");\n lines.push(\"## Dimension Scores (0-100)\");\n lines.push(`- structural: \\`${formatDimension(dimensionScores.structural)}\\``);\n lines.push(`- evolution: \\`${formatDimension(dimensionScores.evolution)}\\``);\n lines.push(`- external: \\`${formatDimension(dimensionScores.external)}\\``);\n lines.push(`- interactions: \\`${formatDimension(dimensionScores.interactions)}\\``);\n lines.push(\"\");\n lines.push(`## Summary`);\n lines.push(\n `- key drivers: ${repositoryTopFactors.map(formatFactorSummary).join(\"; \") || \"insufficient data\"}`,\n );\n lines.push(\n `- contributions: ${repositoryTopFactors.map(formatFactorContribution).join(\", \") || \"insufficient data\"}`,\n );\n lines.push(\n `- interaction effects: ${compositeFactors.map((factor) => `${formatFactorLabel(factor.factorId)} [${formatFactorEvidence(factor)}]`).join(\"; \") || \"none\"}`,\n );\n lines.push(`- priority actions: ${buildRepositoryActions(payload, repositoryTarget).join(\" \")}`);\n lines.push(\"\");\n\n for (const target of payload.selectedTargets) {\n lines.push(`## ${target.targetType}: \\`${target.targetId}\\``);\n lines.push(`- score: \\`${target.totalScore}\\` (\\`${target.normalizedScore}\\`)`);\n lines.push(`- Top factors:`);\n for (const factor of [...target.factors].sort(sortFactorByContribution).slice(0, 5)) {\n lines.push(\n ` - \\`${formatFactorLabel(factor.factorId)}\\` contribution=\\`${factor.contribution}\\` confidence=\\`${factor.confidence}\\``,\n );\n lines.push(` - evidence: \\`${formatFactorEvidence(factor)}\\``);\n }\n lines.push(`- Reduction levers:`);\n for (const lever of target.reductionLevers) {\n lines.push(\n ` - \\`${formatFactorLabel(lever.factorId)}\\` estimatedImpact=\\`${lever.estimatedImpact}\\``,\n );\n }\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\").trimEnd();\n};\n\nexport const formatExplainOutput = (\n payload: ExplainOutputPayload,\n format: ExplainFormat,\n): string => {\n if (format === \"json\") {\n return JSON.stringify(payload, null, 2);\n }\n\n if (format === \"md\") {\n return renderMarkdown(payload);\n }\n\n return renderText(payload);\n};\n","import type { AnalyzeDependencyCandidateResult } from \"@codesentinel/dependency-firewall\";\n\nexport type DependencyRiskOutputMode = \"summary\" | \"json\";\n\ntype UnavailableResult = Extract<AnalyzeDependencyCandidateResult, { available: false }>;\ntype AvailableResult = Extract<AnalyzeDependencyCandidateResult, { available: true }>;\n\ntype DependencyRiskSummaryShape =\n | {\n available: false;\n reason: UnavailableResult[\"reason\"];\n dependency: string;\n }\n | {\n available: true;\n dependency: AvailableResult[\"dependency\"];\n graph: AvailableResult[\"graph\"];\n assumptions: readonly string[];\n external: {\n available: boolean;\n metrics: Record<string, unknown> | null;\n ownRiskSignals: readonly string[];\n inheritedRiskSignals: readonly string[];\n highRiskDependenciesTop: readonly string[];\n transitiveExposureDependenciesTop: readonly string[];\n };\n };\n\nconst createSummaryShape = (\n result: AnalyzeDependencyCandidateResult,\n): DependencyRiskSummaryShape => {\n if (!result.available) {\n return {\n available: false,\n reason: result.reason,\n dependency: result.dependency,\n };\n }\n\n const direct = result.external.available ? result.external.dependencies[0] : undefined;\n\n return {\n available: true,\n dependency: result.dependency,\n graph: result.graph,\n assumptions: result.assumptions,\n external: {\n available: result.external.available,\n metrics: result.external.available ? result.external.metrics : null,\n ownRiskSignals: direct?.ownRiskSignals ?? [],\n inheritedRiskSignals: direct?.inheritedRiskSignals ?? [],\n highRiskDependenciesTop: result.external.available\n ? result.external.highRiskDependencies.slice(0, 10)\n : [],\n transitiveExposureDependenciesTop: result.external.available\n ? result.external.transitiveExposureDependencies.slice(0, 10)\n : [],\n },\n };\n};\n\nexport const formatDependencyRiskOutput = (\n result: AnalyzeDependencyCandidateResult,\n mode: DependencyRiskOutputMode,\n): string =>\n mode === \"json\"\n ? JSON.stringify(result, null, 2)\n : JSON.stringify(createSummaryShape(result), null, 2);\n","export type LogLevel = \"silent\" | \"error\" | \"warn\" | \"info\" | \"debug\";\n\nconst logLevelRank: Readonly<Record<Exclude<LogLevel, \"silent\">, number>> = {\n error: 0,\n warn: 1,\n info: 2,\n debug: 3,\n};\n\nexport type Logger = {\n error: (message: string) => void;\n warn: (message: string) => void;\n info: (message: string) => void;\n debug: (message: string) => void;\n};\n\nconst noop = (): void => {};\n\nexport const createSilentLogger = (): Logger => ({\n error: noop,\n warn: noop,\n info: noop,\n debug: noop,\n});\n\nconst shouldLog = (\n configuredLevel: LogLevel,\n messageLevel: Exclude<LogLevel, \"silent\">,\n): boolean => {\n if (configuredLevel === \"silent\") {\n return false;\n }\n\n return logLevelRank[messageLevel] <= logLevelRank[configuredLevel];\n};\n\nconst write = (messageLevel: Exclude<LogLevel, \"silent\">, message: string): void => {\n process.stderr.write(`[codesentinel] ${messageLevel.toUpperCase()} ${message}\\n`);\n};\n\nexport const createStderrLogger = (level: LogLevel): Logger => {\n if (level === \"silent\") {\n return createSilentLogger();\n }\n\n return {\n error: (message) => {\n if (shouldLog(level, \"error\")) {\n write(\"error\", message);\n }\n },\n warn: (message) => {\n if (shouldLog(level, \"warn\")) {\n write(\"warn\", message);\n }\n },\n info: (message) => {\n if (shouldLog(level, \"info\")) {\n write(\"info\", message);\n }\n },\n debug: (message) => {\n if (shouldLog(level, \"debug\")) {\n write(\"debug\", message);\n }\n },\n };\n};\n\nexport const parseLogLevel = (value: string | undefined): LogLevel => {\n switch (value) {\n case \"silent\":\n case \"error\":\n case \"warn\":\n case \"info\":\n case \"debug\":\n return value;\n default:\n return \"info\";\n }\n};\n","import { spawn } from \"node:child_process\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport { stderr, stdin } from \"node:process\";\nimport { clearScreenDown, cursorTo, emitKeypressEvents } from \"node:readline\";\n\nconst UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;\nconst UPDATE_CACHE_PATH = join(homedir(), \".cache\", \"codesentinel\", \"update-check.json\");\nconst SEMVER_PATTERN =\n /^(?<major>\\d+)\\.(?<minor>\\d+)\\.(?<patch>\\d+)(?:-(?<prerelease>[0-9A-Za-z.-]+))?(?:\\+[0-9A-Za-z.-]+)?$/;\nconst ANSI = {\n reset: \"\\x1b[0m\",\n bold: \"\\x1b[1m\",\n dim: \"\\x1b[2m\",\n cyan: \"\\x1b[36m\",\n green: \"\\x1b[32m\",\n yellow: \"\\x1b[33m\",\n} as const;\n\nconst hideCursor = (): void => {\n stderr.write(\"\\x1b[?25l\");\n};\n\nconst showCursor = (): void => {\n stderr.write(\"\\x1b[?25h\");\n};\n\ntype Semver = {\n major: number;\n minor: number;\n patch: number;\n prerelease: readonly (number | string)[];\n};\n\ntype UpdateCheckCache = {\n lastCheckedAt: string;\n};\n\nconst parsePrereleaseIdentifier = (identifier: string): number | string => {\n if (/^\\d+$/.test(identifier)) {\n return Number.parseInt(identifier, 10);\n }\n return identifier;\n};\n\nconst parseSemver = (value: string): Semver | null => {\n const match = SEMVER_PATTERN.exec(value.trim());\n if (match === null) {\n return null;\n }\n\n const groups = match.groups;\n if (groups === undefined) {\n return null;\n }\n\n const majorRaw = groups[\"major\"];\n const minorRaw = groups[\"minor\"];\n const patchRaw = groups[\"patch\"];\n const prereleaseRaw = groups[\"prerelease\"];\n if (majorRaw === undefined || minorRaw === undefined || patchRaw === undefined) {\n return null;\n }\n\n const prerelease =\n prereleaseRaw === undefined || prereleaseRaw.length === 0\n ? []\n : prereleaseRaw.split(\".\").map(parsePrereleaseIdentifier);\n\n return {\n major: Number.parseInt(majorRaw, 10),\n minor: Number.parseInt(minorRaw, 10),\n patch: Number.parseInt(patchRaw, 10),\n prerelease,\n };\n};\n\nconst comparePrerelease = (\n left: readonly (number | string)[],\n right: readonly (number | string)[],\n): number => {\n if (left.length === 0 && right.length === 0) {\n return 0;\n }\n if (left.length === 0) {\n return 1;\n }\n if (right.length === 0) {\n return -1;\n }\n\n const length = Math.max(left.length, right.length);\n for (let index = 0; index < length; index += 1) {\n const leftValue = left[index];\n const rightValue = right[index];\n if (leftValue === undefined) {\n return -1;\n }\n if (rightValue === undefined) {\n return 1;\n }\n\n if (typeof leftValue === \"number\" && typeof rightValue === \"number\") {\n if (leftValue !== rightValue) {\n return leftValue > rightValue ? 1 : -1;\n }\n continue;\n }\n\n if (typeof leftValue === \"number\" && typeof rightValue === \"string\") {\n return -1;\n }\n if (typeof leftValue === \"string\" && typeof rightValue === \"number\") {\n return 1;\n }\n\n if (leftValue !== rightValue) {\n return leftValue > rightValue ? 1 : -1;\n }\n }\n\n return 0;\n};\n\nexport const compareVersions = (left: string, right: string): number | null => {\n const leftParsed = parseSemver(left);\n const rightParsed = parseSemver(right);\n if (leftParsed === null || rightParsed === null) {\n return null;\n }\n\n if (leftParsed.major !== rightParsed.major) {\n return leftParsed.major > rightParsed.major ? 1 : -1;\n }\n if (leftParsed.minor !== rightParsed.minor) {\n return leftParsed.minor > rightParsed.minor ? 1 : -1;\n }\n if (leftParsed.patch !== rightParsed.patch) {\n return leftParsed.patch > rightParsed.patch ? 1 : -1;\n }\n\n return comparePrerelease(leftParsed.prerelease, rightParsed.prerelease);\n};\n\nconst isTruthy = (value: string | undefined): boolean => {\n if (value === undefined) {\n return false;\n }\n return [\"1\", \"true\", \"yes\", \"on\"].includes(value.trim().toLowerCase());\n};\n\nexport const parseNpmViewVersionOutput = (output: string): string | null => {\n const trimmed = output.trim();\n if (trimmed.length === 0) {\n return null;\n }\n\n try {\n const parsed = JSON.parse(trimmed) as unknown;\n if (typeof parsed === \"string\" && parsed.trim().length > 0) {\n return parsed.trim();\n }\n if (Array.isArray(parsed) && parsed.length > 0) {\n const latest = (parsed as unknown[]).at(-1);\n if (typeof latest === \"string\" && latest.trim().length > 0) {\n return latest.trim();\n }\n }\n } catch {\n return trimmed;\n }\n\n return null;\n};\n\nexport const renderUpdateInProgressMessage = (packageName: string): string =>\n `Updating CodeSentinel via \\`npm install -g ${packageName}\\`...\\n`;\n\nexport const renderUpdateSuccessMessage = (): string =>\n \"🎉 Update ran successfully! Please restart CodeSentinel.\\n\";\n\nexport const renderAlreadyUpToDateMessage = (currentVersion: string): string =>\n `CodeSentinel is already up to date (${currentVersion}).\\n`;\n\nexport const renderUpdateCheckFailedMessage = (): string =>\n \"CodeSentinel could not check for updates right now. Please try again later.\\n\";\n\nconst readCache = async (): Promise<UpdateCheckCache | null> => {\n try {\n const raw = await readFile(UPDATE_CACHE_PATH, \"utf8\");\n const parsed = JSON.parse(raw) as unknown;\n if (\n typeof parsed === \"object\" &&\n parsed !== null &&\n typeof (parsed as { lastCheckedAt?: unknown }).lastCheckedAt === \"string\"\n ) {\n return { lastCheckedAt: (parsed as { lastCheckedAt: string }).lastCheckedAt };\n }\n } catch {\n return null;\n }\n\n return null;\n};\n\nconst writeCache = async (cache: UpdateCheckCache): Promise<void> => {\n await mkdir(dirname(UPDATE_CACHE_PATH), { recursive: true });\n await writeFile(UPDATE_CACHE_PATH, JSON.stringify(cache), \"utf8\");\n};\n\nexport const shouldRunUpdateCheck = (input: {\n argv: readonly string[];\n env: NodeJS.ProcessEnv;\n isInteractive: boolean;\n nowMs: number;\n lastCheckedAt: string | null;\n}): boolean => {\n if (!input.isInteractive) {\n return false;\n }\n if (isTruthy(input.env[\"CI\"])) {\n return false;\n }\n if (isTruthy(input.env[\"CODESENTINEL_NO_UPDATE_NOTIFIER\"])) {\n return false;\n }\n if (input.argv.some((argument) => argument === \"--help\" || argument === \"-h\")) {\n return false;\n }\n if (input.argv.some((argument) => argument === \"--version\" || argument === \"-V\")) {\n return false;\n }\n\n if (input.lastCheckedAt === null) {\n return true;\n }\n\n const lastCheckedMs = Date.parse(input.lastCheckedAt);\n if (!Number.isFinite(lastCheckedMs)) {\n return true;\n }\n\n return input.nowMs - lastCheckedMs >= UPDATE_CHECK_INTERVAL_MS;\n};\n\nconst runCommand = async (\n command: string,\n args: readonly string[],\n mode: \"capture\" | \"inherit\",\n): Promise<{ code: number; stdout: string }> => {\n return await new Promise((resolvePromise, reject) => {\n const child = spawn(command, [...args], {\n stdio: mode === \"inherit\" ? \"inherit\" : [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n let stdoutRaw = \"\";\n if (mode === \"capture\" && child.stdout !== null) {\n child.stdout.setEncoding(\"utf8\");\n child.stdout.on(\"data\", (chunk: string) => {\n stdoutRaw += chunk;\n });\n }\n\n child.on(\"error\", (error) => {\n reject(error);\n });\n child.on(\"close\", (code) => {\n resolvePromise({ code: code ?? 1, stdout: stdoutRaw });\n });\n });\n};\n\nconst fetchLatestVersion = async (packageName: string): Promise<string | null> => {\n const result = await runCommand(\"npm\", [\"view\", packageName, \"version\", \"--json\"], \"capture\");\n if (result.code !== 0) {\n return null;\n }\n return parseNpmViewVersionOutput(result.stdout);\n};\n\ntype UpdatePromptChoice = \"install\" | \"skip\";\n\nconst renderUpdatePrompt = (\n packageName: string,\n latestVersion: string,\n currentVersion: string,\n selectedIndex: number,\n): number => {\n const options: readonly string[] = [\n `1. Update now (runs \\`npm install -g ${packageName}\\`)`,\n \"2. Skip\",\n ];\n\n const lines = [\n ` ${ANSI.bold}${ANSI.cyan}✨ Update available! ${currentVersion} -> ${latestVersion}${ANSI.reset}`,\n \"\",\n ` ${ANSI.dim}Release notes: https://github.com/getcodesentinel/codesentinel/releases/latest${ANSI.reset}`,\n \"\",\n ...options.map((option, index) => {\n const selected = index === selectedIndex;\n const prefix = selected ? `${ANSI.green}>${ANSI.reset}` : \" \";\n const text = selected ? `${ANSI.bold}${option}${ANSI.reset}` : option;\n return `${prefix} ${text}`;\n }),\n \"\",\n ` ${ANSI.dim}Use ↑/↓ to choose. Press enter to continue. Press q or Ctrl+C to exit.${ANSI.reset}`,\n ];\n\n stderr.write(lines.join(\"\\n\"));\n return lines.length;\n};\n\nconst promptInstall = async (\n packageName: string,\n latestVersion: string,\n currentVersion: string,\n): Promise<UpdatePromptChoice> => {\n if (!stdin.isTTY || !stderr.isTTY || typeof stdin.setRawMode !== \"function\") {\n stderr.write(\n `New version ${latestVersion} is available (current ${currentVersion}). Run: npm install -g @getcodesentinel/codesentinel@latest\\n`,\n );\n return \"skip\";\n }\n\n return await new Promise<UpdatePromptChoice>((resolve) => {\n emitKeypressEvents(stdin);\n\n let selectedIndex = 0;\n const previousRawMode = stdin.isRaw;\n\n const clearPromptArea = (): void => {\n cursorTo(stderr, 0, 0);\n clearScreenDown(stderr);\n };\n\n const redraw = (): void => {\n clearPromptArea();\n renderUpdatePrompt(packageName, latestVersion, currentVersion, selectedIndex);\n };\n\n const cleanup = (choice: UpdatePromptChoice): void => {\n stdin.off(\"keypress\", onKeypress);\n stdin.pause();\n if (typeof stdin.setRawMode === \"function\") {\n stdin.setRawMode(previousRawMode);\n }\n clearPromptArea();\n showCursor();\n if (choice === \"install\") {\n stderr.write(`${ANSI.yellow}${renderUpdateInProgressMessage(packageName)}${ANSI.reset}`);\n } else {\n stderr.write(\"\\n\");\n }\n resolve(choice);\n };\n\n const onKeypress = (_str: string, key: { name?: string; ctrl?: boolean }): void => {\n if (key.ctrl === true && key.name === \"c\") {\n cleanup(\"skip\");\n return;\n }\n\n if (key.name === \"q\") {\n cleanup(\"skip\");\n return;\n }\n\n if (key.name === \"up\") {\n selectedIndex = selectedIndex > 0 ? selectedIndex - 1 : 1;\n redraw();\n return;\n }\n if (key.name === \"down\") {\n selectedIndex = selectedIndex < 1 ? selectedIndex + 1 : 0;\n redraw();\n return;\n }\n if (key.name === \"return\" || key.name === \"enter\") {\n cleanup(selectedIndex === 0 ? \"install\" : \"skip\");\n }\n };\n\n stdin.on(\"keypress\", onKeypress);\n if (typeof stdin.setRawMode === \"function\") {\n hideCursor();\n stdin.setRawMode(true);\n }\n stdin.resume();\n redraw();\n });\n};\n\nconst installLatestVersion = async (packageName: string): Promise<boolean> => {\n const result = await runCommand(\"npm\", [\"install\", \"-g\", `${packageName}@latest`], \"inherit\");\n return result.code === 0;\n};\n\nexport const runManualCliUpdate = async (input: {\n packageName: string;\n currentVersion: string;\n}): Promise<number> => {\n const latestVersion = await fetchLatestVersion(input.packageName);\n if (latestVersion === null) {\n stderr.write(renderUpdateCheckFailedMessage());\n return 1;\n }\n\n const comparison = compareVersions(latestVersion, input.currentVersion);\n if (comparison === null) {\n stderr.write(renderUpdateCheckFailedMessage());\n return 1;\n }\n\n if (comparison <= 0) {\n stderr.write(renderAlreadyUpToDateMessage(input.currentVersion));\n return 0;\n }\n\n const choice = await promptInstall(input.packageName, latestVersion, input.currentVersion);\n if (choice !== \"install\") {\n return 0;\n }\n\n const installed = await installLatestVersion(input.packageName);\n if (installed) {\n stderr.write(renderUpdateSuccessMessage());\n return 0;\n }\n\n stderr.write(\n \"CodeSentinel update failed. You can retry with: npm install -g @getcodesentinel/codesentinel@latest\\n\",\n );\n return 1;\n};\n\nexport const checkForCliUpdates = async (input: {\n packageName: string;\n currentVersion: string;\n argv: readonly string[];\n env: NodeJS.ProcessEnv;\n}): Promise<void> => {\n try {\n const nowMs = Date.now();\n const cache = await readCache();\n const shouldCheck = shouldRunUpdateCheck({\n argv: input.argv,\n env: input.env,\n isInteractive: Boolean(process.stdout.isTTY) && Boolean(process.stdin.isTTY),\n nowMs,\n lastCheckedAt: cache?.lastCheckedAt ?? null,\n });\n if (!shouldCheck) {\n return;\n }\n\n await writeCache({ lastCheckedAt: new Date(nowMs).toISOString() });\n\n const latestVersion = await fetchLatestVersion(input.packageName);\n if (latestVersion === null) {\n return;\n }\n\n const comparison = compareVersions(latestVersion, input.currentVersion);\n if (comparison === null || comparison <= 0) {\n return;\n }\n\n const choice = await promptInstall(input.packageName, latestVersion, input.currentVersion);\n if (choice !== \"install\") {\n return;\n }\n\n const installed = await installLatestVersion(input.packageName);\n if (installed) {\n stderr.write(renderUpdateSuccessMessage());\n process.exit(0);\n } else {\n stderr.write(\n \"CodeSentinel update failed. You can retry with: npm install -g @getcodesentinel/codesentinel@latest\\n\",\n );\n }\n } catch {\n // Update checks are best-effort and must never block the CLI command.\n }\n};\n","import { spawn } from \"node:child_process\";\nimport type { Readable } from \"node:stream\";\nimport { stderr, stdin, stdout } from \"node:process\";\nimport { clearScreenDown, cursorTo, emitKeypressEvents, moveCursor } from \"node:readline\";\nimport type { Interface as ReadlineInterface } from \"node:readline\";\nimport { createInterface as createPromisesInterface } from \"node:readline/promises\";\n\nconst ANSI = {\n reset: \"\\x1b[0m\",\n bold: \"\\x1b[1m\",\n dim: \"\\x1b[2m\",\n cyan: \"\\x1b[36m\",\n green: \"\\x1b[32m\",\n} as const;\nconst PROMPT_PADDING = \" \";\n\ntype MenuActionDefinition = {\n label: string;\n description: string;\n commandBuilder: () => MenuActionResult | Promise<MenuActionResult>;\n};\n\ntype MenuActionResult =\n | {\n kind: \"run\";\n args: readonly string[];\n }\n | {\n kind: \"cancel\";\n };\n\nconst isWhitespace = (value: string): boolean => /\\s/.test(value);\n\nexport const splitShellLikeArgs = (input: string): string[] => {\n const trimmed = input.trim();\n if (trimmed.length === 0) {\n return [];\n }\n\n const result: string[] = [];\n let current = \"\";\n let quote: '\"' | \"'\" | null = null;\n let escaping = false;\n\n for (const character of trimmed) {\n if (escaping) {\n current += character;\n escaping = false;\n continue;\n }\n\n if (character === \"\\\\\") {\n escaping = true;\n continue;\n }\n\n if (quote !== null) {\n if (character === quote) {\n quote = null;\n } else {\n current += character;\n }\n continue;\n }\n\n if (character === '\"' || character === \"'\") {\n quote = character;\n continue;\n }\n\n if (isWhitespace(character)) {\n if (current.length > 0) {\n result.push(current);\n current = \"\";\n }\n continue;\n }\n\n current += character;\n }\n\n if (escaping) {\n current += \"\\\\\";\n }\n if (quote !== null) {\n throw new Error(\"Unterminated quoted argument\");\n }\n if (current.length > 0) {\n result.push(current);\n }\n\n return result;\n};\n\nconst renderMenu = (\n currentVersion: string,\n actions: readonly MenuActionDefinition[],\n selectedIndex: number,\n): void => {\n const optionLabels = actions.map((action, index) => `${index + 1}. ${action.label}`);\n const labelWidth = optionLabels.reduce((max, label) => Math.max(max, label.length), 0);\n const lines = [\n ` ${ANSI.bold}${ANSI.cyan}CodeSentinel${ANSI.reset} ${ANSI.dim}v${currentVersion}${ANSI.reset}`,\n \"\",\n \" Choose an action:\",\n \"\",\n ...actions.map((action, index) => {\n const selected = index === selectedIndex;\n const prefix = selected ? `${ANSI.green}>${ANSI.reset}` : \" \";\n const label = optionLabels[index]?.padEnd(labelWidth, \" \") ?? \"\";\n const renderedLabel = selected ? `${ANSI.bold}${label}${ANSI.reset}` : label;\n return `${prefix} ${renderedLabel} ${ANSI.dim}${action.description}${ANSI.reset}`;\n }),\n \"\",\n ` ${ANSI.dim}Use ↑/↓ to choose. Press enter to continue. Press q or Ctrl+C to exit.${ANSI.reset}`,\n ];\n\n stderr.write(lines.join(\"\\n\"));\n};\n\nconst clearTerminal = (): void => {\n cursorTo(stderr, 0, 0);\n clearScreenDown(stderr);\n};\n\nconst hideCursor = (): void => {\n stderr.write(\"\\x1b[?25l\");\n};\n\nconst showCursor = (): void => {\n stderr.write(\"\\x1b[?25h\");\n};\n\nconst pipeWithPadding = (\n stream: Readable | null,\n target: NodeJS.WriteStream,\n padding: string,\n): void => {\n if (stream === null) {\n return;\n }\n\n stream.setEncoding(\"utf8\");\n\n let buffer = \"\";\n let needsPrefix = true;\n\n const writeChunk = (chunk: string): void => {\n let start = 0;\n while (start < chunk.length) {\n if (needsPrefix) {\n target.write(padding);\n needsPrefix = false;\n }\n\n const newlineIndex = chunk.indexOf(\"\\n\", start);\n if (newlineIndex === -1) {\n target.write(chunk.slice(start));\n return;\n }\n\n target.write(chunk.slice(start, newlineIndex + 1));\n needsPrefix = true;\n start = newlineIndex + 1;\n }\n };\n\n stream.on(\"data\", (chunk: string) => {\n buffer += chunk;\n const lastNewlineIndex = buffer.lastIndexOf(\"\\n\");\n\n if (lastNewlineIndex === -1) {\n return;\n }\n\n writeChunk(buffer.slice(0, lastNewlineIndex + 1));\n buffer = buffer.slice(lastNewlineIndex + 1);\n });\n\n stream.on(\"end\", () => {\n if (buffer.length > 0) {\n writeChunk(buffer);\n buffer = \"\";\n }\n });\n};\n\nconst promptSelection = async (\n currentVersion: string,\n actions: readonly MenuActionDefinition[],\n): Promise<number | \"exit\"> => {\n if (!stdin.isTTY || !stderr.isTTY || typeof stdin.setRawMode !== \"function\") {\n return \"exit\";\n }\n\n return await new Promise<number | \"exit\">((resolve) => {\n emitKeypressEvents(stdin);\n\n let selectedIndex = 0;\n const previousRawMode = stdin.isRaw;\n\n const redraw = (): void => {\n clearTerminal();\n renderMenu(currentVersion, actions, selectedIndex);\n moveCursor(stderr, -1, 0);\n };\n\n const cleanup = (selection: number | \"exit\"): void => {\n stdin.off(\"keypress\", onKeypress);\n stdin.pause();\n stdin.setRawMode(previousRawMode);\n clearTerminal();\n showCursor();\n resolve(selection);\n };\n\n const onKeypress = (_str: string, key: { name?: string; ctrl?: boolean }): void => {\n if (key.ctrl === true && key.name === \"c\") {\n cleanup(\"exit\");\n return;\n }\n\n if (key.name === \"q\") {\n cleanup(\"exit\");\n return;\n }\n\n if (key.name === \"up\") {\n selectedIndex = selectedIndex > 0 ? selectedIndex - 1 : actions.length - 1;\n redraw();\n return;\n }\n\n if (key.name === \"down\") {\n selectedIndex = selectedIndex < actions.length - 1 ? selectedIndex + 1 : 0;\n redraw();\n return;\n }\n\n if (key.name === \"return\" || key.name === \"enter\") {\n cleanup(selectedIndex);\n }\n };\n\n stdin.on(\"keypress\", onKeypress);\n hideCursor();\n stdin.setRawMode(true);\n stdin.resume();\n redraw();\n });\n};\n\nconst createPrompt = (): ReadlineInterface =>\n createPromisesInterface({\n input: stdin,\n output: stderr,\n }) as unknown as ReadlineInterface;\n\nconst promptText = async (\n prompt: ReadlineInterface,\n label: string,\n defaultValue?: string,\n): Promise<string | null> => {\n const suffix =\n defaultValue === undefined || defaultValue.length === 0 ? \"\" : ` [${defaultValue}]`;\n let answer: string;\n\n try {\n answer = await (prompt as unknown as ReturnType<typeof createPromisesInterface>).question(\n `${PROMPT_PADDING}${label}${suffix}: `,\n );\n } catch (error) {\n if (error instanceof Error && \"code\" in error && error.code === \"ABORT_ERR\") {\n stderr.write(\"\\n\");\n return null;\n }\n throw error;\n }\n\n const trimmed = answer.trim();\n return trimmed.length > 0 ? trimmed : (defaultValue ?? \"\");\n};\n\nconst renderDependencyRiskPrompt = (errorMessage?: string): void => {\n clearTerminal();\n stderr.write(`${PROMPT_PADDING}${ANSI.bold}Scan dependency risk${ANSI.reset}\\n`);\n if (errorMessage !== undefined) {\n stderr.write(`\\n${PROMPT_PADDING}${errorMessage}\\n`);\n }\n stderr.write(\"\\n\");\n};\n\nconst buildDependencyRiskArgs = async (): Promise<MenuActionResult> => {\n const prompt = createPrompt();\n\n try {\n let errorMessage: string | undefined;\n\n while (true) {\n renderDependencyRiskPrompt(errorMessage);\n const dependency = await promptText(prompt, \"Package name\");\n if (dependency === null) {\n return { kind: \"cancel\" };\n }\n\n if (dependency.length === 0) {\n errorMessage = \"A package name is required.\";\n continue;\n }\n\n return {\n kind: \"run\",\n args: [\"dependency-risk\", dependency],\n };\n }\n } finally {\n prompt.close();\n }\n};\n\nconst waitForReturnToMenu = async (): Promise<void> => {\n if (!stdin.isTTY || !stderr.isTTY || typeof stdin.setRawMode !== \"function\") {\n return;\n }\n\n stderr.write(`\\n${PROMPT_PADDING}Press enter to return to the menu...`);\n\n await new Promise<void>((resolve) => {\n emitKeypressEvents(stdin);\n const previousRawMode = stdin.isRaw;\n\n const cleanup = (): void => {\n stdin.off(\"keypress\", onKeypress);\n stdin.pause();\n stdin.setRawMode(previousRawMode);\n showCursor();\n stderr.write(\"\\n\");\n resolve();\n };\n\n const onKeypress = (_str: string, key: { name?: string; ctrl?: boolean }): void => {\n if (key.ctrl === true && key.name === \"c\") {\n cleanup();\n return;\n }\n\n if (key.name === \"return\" || key.name === \"enter\") {\n cleanup();\n }\n };\n\n hideCursor();\n stdin.on(\"keypress\", onKeypress);\n stdin.setRawMode(true);\n stdin.resume();\n });\n};\n\nconst runCliCommand = async (scriptPath: string, args: readonly string[]): Promise<number> => {\n return await new Promise((resolve, reject) => {\n const child = spawn(process.execPath, [...process.execArgv, scriptPath, ...args], {\n stdio: [\"inherit\", \"pipe\", \"pipe\"],\n env: {\n ...process.env,\n CODESENTINEL_NO_UPDATE_NOTIFIER: \"1\",\n },\n });\n\n pipeWithPadding(child.stdout, stdout, PROMPT_PADDING);\n pipeWithPadding(child.stderr, stderr, PROMPT_PADDING);\n\n child.on(\"error\", (error) => {\n reject(error);\n });\n child.on(\"close\", (code) => {\n resolve(code ?? 1);\n });\n });\n};\n\nexport const runInteractiveCliMenu = async (input: {\n currentVersion: string;\n scriptPath: string;\n}): Promise<number> => {\n if (!stdin.isTTY || !stderr.isTTY || !stdout.isTTY) {\n stderr.write(`${PROMPT_PADDING}Interactive menu requires a TTY.\\n`);\n return 1;\n }\n\n const actions: readonly MenuActionDefinition[] = [\n {\n label: \"Run overview\",\n description: \"combined analyze + explain + report\",\n commandBuilder: () => ({ kind: \"run\", args: [\"run\"] }),\n },\n {\n label: \"Analyze repository\",\n description: \"structural and health scoring summary\",\n commandBuilder: () => ({ kind: \"run\", args: [\"analyze\"] }),\n },\n {\n label: \"Explain hotspots\",\n description: \"top findings in markdown by default\",\n commandBuilder: () => ({ kind: \"run\", args: [\"explain\", \"--format\", \"md\"] }),\n },\n {\n label: \"Generate report\",\n description: \"create a full report for a repository\",\n commandBuilder: () => ({ kind: \"run\", args: [\"report\", \"--format\", \"md\"] }),\n },\n {\n label: \"Run policy check\",\n description: \"execute governance gates\",\n commandBuilder: () => ({ kind: \"run\", args: [\"check\"] }),\n },\n {\n label: \"Scan dependency risk\",\n description: \"inspect a package from the registry\",\n commandBuilder: buildDependencyRiskArgs,\n },\n ];\n\n while (true) {\n const selectedIndex = await promptSelection(input.currentVersion, actions);\n if (selectedIndex === \"exit\") {\n stderr.write(\"\\n\");\n return 0;\n }\n\n const selectedAction = actions[selectedIndex];\n if (selectedAction === undefined) {\n stderr.write(`\\n${PROMPT_PADDING}`);\n return 1;\n }\n\n const actionResult = await selectedAction.commandBuilder();\n if (actionResult.kind === \"cancel\") {\n continue;\n }\n\n const exitCode = await runCliCommand(input.scriptPath, actionResult.args);\n if (exitCode !== 0) {\n stderr.write(`\\n${PROMPT_PADDING}Command exited with code ${exitCode}.\\n`);\n } else {\n stderr.write(\"\\n\");\n }\n await waitForReturnToMenu();\n }\n};\n","import { resolve } from \"node:path\";\nimport type { AnalyzeSummary } from \"@codesentinel/core\";\nimport {\n buildProjectGraphSummary,\n type ParseTypescriptProjectProgressEvent,\n} from \"@codesentinel/code-graph\";\nimport {\n analyzeDependencyExposureFromProject,\n type DependencyExposureProgressEvent,\n} from \"@codesentinel/dependency-firewall\";\nimport {\n analyzeRepositoryEvolutionFromGit,\n enrichEvolutionSummaryWithWorkspaces,\n type EvolutionAnalysisProgressEvent,\n} from \"@codesentinel/git-analyzer\";\nimport {\n computeRepositoryHealthSummary,\n type HealthEngineConfig,\n} from \"@codesentinel/health-engine\";\nimport { computeRepositoryRiskSummary, type RiskEngineConfig } from \"@codesentinel/risk-engine\";\nimport { createSilentLogger, type Logger } from \"./logger.js\";\n\nexport type AuthorIdentityCliMode = \"likely_merge\" | \"strict_email\";\nexport type ScoringProfileCliMode = \"default\" | \"personal\";\nexport type AnalysisRuntimeOptions = {\n recentWindowDays?: number;\n scoringProfile?: ScoringProfileCliMode;\n};\n\nconst resolveTargetPath = (inputPath: string | undefined, cwd: string): string =>\n resolve(cwd, inputPath ?? \".\");\n\nexport type AnalysisInputs = {\n structural: AnalyzeSummary[\"structural\"];\n evolution: AnalyzeSummary[\"evolution\"];\n external: AnalyzeSummary[\"external\"];\n};\n\nconst scoringProfileConfig: Readonly<\n Record<ScoringProfileCliMode, Partial<RiskEngineConfig> | undefined>\n> = {\n default: undefined,\n personal: {\n evolutionFactorWeights: {\n frequency: 0.26,\n churn: 0.24,\n recentVolatility: 0.2,\n ownershipConcentration: 0.08,\n busFactorRisk: 0.04,\n },\n },\n};\n\nconst healthProfileConfig: Readonly<\n Record<ScoringProfileCliMode, Partial<HealthEngineConfig> | undefined>\n> = {\n default: undefined,\n personal: {\n ownershipPenaltyMultiplier: 0.25,\n },\n};\n\nexport const resolveRiskConfigForProfile = (\n scoringProfile: ScoringProfileCliMode | undefined,\n): Partial<RiskEngineConfig> | undefined => {\n return scoringProfileConfig[scoringProfile ?? \"default\"];\n};\n\nexport const resolveHealthConfigForProfile = (\n scoringProfile: ScoringProfileCliMode | undefined,\n): Partial<HealthEngineConfig> | undefined => {\n return healthProfileConfig[scoringProfile ?? \"default\"];\n};\n\nconst createExternalProgressReporter = (\n logger: Logger,\n): ((event: DependencyExposureProgressEvent) => void) => {\n let lastLoggedProgress = 0;\n\n return (event) => {\n switch (event.stage) {\n case \"package_json_loaded\":\n logger.debug(\"external: package.json loaded\");\n break;\n case \"lockfile_selected\":\n logger.info(`external: lockfile selected (${event.kind})`);\n break;\n case \"lockfile_parsed\":\n logger.info(\n `external: parsed ${event.dependencyNodes} locked dependencies (${event.directDependencies} direct)`,\n );\n break;\n case \"metadata_fetch_started\":\n logger.info(`external: fetching dependency metadata (${event.total} packages)`);\n break;\n case \"metadata_fetch_progress\": {\n const currentPercent =\n event.total === 0 ? 100 : Math.floor((event.completed / event.total) * 100);\n if (\n event.completed === event.total ||\n event.completed === 1 ||\n event.completed - lastLoggedProgress >= 25\n ) {\n lastLoggedProgress = event.completed;\n logger.info(\n `external: metadata progress ${event.completed}/${event.total} (${currentPercent}%)`,\n );\n logger.debug(`external: last package processed ${event.packageName}`);\n }\n break;\n }\n case \"metadata_fetch_completed\":\n logger.info(`external: metadata fetch completed (${event.total} packages)`);\n break;\n case \"summary_built\":\n logger.info(\n `external: summary built (${event.totalDependencies} total, ${event.directDependencies} direct)`,\n );\n break;\n }\n };\n};\n\nconst createStructuralProgressReporter = (\n logger: Logger,\n): ((event: ParseTypescriptProjectProgressEvent) => void) => {\n let lastProcessed = 0;\n\n return (event) => {\n switch (event.stage) {\n case \"config_resolved\":\n if (event.usedFallbackScan) {\n logger.info(\n `structural: using filesystem scan discovery (tsconfigs=${event.tsconfigCount})`,\n );\n } else {\n logger.info(`structural: discovered tsconfig graph (${event.tsconfigCount} configs)`);\n }\n break;\n case \"files_discovered\":\n logger.info(`structural: discovered ${event.totalSourceFiles} source files`);\n break;\n case \"program_created\":\n logger.debug(`structural: TypeScript program created (${event.totalSourceFiles} files)`);\n break;\n case \"file_processed\":\n if (\n event.processed === event.total ||\n event.processed === 1 ||\n event.processed - lastProcessed >= 50\n ) {\n lastProcessed = event.processed;\n logger.info(`structural: resolved ${event.processed}/${event.total} files`);\n logger.debug(`structural: last file processed ${event.filePath}`);\n }\n break;\n case \"edges_resolved\":\n logger.info(`structural: resolved ${event.totalEdges} dependency edges`);\n break;\n }\n };\n};\n\nconst createEvolutionProgressReporter = (\n logger: Logger,\n): ((event: EvolutionAnalysisProgressEvent) => void) => {\n let lastParsedRecords = 0;\n\n return (event) => {\n switch (event.stage) {\n case \"checking_git_repository\":\n logger.debug(\"evolution: checking git repository\");\n break;\n case \"not_git_repository\":\n logger.warn(\"evolution: target path is not a git repository\");\n break;\n case \"loading_commit_history\":\n logger.info(\"evolution: loading git history\");\n break;\n case \"history\":\n if (event.event.stage === \"git_log_received\") {\n logger.info(`evolution: git log loaded (${event.event.bytes} bytes)`);\n break;\n }\n\n if (event.event.stage === \"git_log_parsed\") {\n logger.info(`evolution: parsed ${event.event.commits} commits`);\n break;\n }\n\n if (\n event.event.stage === \"git_log_parse_progress\" &&\n (event.event.parsedRecords === event.event.totalRecords ||\n event.event.parsedRecords === 1 ||\n event.event.parsedRecords - lastParsedRecords >= 500)\n ) {\n lastParsedRecords = event.event.parsedRecords;\n const currentPercent =\n event.event.totalRecords === 0\n ? 100\n : Math.floor((event.event.parsedRecords / event.event.totalRecords) * 100);\n logger.info(\n `evolution: parse progress ${event.event.parsedRecords}/${event.event.totalRecords} (${currentPercent}%)`,\n );\n }\n break;\n case \"computing_metrics\":\n logger.info(\"evolution: computing metrics\");\n break;\n case \"analysis_completed\":\n logger.debug(`evolution: analysis completed (available=${event.available})`);\n break;\n }\n };\n};\n\nexport const collectAnalysisInputs = async (\n inputPath: string | undefined,\n authorIdentityMode: AuthorIdentityCliMode,\n options: AnalysisRuntimeOptions = {},\n logger: Logger = createSilentLogger(),\n): Promise<AnalysisInputs> => {\n const invocationCwd = process.env[\"INIT_CWD\"] ?? process.cwd();\n const targetPath = resolveTargetPath(inputPath, invocationCwd);\n logger.info(`analyzing repository: ${targetPath}`);\n\n logger.info(\"building structural graph\");\n const structural = buildProjectGraphSummary({\n projectPath: targetPath,\n onProgress: createStructuralProgressReporter(logger),\n });\n logger.debug(\n `structural metrics: nodes=${structural.metrics.nodeCount}, edges=${structural.metrics.edgeCount}, cycles=${structural.metrics.cycleCount}`,\n );\n\n logger.info(`analyzing git evolution (author identity: ${authorIdentityMode})`);\n const repositoryEvolution = analyzeRepositoryEvolutionFromGit(\n {\n repositoryPath: targetPath,\n config: {\n authorIdentityMode,\n ...(options.recentWindowDays === undefined\n ? {}\n : { recentWindowDays: options.recentWindowDays }),\n },\n },\n createEvolutionProgressReporter(logger),\n );\n const evolution = enrichEvolutionSummaryWithWorkspaces(structural, repositoryEvolution);\n if (evolution.available) {\n logger.debug(\n `evolution metrics: commits=${evolution.metrics.totalCommits}, files=${evolution.metrics.totalFiles}, hotspotThreshold=${evolution.metrics.hotspotThresholdCommitCount}`,\n );\n } else {\n logger.warn(`evolution analysis unavailable: ${evolution.reason}`);\n }\n\n logger.info(\"analyzing external dependencies\");\n const external = await analyzeDependencyExposureFromProject(\n { repositoryPath: targetPath },\n createExternalProgressReporter(logger),\n );\n if (external.available) {\n logger.debug(\n `external metrics: total=${external.metrics.totalDependencies}, direct=${external.metrics.directDependencies}, transitive=${external.metrics.transitiveDependencies}`,\n );\n } else {\n logger.warn(`external analysis unavailable: ${external.reason}`);\n }\n\n return {\n structural,\n evolution,\n external,\n };\n};\n\nexport const runAnalyzeCommand = async (\n inputPath: string | undefined,\n authorIdentityMode: AuthorIdentityCliMode,\n options: AnalysisRuntimeOptions = {},\n logger: Logger = createSilentLogger(),\n): Promise<AnalyzeSummary> => {\n const analysisInputs = await collectAnalysisInputs(\n inputPath,\n authorIdentityMode,\n options,\n logger,\n );\n logger.info(\"computing risk summary\");\n const riskConfig = resolveRiskConfigForProfile(options.scoringProfile);\n const healthConfig = resolveHealthConfigForProfile(options.scoringProfile);\n const risk = computeRepositoryRiskSummary({\n structural: analysisInputs.structural,\n evolution: analysisInputs.evolution,\n external: analysisInputs.external,\n ...(riskConfig === undefined ? {} : { config: riskConfig }),\n });\n const health = computeRepositoryHealthSummary({\n structural: analysisInputs.structural,\n evolution: analysisInputs.evolution,\n ...(healthConfig === undefined ? {} : { config: healthConfig }),\n });\n logger.info(\n `analysis completed (riskScore=${risk.riskScore}, healthScore=${health.healthScore})`,\n );\n\n return {\n structural: analysisInputs.structural,\n evolution: analysisInputs.evolution,\n external: analysisInputs.external,\n risk,\n health,\n };\n};\n","export type GraphNode = {\n id: string;\n absolutePath: string;\n relativePath: string;\n};\n\nexport type GraphEdge = {\n from: string;\n to: string;\n};\n\nexport type GraphCycle = {\n nodes: readonly string[];\n};\n\nexport type FileDependency = {\n id: string;\n relativePath: string;\n directDependencies: readonly string[];\n fanIn: number;\n fanOut: number;\n depth: number;\n};\n\nexport type GraphMetrics = {\n nodeCount: number;\n edgeCount: number;\n cycleCount: number;\n graphDepth: number;\n maxFanIn: number;\n maxFanOut: number;\n};\n\nexport type WorkspaceKind = \"app\" | \"package\" | \"docs\" | \"example\" | \"tooling\" | \"unknown\";\n\nexport type WorkspacePackage = {\n name: string;\n path: string;\n kind: WorkspaceKind;\n};\n\nexport type WorkspaceStructuralSummary = WorkspacePackage & {\n fileCount: number;\n internalEdgeCount: number;\n incomingEdgeCount: number;\n outgoingEdgeCount: number;\n};\n\nexport type CrossWorkspaceEdge = {\n fromWorkspace: string;\n toWorkspace: string;\n from: string;\n to: string;\n};\n\nexport type GraphAnalysisSummary = {\n targetPath: string;\n nodes: readonly GraphNode[];\n edges: readonly GraphEdge[];\n cycles: readonly GraphCycle[];\n files: readonly FileDependency[];\n metrics: GraphMetrics;\n workspaces?: readonly WorkspaceStructuralSummary[];\n crossWorkspaceEdges?: readonly CrossWorkspaceEdge[];\n};\n\nexport type FileAuthorShare = {\n authorId: string;\n commits: number;\n share: number;\n};\n\nexport type FileAuthorChurnShare = {\n authorId: string;\n churnAdded: number;\n churnDeleted: number;\n churnTotal: number;\n share: number;\n};\n\nexport type FileEvolutionMetrics = {\n filePath: string;\n commitCount: number;\n frequencyPer100Commits: number;\n churnAdded: number;\n churnDeleted: number;\n churnTotal: number;\n lastCommitTimestamp: number | null;\n recentCommitCount: number;\n recentVolatility: number;\n topAuthorShareByCommits: number;\n busFactorByCommits: number;\n authorDistributionByCommits: readonly FileAuthorShare[];\n topAuthorShareByChurn: number;\n busFactorByChurn: number;\n authorDistributionByChurn: readonly FileAuthorChurnShare[];\n};\n\nexport type Hotspot = {\n filePath: string;\n rank: number;\n commitCount: number;\n churnTotal: number;\n};\n\nexport type FileCoupling = {\n fileA: string;\n fileB: string;\n coChangeCommits: number;\n couplingScore: number;\n};\n\nexport type RecentActivityPoint = {\n bucketStartUtcDate: string;\n commitCount: number;\n fileTouchCount: number;\n churnTotal: number;\n activeAuthorCount: number;\n volatilityScore: number;\n};\n\nexport type CouplingMatrix = {\n pairs: readonly FileCoupling[];\n totalPairCount: number;\n consideredCommits: number;\n skippedLargeCommits: number;\n truncated: boolean;\n};\n\nexport type RepositoryEvolutionMetrics = {\n totalCommits: number;\n totalFiles: number;\n headCommitTimestamp: number | null;\n recentWindowDays: number;\n hotspotTopPercent: number;\n hotspotThresholdCommitCount: number;\n};\n\nexport type WorkspaceEvolutionSummary = WorkspacePackage & {\n fileCount: number;\n commitCount: number;\n churnAdded: number;\n churnDeleted: number;\n churnTotal: number;\n recentCommitCount: number;\n recentVolatility: number;\n topAuthorShareByCommits: number;\n busFactorByCommits: number;\n hotspotCount: number;\n topHotspots: readonly Hotspot[];\n internalCouplingPairCount: number;\n incomingCouplingPairCount: number;\n outgoingCouplingPairCount: number;\n};\n\nexport type RepositoryEvolutionAvailable = {\n targetPath: string;\n available: true;\n files: readonly FileEvolutionMetrics[];\n hotspots: readonly Hotspot[];\n coupling: CouplingMatrix;\n recentActivity?: readonly RecentActivityPoint[];\n workspaces?: readonly WorkspaceEvolutionSummary[];\n metrics: RepositoryEvolutionMetrics;\n};\n\nexport type RepositoryEvolutionUnavailable = {\n targetPath: string;\n available: false;\n reason: \"not_git_repository\";\n};\n\nexport type RepositoryEvolutionSummary =\n | RepositoryEvolutionAvailable\n | RepositoryEvolutionUnavailable;\n\nexport type DependencyRiskSignal =\n | \"single_maintainer\"\n | \"abandoned\"\n | \"high_centrality\"\n | \"deep_chain\"\n | \"high_fanout\"\n | \"metadata_unavailable\";\n\nexport type DependencyExposureRecord = {\n name: string;\n direct: boolean;\n dependencyScope: \"prod\" | \"dev\";\n requestedRange: string | null;\n resolvedVersion: string | null;\n transitiveDependencies: readonly string[];\n weeklyDownloads: number | null;\n dependencyDepth: number;\n fanOut: number;\n dependents: number;\n maintainerCount: number | null;\n releaseFrequencyDays: number | null;\n daysSinceLastRelease: number | null;\n repositoryActivity30d: number | null;\n busFactor: number | null;\n ownRiskSignals: readonly DependencyRiskSignal[];\n inheritedRiskSignals: readonly DependencyRiskSignal[];\n riskSignals: readonly DependencyRiskSignal[];\n};\n\nexport type CentralDependency = {\n name: string;\n dependents: number;\n fanOut: number;\n direct: boolean;\n};\n\nexport type ExternalAnalysisMetrics = {\n totalDependencies: number;\n directDependencies: number;\n directProductionDependencies: number;\n directDevelopmentDependencies: number;\n transitiveDependencies: number;\n dependencyDepth: number;\n lockfileKind: \"pnpm\" | \"npm\" | \"npm-shrinkwrap\" | \"yarn\" | \"bun\";\n metadataCoverage: number;\n};\n\nexport type ExternalAnalysisAvailable = {\n targetPath: string;\n available: true;\n metrics: ExternalAnalysisMetrics;\n dependencies: readonly DependencyExposureRecord[];\n workspaces?: readonly WorkspaceDependencyExposureSummary[];\n highRiskDependencies: readonly string[];\n highRiskDevelopmentDependencies: readonly string[];\n transitiveExposureDependencies: readonly string[];\n singleMaintainerDependencies: readonly string[];\n abandonedDependencies: readonly string[];\n centralityRanking: readonly CentralDependency[];\n};\n\nexport type WorkspaceDependencyExposureSummary = WorkspacePackage & {\n directDependencies: number;\n directProductionDependencies: number;\n directDevelopmentDependencies: number;\n unresolvedDependencies: readonly string[];\n dependencyNames: readonly string[];\n sharedDependencies: readonly string[];\n highRiskDependencies: readonly string[];\n highRiskDevelopmentDependencies: readonly string[];\n transitiveExposureDependencies: readonly string[];\n singleMaintainerDependencies: readonly string[];\n abandonedDependencies: readonly string[];\n};\n\nexport type ExternalAnalysisUnavailable = {\n targetPath: string;\n available: false;\n reason:\n | \"package_json_not_found\"\n | \"lockfile_not_found\"\n | \"unsupported_lockfile_format\"\n | \"invalid_lockfile\";\n};\n\nexport type ExternalAnalysisSummary = ExternalAnalysisAvailable | ExternalAnalysisUnavailable;\n\nexport type RiskFactors = {\n structural: number;\n evolution: number;\n external: number;\n};\n\nexport type FileRiskScore = {\n file: string;\n score: number;\n normalizedScore: number;\n factors: RiskFactors;\n};\n\nexport type ModuleRiskScore = {\n module: string;\n score: number;\n normalizedScore: number;\n fileCount: number;\n};\n\nexport type DependencyRiskScore = {\n dependency: string;\n score: number;\n normalizedScore: number;\n ownRiskSignals: readonly DependencyRiskSignal[];\n inheritedRiskSignals: readonly DependencyRiskSignal[];\n};\n\nexport type WorkspaceRiskScore = WorkspacePackage & {\n score: number;\n normalizedScore: number;\n fileCount: number;\n averageFileRisk: number;\n peakFileRisk: number;\n internalEdgeCount: number;\n incomingEdgeCount: number;\n outgoingEdgeCount: number;\n topFiles: readonly RiskHotspot[];\n};\n\nexport type RiskHotspot = {\n file: string;\n score: number;\n factors: RiskFactors;\n};\n\nexport type FragileCluster = {\n id: string;\n kind: \"structural_cycle\" | \"change_coupling\";\n files: readonly string[];\n score: number;\n};\n\nexport type DependencyAmplificationZone = {\n file: string;\n score: number;\n externalPressure: number;\n};\n\nexport type RiskFactorFamily = \"structural\" | \"evolution\" | \"external\" | \"composite\";\n\nexport type EvidenceRef =\n | {\n kind: \"file_metric\";\n target: string;\n metric: string;\n }\n | {\n kind: \"repository_metric\";\n metric: string;\n }\n | {\n kind: \"dependency_metric\";\n target: string;\n metric: string;\n }\n | {\n kind: \"graph_cycle\";\n cycleId: string;\n files: readonly string[];\n }\n | {\n kind: \"coupling_pair\";\n fileA: string;\n fileB: string;\n };\n\nexport type RiskFactorTrace = {\n factorId: string;\n family: RiskFactorFamily;\n contribution: number;\n rawMetrics: Readonly<Record<string, number | null>>;\n normalizedMetrics: Readonly<Record<string, number | null>>;\n weight: number | null;\n amplification: number | null;\n evidence: readonly EvidenceRef[];\n confidence: number;\n};\n\nexport type RiskReductionLever = {\n factorId: string;\n estimatedImpact: number;\n};\n\nexport type TargetTrace = {\n targetType: \"repository\" | \"file\" | \"module\" | \"dependency\";\n targetId: string;\n totalScore: number;\n normalizedScore: number;\n factors: readonly RiskFactorTrace[];\n dominantFactors: readonly string[];\n reductionLevers: readonly RiskReductionLever[];\n};\n\nexport type RiskTrace = {\n schemaVersion: \"1\";\n contributionTolerance: number;\n targets: readonly TargetTrace[];\n};\n\nexport type RepositoryRiskSummary = {\n riskScore: number;\n normalizedScore: number;\n percentileRank?: number;\n hotspots: readonly RiskHotspot[];\n fragileClusters: readonly FragileCluster[];\n dependencyAmplificationZones: readonly DependencyAmplificationZone[];\n fileScores: readonly FileRiskScore[];\n moduleScores: readonly ModuleRiskScore[];\n workspaceScores: readonly WorkspaceRiskScore[];\n dependencyScores: readonly DependencyRiskScore[];\n};\n\nexport type RepositoryRiskEvaluation = {\n summary: RepositoryRiskSummary;\n trace?: RiskTrace;\n};\n\nexport type HealthDimension =\n | \"modularity\"\n | \"changeHygiene\"\n | \"testHealth\"\n | \"ownershipDistribution\";\n\nexport type HealthIssueSeverity = \"warn\" | \"error\";\n\nexport type HealthIssue = {\n id: string;\n ruleId?: string;\n signal: string;\n severity: HealthIssueSeverity;\n target: string;\n message: string;\n dimension: HealthDimension;\n evidenceMetrics: Readonly<Record<string, number | null>>;\n};\n\nexport type RepositoryHealthDimensions = {\n modularity: number;\n changeHygiene: number;\n testHealth: number;\n ownershipDistribution: number;\n};\n\nexport type HealthEvidenceRef =\n | {\n kind: \"repository_metric\";\n metric: string;\n }\n | {\n kind: \"file_metric\";\n target: string;\n metric: string;\n }\n | {\n kind: \"lint_rule\";\n ruleId: string;\n };\n\nexport type HealthFactorTrace = {\n factorId: string;\n contribution: number;\n penalty: number;\n rawMetrics: Readonly<Record<string, number | null>>;\n normalizedMetrics: Readonly<Record<string, number | null>>;\n weight: number;\n evidence: readonly HealthEvidenceRef[];\n};\n\nexport type HealthDimensionTrace = {\n dimension: HealthDimension;\n normalizedScore: number;\n score: number;\n factors: readonly HealthFactorTrace[];\n};\n\nexport type HealthTrace = {\n schemaVersion: \"1\";\n dimensions: readonly HealthDimensionTrace[];\n};\n\nexport type RepositoryHealthSummary = {\n healthScore: number;\n normalizedScore: number;\n dimensions: RepositoryHealthDimensions;\n topIssues: readonly HealthIssue[];\n trace?: HealthTrace;\n};\n\nexport const normalizeWorkspacePath = (pathValue: string): string =>\n pathValue.replaceAll(\"\\\\\", \"/\");\n\nexport const fileBelongsToWorkspace = (filePath: string, workspace: WorkspacePackage): boolean => {\n const normalizedFilePath = normalizeWorkspacePath(filePath);\n const normalizedWorkspacePath = normalizeWorkspacePath(workspace.path);\n return (\n normalizedFilePath === normalizedWorkspacePath ||\n normalizedFilePath.startsWith(`${normalizedWorkspacePath}/`)\n );\n};\n\nexport const findWorkspaceForFile = (\n filePath: string,\n workspaces: readonly WorkspacePackage[],\n): WorkspacePackage | null => {\n let match: WorkspacePackage | null = null;\n for (const workspace of workspaces) {\n if (fileBelongsToWorkspace(filePath, workspace)) {\n if (match === null || workspace.path.length > match.path.length) {\n match = workspace;\n }\n }\n }\n\n return match;\n};\n\nexport const createWorkspaceByFile = (\n filePaths: readonly string[],\n workspaces: readonly WorkspacePackage[],\n): ReadonlyMap<string, WorkspacePackage> => {\n const workspaceByFile = new Map<string, WorkspacePackage>();\n\n for (const filePath of filePaths) {\n const workspace = findWorkspaceForFile(filePath, workspaces);\n if (workspace !== null) {\n workspaceByFile.set(filePath, workspace);\n }\n }\n\n return workspaceByFile;\n};\n\nexport type AnalyzeSummary = {\n structural: GraphAnalysisSummary;\n evolution: RepositoryEvolutionSummary;\n external: ExternalAnalysisSummary;\n risk: RepositoryRiskSummary;\n health: RepositoryHealthSummary;\n};\n","export type NodeRecord = {\n id: string;\n absolutePath: string;\n relativePath: string;\n};\n\nexport type EdgeRecord = {\n from: string;\n to: string;\n};\n\nexport type GraphData = {\n nodes: readonly NodeRecord[];\n edges: readonly EdgeRecord[];\n adjacencyById: ReadonlyMap<string, readonly string[]>;\n};\n\nconst edgeKey = (from: string, to: string): string => `${from}\\u0000${to}`;\n\nexport const createGraphData = (\n nodes: readonly NodeRecord[],\n rawEdges: readonly EdgeRecord[],\n): GraphData => {\n const sortedNodes = [...nodes].sort((a, b) => a.id.localeCompare(b.id));\n const knownNodeIds = new Set(sortedNodes.map((node) => node.id));\n\n const uniqueEdgeMap = new Map<string, EdgeRecord>();\n for (const edge of rawEdges) {\n if (edge.from === edge.to) {\n continue;\n }\n\n if (!knownNodeIds.has(edge.from) || !knownNodeIds.has(edge.to)) {\n continue;\n }\n\n uniqueEdgeMap.set(edgeKey(edge.from, edge.to), edge);\n }\n\n const sortedEdges = [...uniqueEdgeMap.values()].sort((a, b) => {\n const fromCompare = a.from.localeCompare(b.from);\n if (fromCompare !== 0) {\n return fromCompare;\n }\n\n return a.to.localeCompare(b.to);\n });\n\n const adjacency = new Map<string, string[]>();\n for (const node of sortedNodes) {\n adjacency.set(node.id, []);\n }\n\n for (const edge of sortedEdges) {\n adjacency.get(edge.from)?.push(edge.to);\n }\n\n const adjacencyById = new Map<string, readonly string[]>();\n for (const [nodeId, targets] of adjacency.entries()) {\n adjacencyById.set(nodeId, [...targets]);\n }\n\n return {\n nodes: sortedNodes,\n edges: sortedEdges,\n adjacencyById,\n };\n};\n","import type {\n CrossWorkspaceEdge,\n FileDependency,\n GraphAnalysisSummary,\n GraphCycle,\n GraphMetrics,\n WorkspacePackage,\n WorkspaceStructuralSummary,\n} from \"@codesentinel/core\";\nimport { createWorkspaceByFile as createWorkspaceMembershipByFile } from \"@codesentinel/core\";\nimport type { GraphData } from \"./graph-model.js\";\nimport { runTarjanScc } from \"./tarjan.js\";\n\ntype DepthComputation = {\n depthByNodeId: ReadonlyMap<string, number>;\n graphDepth: number;\n cycles: readonly GraphCycle[];\n};\n\nconst hasSelfLoop = (\n nodeId: string,\n adjacencyById: ReadonlyMap<string, readonly string[]>,\n): boolean => {\n const targets = adjacencyById.get(nodeId) ?? [];\n return targets.includes(nodeId);\n};\n\nconst computeCyclesAndDepth = (graph: GraphData): DepthComputation => {\n const { components } = runTarjanScc(graph.adjacencyById);\n\n const cycles: GraphCycle[] = [];\n const componentByNodeId = new Map<string, number>();\n components.forEach((component, index) => {\n for (const nodeId of component) {\n componentByNodeId.set(nodeId, index);\n }\n\n if (component.length > 1) {\n cycles.push({ nodes: [...component] });\n return;\n }\n\n const onlyNode = component[0];\n if (onlyNode !== undefined && hasSelfLoop(onlyNode, graph.adjacencyById)) {\n cycles.push({ nodes: [...component] });\n }\n });\n\n const dagOutgoing = new Map<number, Set<number>>();\n const inDegree = new Map<number, number>();\n\n for (let i = 0; i < components.length; i += 1) {\n dagOutgoing.set(i, new Set());\n inDegree.set(i, 0);\n }\n\n for (const edge of graph.edges) {\n const fromComponent = componentByNodeId.get(edge.from);\n const toComponent = componentByNodeId.get(edge.to);\n\n if (fromComponent === undefined || toComponent === undefined || fromComponent === toComponent) {\n continue;\n }\n\n const outgoing = dagOutgoing.get(fromComponent);\n if (outgoing?.has(toComponent) === true) {\n continue;\n }\n\n outgoing?.add(toComponent);\n inDegree.set(toComponent, (inDegree.get(toComponent) ?? 0) + 1);\n }\n\n const queue: number[] = [];\n const depthByComponent = new Map<number, number>();\n\n for (let i = 0; i < components.length; i += 1) {\n if ((inDegree.get(i) ?? 0) === 0) {\n queue.push(i);\n depthByComponent.set(i, 0);\n }\n }\n\n let cursor = 0;\n while (cursor < queue.length) {\n const componentId = queue[cursor];\n cursor += 1;\n\n if (componentId === undefined) {\n continue;\n }\n\n const currentDepth = depthByComponent.get(componentId) ?? 0;\n const outgoing = dagOutgoing.get(componentId) ?? new Set<number>();\n\n for (const nextComponent of outgoing) {\n const nextDepth = depthByComponent.get(nextComponent) ?? 0;\n if (currentDepth + 1 > nextDepth) {\n depthByComponent.set(nextComponent, currentDepth + 1);\n }\n\n const remainingIncoming = (inDegree.get(nextComponent) ?? 0) - 1;\n inDegree.set(nextComponent, remainingIncoming);\n if (remainingIncoming === 0) {\n queue.push(nextComponent);\n }\n }\n }\n\n const depthByNodeId = new Map<string, number>();\n let graphDepth = 0;\n\n components.forEach((component, componentId) => {\n const componentDepth = depthByComponent.get(componentId) ?? 0;\n if (componentDepth > graphDepth) {\n graphDepth = componentDepth;\n }\n\n for (const nodeId of component) {\n depthByNodeId.set(nodeId, componentDepth);\n }\n });\n\n cycles.sort((a, b) => {\n const firstA = a.nodes[0] ?? \"\";\n const firstB = b.nodes[0] ?? \"\";\n return firstA.localeCompare(firstB);\n });\n\n return {\n depthByNodeId,\n graphDepth,\n cycles,\n };\n};\n\nconst createWorkspaceByFile = (\n graph: GraphData,\n workspaces: readonly WorkspacePackage[],\n): ReadonlyMap<string, WorkspacePackage> => {\n return createWorkspaceMembershipByFile(\n graph.nodes.map((node) => node.id),\n workspaces,\n );\n};\n\nconst createCrossWorkspaceEdges = (\n graph: GraphData,\n workspaceByFile: ReadonlyMap<string, WorkspacePackage>,\n): readonly CrossWorkspaceEdge[] => {\n const edges: CrossWorkspaceEdge[] = [];\n\n for (const edge of graph.edges) {\n const fromWorkspace = workspaceByFile.get(edge.from);\n const toWorkspace = workspaceByFile.get(edge.to);\n if (\n fromWorkspace === undefined ||\n toWorkspace === undefined ||\n fromWorkspace.path === toWorkspace.path\n ) {\n continue;\n }\n\n edges.push({\n fromWorkspace: fromWorkspace.path,\n toWorkspace: toWorkspace.path,\n from: edge.from,\n to: edge.to,\n });\n }\n\n return edges;\n};\n\nconst createWorkspaceSummaries = (\n graph: GraphData,\n workspaces: readonly WorkspacePackage[],\n workspaceByFile: ReadonlyMap<string, WorkspacePackage>,\n): readonly WorkspaceStructuralSummary[] => {\n if (workspaces.length === 0) {\n return [];\n }\n\n const fileCountByWorkspacePath = new Map<string, number>();\n const internalEdgesByWorkspacePath = new Map<string, number>();\n const incomingEdgesByWorkspacePath = new Map<string, number>();\n const outgoingEdgesByWorkspacePath = new Map<string, number>();\n\n for (const workspace of workspaces) {\n fileCountByWorkspacePath.set(workspace.path, 0);\n internalEdgesByWorkspacePath.set(workspace.path, 0);\n incomingEdgesByWorkspacePath.set(workspace.path, 0);\n outgoingEdgesByWorkspacePath.set(workspace.path, 0);\n }\n\n for (const node of graph.nodes) {\n const workspace = workspaceByFile.get(node.id);\n if (workspace === undefined) {\n continue;\n }\n\n fileCountByWorkspacePath.set(\n workspace.path,\n (fileCountByWorkspacePath.get(workspace.path) ?? 0) + 1,\n );\n }\n\n for (const edge of graph.edges) {\n const fromWorkspace = workspaceByFile.get(edge.from) ?? null;\n const toWorkspace = workspaceByFile.get(edge.to) ?? null;\n\n if (fromWorkspace === null && toWorkspace === null) {\n continue;\n }\n\n if (fromWorkspace?.path === toWorkspace?.path && fromWorkspace !== null) {\n internalEdgesByWorkspacePath.set(\n fromWorkspace.path,\n (internalEdgesByWorkspacePath.get(fromWorkspace.path) ?? 0) + 1,\n );\n continue;\n }\n\n if (fromWorkspace !== null) {\n outgoingEdgesByWorkspacePath.set(\n fromWorkspace.path,\n (outgoingEdgesByWorkspacePath.get(fromWorkspace.path) ?? 0) + 1,\n );\n }\n\n if (toWorkspace !== null) {\n incomingEdgesByWorkspacePath.set(\n toWorkspace.path,\n (incomingEdgesByWorkspacePath.get(toWorkspace.path) ?? 0) + 1,\n );\n }\n }\n\n return workspaces.map((workspace) => ({\n ...workspace,\n fileCount: fileCountByWorkspacePath.get(workspace.path) ?? 0,\n internalEdgeCount: internalEdgesByWorkspacePath.get(workspace.path) ?? 0,\n incomingEdgeCount: incomingEdgesByWorkspacePath.get(workspace.path) ?? 0,\n outgoingEdgeCount: outgoingEdgesByWorkspacePath.get(workspace.path) ?? 0,\n }));\n};\n\nexport const createGraphAnalysisSummary = (\n targetPath: string,\n graph: GraphData,\n workspaces: readonly WorkspacePackage[] = [],\n): GraphAnalysisSummary => {\n const fanInById = new Map<string, number>();\n const fanOutById = new Map<string, number>();\n\n for (const node of graph.nodes) {\n fanInById.set(node.id, 0);\n fanOutById.set(node.id, graph.adjacencyById.get(node.id)?.length ?? 0);\n }\n\n for (const edge of graph.edges) {\n fanInById.set(edge.to, (fanInById.get(edge.to) ?? 0) + 1);\n }\n\n const { cycles, depthByNodeId, graphDepth } = computeCyclesAndDepth(graph);\n\n let maxFanIn = 0;\n let maxFanOut = 0;\n\n const files: FileDependency[] = graph.nodes.map((node) => {\n const fanIn = fanInById.get(node.id) ?? 0;\n const fanOut = fanOutById.get(node.id) ?? 0;\n\n if (fanIn > maxFanIn) {\n maxFanIn = fanIn;\n }\n\n if (fanOut > maxFanOut) {\n maxFanOut = fanOut;\n }\n\n return {\n id: node.id,\n relativePath: node.relativePath,\n directDependencies: graph.adjacencyById.get(node.id) ?? [],\n fanIn,\n fanOut,\n depth: depthByNodeId.get(node.id) ?? 0,\n };\n });\n\n const metrics: GraphMetrics = {\n nodeCount: graph.nodes.length,\n edgeCount: graph.edges.length,\n cycleCount: cycles.length,\n graphDepth,\n maxFanIn,\n maxFanOut,\n };\n const workspaceByFile = createWorkspaceByFile(graph, workspaces);\n\n return {\n targetPath,\n nodes: graph.nodes,\n edges: graph.edges,\n cycles,\n files,\n metrics,\n ...(workspaces.length === 0\n ? {}\n : {\n workspaces: createWorkspaceSummaries(graph, workspaces, workspaceByFile),\n crossWorkspaceEdges: createCrossWorkspaceEdges(graph, workspaceByFile),\n }),\n };\n};\n","type TarjanResult = {\n components: readonly (readonly string[])[];\n};\n\nexport const runTarjanScc = (\n adjacencyById: ReadonlyMap<string, readonly string[]>,\n): TarjanResult => {\n // SCC = group of nodes where every node can reach every other node through directed edges.\n // In this codebase, SCCs are used to detect dependency cycles before computing graph depth.\n let index = 0;\n const indices = new Map<string, number>();\n const lowLink = new Map<string, number>();\n const stack: string[] = [];\n const onStack = new Set<string>();\n const components: string[][] = [];\n\n const strongConnect = (nodeId: string): void => {\n indices.set(nodeId, index);\n lowLink.set(nodeId, index);\n index += 1;\n\n stack.push(nodeId);\n onStack.add(nodeId);\n\n const neighbors = adjacencyById.get(nodeId) ?? [];\n for (const nextId of neighbors) {\n if (!indices.has(nextId)) {\n strongConnect(nextId);\n const nodeLowLink = lowLink.get(nodeId);\n const nextLowLink = lowLink.get(nextId);\n if (nodeLowLink !== undefined && nextLowLink !== undefined && nextLowLink < nodeLowLink) {\n lowLink.set(nodeId, nextLowLink);\n }\n continue;\n }\n\n if (onStack.has(nextId)) {\n const nodeLowLink = lowLink.get(nodeId);\n const nextIndex = indices.get(nextId);\n if (nodeLowLink !== undefined && nextIndex !== undefined && nextIndex < nodeLowLink) {\n lowLink.set(nodeId, nextIndex);\n }\n }\n }\n\n const nodeLowLink = lowLink.get(nodeId);\n const nodeIndex = indices.get(nodeId);\n if (nodeLowLink === undefined || nodeIndex === undefined || nodeLowLink !== nodeIndex) {\n return;\n }\n\n const component: string[] = [];\n for (;;) {\n const popped = stack.pop();\n if (popped === undefined) {\n break;\n }\n\n onStack.delete(popped);\n component.push(popped);\n if (popped === nodeId) {\n break;\n }\n }\n\n component.sort((a, b) => a.localeCompare(b));\n components.push(component);\n };\n\n const nodeIds = [...adjacencyById.keys()].sort((a, b) => a.localeCompare(b));\n for (const nodeId of nodeIds) {\n if (!indices.has(nodeId)) {\n strongConnect(nodeId);\n }\n }\n\n components.sort((a, b) => {\n const firstA = a[0] ?? \"\";\n const firstB = b[0] ?? \"\";\n return firstA.localeCompare(firstB);\n });\n\n return { components };\n};\n","import { existsSync, readFileSync } from \"node:fs\";\nimport { extname, isAbsolute, join, relative, resolve } from \"node:path\";\nimport * as ts from \"typescript\";\nimport type { WorkspacePackage } from \"@codesentinel/core\";\nimport type { EdgeRecord, NodeRecord } from \"../domain/graph-model.js\";\n\ntype ParsedProject = {\n nodes: readonly NodeRecord[];\n edges: readonly EdgeRecord[];\n};\n\ntype PackageJsonExportMap = {\n readonly [key: string]: PackageJsonExportValue | undefined;\n};\n\ntype PackageJsonExportValue = string | readonly PackageJsonExportValue[] | PackageJsonExportMap;\n\ntype PackageJsonEntryFields = {\n main?: string;\n module?: string;\n source?: string;\n types?: string;\n typings?: string;\n exports?: PackageJsonExportValue;\n};\n\nexport type ParseTypescriptProjectProgressEvent =\n | { stage: \"config_resolved\"; tsconfigCount: number; usedFallbackScan: boolean }\n | { stage: \"files_discovered\"; totalSourceFiles: number }\n | { stage: \"program_created\"; totalSourceFiles: number }\n | { stage: \"file_processed\"; processed: number; total: number; filePath: string }\n | { stage: \"edges_resolved\"; totalEdges: number };\n\nconst SOURCE_EXTENSIONS = new Set([\".ts\", \".tsx\", \".mts\", \".cts\", \".js\", \".jsx\", \".mjs\", \".cjs\"]);\nconst SCAN_EXCLUDES = [\n \"**/node_modules/**\",\n \"**/.git/**\",\n \"**/dist/**\",\n \"**/build/**\",\n \"**/.next/**\",\n \"**/coverage/**\",\n \"**/.turbo/**\",\n \"**/.cache/**\",\n \"**/out/**\",\n];\nconst SCAN_INCLUDES = [\"**/*\"];\nconst IGNORED_SEGMENTS = new Set([\n \"node_modules\",\n \".git\",\n \"dist\",\n \"build\",\n \".next\",\n \"coverage\",\n \".turbo\",\n \".cache\",\n \"out\",\n]);\n\nconst normalizePath = (pathValue: string): string => pathValue.replaceAll(\"\\\\\", \"/\");\n\nconst readPackageJson = (packageJsonPath: string): PackageJsonEntryFields | null => {\n try {\n return JSON.parse(readFileSync(packageJsonPath, \"utf8\")) as PackageJsonEntryFields;\n } catch {\n return null;\n }\n};\n\nconst isProjectSourceFile = (filePath: string, projectRoot: string): boolean => {\n const extension = extname(filePath);\n if (!SOURCE_EXTENSIONS.has(extension)) {\n return false;\n }\n\n const relativePath = relative(projectRoot, filePath);\n if (relativePath.startsWith(\"..\")) {\n return false;\n }\n\n const normalizedRelativePath = normalizePath(relativePath);\n const segments = normalizedRelativePath.split(\"/\");\n return !segments.some((segment) => IGNORED_SEGMENTS.has(segment));\n};\n\nconst discoverSourceFilesByScan = (projectRoot: string): readonly string[] => {\n const files = ts.sys.readDirectory(\n projectRoot,\n [...SOURCE_EXTENSIONS],\n SCAN_EXCLUDES,\n SCAN_INCLUDES,\n );\n return files.map((filePath) => resolve(filePath));\n};\n\nconst parseTsConfigFile = (configPath: string): ts.ParsedCommandLine => {\n const parsedCommandLine = ts.getParsedCommandLineOfConfigFile(\n configPath,\n {},\n {\n ...ts.sys,\n onUnRecoverableConfigFileDiagnostic: () => {\n throw new Error(`Failed to parse TypeScript configuration at ${configPath}`);\n },\n },\n );\n\n if (parsedCommandLine === undefined) {\n throw new Error(`Failed to parse TypeScript configuration at ${configPath}`);\n }\n\n return parsedCommandLine;\n};\n\ntype CollectedTsConfigData = {\n fileNames: readonly string[];\n rootOptions: ts.CompilerOptions;\n visitedConfigCount: number;\n};\n\nconst collectFilesFromTsConfigGraph = (projectRoot: string): CollectedTsConfigData | null => {\n const rootConfigPath = ts.findConfigFile(\n projectRoot,\n (filePath) => ts.sys.fileExists(filePath),\n \"tsconfig.json\",\n );\n if (rootConfigPath === undefined) {\n return null;\n }\n\n const visitedConfigPaths = new Set<string>();\n const collectedFiles = new Set<string>();\n let rootOptions: ts.CompilerOptions | null = null;\n\n const visitConfig = (configPath: string): void => {\n const absoluteConfigPath = resolve(configPath);\n if (visitedConfigPaths.has(absoluteConfigPath)) {\n return;\n }\n\n visitedConfigPaths.add(absoluteConfigPath);\n const parsed = parseTsConfigFile(absoluteConfigPath);\n if (rootOptions === null) {\n rootOptions = parsed.options;\n }\n\n for (const filePath of parsed.fileNames) {\n collectedFiles.add(resolve(filePath));\n }\n\n for (const reference of parsed.projectReferences ?? []) {\n const referencePath = resolve(reference.path);\n const referenceConfigPath = ts.sys.directoryExists(referencePath)\n ? ts.findConfigFile(\n referencePath,\n (filePath) => ts.sys.fileExists(filePath),\n \"tsconfig.json\",\n )\n : referencePath;\n\n if (referenceConfigPath !== undefined && ts.sys.fileExists(referenceConfigPath)) {\n visitConfig(referenceConfigPath);\n }\n }\n };\n\n visitConfig(rootConfigPath);\n\n return {\n fileNames: [...collectedFiles],\n rootOptions: rootOptions ?? {\n moduleResolution: ts.ModuleResolutionKind.NodeNext,\n },\n visitedConfigCount: visitedConfigPaths.size,\n };\n};\n\nconst createCompilerOptions = (base: ts.CompilerOptions | undefined): ts.CompilerOptions => ({\n ...base,\n allowJs: true,\n moduleResolution: base?.moduleResolution ?? ts.ModuleResolutionKind.NodeNext,\n});\n\nconst parseTsConfig = (\n projectRoot: string,\n): {\n fileNames: readonly string[];\n options: ts.CompilerOptions;\n tsconfigCount: number;\n usedFallbackScan: boolean;\n} => {\n const collected = collectFilesFromTsConfigGraph(projectRoot);\n if (collected === null) {\n return {\n fileNames: discoverSourceFilesByScan(projectRoot),\n options: createCompilerOptions(undefined),\n tsconfigCount: 0,\n usedFallbackScan: true,\n };\n }\n\n if (collected.fileNames.length === 0) {\n return {\n fileNames: discoverSourceFilesByScan(projectRoot),\n options: createCompilerOptions(collected.rootOptions),\n tsconfigCount: collected.visitedConfigCount,\n usedFallbackScan: true,\n };\n }\n\n return {\n fileNames: collected.fileNames,\n options: createCompilerOptions(collected.rootOptions),\n tsconfigCount: collected.visitedConfigCount,\n usedFallbackScan: false,\n };\n};\n\nconst getSpecifierFromExpression = (expression: ts.Expression): string | undefined => {\n if (ts.isStringLiteral(expression)) {\n return expression.text;\n }\n\n if (ts.isNoSubstitutionTemplateLiteral(expression)) {\n return expression.text;\n }\n\n return undefined;\n};\n\nconst hasRuntimeImport = (importDeclaration: ts.ImportDeclaration): boolean => {\n const importClause = importDeclaration.importClause;\n if (importClause === undefined) {\n return true;\n }\n\n if (importClause.isTypeOnly) {\n return false;\n }\n\n if (importClause.name !== undefined) {\n return true;\n }\n\n const namedBindings = importClause.namedBindings;\n if (namedBindings === undefined) {\n return false;\n }\n\n if (ts.isNamespaceImport(namedBindings)) {\n return true;\n }\n\n if (namedBindings.elements.length === 0) {\n return true;\n }\n\n return namedBindings.elements.some((element) => !element.isTypeOnly);\n};\n\nconst extractModuleSpecifiers = (sourceFile: ts.SourceFile): readonly string[] => {\n const specifiers = new Set<string>();\n\n const visit = (node: ts.Node): void => {\n if (ts.isImportDeclaration(node)) {\n if (hasRuntimeImport(node) && node.moduleSpecifier !== undefined) {\n const specifier = getSpecifierFromExpression(node.moduleSpecifier);\n if (specifier !== undefined) {\n specifiers.add(specifier);\n }\n }\n return;\n }\n\n if (ts.isExportDeclaration(node)) {\n if (!node.isTypeOnly && node.moduleSpecifier !== undefined) {\n const specifier = getSpecifierFromExpression(node.moduleSpecifier);\n if (specifier !== undefined) {\n specifiers.add(specifier);\n }\n }\n return;\n }\n\n if (ts.isCallExpression(node)) {\n if (node.expression.kind === ts.SyntaxKind.ImportKeyword && node.arguments.length > 0) {\n const firstArgument = node.arguments[0];\n if (firstArgument !== undefined) {\n const specifier = getSpecifierFromExpression(firstArgument);\n if (specifier !== undefined) {\n specifiers.add(specifier);\n }\n }\n }\n\n if (\n ts.isIdentifier(node.expression) &&\n node.expression.text === \"require\" &&\n node.arguments.length > 0\n ) {\n const firstArgument = node.arguments[0];\n if (firstArgument !== undefined) {\n const specifier = getSpecifierFromExpression(firstArgument);\n if (specifier !== undefined) {\n specifiers.add(specifier);\n }\n }\n }\n }\n\n ts.forEachChild(node, visit);\n };\n\n visit(sourceFile);\n return [...specifiers];\n};\n\nconst parseWorkspaceSpecifier = (\n specifier: string,\n workspaceNames: ReadonlySet<string>,\n): { packageName: string; subpath: string | null } | null => {\n const parts = specifier.split(\"/\");\n const packageName = specifier.startsWith(\"@\") ? parts.slice(0, 2).join(\"/\") : (parts[0] ?? \"\");\n\n if (!workspaceNames.has(packageName)) {\n return null;\n }\n\n const subpath = specifier.slice(packageName.length).replace(/^\\//, \"\");\n return {\n packageName,\n subpath: subpath.length === 0 ? null : subpath,\n };\n};\n\nconst expandFileCandidates = (pathWithoutExtension: string): readonly string[] => [\n pathWithoutExtension,\n ...[...SOURCE_EXTENSIONS].map((extension) => `${pathWithoutExtension}${extension}`),\n ...[...SOURCE_EXTENSIONS].map((extension) => join(pathWithoutExtension, `index${extension}`)),\n];\n\nconst isExportArray = (value: PackageJsonExportValue): value is readonly PackageJsonExportValue[] =>\n Array.isArray(value);\n\nconst isExportMap = (value: PackageJsonExportValue): value is PackageJsonExportMap =>\n typeof value !== \"string\" && !isExportArray(value);\n\nconst collectExportTargetCandidates = (\n value: PackageJsonExportValue | undefined,\n): readonly string[] => {\n if (value === undefined) {\n return [];\n }\n\n if (typeof value === \"string\") {\n return [value];\n }\n\n if (isExportArray(value)) {\n return value.flatMap((entry) => collectExportTargetCandidates(entry));\n }\n\n if (!isExportMap(value)) {\n return [];\n }\n\n const candidates: string[] = [];\n for (const key of [\"source\", \"types\", \"typings\", \"import\", \"module\", \"require\", \"default\"]) {\n candidates.push(...collectExportTargetCandidates(value[key]));\n }\n\n return candidates;\n};\n\nconst collectPackageExportCandidates = (\n packageJson: PackageJsonEntryFields | null,\n subpath: string | null,\n): readonly string[] => {\n const exportsValue = packageJson?.exports;\n if (exportsValue === undefined) {\n return [];\n }\n\n if (subpath === null) {\n if (typeof exportsValue === \"string\" || isExportArray(exportsValue)) {\n return collectExportTargetCandidates(exportsValue);\n }\n\n return collectExportTargetCandidates(exportsValue[\".\"]);\n }\n\n if (typeof exportsValue === \"string\" || isExportArray(exportsValue)) {\n return [];\n }\n\n const exportKey = `./${subpath}`;\n const exactCandidates = collectExportTargetCandidates(exportsValue[exportKey]);\n if (exactCandidates.length > 0) {\n return exactCandidates;\n }\n\n const wildcardCandidates: string[] = [];\n for (const [key, value] of Object.entries(exportsValue)) {\n if (!key.includes(\"*\")) {\n continue;\n }\n\n const [prefix = \"\", suffix = \"\"] = key.split(\"*\");\n if (!exportKey.startsWith(prefix) || !exportKey.endsWith(suffix)) {\n continue;\n }\n\n const replacement = exportKey.slice(prefix.length, exportKey.length - suffix.length);\n for (const candidate of collectExportTargetCandidates(value)) {\n wildcardCandidates.push(candidate.replaceAll(\"*\", replacement));\n }\n }\n\n return wildcardCandidates;\n};\n\nconst resolveFirstAnalyzedCandidate = (\n candidates: readonly string[],\n sourceFilePathSet: ReadonlySet<string>,\n): string | undefined => {\n for (const candidate of candidates) {\n for (const expanded of expandFileCandidates(candidate)) {\n const normalized = normalizePath(expanded);\n if (sourceFilePathSet.has(normalized) && existsSync(normalized)) {\n return normalized;\n }\n }\n }\n\n return undefined;\n};\n\nconst createWorkspaceResolver = (\n projectRoot: string,\n workspaces: readonly WorkspacePackage[],\n sourceFilePathSet: ReadonlySet<string>,\n): ((specifier: string) => string | undefined) => {\n const workspaceByName = new Map(workspaces.map((workspace) => [workspace.name, workspace]));\n const workspaceNames = new Set(workspaceByName.keys());\n\n return (specifier) => {\n const parsed = parseWorkspaceSpecifier(specifier, workspaceNames);\n if (parsed === null) {\n return undefined;\n }\n\n const workspace = workspaceByName.get(parsed.packageName);\n if (workspace === undefined) {\n return undefined;\n }\n\n const workspaceRoot = resolve(projectRoot, workspace.path);\n const packageJson = readPackageJson(join(workspaceRoot, \"package.json\"));\n const candidates =\n parsed.subpath === null\n ? [\n ...collectPackageExportCandidates(packageJson, null),\n packageJson?.source,\n packageJson?.types,\n packageJson?.typings,\n packageJson?.module,\n packageJson?.main,\n \"src/index\",\n \"index\",\n ].filter((candidate): candidate is string => candidate !== undefined)\n : [\n ...collectPackageExportCandidates(packageJson, parsed.subpath),\n parsed.subpath,\n join(\"src\", parsed.subpath),\n ];\n\n return resolveFirstAnalyzedCandidate(\n candidates.map((candidate) => resolve(workspaceRoot, candidate)),\n sourceFilePathSet,\n );\n };\n};\n\nconst createTsPathAliasResolver = (\n projectRoot: string,\n options: ts.CompilerOptions,\n sourceFilePathSet: ReadonlySet<string>,\n): ((specifier: string) => string | undefined) => {\n const paths = options.paths;\n if (paths === undefined) {\n return () => undefined;\n }\n\n const baseUrl = options.baseUrl === undefined ? projectRoot : options.baseUrl;\n const pathEntries = Object.entries(paths).sort(([left], [right]) => {\n const leftPrefix = left.split(\"*\")[0]?.length ?? left.length;\n const rightPrefix = right.split(\"*\")[0]?.length ?? right.length;\n return rightPrefix - leftPrefix || left.localeCompare(right);\n });\n\n return (specifier) => {\n for (const [pattern, substitutions] of pathEntries) {\n const [prefix = \"\", suffix = \"\"] = pattern.split(\"*\");\n const hasWildcard = pattern.includes(\"*\");\n if (hasWildcard) {\n if (!specifier.startsWith(prefix) || !specifier.endsWith(suffix)) {\n continue;\n }\n } else if (specifier !== pattern) {\n continue;\n }\n\n const replacement = hasWildcard\n ? specifier.slice(prefix.length, specifier.length - suffix.length)\n : \"\";\n const candidates = substitutions.map((substitution) =>\n resolve(baseUrl, hasWildcard ? substitution.replaceAll(\"*\", replacement) : substitution),\n );\n const resolved = resolveFirstAnalyzedCandidate(candidates, sourceFilePathSet);\n if (resolved !== undefined) {\n return resolved;\n }\n }\n\n return undefined;\n };\n};\n\nexport const parseTypescriptProject = (\n projectPath: string,\n onProgress?: (event: ParseTypescriptProjectProgressEvent) => void,\n workspaces: readonly WorkspacePackage[] = [],\n): ParsedProject => {\n const projectRoot = isAbsolute(projectPath) ? projectPath : resolve(projectPath);\n const { fileNames, options, tsconfigCount, usedFallbackScan } = parseTsConfig(projectRoot);\n onProgress?.({ stage: \"config_resolved\", tsconfigCount, usedFallbackScan });\n\n const sourceFilePaths = fileNames\n .filter((filePath) => isProjectSourceFile(filePath, projectRoot))\n .map((filePath) => normalizePath(resolve(filePath)));\n\n const uniqueSourceFilePaths = [...new Set(sourceFilePaths)].sort((a, b) => a.localeCompare(b));\n const sourceFilePathSet = new Set(uniqueSourceFilePaths);\n onProgress?.({ stage: \"files_discovered\", totalSourceFiles: uniqueSourceFilePaths.length });\n\n const program = ts.createProgram({\n rootNames: uniqueSourceFilePaths,\n options,\n });\n onProgress?.({ stage: \"program_created\", totalSourceFiles: uniqueSourceFilePaths.length });\n\n const nodeByAbsolutePath = new Map<string, NodeRecord>();\n for (const sourcePath of uniqueSourceFilePaths) {\n const relativePath = normalizePath(relative(projectRoot, sourcePath));\n const nodeId = relativePath;\n nodeByAbsolutePath.set(sourcePath, {\n id: nodeId,\n absolutePath: sourcePath,\n relativePath,\n });\n }\n\n const resolverCache = new Map<string, string | undefined>();\n const resolveWorkspaceSpecifier = createWorkspaceResolver(\n projectRoot,\n workspaces,\n sourceFilePathSet,\n );\n const resolveTsPathAlias = createTsPathAliasResolver(projectRoot, options, sourceFilePathSet);\n const edges: EdgeRecord[] = [];\n\n for (const [index, sourcePath] of uniqueSourceFilePaths.entries()) {\n const sourceFile = program.getSourceFile(sourcePath);\n if (sourceFile === undefined) {\n continue;\n }\n\n const fromNode = nodeByAbsolutePath.get(sourcePath);\n if (fromNode === undefined) {\n continue;\n }\n\n const moduleSpecifiers = extractModuleSpecifiers(sourceFile);\n for (const specifier of moduleSpecifiers) {\n const cacheKey = `${sourcePath}\\u0000${specifier}`;\n let resolvedPath = resolverCache.get(cacheKey);\n\n if (resolvedPath === undefined && !resolverCache.has(cacheKey)) {\n const resolved = ts.resolveModuleName(\n specifier,\n sourcePath,\n options,\n ts.sys,\n ).resolvedModule;\n if (resolved !== undefined) {\n resolvedPath = normalizePath(resolve(resolved.resolvedFileName));\n }\n if (resolvedPath === undefined || !sourceFilePathSet.has(resolvedPath)) {\n resolvedPath = resolveTsPathAlias(specifier);\n }\n if (resolvedPath === undefined || !sourceFilePathSet.has(resolvedPath)) {\n resolvedPath = resolveWorkspaceSpecifier(specifier);\n }\n resolverCache.set(cacheKey, resolvedPath);\n }\n\n if (resolvedPath === undefined || !sourceFilePathSet.has(resolvedPath)) {\n continue;\n }\n\n const toNode = nodeByAbsolutePath.get(resolvedPath);\n if (toNode === undefined) {\n continue;\n }\n\n edges.push({ from: fromNode.id, to: toNode.id });\n }\n\n const processed = index + 1;\n if (processed === 1 || processed === uniqueSourceFilePaths.length || processed % 50 === 0) {\n onProgress?.({\n stage: \"file_processed\",\n processed,\n total: uniqueSourceFilePaths.length,\n filePath: fromNode.id,\n });\n }\n }\n onProgress?.({ stage: \"edges_resolved\", totalEdges: edges.length });\n\n return {\n nodes: [...nodeByAbsolutePath.values()],\n edges,\n };\n};\n","import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { basename, join, relative, resolve } from \"node:path\";\nimport type { WorkspaceKind, WorkspacePackage } from \"@codesentinel/core\";\n\ntype PackageJsonWorkspaceConfig = {\n name?: string;\n workspaces?: readonly string[] | { packages?: readonly string[] };\n};\n\nconst normalizePath = (pathValue: string): string => pathValue.replaceAll(\"\\\\\", \"/\");\n\nconst stripQuotes = (value: string): string => value.replace(/^['\"]|['\"]$/g, \"\");\n\nconst readPackageJson = (path: string): PackageJsonWorkspaceConfig | null => {\n try {\n return JSON.parse(readFileSync(path, \"utf8\")) as PackageJsonWorkspaceConfig;\n } catch {\n return null;\n }\n};\n\nconst inferWorkspaceKind = (workspacePath: string): WorkspaceKind => {\n const segments = workspacePath.split(\"/\");\n const first = segments[0] ?? \"\";\n\n if (first === \"apps\" || first === \"app\") {\n return \"app\";\n }\n\n if (first === \"packages\" || first === \"package\") {\n return \"package\";\n }\n\n if (first === \"docs\" || first === \"documentation\") {\n return \"docs\";\n }\n\n if (first === \"examples\" || first === \"example-apps\" || first === \"playground\") {\n return \"example\";\n }\n\n if (first === \"tooling\" || first === \"tools\") {\n return \"tooling\";\n }\n\n return \"unknown\";\n};\n\nconst readWorkspacePatternsFromPackageJson = (projectRoot: string): readonly string[] => {\n const packageJson = readPackageJson(join(projectRoot, \"package.json\"));\n if (packageJson?.workspaces === undefined) {\n return [];\n }\n\n const workspaces = packageJson.workspaces;\n if (Array.isArray(workspaces)) {\n const workspaceArray: readonly unknown[] = workspaces;\n return workspaceArray.filter((workspace): workspace is string => typeof workspace === \"string\");\n }\n\n const workspaceObject = workspaces as { packages?: readonly string[] };\n return workspaceObject.packages ?? [];\n};\n\nconst readWorkspacePatternsFromPnpmWorkspace = (projectRoot: string): readonly string[] => {\n const workspacePath = join(projectRoot, \"pnpm-workspace.yaml\");\n if (!existsSync(workspacePath)) {\n return [];\n }\n\n const patterns: string[] = [];\n const lines = readFileSync(workspacePath, \"utf8\").split(\"\\n\");\n let readingPackages = false;\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed.length === 0 || trimmed.startsWith(\"#\")) {\n continue;\n }\n\n if (!line.startsWith(\" \") && !line.startsWith(\"-\")) {\n readingPackages = trimmed === \"packages:\";\n continue;\n }\n\n if (!readingPackages) {\n continue;\n }\n\n const match = trimmed.match(/^-\\s+(.+)$/);\n if (match?.[1] !== undefined) {\n patterns.push(stripQuotes(match[1].trim()));\n }\n }\n\n return patterns;\n};\n\nconst expandPattern = (projectRoot: string, pattern: string): readonly string[] => {\n const segments = normalizePath(pattern)\n .split(\"/\")\n .filter((segment) => segment.length > 0);\n let current = [projectRoot];\n\n for (const segment of segments) {\n const next: string[] = [];\n if (segment === \"*\") {\n for (const directory of current) {\n if (!existsSync(directory)) {\n continue;\n }\n\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n if (entry.isDirectory()) {\n next.push(join(directory, entry.name));\n }\n }\n }\n } else {\n for (const directory of current) {\n const candidate = join(directory, segment);\n if (existsSync(candidate) && statSync(candidate).isDirectory()) {\n next.push(candidate);\n }\n }\n }\n\n current = next;\n }\n\n return current;\n};\n\nexport const discoverWorkspacePackages = (projectRoot: string): readonly WorkspacePackage[] => {\n const absoluteRoot = resolve(projectRoot);\n const packageJsonPatterns = readWorkspacePatternsFromPackageJson(absoluteRoot);\n const pnpmPatterns = readWorkspacePatternsFromPnpmWorkspace(absoluteRoot);\n const patterns = packageJsonPatterns.length > 0 ? packageJsonPatterns : pnpmPatterns;\n const includePatterns = patterns.filter((pattern) => !pattern.startsWith(\"!\"));\n const excludePatterns = patterns\n .filter((pattern) => pattern.startsWith(\"!\"))\n .map((pattern) => pattern.slice(1));\n\n const excludedPaths = new Set(\n excludePatterns\n .flatMap((pattern) => expandPattern(absoluteRoot, pattern))\n .map((path) => normalizePath(relative(absoluteRoot, path))),\n );\n\n const packagesByPath = new Map<string, WorkspacePackage>();\n for (const pattern of includePatterns) {\n for (const absoluteWorkspacePath of expandPattern(absoluteRoot, pattern)) {\n const relativePath = normalizePath(relative(absoluteRoot, absoluteWorkspacePath));\n if (\n relativePath.length === 0 ||\n relativePath.startsWith(\"..\") ||\n excludedPaths.has(relativePath)\n ) {\n continue;\n }\n\n const packageJsonPath = join(absoluteWorkspacePath, \"package.json\");\n if (!existsSync(packageJsonPath)) {\n continue;\n }\n\n const packageJson = readPackageJson(packageJsonPath);\n packagesByPath.set(relativePath, {\n name: packageJson?.name ?? basename(absoluteWorkspacePath),\n path: relativePath,\n kind: inferWorkspaceKind(relativePath),\n });\n }\n }\n\n return [...packagesByPath.values()].sort((a, b) => a.path.localeCompare(b.path));\n};\n","import type { GraphAnalysisSummary } from \"@codesentinel/core\";\nimport { createGraphData } from \"../domain/graph-model.js\";\nimport { createGraphAnalysisSummary } from \"../domain/graph-metrics.js\";\nimport {\n parseTypescriptProject,\n type ParseTypescriptProjectProgressEvent,\n} from \"../infrastructure/typescript-project.js\";\nimport { discoverWorkspacePackages } from \"../infrastructure/workspace-discovery.js\";\n\nexport type BuildProjectGraphSummaryInput = {\n projectPath: string;\n onProgress?: (event: ParseTypescriptProjectProgressEvent) => void;\n};\n\nexport const buildProjectGraphSummary = (\n input: BuildProjectGraphSummaryInput,\n): GraphAnalysisSummary => {\n const workspaces = discoverWorkspacePackages(input.projectPath);\n const parsedProject = parseTypescriptProject(input.projectPath, input.onProgress, workspaces);\n const graphData = createGraphData(parsedProject.nodes, parsedProject.edges);\n return createGraphAnalysisSummary(input.projectPath, graphData, workspaces);\n};\n","import type {\n CouplingMatrix,\n FileAuthorShare,\n FileAuthorChurnShare,\n FileCoupling,\n FileEvolutionMetrics,\n Hotspot,\n RecentActivityPoint,\n RepositoryEvolutionSummary,\n} from \"@codesentinel/core\";\nimport type { EvolutionComputationConfig, GitCommitRecord } from \"./evolution-types.js\";\n\ntype FileAccumulator = {\n commitCount: number;\n recentCommitCount: number;\n lastCommitTimestamp: number | null;\n churnAdded: number;\n churnDeleted: number;\n authorsByCommits: Map<string, number>;\n authorsByChurn: Map<string, { churnAdded: number; churnDeleted: number }>;\n};\n\ntype AuthorProfile = {\n authorId: string;\n commitCount: number;\n primaryName: string;\n emailStem: string | null;\n isBot: boolean;\n};\n\nconst pairKey = (a: string, b: string): string => `${a}\\u0000${b}`;\n\nconst round4 = (value: number): number => Number(value.toFixed(4));\n\nconst dayBucketStart = (value: number): number => Math.floor(value / 86_400) * 86_400;\n\nconst utcDateStringFromBucket = (value: number): string =>\n new Date(value * 1000).toISOString().slice(0, 10);\n\nconst normalizeRatio = (value: number, max: number): number =>\n max <= 0 ? 0 : Math.max(0, Math.min(1, value / max));\n\nconst normalizeName = (value: string): string =>\n value\n .toLowerCase()\n .replace(/[^a-z0-9\\s]/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim();\n\nconst extractEmailStem = (authorId: string): string | null => {\n const normalized = authorId.trim().toLowerCase();\n const githubNoReplyMatch = normalized.match(/^\\d+\\+([^@]+)@users\\.noreply\\.github\\.com$/);\n if (githubNoReplyMatch?.[1] !== undefined) {\n return githubNoReplyMatch[1].replace(/[._+-]/g, \"\");\n }\n\n const atIndex = normalized.indexOf(\"@\");\n if (atIndex <= 0) {\n return null;\n }\n\n return normalized.slice(0, atIndex).replace(/[._+-]/g, \"\");\n};\n\nconst areNamesCompatible = (left: string, right: string): boolean => {\n if (left.length === 0 || right.length === 0) {\n return false;\n }\n\n if (left === right) {\n return true;\n }\n\n if (left.startsWith(`${right} `) || right.startsWith(`${left} `)) {\n return true;\n }\n\n return false;\n};\n\nconst chooseCanonicalAuthorId = (profiles: readonly AuthorProfile[]): string => {\n const ordered = [...profiles].sort((a, b) => {\n const aIsNoReply = a.authorId.includes(\"@users.noreply.github.com\");\n const bIsNoReply = b.authorId.includes(\"@users.noreply.github.com\");\n if (aIsNoReply !== bIsNoReply) {\n return aIsNoReply ? 1 : -1;\n }\n\n if (a.commitCount !== b.commitCount) {\n return b.commitCount - a.commitCount;\n }\n\n return a.authorId.localeCompare(b.authorId);\n });\n\n return ordered[0]?.authorId ?? \"\";\n};\n\nconst buildAuthorAliasMap = (commits: readonly GitCommitRecord[]): ReadonlyMap<string, string> => {\n const nameCountsByAuthorId = new Map<string, Map<string, number>>();\n const commitCountByAuthorId = new Map<string, number>();\n\n for (const commit of commits) {\n commitCountByAuthorId.set(\n commit.authorId,\n (commitCountByAuthorId.get(commit.authorId) ?? 0) + 1,\n );\n\n const normalizedName = normalizeName(commit.authorName);\n const names = nameCountsByAuthorId.get(commit.authorId) ?? new Map<string, number>();\n if (normalizedName.length > 0) {\n names.set(normalizedName, (names.get(normalizedName) ?? 0) + 1);\n }\n nameCountsByAuthorId.set(commit.authorId, names);\n }\n\n const profiles: AuthorProfile[] = [...commitCountByAuthorId.entries()].map(\n ([authorId, commitCount]) => {\n const names = nameCountsByAuthorId.get(authorId);\n const primaryName =\n names === undefined\n ? \"\"\n : ([...names.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0]?.[0] ??\n \"\");\n const normalizedAuthorId = authorId.toLowerCase();\n const isBot = normalizedAuthorId.includes(\"[bot]\");\n\n return {\n authorId,\n commitCount,\n primaryName,\n emailStem: isBot ? null : extractEmailStem(authorId),\n isBot,\n };\n },\n );\n\n const groupsByStem = new Map<string, AuthorProfile[]>();\n for (const profile of profiles) {\n if (profile.emailStem === null || profile.emailStem.length < 4) {\n continue;\n }\n\n const current = groupsByStem.get(profile.emailStem) ?? [];\n current.push(profile);\n groupsByStem.set(profile.emailStem, current);\n }\n\n const aliasMap = new Map<string, string>();\n for (const profile of profiles) {\n aliasMap.set(profile.authorId, profile.authorId);\n }\n\n for (const group of groupsByStem.values()) {\n if (group.length < 2) {\n continue;\n }\n\n const compatible: AuthorProfile[] = [];\n for (const profile of group) {\n if (profile.isBot || profile.primaryName.length === 0) {\n continue;\n }\n\n compatible.push(profile);\n }\n\n if (compatible.length < 2) {\n continue;\n }\n\n const canonical = chooseCanonicalAuthorId(compatible);\n const canonicalProfile = compatible.find((candidate) => candidate.authorId === canonical);\n if (canonicalProfile === undefined) {\n continue;\n }\n\n for (const profile of compatible) {\n if (areNamesCompatible(profile.primaryName, canonicalProfile.primaryName)) {\n aliasMap.set(profile.authorId, canonical);\n }\n }\n }\n\n return aliasMap;\n};\n\nconst computeBusFactor = (\n authorDistribution: readonly { share: number }[],\n threshold: number,\n): number => {\n if (authorDistribution.length === 0) {\n return 0;\n }\n\n let coveredShare = 0;\n for (let i = 0; i < authorDistribution.length; i += 1) {\n const entry = authorDistribution[i];\n if (entry === undefined) {\n continue;\n }\n\n coveredShare += entry.share;\n if (coveredShare >= threshold) {\n return i + 1;\n }\n }\n\n return authorDistribution.length;\n};\n\nconst finalizeAuthorDistribution = (\n authorCommits: ReadonlyMap<string, number>,\n): readonly FileAuthorShare[] => {\n const totalCommits = [...authorCommits.values()].reduce((sum, value) => sum + value, 0);\n if (totalCommits === 0) {\n return [];\n }\n\n return [...authorCommits.entries()]\n .map(([authorId, commits]) => ({\n authorId,\n commits,\n share: round4(commits / totalCommits),\n }))\n .sort((a, b) => b.commits - a.commits || a.authorId.localeCompare(b.authorId));\n};\n\nconst finalizeAuthorChurnDistribution = (\n authorChurn: ReadonlyMap<string, { churnAdded: number; churnDeleted: number }>,\n): readonly FileAuthorChurnShare[] => {\n const entries = [...authorChurn.entries()].map(([authorId, churn]) => {\n const churnAdded = churn.churnAdded;\n const churnDeleted = churn.churnDeleted;\n return {\n authorId,\n churnAdded,\n churnDeleted,\n churnTotal: churnAdded + churnDeleted,\n };\n });\n\n const totalChurn = entries.reduce((sum, entry) => sum + entry.churnTotal, 0);\n if (totalChurn === 0) {\n return [];\n }\n\n return entries\n .map((entry) => ({\n ...entry,\n share: round4(entry.churnTotal / totalChurn),\n }))\n .sort((a, b) => b.churnTotal - a.churnTotal || a.authorId.localeCompare(b.authorId));\n};\n\nconst buildCouplingMatrix = (\n coChangeByPair: ReadonlyMap<string, number>,\n fileCommitCount: ReadonlyMap<string, number>,\n consideredCommits: number,\n skippedLargeCommits: number,\n maxCouplingPairs: number,\n): CouplingMatrix => {\n const allPairs: FileCoupling[] = [];\n\n for (const [key, coChangeCommits] of coChangeByPair.entries()) {\n const [fileA, fileB] = key.split(\"\\u0000\");\n if (fileA === undefined || fileB === undefined) {\n continue;\n }\n\n const fileACommits = fileCommitCount.get(fileA) ?? 0;\n const fileBCommits = fileCommitCount.get(fileB) ?? 0;\n const denominator = fileACommits + fileBCommits - coChangeCommits;\n const couplingScore = denominator === 0 ? 0 : round4(coChangeCommits / denominator);\n\n allPairs.push({\n fileA,\n fileB,\n coChangeCommits,\n couplingScore,\n });\n }\n\n allPairs.sort(\n (a, b) =>\n b.coChangeCommits - a.coChangeCommits ||\n b.couplingScore - a.couplingScore ||\n a.fileA.localeCompare(b.fileA) ||\n a.fileB.localeCompare(b.fileB),\n );\n\n const truncated = allPairs.length > maxCouplingPairs;\n\n return {\n pairs: truncated ? allPairs.slice(0, maxCouplingPairs) : allPairs,\n totalPairCount: allPairs.length,\n consideredCommits,\n skippedLargeCommits,\n truncated,\n };\n};\n\nconst selectHotspots = (\n files: readonly FileEvolutionMetrics[],\n config: EvolutionComputationConfig,\n): { hotspots: readonly Hotspot[]; threshold: number } => {\n if (files.length === 0) {\n return { hotspots: [], threshold: 0 };\n }\n\n const sorted = [...files].sort(\n (a, b) =>\n b.commitCount - a.commitCount ||\n b.churnTotal - a.churnTotal ||\n a.filePath.localeCompare(b.filePath),\n );\n\n const hotspotCount = Math.max(\n config.hotspotMinFiles,\n Math.ceil(sorted.length * config.hotspotTopPercent),\n );\n const selected = sorted.slice(0, hotspotCount);\n\n const hotspots = selected.map((file, index) => ({\n filePath: file.filePath,\n rank: index + 1,\n commitCount: file.commitCount,\n churnTotal: file.churnTotal,\n }));\n\n const threshold = selected[selected.length - 1]?.commitCount ?? 0;\n return { hotspots, threshold };\n};\n\nexport const computeRepositoryEvolutionSummary = (\n targetPath: string,\n commits: readonly GitCommitRecord[],\n config: EvolutionComputationConfig,\n): RepositoryEvolutionSummary => {\n const authorAliasById =\n config.authorIdentityMode === \"likely_merge\"\n ? buildAuthorAliasMap(commits)\n : new Map<string, string>();\n const fileStats = new Map<string, FileAccumulator>();\n const coChangeByPair = new Map<string, number>();\n const recentActivityByDay = new Map<\n number,\n {\n commitCount: number;\n fileTouchCount: number;\n churnTotal: number;\n authors: Set<string>;\n }\n >();\n\n const headCommitTimestamp =\n commits.length === 0 ? null : (commits[commits.length - 1]?.authoredAtUnix ?? null);\n const recentWindowStart =\n headCommitTimestamp === null\n ? Number.NEGATIVE_INFINITY\n : headCommitTimestamp - config.recentWindowDays * 24 * 60 * 60;\n\n let consideredCommits = 0;\n let skippedLargeCommits = 0;\n\n for (const commit of commits) {\n const uniqueFiles = new Set<string>();\n\n for (const fileChange of commit.fileChanges) {\n uniqueFiles.add(fileChange.filePath);\n const current = fileStats.get(fileChange.filePath) ?? {\n commitCount: 0,\n recentCommitCount: 0,\n lastCommitTimestamp: null,\n churnAdded: 0,\n churnDeleted: 0,\n authorsByCommits: new Map<string, number>(),\n authorsByChurn: new Map<string, { churnAdded: number; churnDeleted: number }>(),\n };\n\n current.lastCommitTimestamp =\n current.lastCommitTimestamp === null\n ? commit.authoredAtUnix\n : Math.max(current.lastCommitTimestamp, commit.authoredAtUnix);\n\n current.churnAdded += fileChange.additions;\n current.churnDeleted += fileChange.deletions;\n\n const effectiveAuthorId = authorAliasById.get(commit.authorId) ?? commit.authorId;\n const authorChurn = current.authorsByChurn.get(effectiveAuthorId) ?? {\n churnAdded: 0,\n churnDeleted: 0,\n };\n authorChurn.churnAdded += fileChange.additions;\n authorChurn.churnDeleted += fileChange.deletions;\n current.authorsByChurn.set(effectiveAuthorId, authorChurn);\n\n fileStats.set(fileChange.filePath, current);\n }\n\n for (const filePath of uniqueFiles) {\n const current = fileStats.get(filePath);\n if (current === undefined) {\n continue;\n }\n\n current.commitCount += 1;\n if (commit.authoredAtUnix >= recentWindowStart) {\n current.recentCommitCount += 1;\n }\n\n const effectiveAuthorId = authorAliasById.get(commit.authorId) ?? commit.authorId;\n current.authorsByCommits.set(\n effectiveAuthorId,\n (current.authorsByCommits.get(effectiveAuthorId) ?? 0) + 1,\n );\n }\n\n const orderedFiles = [...uniqueFiles].sort((a, b) => a.localeCompare(b));\n if (commit.authoredAtUnix >= recentWindowStart) {\n const bucketStartTimestamp = dayBucketStart(commit.authoredAtUnix);\n const activity = recentActivityByDay.get(bucketStartTimestamp) ?? {\n commitCount: 0,\n fileTouchCount: 0,\n churnTotal: 0,\n authors: new Set<string>(),\n };\n const effectiveAuthorId = authorAliasById.get(commit.authorId) ?? commit.authorId;\n const commitChurn = commit.fileChanges.reduce(\n (sum, fileChange) => sum + fileChange.additions + fileChange.deletions,\n 0,\n );\n\n activity.commitCount += 1;\n activity.fileTouchCount += uniqueFiles.size;\n activity.churnTotal += commitChurn;\n activity.authors.add(effectiveAuthorId);\n recentActivityByDay.set(bucketStartTimestamp, activity);\n }\n\n if (orderedFiles.length > 1) {\n if (orderedFiles.length <= config.maxFilesPerCommitForCoupling) {\n consideredCommits += 1;\n for (let i = 0; i < orderedFiles.length - 1; i += 1) {\n for (let j = i + 1; j < orderedFiles.length; j += 1) {\n const fileA = orderedFiles[i];\n const fileB = orderedFiles[j];\n if (fileA === undefined || fileB === undefined) {\n continue;\n }\n\n const key = pairKey(fileA, fileB);\n coChangeByPair.set(key, (coChangeByPair.get(key) ?? 0) + 1);\n }\n }\n } else {\n skippedLargeCommits += 1;\n }\n }\n }\n\n const files: FileEvolutionMetrics[] = [...fileStats.entries()]\n .map(([filePath, stats]) => {\n const authorDistributionByCommits = finalizeAuthorDistribution(stats.authorsByCommits);\n const authorDistributionByChurn = finalizeAuthorChurnDistribution(stats.authorsByChurn);\n const topAuthorShareByCommits = authorDistributionByCommits[0]?.share ?? 0;\n const topAuthorShareByChurn = authorDistributionByChurn[0]?.share ?? 0;\n return {\n filePath,\n commitCount: stats.commitCount,\n frequencyPer100Commits:\n commits.length === 0 ? 0 : round4((stats.commitCount / commits.length) * 100),\n churnAdded: stats.churnAdded,\n churnDeleted: stats.churnDeleted,\n churnTotal: stats.churnAdded + stats.churnDeleted,\n lastCommitTimestamp: stats.lastCommitTimestamp,\n recentCommitCount: stats.recentCommitCount,\n recentVolatility:\n stats.commitCount === 0 ? 0 : round4(stats.recentCommitCount / stats.commitCount),\n topAuthorShareByCommits,\n busFactorByCommits: computeBusFactor(\n authorDistributionByCommits,\n config.busFactorCoverageThreshold,\n ),\n authorDistributionByCommits,\n topAuthorShareByChurn,\n busFactorByChurn: computeBusFactor(\n authorDistributionByChurn,\n config.busFactorCoverageThreshold,\n ),\n authorDistributionByChurn,\n };\n })\n .sort((a, b) => a.filePath.localeCompare(b.filePath));\n\n const fileCommitCount = new Map(files.map((file) => [file.filePath, file.commitCount]));\n const coupling = buildCouplingMatrix(\n coChangeByPair,\n fileCommitCount,\n consideredCommits,\n skippedLargeCommits,\n config.maxCouplingPairs,\n );\n\n const { hotspots, threshold } = selectHotspots(files, config);\n const recentActivityBase =\n headCommitTimestamp === null\n ? []\n : Array.from({ length: config.recentWindowDays }, (_, index) => {\n const bucketStartTimestamp =\n dayBucketStart(headCommitTimestamp) - (config.recentWindowDays - 1 - index) * 86_400;\n const activity = recentActivityByDay.get(bucketStartTimestamp);\n return {\n bucketStartUtcDate: utcDateStringFromBucket(bucketStartTimestamp),\n commitCount: activity?.commitCount ?? 0,\n fileTouchCount: activity?.fileTouchCount ?? 0,\n churnTotal: activity?.churnTotal ?? 0,\n activeAuthorCount: activity?.authors.size ?? 0,\n };\n });\n const maxRecentCommitCount = Math.max(1, ...recentActivityBase.map((point) => point.commitCount));\n const maxRecentFileTouches = Math.max(\n 1,\n ...recentActivityBase.map((point) => point.fileTouchCount),\n );\n const maxRecentChurn = Math.max(1, ...recentActivityBase.map((point) => point.churnTotal));\n const maxRecentChurnLog = Math.log1p(maxRecentChurn);\n const recentActivity: RecentActivityPoint[] = recentActivityBase.map((point) => {\n const commitIntensity = normalizeRatio(point.commitCount, maxRecentCommitCount);\n const fileTouchIntensity = normalizeRatio(point.fileTouchCount, maxRecentFileTouches);\n const churnIntensity =\n point.churnTotal <= 0 ? 0 : Math.log1p(point.churnTotal) / maxRecentChurnLog;\n\n return {\n ...point,\n volatilityScore: round4(\n commitIntensity * 0.35 + fileTouchIntensity * 0.2 + churnIntensity * 0.45,\n ),\n };\n });\n\n return {\n targetPath,\n available: true,\n files,\n hotspots,\n coupling,\n recentActivity,\n metrics: {\n totalCommits: commits.length,\n totalFiles: files.length,\n headCommitTimestamp,\n recentWindowDays: config.recentWindowDays,\n hotspotTopPercent: config.hotspotTopPercent,\n hotspotThresholdCommitCount: threshold,\n },\n };\n};\n","export type GitFileChange = {\n filePath: string;\n additions: number;\n deletions: number;\n};\n\nexport type GitCommitRecord = {\n hash: string;\n authorId: string;\n authorName: string;\n authoredAtUnix: number;\n fileChanges: readonly GitFileChange[];\n};\n\nexport type EvolutionComputationConfig = {\n authorIdentityMode: \"likely_merge\" | \"strict_email\";\n recentWindowDays: number;\n hotspotTopPercent: number;\n hotspotMinFiles: number;\n maxFilesPerCommitForCoupling: number;\n maxCouplingPairs: number;\n busFactorCoverageThreshold: number;\n};\n\nexport const DEFAULT_EVOLUTION_CONFIG: EvolutionComputationConfig = {\n authorIdentityMode: \"likely_merge\",\n recentWindowDays: 30,\n hotspotTopPercent: 0.1,\n hotspotMinFiles: 1,\n maxFilesPerCommitForCoupling: 200,\n maxCouplingPairs: 500,\n busFactorCoverageThreshold: 0.6,\n};\n","import type { RepositoryEvolutionSummary } from \"@codesentinel/core\";\nimport { computeRepositoryEvolutionSummary } from \"../domain/evolution-metrics.js\";\nimport {\n DEFAULT_EVOLUTION_CONFIG,\n type EvolutionComputationConfig,\n} from \"../domain/evolution-types.js\";\nimport type { GitHistoryProvider, GitHistoryProgressEvent } from \"./git-history-provider.js\";\n\nexport type AnalyzeRepositoryEvolutionInput = {\n repositoryPath: string;\n config?: Partial<EvolutionComputationConfig>;\n};\n\nexport type EvolutionAnalysisProgressEvent =\n | { stage: \"checking_git_repository\" }\n | { stage: \"not_git_repository\" }\n | { stage: \"loading_commit_history\" }\n | { stage: \"computing_metrics\" }\n | { stage: \"analysis_completed\"; available: boolean }\n | { stage: \"history\"; event: GitHistoryProgressEvent };\n\nconst createEffectiveConfig = (\n overrides: Partial<EvolutionComputationConfig> | undefined,\n): EvolutionComputationConfig => ({\n ...DEFAULT_EVOLUTION_CONFIG,\n ...overrides,\n});\n\nexport const analyzeRepositoryEvolution = (\n input: AnalyzeRepositoryEvolutionInput,\n historyProvider: GitHistoryProvider,\n onProgress?: (event: EvolutionAnalysisProgressEvent) => void,\n): RepositoryEvolutionSummary => {\n onProgress?.({ stage: \"checking_git_repository\" });\n if (!historyProvider.isGitRepository(input.repositoryPath)) {\n onProgress?.({ stage: \"not_git_repository\" });\n return {\n targetPath: input.repositoryPath,\n available: false,\n reason: \"not_git_repository\",\n };\n }\n\n onProgress?.({ stage: \"loading_commit_history\" });\n const commits = historyProvider.getCommitHistory(input.repositoryPath, (event) =>\n onProgress?.({ stage: \"history\", event }),\n );\n const config = createEffectiveConfig(input.config);\n onProgress?.({ stage: \"computing_metrics\" });\n\n const summary = computeRepositoryEvolutionSummary(input.repositoryPath, commits, config);\n onProgress?.({ stage: \"analysis_completed\", available: summary.available });\n return summary;\n};\n","import type {\n GraphAnalysisSummary,\n RepositoryEvolutionSummary,\n WorkspaceEvolutionSummary,\n} from \"@codesentinel/core\";\nimport { createWorkspaceByFile, normalizeWorkspacePath } from \"@codesentinel/core\";\n\nexport const enrichEvolutionSummaryWithWorkspaces = (\n structural: GraphAnalysisSummary,\n evolution: RepositoryEvolutionSummary,\n): RepositoryEvolutionSummary => {\n if (!evolution.available || structural.workspaces === undefined) {\n return evolution;\n }\n\n const workspaces = structural.workspaces;\n const workspaceByFile = createWorkspaceByFile(\n evolution.files.map((file) => normalizeWorkspacePath(file.filePath)),\n workspaces,\n );\n const structuralWorkspacePaths = new Set(workspaces.map((workspace) => workspace.path));\n\n const internalCouplingPairCountByWorkspace = new Map<string, number>();\n const incomingCouplingPairCountByWorkspace = new Map<string, number>();\n const outgoingCouplingPairCountByWorkspace = new Map<string, number>();\n\n for (const pair of evolution.coupling.pairs) {\n const fromWorkspace = workspaceByFile.get(normalizeWorkspacePath(pair.fileA));\n const toWorkspace = workspaceByFile.get(normalizeWorkspacePath(pair.fileB));\n if (fromWorkspace === undefined && toWorkspace === undefined) {\n continue;\n }\n\n if (fromWorkspace?.path === toWorkspace?.path && fromWorkspace !== undefined) {\n internalCouplingPairCountByWorkspace.set(\n fromWorkspace.path,\n (internalCouplingPairCountByWorkspace.get(fromWorkspace.path) ?? 0) + 1,\n );\n continue;\n }\n\n if (fromWorkspace !== undefined) {\n outgoingCouplingPairCountByWorkspace.set(\n fromWorkspace.path,\n (outgoingCouplingPairCountByWorkspace.get(fromWorkspace.path) ?? 0) + 1,\n );\n }\n\n if (toWorkspace !== undefined) {\n incomingCouplingPairCountByWorkspace.set(\n toWorkspace.path,\n (incomingCouplingPairCountByWorkspace.get(toWorkspace.path) ?? 0) + 1,\n );\n }\n }\n\n const workspaceSummaries: WorkspaceEvolutionSummary[] = workspaces\n .filter((workspace) => structuralWorkspacePaths.has(workspace.path))\n .map((workspace) => {\n const files = evolution.files\n .filter(\n (file) =>\n workspaceByFile.get(normalizeWorkspacePath(file.filePath))?.path === workspace.path,\n )\n .sort((a, b) => a.filePath.localeCompare(b.filePath));\n const commitCount = files.reduce((sum, file) => sum + file.commitCount, 0);\n const recentCommitCount = files.reduce((sum, file) => sum + file.recentCommitCount, 0);\n const churnAdded = files.reduce((sum, file) => sum + file.churnAdded, 0);\n const churnDeleted = files.reduce((sum, file) => sum + file.churnDeleted, 0);\n const churnTotal = churnAdded + churnDeleted;\n const topAuthorShareByCommits =\n files.length === 0 ? 0 : Math.max(...files.map((file) => file.topAuthorShareByCommits));\n const busFactorByCommits =\n files.length === 0 ? 0 : Math.min(...files.map((file) => file.busFactorByCommits));\n const topHotspots = evolution.hotspots.filter(\n (hotspot) =>\n workspaceByFile.get(normalizeWorkspacePath(hotspot.filePath))?.path === workspace.path,\n );\n\n return {\n name: workspace.name,\n path: workspace.path,\n kind: workspace.kind,\n fileCount: files.length,\n commitCount,\n churnAdded,\n churnDeleted,\n churnTotal,\n recentCommitCount,\n recentVolatility:\n commitCount === 0 ? 0 : Number((recentCommitCount / commitCount).toFixed(4)),\n topAuthorShareByCommits,\n busFactorByCommits,\n hotspotCount: topHotspots.length,\n topHotspots,\n internalCouplingPairCount: internalCouplingPairCountByWorkspace.get(workspace.path) ?? 0,\n incomingCouplingPairCount: incomingCouplingPairCountByWorkspace.get(workspace.path) ?? 0,\n outgoingCouplingPairCount: outgoingCouplingPairCountByWorkspace.get(workspace.path) ?? 0,\n };\n })\n .sort(\n (a, b) =>\n b.commitCount - a.commitCount ||\n b.churnTotal - a.churnTotal ||\n a.path.localeCompare(b.path),\n );\n\n return {\n ...evolution,\n workspaces: workspaceSummaries,\n };\n};\n","import { execFileSync } from \"node:child_process\";\n\nexport class GitCommandError extends Error {\n readonly args: readonly string[];\n\n constructor(message: string, args: readonly string[]) {\n super(message);\n this.name = \"GitCommandError\";\n this.args = args;\n }\n}\n\nexport interface GitCommandClient {\n run(repositoryPath: string, args: readonly string[]): string;\n}\n\nexport class ExecGitCommandClient implements GitCommandClient {\n run(repositoryPath: string, args: readonly string[]): string {\n try {\n return execFileSync(\"git\", [\"-C\", repositoryPath, ...args], {\n encoding: \"utf8\",\n maxBuffer: 1024 * 1024 * 64,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown git execution error\";\n throw new GitCommandError(message, args);\n }\n }\n}\n","export const COMMIT_RECORD_SEPARATOR = \"\\u001e\";\nexport const COMMIT_FIELD_SEPARATOR = \"\\u001f\";\n\nexport const GIT_LOG_FORMAT = `%x1e%H%x1f%at%x1f%an%x1f%ae`;\n","import type { GitCommitRecord } from \"../domain/evolution-types.js\";\nimport type { ParseGitLogProgressEvent } from \"../parsing/git-log-parser.js\";\n\nexport type GitHistoryProgressEvent =\n | { stage: \"git_log_received\"; bytes: number }\n | { stage: \"git_log_parsed\"; commits: number }\n | { stage: \"git_log_parse_progress\"; parsedRecords: number; totalRecords: number };\n\nexport interface GitHistoryProvider {\n isGitRepository(repositoryPath: string): boolean;\n getCommitHistory(\n repositoryPath: string,\n onProgress?: (event: GitHistoryProgressEvent) => void,\n ): readonly GitCommitRecord[];\n}\n\nexport const mapParseProgressToHistoryProgress = (\n event: ParseGitLogProgressEvent,\n): GitHistoryProgressEvent => ({\n stage: \"git_log_parse_progress\",\n parsedRecords: event.parsedRecords,\n totalRecords: event.totalRecords,\n});\n","import { COMMIT_FIELD_SEPARATOR, COMMIT_RECORD_SEPARATOR } from \"../domain/git-log-format.js\";\nimport type { GitCommitRecord, GitFileChange } from \"../domain/evolution-types.js\";\n\nexport type ParseGitLogProgressEvent = {\n parsedRecords: number;\n totalRecords: number;\n};\n\nconst parseInteger = (value: string): number | null => {\n if (value.length === 0) {\n return null;\n }\n\n const parsed = Number.parseInt(value, 10);\n if (Number.isNaN(parsed)) {\n return null;\n }\n\n return parsed;\n};\n\nconst normalizeAuthorIdentity = (authorName: string, authorEmail: string): string => {\n const normalizedName = authorName.trim().replace(/\\s+/g, \" \").toLowerCase();\n const normalizedEmail = authorEmail.trim().toLowerCase();\n\n if (/\\[bot\\]/i.test(normalizedName) || /\\[bot\\]/i.test(normalizedEmail)) {\n return normalizedEmail.length > 0 ? normalizedEmail : normalizedName;\n }\n\n const githubNoReplyMatch = normalizedEmail.match(/^\\d+\\+([^@]+)@users\\.noreply\\.github\\.com$/);\n const githubHandle = githubNoReplyMatch?.[1]?.trim().toLowerCase();\n if (githubHandle !== undefined && githubHandle.length > 0) {\n return `${githubHandle}@users.noreply.github.com`;\n }\n\n if (normalizedEmail.length > 0) {\n return normalizedEmail;\n }\n\n return normalizedName;\n};\n\nconst parseRenamedPath = (pathSpec: string): string => {\n if (!pathSpec.includes(\" => \")) {\n return pathSpec;\n }\n\n const braceRenameMatch = pathSpec.match(/^(.*)\\{(.+) => (.+)\\}(.*)$/);\n if (braceRenameMatch !== null) {\n const [, prefix, , renamedTo, suffix] = braceRenameMatch;\n return `${prefix}${renamedTo}${suffix}`;\n }\n\n const parts = pathSpec.split(\" => \");\n const finalPart = parts[parts.length - 1];\n return finalPart ?? pathSpec;\n};\n\nconst parseNumstatLine = (line: string): GitFileChange | null => {\n const parts = line.split(\"\\t\");\n if (parts.length < 3) {\n return null;\n }\n\n const additionsRaw = parts[0];\n const deletionsRaw = parts[1];\n const pathRaw = parts.slice(2).join(\"\\t\");\n\n if (additionsRaw === undefined || deletionsRaw === undefined) {\n return null;\n }\n\n const additions = additionsRaw === \"-\" ? 0 : parseInteger(additionsRaw);\n const deletions = deletionsRaw === \"-\" ? 0 : parseInteger(deletionsRaw);\n\n if (additions === null || deletions === null) {\n return null;\n }\n\n const filePath = parseRenamedPath(pathRaw);\n return {\n filePath,\n additions,\n deletions,\n };\n};\n\nexport const parseGitLog = (\n rawLog: string,\n onProgress?: (event: ParseGitLogProgressEvent) => void,\n): readonly GitCommitRecord[] => {\n const records = rawLog\n .split(COMMIT_RECORD_SEPARATOR)\n .map((record) => record.trim())\n .filter((record) => record.length > 0);\n\n const commits: GitCommitRecord[] = [];\n\n for (const [index, record] of records.entries()) {\n const lines = record\n .split(\"\\n\")\n .map((line) => line.trimEnd())\n .filter((line) => line.length > 0);\n\n if (lines.length === 0) {\n continue;\n }\n\n const headerParts = lines[0]?.split(COMMIT_FIELD_SEPARATOR) ?? [];\n if (headerParts.length !== 4) {\n continue;\n }\n\n const [hash, authoredAtRaw, authorName, authorEmail] = headerParts;\n if (\n hash === undefined ||\n authoredAtRaw === undefined ||\n authorName === undefined ||\n authorEmail === undefined\n ) {\n continue;\n }\n\n const authoredAtUnix = parseInteger(authoredAtRaw);\n if (authoredAtUnix === null) {\n continue;\n }\n\n const fileChanges: GitFileChange[] = [];\n for (const line of lines.slice(1)) {\n const parsedLine = parseNumstatLine(line);\n if (parsedLine !== null) {\n fileChanges.push(parsedLine);\n }\n }\n\n commits.push({\n hash,\n authorId: normalizeAuthorIdentity(authorName, authorEmail),\n authorName,\n authoredAtUnix,\n fileChanges,\n });\n\n const parsedRecords = index + 1;\n if (parsedRecords === 1 || parsedRecords === records.length || parsedRecords % 500 === 0) {\n onProgress?.({ parsedRecords, totalRecords: records.length });\n }\n }\n\n commits.sort((a, b) => a.authoredAtUnix - b.authoredAtUnix || a.hash.localeCompare(b.hash));\n return commits;\n};\n","import { GIT_LOG_FORMAT } from \"../domain/git-log-format.js\";\nimport type { GitCommitRecord } from \"../domain/evolution-types.js\";\nimport {\n mapParseProgressToHistoryProgress,\n type GitHistoryProvider,\n type GitHistoryProgressEvent,\n} from \"../application/git-history-provider.js\";\nimport { GitCommandError, type GitCommandClient } from \"./git-command-client.js\";\nimport { parseGitLog } from \"../parsing/git-log-parser.js\";\n\nconst NON_GIT_CODES = [\"not a git repository\", \"not in a git directory\"];\n\nconst isNotGitError = (error: GitCommandError): boolean => {\n const lower = error.message.toLowerCase();\n return NON_GIT_CODES.some((code) => lower.includes(code));\n};\n\nexport class GitCliHistoryProvider implements GitHistoryProvider {\n constructor(private readonly gitClient: GitCommandClient) {}\n\n isGitRepository(repositoryPath: string): boolean {\n try {\n const output = this.gitClient.run(repositoryPath, [\"rev-parse\", \"--is-inside-work-tree\"]);\n return output.trim() === \"true\";\n } catch (error) {\n if (error instanceof GitCommandError && isNotGitError(error)) {\n return false;\n }\n\n throw error;\n }\n }\n\n getCommitHistory(\n repositoryPath: string,\n onProgress?: (event: GitHistoryProgressEvent) => void,\n ): readonly GitCommitRecord[] {\n const output = this.gitClient.run(repositoryPath, [\n \"-c\",\n \"core.quotepath=false\",\n \"log\",\n \"--use-mailmap\",\n \"--no-merges\",\n \"--date=unix\",\n `--pretty=format:${GIT_LOG_FORMAT}`,\n \"--numstat\",\n \"--find-renames\",\n ]);\n onProgress?.({ stage: \"git_log_received\", bytes: Buffer.byteLength(output, \"utf8\") });\n const commits = parseGitLog(output, (event) =>\n onProgress?.(mapParseProgressToHistoryProgress(event)),\n );\n onProgress?.({ stage: \"git_log_parsed\", commits: commits.length });\n return commits;\n }\n}\n","import type { RepositoryEvolutionSummary } from \"@codesentinel/core\";\nimport {\n analyzeRepositoryEvolution,\n type EvolutionAnalysisProgressEvent,\n type AnalyzeRepositoryEvolutionInput,\n} from \"./application/analyze-repository-evolution.js\";\nexport { enrichEvolutionSummaryWithWorkspaces } from \"./application/enrich-evolution-with-workspaces.js\";\nimport { ExecGitCommandClient } from \"./infrastructure/git-command-client.js\";\nimport { GitCliHistoryProvider } from \"./infrastructure/git-history-provider.js\";\n\nexport type { AnalyzeRepositoryEvolutionInput } from \"./application/analyze-repository-evolution.js\";\nexport type { EvolutionAnalysisProgressEvent } from \"./application/analyze-repository-evolution.js\";\n\nexport const analyzeRepositoryEvolutionFromGit = (\n input: AnalyzeRepositoryEvolutionInput,\n onProgress?: (event: EvolutionAnalysisProgressEvent) => void,\n): RepositoryEvolutionSummary => {\n const historyProvider = new GitCliHistoryProvider(new ExecGitCommandClient());\n return analyzeRepositoryEvolution(input, historyProvider, onProgress);\n};\n","export const clamp01 = (value: number): number => {\n if (!Number.isFinite(value)) {\n return 0;\n }\n if (value <= 0) {\n return 0;\n }\n if (value >= 1) {\n return 1;\n }\n return value;\n};\n\nexport const round4 = (value: number): number => Number(value.toFixed(4));\n\nexport const average = (values: readonly number[]): number => {\n if (values.length === 0) {\n return 0;\n }\n\n const total = values.reduce((sum, value) => sum + value, 0);\n return total / values.length;\n};\n\nexport const concentration = (rawValues: readonly number[]): number => {\n const values = rawValues.filter((value) => value > 0);\n const count = values.length;\n if (count <= 1) {\n return 0;\n }\n\n const total = values.reduce((sum, value) => sum + value, 0);\n if (total <= 0) {\n return 0;\n }\n\n const hhi = values.reduce((sum, value) => {\n const share = value / total;\n return sum + share * share;\n }, 0);\n\n const minHhi = 1 / count;\n const normalized = (hhi - minHhi) / (1 - minHhi);\n return clamp01(normalized);\n};\n","import type {\n GraphAnalysisSummary,\n HealthDimension,\n HealthDimensionTrace,\n HealthEvidenceRef,\n HealthFactorTrace,\n HealthIssue,\n RepositoryEvolutionSummary,\n RepositoryHealthSummary,\n} from \"@codesentinel/core\";\nimport { average, clamp01, concentration, round4 } from \"../domain/math.js\";\n\nexport type ComputeRepositoryHealthSummaryInput = {\n structural: GraphAnalysisSummary;\n evolution: RepositoryEvolutionSummary;\n config?: HealthEngineConfig;\n};\n\nexport type HealthEngineConfig = {\n ownershipPenaltyMultiplier?: number;\n};\n\ntype HealthIssueWithImpact = HealthIssue & {\n impact: number;\n};\n\ntype FactorSpec = {\n factorId: string;\n penalty: number;\n rawMetrics: Readonly<Record<string, number | null>>;\n normalizedMetrics: Readonly<Record<string, number | null>>;\n weight: number;\n evidence: readonly HealthEvidenceRef[];\n};\n\nconst DIMENSION_WEIGHTS: Readonly<Record<HealthDimension, number>> = {\n modularity: 0.35,\n changeHygiene: 0.3,\n testHealth: 0.2,\n ownershipDistribution: 0.15,\n};\n\nconst HEALTH_TRACE_VERSION = \"1\" as const;\n\nconst toPercentage = (normalizedHealth: number): number => round4(clamp01(normalizedHealth) * 100);\n\nconst dampenForSmallSamples = (\n penalty: number,\n sampleSize: number,\n warmupSize: number,\n minimumWeight = 0.35,\n): number => {\n const reliability = clamp01(sampleSize / Math.max(1, warmupSize));\n const dampeningWeight = minimumWeight + (1 - minimumWeight) * reliability;\n return clamp01(penalty) * dampeningWeight;\n};\n\nconst topPercentShare = (values: readonly number[], fraction: number): number => {\n const positive = values.filter((value) => value > 0).sort((a, b) => b - a);\n if (positive.length === 0) {\n return 0;\n }\n\n const topCount = Math.max(1, Math.ceil(positive.length * clamp01(fraction)));\n const total = positive.reduce((sum, value) => sum + value, 0);\n const topTotal = positive.slice(0, topCount).reduce((sum, value) => sum + value, 0);\n if (total <= 0) {\n return 0;\n }\n\n return clamp01(topTotal / total);\n};\n\nconst normalizedEntropy = (weights: readonly number[]): number => {\n const positive = weights.filter((value) => value > 0);\n if (positive.length <= 1) {\n return 0;\n }\n\n const total = positive.reduce((sum, value) => sum + value, 0);\n if (total <= 0) {\n return 0;\n }\n\n const entropy = positive.reduce((sum, value) => {\n const p = value / total;\n return sum - p * Math.log(p);\n }, 0);\n return clamp01(entropy / Math.log(positive.length));\n};\n\nconst toFactorTrace = (spec: FactorSpec): HealthFactorTrace => ({\n factorId: spec.factorId,\n contribution: round4(spec.penalty * spec.weight * 100),\n penalty: round4(spec.penalty),\n rawMetrics: spec.rawMetrics,\n normalizedMetrics: spec.normalizedMetrics,\n weight: round4(spec.weight),\n evidence: spec.evidence,\n});\n\nconst createDimensionTrace = (\n dimension: HealthDimension,\n health: number,\n factors: readonly FactorSpec[],\n): HealthDimensionTrace => ({\n dimension,\n normalizedScore: round4(clamp01(health)),\n score: toPercentage(health),\n factors: factors.map((factor) => toFactorTrace(factor)),\n});\n\nconst filePaths = (structural: GraphAnalysisSummary): readonly string[] =>\n structural.files.map((file) => file.relativePath);\n\nconst normalizePath = (value: string): string => value.replaceAll(\"\\\\\", \"/\").toLowerCase();\n\nconst isTestPath = (path: string): boolean => {\n const normalized = normalizePath(path);\n return (\n normalized.includes(\"/__tests__/\") ||\n normalized.includes(\"/tests/\") ||\n normalized.includes(\"/test/\") ||\n normalized.includes(\".test.\") ||\n normalized.includes(\".spec.\")\n );\n};\n\nconst isSourcePath = (path: string): boolean => {\n if (path.endsWith(\".d.ts\")) {\n return false;\n }\n return !isTestPath(path);\n};\n\nconst hasTestDirectory = (paths: readonly string[]): boolean =>\n paths.some((path) => {\n const normalized = normalizePath(path);\n return (\n normalized.includes(\"/__tests__/\") ||\n normalized.includes(\"/tests/\") ||\n normalized.includes(\"/test/\")\n );\n });\n\nconst moduleNameFromPath = (path: string): string => {\n const normalized = path.replaceAll(\"\\\\\", \"/\");\n const firstSegment = normalized.split(\"/\")[0] ?? normalized;\n return firstSegment.length === 0 ? normalized : firstSegment;\n};\n\nconst pushIssue = (\n issues: HealthIssueWithImpact[],\n issue: Omit<HealthIssueWithImpact, \"severity\"> & { severity?: HealthIssue[\"severity\"] },\n): void => {\n issues.push({\n ...issue,\n severity: issue.severity ?? \"warn\",\n });\n};\n\nconst weightedPenalty = (factors: readonly FactorSpec[]): number =>\n clamp01(factors.reduce((sum, factor) => sum + factor.penalty * factor.weight, 0));\n\nexport const computeRepositoryHealthSummary = (\n input: ComputeRepositoryHealthSummaryInput,\n): RepositoryHealthSummary => {\n const ownershipPenaltyMultiplier = clamp01(input.config?.ownershipPenaltyMultiplier ?? 1);\n const issues: HealthIssueWithImpact[] = [];\n const sourceFileSet = new Set(input.structural.files.map((file) => file.relativePath));\n\n const sourceFileCount = Math.max(1, input.structural.files.length);\n const structuralEdges = input.structural.edges;\n\n const cycleSets = input.structural.cycles\n .map((cycle) => new Set(cycle.nodes))\n .filter((set) => set.size >= 2);\n\n const cycleNodeSet = new Set<string>();\n for (const cycleSet of cycleSets) {\n for (const node of cycleSet) {\n cycleNodeSet.add(node);\n }\n }\n\n const edgesInsideCycles = structuralEdges.filter((edge) =>\n cycleSets.some((cycleSet) => cycleSet.has(edge.from) && cycleSet.has(edge.to)),\n ).length;\n\n const cycleEdgeRatio =\n structuralEdges.length === 0 ? 0 : clamp01(edgesInsideCycles / structuralEdges.length);\n const cycleNodeRatio = clamp01(cycleNodeSet.size / sourceFileCount);\n const cycleDensityPenalty = clamp01(\n clamp01(cycleEdgeRatio / 0.2) * 0.75 + clamp01(cycleNodeRatio / 0.35) * 0.25,\n );\n\n const fanInConcentration = concentration(input.structural.files.map((file) => file.fanIn));\n const fanOutConcentration = concentration(input.structural.files.map((file) => file.fanOut));\n const fanConcentration = average([fanInConcentration, fanOutConcentration]);\n\n const centralityPressure = input.structural.files.map((file) => file.fanIn + file.fanOut);\n const centralityConcentration = concentration(centralityPressure);\n\n let structuralHotspotOverlap = 0;\n if (input.evolution.available) {\n const evolutionSourceFiles = input.evolution.files.filter((file) =>\n sourceFileSet.has(file.filePath),\n );\n const topStructuralCount = Math.max(1, Math.ceil(sourceFileCount * 0.1));\n const topChangeCount = Math.max(1, Math.ceil(Math.max(1, evolutionSourceFiles.length) * 0.1));\n\n const topStructural = new Set(\n [...input.structural.files]\n .map((file) => ({\n filePath: file.relativePath,\n pressure: file.fanIn + file.fanOut,\n }))\n .sort((a, b) => b.pressure - a.pressure || a.filePath.localeCompare(b.filePath))\n .slice(0, topStructuralCount)\n .map((item) => item.filePath),\n );\n\n const topChange = new Set(\n [...evolutionSourceFiles]\n .sort((a, b) => b.churnTotal - a.churnTotal || a.filePath.localeCompare(b.filePath))\n .slice(0, topChangeCount)\n .map((item) => item.filePath),\n );\n\n const overlapCount = [...topStructural].filter((filePath) => topChange.has(filePath)).length;\n structuralHotspotOverlap =\n topStructural.size === 0 || topChange.size === 0\n ? 0\n : clamp01(overlapCount / Math.min(topStructural.size, topChange.size));\n }\n\n const modularityFactors: readonly FactorSpec[] = [\n {\n factorId: \"health.modularity.cycle_density\",\n penalty: cycleDensityPenalty,\n rawMetrics: {\n cycleCount: input.structural.metrics.cycleCount,\n cycleEdgeRatio: round4(cycleEdgeRatio),\n cycleNodeRatio: round4(cycleNodeRatio),\n },\n normalizedMetrics: {\n cycleDensityPenalty: round4(cycleDensityPenalty),\n },\n weight: 0.4,\n evidence: [{ kind: \"repository_metric\", metric: \"structural.cycleEdgeRatio\" }],\n },\n {\n factorId: \"health.modularity.fan_concentration\",\n penalty: fanConcentration,\n rawMetrics: {\n fanInConcentration: round4(fanInConcentration),\n fanOutConcentration: round4(fanOutConcentration),\n },\n normalizedMetrics: {\n fanConcentration: round4(fanConcentration),\n },\n weight: 0.25,\n evidence: [{ kind: \"repository_metric\", metric: \"structural.files.fanIn/fanOut\" }],\n },\n {\n factorId: \"health.modularity.centrality_concentration\",\n penalty: centralityConcentration,\n rawMetrics: {\n centralityConcentration: round4(centralityConcentration),\n },\n normalizedMetrics: {\n centralityConcentration: round4(centralityConcentration),\n },\n weight: 0.2,\n evidence: [{ kind: \"repository_metric\", metric: \"structural.centralityPressure\" }],\n },\n {\n factorId: \"health.modularity.hotspot_overlap\",\n penalty: structuralHotspotOverlap,\n rawMetrics: {\n structuralHotspotOverlap: round4(structuralHotspotOverlap),\n },\n normalizedMetrics: {\n structuralHotspotOverlap: round4(structuralHotspotOverlap),\n },\n weight: 0.15,\n evidence: [{ kind: \"repository_metric\", metric: \"structural.evolution.hotspotOverlap\" }],\n },\n ];\n\n const modularityPenalty = dampenForSmallSamples(\n weightedPenalty(modularityFactors),\n sourceFileCount,\n 8,\n 0.45,\n );\n\n if (cycleDensityPenalty >= 0.35) {\n const firstCycle = input.structural.cycles[0];\n pushIssue(issues, {\n id: \"health.modularity.cycle_density\",\n ruleId: \"graph.cycle_density\",\n signal: \"structural.cycleEdgeRatio\",\n dimension: \"modularity\",\n target:\n firstCycle?.nodes\n .slice()\n .sort((a, b) => a.localeCompare(b))\n .join(\" -> \") ?? input.structural.targetPath,\n message:\n \"Dependencies inside cycles consume a high share of graph edges, reducing refactor flexibility.\",\n severity: cycleDensityPenalty >= 0.7 ? \"error\" : \"warn\",\n evidenceMetrics: {\n cycleCount: input.structural.metrics.cycleCount,\n cycleEdgeRatio: round4(cycleEdgeRatio),\n cycleNodeRatio: round4(cycleNodeRatio),\n },\n impact: round4(modularityPenalty * 0.35),\n });\n }\n\n if (centralityConcentration >= 0.5) {\n const hottest = [...input.structural.files]\n .map((file) => ({\n path: file.relativePath,\n pressure: file.fanIn + file.fanOut,\n }))\n .sort((a, b) => b.pressure - a.pressure || a.path.localeCompare(b.path))[0];\n\n pushIssue(issues, {\n id: \"health.modularity.centrality_concentration\",\n ruleId: \"graph.centrality_concentration\",\n signal: \"structural.centralityPressure\",\n dimension: \"modularity\",\n target: hottest?.path ?? input.structural.targetPath,\n message:\n \"Dependency flow is concentrated in a narrow set of files, creating architectural bottlenecks.\",\n evidenceMetrics: {\n fanConcentration: round4(fanConcentration),\n centralityConcentration: round4(centralityConcentration),\n },\n impact: round4(modularityPenalty * 0.25),\n });\n }\n\n if (structuralHotspotOverlap >= 0.5) {\n pushIssue(issues, {\n id: \"health.modularity.hotspot_overlap\",\n ruleId: \"graph.hotspot_overlap\",\n signal: \"structural.evolution.hotspotOverlap\",\n dimension: \"modularity\",\n target: input.structural.targetPath,\n message:\n \"Structural hubs overlap with top churn hotspots, making change pressure harder to isolate.\",\n evidenceMetrics: {\n structuralHotspotOverlap: round4(structuralHotspotOverlap),\n },\n impact: round4(modularityPenalty * 0.2),\n });\n }\n\n let churnConcentrationPenalty = 0;\n let volatilityConcentrationPenalty = 0;\n let coChangeClusterPenalty = 0;\n let top10PercentFilesChurnShare = 0;\n let top10PercentFilesVolatilityShare = 0;\n let denseCoChangePairRatio = 0;\n\n if (input.evolution.available) {\n const evolutionSourceFiles = input.evolution.files.filter((file) =>\n sourceFileSet.has(file.filePath),\n );\n const evolutionFileCount = evolutionSourceFiles.length;\n\n top10PercentFilesChurnShare = topPercentShare(\n evolutionSourceFiles.map((file) => file.churnTotal),\n 0.1,\n );\n top10PercentFilesVolatilityShare = topPercentShare(\n evolutionSourceFiles.map((file) => file.recentVolatility),\n 0.1,\n );\n\n const sourcePairs = input.evolution.coupling.pairs.filter(\n (pair) => sourceFileSet.has(pair.fileA) && sourceFileSet.has(pair.fileB),\n );\n const maxPairs = (evolutionFileCount * (evolutionFileCount - 1)) / 2;\n const densePairs = sourcePairs.filter((pair) => pair.couplingScore >= 0.55);\n denseCoChangePairRatio = maxPairs <= 0 ? 0 : clamp01(densePairs.length / maxPairs);\n const couplingScoreConcentration = concentration(sourcePairs.map((pair) => pair.couplingScore));\n\n churnConcentrationPenalty = dampenForSmallSamples(\n clamp01((top10PercentFilesChurnShare - 0.35) / 0.55),\n evolutionFileCount,\n 12,\n 0.3,\n );\n volatilityConcentrationPenalty = dampenForSmallSamples(\n clamp01((top10PercentFilesVolatilityShare - 0.35) / 0.55),\n evolutionFileCount,\n 12,\n 0.3,\n );\n\n const coChangeRaw = average([\n clamp01(denseCoChangePairRatio / 0.2),\n couplingScoreConcentration,\n ]);\n coChangeClusterPenalty = dampenForSmallSamples(coChangeRaw, sourcePairs.length, 20, 0.35);\n\n if (churnConcentrationPenalty >= 0.35) {\n const mostChurn = [...evolutionSourceFiles].sort(\n (a, b) => b.churnTotal - a.churnTotal || a.filePath.localeCompare(b.filePath),\n )[0];\n pushIssue(issues, {\n id: \"health.change_hygiene.churn_concentration\",\n ruleId: \"git.churn_distribution\",\n signal: \"evolution.top10PercentFilesChurnShare\",\n dimension: \"changeHygiene\",\n target: mostChurn?.filePath ?? input.structural.targetPath,\n message: \"A small slice of files carries most churn, reducing change predictability.\",\n evidenceMetrics: {\n top10PercentFilesChurnShare: round4(top10PercentFilesChurnShare),\n },\n impact: round4(churnConcentrationPenalty * 0.4),\n });\n }\n\n if (volatilityConcentrationPenalty >= 0.35) {\n const volatileFile = [...evolutionSourceFiles].sort(\n (a, b) => b.recentVolatility - a.recentVolatility || a.filePath.localeCompare(b.filePath),\n )[0];\n pushIssue(issues, {\n id: \"health.change_hygiene.volatility_concentration\",\n ruleId: \"git.volatility_distribution\",\n signal: \"evolution.top10PercentFilesVolatilityShare\",\n dimension: \"changeHygiene\",\n target: volatileFile?.filePath ?? input.structural.targetPath,\n message: \"Recent volatility is concentrated, increasing review and release uncertainty.\",\n evidenceMetrics: {\n top10PercentFilesVolatilityShare: round4(top10PercentFilesVolatilityShare),\n },\n impact: round4(volatilityConcentrationPenalty * 0.3),\n });\n }\n\n if (coChangeClusterPenalty >= 0.35) {\n const strongestPair = [...sourcePairs].sort(\n (a, b) =>\n b.couplingScore - a.couplingScore ||\n `${a.fileA}|${a.fileB}`.localeCompare(`${b.fileA}|${b.fileB}`),\n )[0];\n\n pushIssue(issues, {\n id: \"health.change_hygiene.dense_co_change_clusters\",\n ruleId: \"git.co_change_clusters\",\n signal: \"evolution.denseCoChangePairRatio\",\n dimension: \"changeHygiene\",\n target:\n strongestPair === undefined\n ? input.structural.targetPath\n : `${strongestPair.fileA}<->${strongestPair.fileB}`,\n message: \"Dense co-change clusters suggest wider coordination scope per change.\",\n evidenceMetrics: {\n denseCoChangePairRatio: round4(denseCoChangePairRatio),\n },\n impact: round4(coChangeClusterPenalty * 0.3),\n });\n }\n }\n\n const changeHygieneFactors: readonly FactorSpec[] = [\n {\n factorId: \"health.change_hygiene.churn_concentration\",\n penalty: churnConcentrationPenalty,\n rawMetrics: {\n top10PercentFilesChurnShare: round4(top10PercentFilesChurnShare),\n },\n normalizedMetrics: {\n churnConcentrationPenalty: round4(churnConcentrationPenalty),\n },\n weight: 0.4,\n evidence: [{ kind: \"repository_metric\", metric: \"evolution.top10PercentFilesChurnShare\" }],\n },\n {\n factorId: \"health.change_hygiene.volatility_concentration\",\n penalty: volatilityConcentrationPenalty,\n rawMetrics: {\n top10PercentFilesVolatilityShare: round4(top10PercentFilesVolatilityShare),\n },\n normalizedMetrics: {\n volatilityConcentrationPenalty: round4(volatilityConcentrationPenalty),\n },\n weight: 0.3,\n evidence: [\n {\n kind: \"repository_metric\",\n metric: \"evolution.top10PercentFilesVolatilityShare\",\n },\n ],\n },\n {\n factorId: \"health.change_hygiene.dense_co_change_clusters\",\n penalty: coChangeClusterPenalty,\n rawMetrics: {\n denseCoChangePairRatio: round4(denseCoChangePairRatio),\n },\n normalizedMetrics: {\n coChangeClusterPenalty: round4(coChangeClusterPenalty),\n },\n weight: 0.3,\n evidence: [{ kind: \"repository_metric\", metric: \"evolution.denseCoChangePairRatio\" }],\n },\n ];\n\n const changeHygienePenalty = input.evolution.available\n ? weightedPenalty(changeHygieneFactors)\n : 0.12;\n\n const paths = filePaths(input.structural);\n const testFiles = paths.filter((path) => isTestPath(path)).length;\n const sourceFiles = paths.filter((path) => isSourcePath(path)).length;\n const testRatio = sourceFiles <= 0 ? 1 : testFiles / sourceFiles;\n const testingDirectoryPresent = hasTestDirectory(paths);\n\n const testPresencePenalty = sourceFiles <= 0 ? 0 : testFiles === 0 ? 1 : 0;\n const testRatioPenalty = sourceFiles <= 0 ? 0 : 1 - clamp01(testRatio / 0.25);\n const testingDirectoryPenalty = sourceFiles <= 0 ? 0 : testingDirectoryPresent ? 0 : 0.35;\n\n const testHealthFactors: readonly FactorSpec[] = [\n {\n factorId: \"health.test_health.test_file_presence\",\n penalty: testPresencePenalty,\n rawMetrics: {\n sourceFiles,\n testFiles,\n },\n normalizedMetrics: {\n testPresencePenalty: round4(testPresencePenalty),\n },\n weight: 0.4,\n evidence: [{ kind: \"repository_metric\", metric: \"tests.filePresence\" }],\n },\n {\n factorId: \"health.test_health.test_to_source_ratio\",\n penalty: testRatioPenalty,\n rawMetrics: {\n testToSourceRatio: round4(testRatio),\n },\n normalizedMetrics: {\n testRatioPenalty: round4(testRatioPenalty),\n },\n weight: 0.45,\n evidence: [{ kind: \"repository_metric\", metric: \"tests.testToSourceRatio\" }],\n },\n {\n factorId: \"health.test_health.testing_directory_presence\",\n penalty: testingDirectoryPenalty,\n rawMetrics: {\n testingDirectoryPresent: testingDirectoryPresent ? 1 : 0,\n },\n normalizedMetrics: {\n testingDirectoryPenalty: round4(testingDirectoryPenalty),\n },\n weight: 0.15,\n evidence: [{ kind: \"repository_metric\", metric: \"tests.directoryPresence\" }],\n },\n ];\n\n const testHealthPenalty = dampenForSmallSamples(\n weightedPenalty(testHealthFactors),\n sourceFiles,\n 10,\n 0.3,\n );\n\n if (sourceFiles > 0 && testFiles === 0) {\n pushIssue(issues, {\n id: \"health.test_health.low_test_presence\",\n ruleId: \"tests.file_presence\",\n signal: \"tests.filePresence\",\n dimension: \"testHealth\",\n target: input.structural.targetPath,\n message: `No test files detected for ${sourceFiles} source file(s).`,\n severity: sourceFiles >= 12 ? \"error\" : \"warn\",\n evidenceMetrics: {\n sourceFiles,\n testFiles,\n testToSourceRatio: round4(testRatio),\n },\n impact: round4(testHealthPenalty * 0.45),\n });\n }\n\n if (sourceFiles > 0 && testRatio < 0.12) {\n pushIssue(issues, {\n id: \"health.test_health.low_test_ratio\",\n ruleId: \"tests.ratio\",\n signal: \"tests.testToSourceRatio\",\n dimension: \"testHealth\",\n target: input.structural.targetPath,\n message: \"Test-to-source ratio is low; long-term change confidence may degrade.\",\n evidenceMetrics: {\n sourceFiles,\n testFiles,\n testToSourceRatio: round4(testRatio),\n },\n impact: round4(testHealthPenalty * 0.35),\n });\n }\n\n if (input.evolution.available) {\n const evolutionSourceFiles = input.evolution.files.filter((file) =>\n sourceFileSet.has(file.filePath),\n );\n const authorTotals = new Map<string, number>();\n const moduleTotals = new Map<string, number>();\n const moduleAuthors = new Map<string, Map<string, number>>();\n\n let singleContributorFiles = 0;\n let trackedFiles = 0;\n\n for (const file of evolutionSourceFiles) {\n if (file.commitCount <= 0 || file.authorDistributionByCommits.length === 0) {\n continue;\n }\n\n trackedFiles += 1;\n const dominantShare = clamp01(file.authorDistributionByCommits[0]?.share ?? 0);\n if (file.authorDistributionByCommits.length === 1 || dominantShare >= 0.9) {\n singleContributorFiles += 1;\n }\n\n for (const author of file.authorDistributionByCommits) {\n const commits = Math.max(0, author.commits);\n if (commits <= 0) {\n continue;\n }\n\n const moduleName = moduleNameFromPath(file.filePath);\n const moduleAuthorTotals = moduleAuthors.get(moduleName) ?? new Map<string, number>();\n if (moduleAuthors.has(moduleName) === false) {\n moduleAuthors.set(moduleName, moduleAuthorTotals);\n }\n\n authorTotals.set(author.authorId, (authorTotals.get(author.authorId) ?? 0) + commits);\n moduleTotals.set(moduleName, (moduleTotals.get(moduleName) ?? 0) + commits);\n moduleAuthorTotals.set(\n author.authorId,\n (moduleAuthorTotals.get(author.authorId) ?? 0) + commits,\n );\n }\n }\n\n const totalAuthorCommits = [...authorTotals.values()].reduce((sum, value) => sum + value, 0);\n const highestAuthorCommits = [...authorTotals.values()].sort((a, b) => b - a)[0] ?? 0;\n const topAuthorCommitShare =\n totalAuthorCommits <= 0 ? 0 : clamp01(highestAuthorCommits / totalAuthorCommits);\n\n const filesWithSingleContributorRatio =\n trackedFiles === 0 ? 0 : clamp01(singleContributorFiles / trackedFiles);\n\n const authorEntropy = normalizedEntropy([...authorTotals.values()]);\n\n let dominatedModules = 0;\n let trackedModules = 0;\n for (const [moduleName, moduleCommitTotal] of moduleTotals.entries()) {\n if (moduleCommitTotal < 5) {\n continue;\n }\n\n const perModuleAuthors = moduleAuthors.get(moduleName);\n if (perModuleAuthors === undefined) {\n continue;\n }\n\n trackedModules += 1;\n const topAuthorModuleCommits = [...perModuleAuthors.values()].sort((a, b) => b - a)[0] ?? 0;\n const moduleTopShare =\n moduleCommitTotal <= 0 ? 0 : topAuthorModuleCommits / moduleCommitTotal;\n if (moduleTopShare >= 0.8) {\n dominatedModules += 1;\n }\n }\n\n const modulesDominatedBySingleContributorRatio =\n trackedModules === 0 ? 0 : clamp01(dominatedModules / trackedModules);\n\n const ownershipSampleSize = trackedFiles;\n const ownershipCommitVolume = totalAuthorCommits;\n\n const ownershipReliability = average([\n clamp01(ownershipSampleSize / 12),\n clamp01(ownershipCommitVolume / 180),\n ]);\n\n const topAuthorPenalty = clamp01((topAuthorCommitShare - 0.55) / 0.4);\n const singleContributorPenalty = clamp01((filesWithSingleContributorRatio - 0.35) / 0.6);\n const entropyPenalty = clamp01((0.75 - authorEntropy) / 0.75);\n const moduleDominancePenalty = clamp01((modulesDominatedBySingleContributorRatio - 0.4) / 0.6);\n\n const ownershipBasePenalty = weightedPenalty([\n {\n factorId: \"health.ownership.top_author_commit_share\",\n penalty: topAuthorPenalty,\n rawMetrics: {\n topAuthorCommitShare: round4(topAuthorCommitShare),\n },\n normalizedMetrics: {\n topAuthorPenalty: round4(topAuthorPenalty),\n },\n weight: 0.35,\n evidence: [{ kind: \"repository_metric\", metric: \"ownership.topAuthorCommitShare\" }],\n },\n {\n factorId: \"health.ownership.files_with_single_contributor_ratio\",\n penalty: singleContributorPenalty,\n rawMetrics: {\n filesWithSingleContributorRatio: round4(filesWithSingleContributorRatio),\n },\n normalizedMetrics: {\n singleContributorPenalty: round4(singleContributorPenalty),\n },\n weight: 0.25,\n evidence: [\n {\n kind: \"repository_metric\",\n metric: \"ownership.filesWithSingleContributorRatio\",\n },\n ],\n },\n {\n factorId: \"health.ownership.author_entropy\",\n penalty: entropyPenalty,\n rawMetrics: {\n authorEntropy: round4(authorEntropy),\n },\n normalizedMetrics: {\n authorEntropyPenalty: round4(entropyPenalty),\n },\n weight: 0.25,\n evidence: [{ kind: \"repository_metric\", metric: \"ownership.authorEntropy\" }],\n },\n {\n factorId: \"health.ownership.module_single_author_dominance\",\n penalty: moduleDominancePenalty,\n rawMetrics: {\n modulesDominatedBySingleContributorRatio: round4(\n modulesDominatedBySingleContributorRatio,\n ),\n },\n normalizedMetrics: {\n moduleDominancePenalty: round4(moduleDominancePenalty),\n },\n weight: 0.15,\n evidence: [{ kind: \"repository_metric\", metric: \"ownership.moduleDominance\" }],\n },\n ]);\n\n const ownershipDistributionPenalty = clamp01(\n ownershipBasePenalty * (0.3 + 0.7 * ownershipReliability) * ownershipPenaltyMultiplier,\n );\n\n const ownershipDistributionFactors: readonly FactorSpec[] = [\n {\n factorId: \"health.ownership.top_author_commit_share\",\n penalty: topAuthorPenalty,\n rawMetrics: {\n topAuthorCommitShare: round4(topAuthorCommitShare),\n },\n normalizedMetrics: {\n topAuthorPenalty: round4(topAuthorPenalty),\n ownershipPenaltyMultiplier: round4(ownershipPenaltyMultiplier),\n ownershipReliability: round4(ownershipReliability),\n },\n weight: 0.35,\n evidence: [{ kind: \"repository_metric\", metric: \"ownership.topAuthorCommitShare\" }],\n },\n {\n factorId: \"health.ownership.files_with_single_contributor_ratio\",\n penalty: singleContributorPenalty,\n rawMetrics: {\n filesWithSingleContributorRatio: round4(filesWithSingleContributorRatio),\n },\n normalizedMetrics: {\n singleContributorPenalty: round4(singleContributorPenalty),\n },\n weight: 0.25,\n evidence: [\n {\n kind: \"repository_metric\",\n metric: \"ownership.filesWithSingleContributorRatio\",\n },\n ],\n },\n {\n factorId: \"health.ownership.author_entropy\",\n penalty: entropyPenalty,\n rawMetrics: {\n authorEntropy: round4(authorEntropy),\n },\n normalizedMetrics: {\n authorEntropyPenalty: round4(entropyPenalty),\n },\n weight: 0.25,\n evidence: [{ kind: \"repository_metric\", metric: \"ownership.authorEntropy\" }],\n },\n {\n factorId: \"health.ownership.module_single_author_dominance\",\n penalty: moduleDominancePenalty,\n rawMetrics: {\n modulesDominatedBySingleContributorRatio: round4(\n modulesDominatedBySingleContributorRatio,\n ),\n },\n normalizedMetrics: {\n moduleDominancePenalty: round4(moduleDominancePenalty),\n },\n weight: 0.15,\n evidence: [{ kind: \"repository_metric\", metric: \"ownership.moduleDominance\" }],\n },\n ];\n\n if (topAuthorPenalty >= 0.35) {\n pushIssue(issues, {\n id: \"health.ownership.top_author_commit_share\",\n ruleId: \"ownership.top_author_share\",\n signal: \"ownership.topAuthorCommitShare\",\n dimension: \"ownershipDistribution\",\n target: input.structural.targetPath,\n message: \"A single contributor owns most commits, concentrating repository knowledge.\",\n severity: topAuthorPenalty >= 0.75 ? \"error\" : \"warn\",\n evidenceMetrics: {\n topAuthorCommitShare: round4(topAuthorCommitShare),\n authorEntropy: round4(authorEntropy),\n },\n impact: round4(ownershipDistributionPenalty * 0.4),\n });\n }\n\n if (singleContributorPenalty >= 0.35) {\n pushIssue(issues, {\n id: \"health.ownership.single_author_dominance\",\n ruleId: \"ownership.file_dominance\",\n signal: \"ownership.filesWithSingleContributorRatio\",\n dimension: \"ownershipDistribution\",\n target: input.structural.targetPath,\n message: \"Many files are dominated by a single contributor, reducing change resilience.\",\n evidenceMetrics: {\n filesWithSingleContributorRatio: round4(filesWithSingleContributorRatio),\n modulesDominatedBySingleContributorRatio: round4(\n modulesDominatedBySingleContributorRatio,\n ),\n },\n impact: round4(ownershipDistributionPenalty * 0.35),\n });\n }\n\n if (entropyPenalty >= 0.35) {\n pushIssue(issues, {\n id: \"health.ownership.low_author_entropy\",\n ruleId: \"ownership.author_entropy\",\n signal: \"ownership.authorEntropy\",\n dimension: \"ownershipDistribution\",\n target: input.structural.targetPath,\n message: \"Contributor distribution is narrow across the repository.\",\n evidenceMetrics: {\n authorEntropy: round4(authorEntropy),\n topAuthorCommitShare: round4(topAuthorCommitShare),\n },\n impact: round4(ownershipDistributionPenalty * 0.25),\n });\n }\n\n const modularityHealth = clamp01(1 - modularityPenalty);\n const changeHygieneHealth = clamp01(1 - changeHygienePenalty);\n const testHealthScore = clamp01(1 - testHealthPenalty);\n const ownershipDistributionHealth = clamp01(1 - ownershipDistributionPenalty);\n\n const normalizedScore = clamp01(\n modularityHealth * DIMENSION_WEIGHTS.modularity +\n changeHygieneHealth * DIMENSION_WEIGHTS.changeHygiene +\n testHealthScore * DIMENSION_WEIGHTS.testHealth +\n ownershipDistributionHealth * DIMENSION_WEIGHTS.ownershipDistribution,\n );\n\n const topIssues = [...issues]\n .sort(\n (a, b) =>\n b.impact - a.impact || a.id.localeCompare(b.id) || a.target.localeCompare(b.target),\n )\n .slice(0, 12)\n .map(({ impact: _impact, ...issue }) => issue);\n\n return {\n healthScore: toPercentage(normalizedScore),\n normalizedScore: round4(normalizedScore),\n dimensions: {\n modularity: toPercentage(modularityHealth),\n changeHygiene: toPercentage(changeHygieneHealth),\n testHealth: toPercentage(testHealthScore),\n ownershipDistribution: toPercentage(ownershipDistributionHealth),\n },\n topIssues,\n trace: {\n schemaVersion: HEALTH_TRACE_VERSION,\n dimensions: [\n createDimensionTrace(\"modularity\", modularityHealth, modularityFactors),\n createDimensionTrace(\"changeHygiene\", changeHygieneHealth, changeHygieneFactors),\n createDimensionTrace(\"testHealth\", testHealthScore, testHealthFactors),\n createDimensionTrace(\n \"ownershipDistribution\",\n ownershipDistributionHealth,\n ownershipDistributionFactors,\n ),\n ],\n },\n };\n }\n\n const ownershipDistributionPenalty = clamp01(0.12 * ownershipPenaltyMultiplier);\n const ownershipDistributionFactors: readonly FactorSpec[] = [\n {\n factorId: \"health.ownership.missing_git_history\",\n penalty: ownershipDistributionPenalty,\n rawMetrics: {\n gitHistoryAvailable: 0,\n },\n normalizedMetrics: {\n ownershipDistributionPenalty: round4(ownershipDistributionPenalty),\n },\n weight: 1,\n evidence: [{ kind: \"repository_metric\", metric: \"evolution.available\" }],\n },\n ];\n\n const modularityHealth = clamp01(1 - modularityPenalty);\n const changeHygieneHealth = clamp01(1 - changeHygienePenalty);\n const testHealthScore = clamp01(1 - testHealthPenalty);\n const ownershipDistributionHealth = clamp01(1 - ownershipDistributionPenalty);\n\n const normalizedScore = clamp01(\n modularityHealth * DIMENSION_WEIGHTS.modularity +\n changeHygieneHealth * DIMENSION_WEIGHTS.changeHygiene +\n testHealthScore * DIMENSION_WEIGHTS.testHealth +\n ownershipDistributionHealth * DIMENSION_WEIGHTS.ownershipDistribution,\n );\n\n const topIssues = [...issues]\n .sort(\n (a, b) => b.impact - a.impact || a.id.localeCompare(b.id) || a.target.localeCompare(b.target),\n )\n .slice(0, 12)\n .map(({ impact: _impact, ...issue }) => issue);\n\n return {\n healthScore: toPercentage(normalizedScore),\n normalizedScore: round4(normalizedScore),\n dimensions: {\n modularity: toPercentage(modularityHealth),\n changeHygiene: toPercentage(changeHygieneHealth),\n testHealth: toPercentage(testHealthScore),\n ownershipDistribution: toPercentage(ownershipDistributionHealth),\n },\n topIssues,\n trace: {\n schemaVersion: HEALTH_TRACE_VERSION,\n dimensions: [\n createDimensionTrace(\"modularity\", modularityHealth, modularityFactors),\n createDimensionTrace(\"changeHygiene\", changeHygieneHealth, changeHygieneFactors),\n createDimensionTrace(\"testHealth\", testHealthScore, testHealthFactors),\n createDimensionTrace(\n \"ownershipDistribution\",\n ownershipDistributionHealth,\n ownershipDistributionFactors,\n ),\n ],\n },\n };\n};\n","export type DimensionWeights = {\n structural: number;\n evolution: number;\n external: number;\n};\n\nexport type InteractionWeights = {\n structuralEvolution: number;\n centralInstability: number;\n dependencyAmplification: number;\n};\n\nexport type StructuralFactorWeights = {\n fanIn: number;\n fanOut: number;\n depth: number;\n cycleParticipation: number;\n};\n\nexport type EvolutionFactorWeights = {\n frequency: number;\n churn: number;\n recentVolatility: number;\n ownershipConcentration: number;\n busFactorRisk: number;\n};\n\nexport type DependencyFactorWeights = {\n signals: number;\n staleness: number;\n maintainerConcentration: number;\n transitiveBurden: number;\n centrality: number;\n chainDepth: number;\n busFactorRisk: number;\n};\n\nexport type RiskEngineConfig = {\n dimensionWeights: DimensionWeights;\n interactionWeights: InteractionWeights;\n structuralFactorWeights: StructuralFactorWeights;\n evolutionFactorWeights: EvolutionFactorWeights;\n dependencyFactorWeights: DependencyFactorWeights;\n quantileClamp: {\n lower: number;\n upper: number;\n };\n hotspotTopPercent: number;\n hotspotMinFiles: number;\n hotspotMaxFiles: number;\n couplingCluster: {\n minCoChangeCommits: number;\n percentileThreshold: number;\n floorScore: number;\n };\n amplificationZone: {\n pressureFloor: number;\n percentileThreshold: number;\n maxZones: number;\n };\n module: {\n maxPrefixSegments: number;\n rootLabel: string;\n commonSourceRoots: readonly string[];\n };\n dependencySignals: {\n inheritedSignalMultiplier: number;\n abandonedHalfLifeDays: number;\n missingMetadataPenalty: number;\n popularityHalfLifeDownloads: number;\n popularityMaxDampening: number;\n };\n externalDimension: {\n topDependencyPercentile: number;\n dependencyDepthHalfLife: number;\n };\n aggregatorAttenuation: {\n enabled: boolean;\n minFanIn: number;\n minFanOut: number;\n minCommitCount: number;\n maxChurnPerCommit: number;\n maxChurnPerDependency: number;\n maxStructuralReduction: number;\n };\n};\n\nexport const DEFAULT_RISK_ENGINE_CONFIG: RiskEngineConfig = {\n // Base dimensional influence. Risk is never dominated by a single dimension by default.\n dimensionWeights: {\n structural: 0.44,\n evolution: 0.36,\n external: 0.2,\n },\n // Interaction terms activate only when both related dimensions are high.\n interactionWeights: {\n structuralEvolution: 0.35,\n centralInstability: 0.25,\n dependencyAmplification: 0.2,\n },\n structuralFactorWeights: {\n fanIn: 0.3,\n fanOut: 0.25,\n depth: 0.2,\n cycleParticipation: 0.25,\n },\n evolutionFactorWeights: {\n frequency: 0.26,\n churn: 0.24,\n recentVolatility: 0.2,\n ownershipConcentration: 0.18,\n busFactorRisk: 0.12,\n },\n dependencyFactorWeights: {\n signals: 0.38,\n staleness: 0.16,\n maintainerConcentration: 0.16,\n transitiveBurden: 0.1,\n centrality: 0.08,\n chainDepth: 0.06,\n busFactorRisk: 0.06,\n },\n quantileClamp: {\n lower: 0.05,\n upper: 0.95,\n },\n hotspotTopPercent: 0.12,\n hotspotMinFiles: 3,\n hotspotMaxFiles: 30,\n couplingCluster: {\n minCoChangeCommits: 2,\n percentileThreshold: 0.9,\n floorScore: 0.35,\n },\n amplificationZone: {\n pressureFloor: 0.2,\n percentileThreshold: 0.85,\n maxZones: 20,\n },\n module: {\n maxPrefixSegments: 2,\n rootLabel: \"(root)\",\n commonSourceRoots: [\"src\", \"lib\", \"app\", \"packages\"],\n },\n dependencySignals: {\n inheritedSignalMultiplier: 0.45,\n // At this age, staleness reaches 50% risk.\n abandonedHalfLifeDays: 540,\n missingMetadataPenalty: 0.5,\n // At this download volume, popularity reaches 50% of its dampening effect.\n popularityHalfLifeDownloads: 100000,\n // Popularity can only reduce dependency risk by this fraction.\n popularityMaxDampening: 0.12,\n },\n externalDimension: {\n topDependencyPercentile: 0.85,\n dependencyDepthHalfLife: 6,\n },\n // Reduce false positives for thin aggregation hubs (for example, barrel/index re-export files)\n // that are structurally central but have low churn density and no cycle participation.\n aggregatorAttenuation: {\n enabled: true,\n minFanIn: 6,\n minFanOut: 4,\n minCommitCount: 4,\n maxChurnPerCommit: 24,\n maxChurnPerDependency: 10,\n maxStructuralReduction: 0.3,\n },\n};\n","import type {\n DependencyRiskScore,\n DependencyRiskSignal,\n EvidenceRef,\n ExternalAnalysisSummary,\n FileEvolutionMetrics,\n FileRiskScore,\n FragileCluster,\n GraphAnalysisSummary,\n ModuleRiskScore,\n RepositoryEvolutionSummary,\n RepositoryRiskSummary,\n RiskFactors,\n RiskFactorFamily,\n RiskFactorTrace,\n TargetTrace,\n WorkspaceRiskScore,\n} from \"@codesentinel/core\";\nimport { fileBelongsToWorkspace } from \"@codesentinel/core\";\nimport type { RiskEngineConfig } from \"../config.js\";\nimport {\n average,\n toUnitInterval,\n halfLifeRisk,\n normalizeWeights,\n percentile,\n round4,\n saturatingComposite,\n} from \"./math.js\";\nimport { buildQuantileScale, logScale, normalizeWithScale } from \"./normalization.js\";\nimport type { TraceCollector } from \"./trace-collector.js\";\n\ntype DependencyScoreComputation = {\n dependencyScores: readonly DependencyRiskScore[];\n repositoryExternalPressure: number;\n dependencyContexts: ReadonlyMap<\n string,\n {\n signalScore: number;\n stalenessRisk: number;\n maintainerConcentrationRisk: number;\n transitiveBurdenRisk: number;\n centralityRisk: number;\n chainDepthRisk: number;\n busFactorRisk: number;\n popularityDampener: number;\n rawMetrics: {\n daysSinceLastRelease: number | null;\n maintainerCount: number | null;\n transitiveCount: number;\n dependents: number;\n dependencyDepth: number;\n busFactor: number | null;\n weeklyDownloads: number | null;\n };\n confidence: number;\n }\n >;\n};\n\ntype FileRiskContext = {\n file: string;\n score: number;\n normalizedScore: number;\n factors: RiskFactors;\n structuralCentrality: number;\n traceTerms: {\n structuralBase: number;\n evolutionBase: number;\n externalBase: number;\n interactionStructuralEvolution: number;\n interactionCentralInstability: number;\n interactionDependencyAmplification: number;\n };\n rawMetrics: {\n fanIn: number;\n fanOut: number;\n depth: number;\n cycleParticipation: number;\n commitCount: number | null;\n churnTotal: number | null;\n recentVolatility: number | null;\n topAuthorShareByCommits: number | null;\n busFactorByCommits: number | null;\n dependencyAffinity: number;\n repositoryExternalPressure: number;\n structuralAttenuation: number;\n };\n normalizedMetrics: {\n fanInRisk: number;\n fanOutRisk: number;\n depthRisk: number;\n frequencyRisk: number;\n churnRisk: number;\n volatilityRisk: number;\n ownershipConcentrationRisk: number;\n busFactorRisk: number;\n };\n};\n\ntype MetricScales = {\n commitCount: ReturnType<typeof buildQuantileScale>;\n churnTotal: ReturnType<typeof buildQuantileScale>;\n busFactor: ReturnType<typeof buildQuantileScale>;\n};\n\ntype FactorTraceInput = {\n factorId: string;\n family: RiskFactorFamily;\n strength: number;\n rawMetrics: Readonly<Record<string, number | null>>;\n normalizedMetrics: Readonly<Record<string, number | null>>;\n weight: number | null;\n amplification: number | null;\n evidence: readonly EvidenceRef[];\n confidence: number;\n};\n\nconst normalizePath = (path: string): string => path.replaceAll(\"\\\\\", \"/\");\n\nconst computeAggregatorAttenuation = (input: {\n fanIn: number;\n fanOut: number;\n inCycle: number;\n evolutionMetrics: FileEvolutionMetrics | undefined;\n config: RiskEngineConfig[\"aggregatorAttenuation\"];\n}): number => {\n const { fanIn, fanOut, inCycle, evolutionMetrics, config } = input;\n if (!config.enabled || inCycle > 0) {\n return 1;\n }\n\n if (fanIn < config.minFanIn || fanOut < config.minFanOut) {\n return 1;\n }\n\n if (evolutionMetrics === undefined || evolutionMetrics.commitCount < config.minCommitCount) {\n return 1;\n }\n\n const churnPerCommit = evolutionMetrics.churnTotal / Math.max(1, evolutionMetrics.commitCount);\n const churnPerDependency = evolutionMetrics.churnTotal / Math.max(1, fanOut);\n\n if (\n churnPerCommit > config.maxChurnPerCommit ||\n churnPerDependency > config.maxChurnPerDependency\n ) {\n return 1;\n }\n\n const fanInSignal = toUnitInterval((fanIn - config.minFanIn) / Math.max(1, config.minFanIn));\n const fanOutSignal = toUnitInterval((fanOut - config.minFanOut) / Math.max(1, config.minFanOut));\n const lowChurnPerCommitSignal = 1 - toUnitInterval(churnPerCommit / config.maxChurnPerCommit);\n const lowChurnPerDependencySignal =\n 1 - toUnitInterval(churnPerDependency / config.maxChurnPerDependency);\n const attenuationConfidence = average([\n fanInSignal,\n fanOutSignal,\n lowChurnPerCommitSignal,\n lowChurnPerDependencySignal,\n ]);\n\n const reduction = toUnitInterval(config.maxStructuralReduction) * attenuationConfidence;\n return round4(toUnitInterval(1 - reduction));\n};\n\nconst dependencySignalWeights: Readonly<Record<DependencyRiskSignal, number>> = {\n single_maintainer: 0.3,\n abandoned: 0.3,\n high_centrality: 0.16,\n deep_chain: 0.14,\n high_fanout: 0.06,\n metadata_unavailable: 0.04,\n};\n\nconst dependencySignalWeightBudget = Object.values(dependencySignalWeights).reduce(\n (sum, value) => sum + value,\n 0,\n);\n\nconst computeDependencySignalScore = (\n ownSignals: readonly DependencyRiskSignal[],\n inheritedSignals: readonly DependencyRiskSignal[],\n inheritedSignalMultiplier: number,\n): number => {\n const ownWeight = ownSignals.reduce(\n (sum, signal) => sum + (dependencySignalWeights[signal] ?? 0),\n 0,\n );\n const inheritedWeight = inheritedSignals.reduce(\n (sum, signal) => sum + (dependencySignalWeights[signal] ?? 0),\n 0,\n );\n\n const weightedTotal = ownWeight + inheritedWeight * inheritedSignalMultiplier;\n const maxWeightedTotal = dependencySignalWeightBudget * (1 + inheritedSignalMultiplier);\n\n if (maxWeightedTotal <= 0) {\n return 0;\n }\n\n return toUnitInterval(weightedTotal / maxWeightedTotal);\n};\n\nconst clampConfidence = (value: number): number => round4(toUnitInterval(value));\n\nconst computeExternalMetadataConfidence = (external: ExternalAnalysisSummary): number => {\n if (!external.available) {\n return 0;\n }\n\n // Topology signals still exist without registry metadata, so keep a non-zero floor.\n return round4(toUnitInterval(0.35 + external.metrics.metadataCoverage * 0.65));\n};\n\nconst computeEvolutionHistoryConfidence = (\n structural: GraphAnalysisSummary,\n evolution: RepositoryEvolutionSummary,\n evolutionByFile: ReadonlyMap<string, FileEvolutionMetrics>,\n): number => {\n if (!evolution.available) {\n return 0;\n }\n\n const totalFiles = structural.files.length;\n if (totalFiles === 0) {\n return 1;\n }\n\n let coveredFiles = 0;\n for (const file of structural.files) {\n if (evolutionByFile.has(normalizePath(file.id))) {\n coveredFiles += 1;\n }\n }\n\n const coverage = coveredFiles / totalFiles;\n // Partial commit history still carries value, but confidence scales with coverage.\n return round4(toUnitInterval(0.3 + coverage * 0.7));\n};\n\nconst buildFactorTraces = (\n totalScore: number,\n inputs: readonly FactorTraceInput[],\n): readonly RiskFactorTrace[] => {\n const positiveInputs = inputs.filter((input) => input.strength > 0);\n const strengthTotal = positiveInputs.reduce((sum, input) => sum + input.strength, 0);\n\n const traces = inputs.map<RiskFactorTrace>((input) => ({\n factorId: input.factorId,\n family: input.family,\n contribution: 0,\n rawMetrics: input.rawMetrics,\n normalizedMetrics: input.normalizedMetrics,\n weight: input.weight,\n amplification: input.amplification,\n evidence: input.evidence,\n confidence: clampConfidence(input.confidence),\n }));\n\n if (strengthTotal <= 0 || totalScore <= 0) {\n return traces;\n }\n\n const scored = positiveInputs.map((input) => ({\n factorId: input.factorId,\n contribution: (totalScore * input.strength) / strengthTotal,\n }));\n\n let distributed = 0;\n for (let index = 0; index < scored.length; index += 1) {\n const current = scored[index];\n if (current === undefined) {\n continue;\n }\n\n const traceIndex = traces.findIndex((trace) => trace.factorId === current.factorId);\n if (traceIndex < 0) {\n continue;\n }\n const existing = traces[traceIndex];\n if (existing === undefined) {\n continue;\n }\n\n if (index === scored.length - 1) {\n const remaining = round4(totalScore - distributed);\n traces[traceIndex] = {\n ...existing,\n contribution: Math.max(0, remaining),\n };\n distributed += Math.max(0, remaining);\n continue;\n }\n\n const rounded = round4(current.contribution);\n traces[traceIndex] = {\n ...existing,\n contribution: rounded,\n };\n distributed += rounded;\n }\n\n return traces;\n};\n\nconst buildReductionLevers = (\n factors: readonly RiskFactorTrace[],\n): readonly { factorId: string; estimatedImpact: number }[] =>\n factors\n .filter((factor) => factor.contribution > 0)\n .sort((a, b) => b.contribution - a.contribution || a.factorId.localeCompare(b.factorId))\n .slice(0, 3)\n .map((factor) => ({\n factorId: factor.factorId,\n estimatedImpact: round4(factor.contribution),\n }));\n\nconst buildTargetTrace = (\n targetType: TargetTrace[\"targetType\"],\n targetId: string,\n totalScore: number,\n normalizedScore: number,\n factors: readonly RiskFactorTrace[],\n): TargetTrace => {\n const dominantFactors = [...factors]\n .filter((factor) => factor.contribution > 0)\n .sort((a, b) => b.contribution - a.contribution || a.factorId.localeCompare(b.factorId))\n .slice(0, 3)\n .map((factor) => factor.factorId);\n\n return {\n targetType,\n targetId,\n totalScore: round4(totalScore),\n normalizedScore: round4(normalizedScore),\n factors,\n dominantFactors,\n reductionLevers: buildReductionLevers(factors),\n };\n};\n\nconst computeDependencyScores = (\n external: ExternalAnalysisSummary,\n config: RiskEngineConfig,\n): DependencyScoreComputation => {\n if (!external.available) {\n return {\n dependencyScores: [],\n repositoryExternalPressure: 0,\n dependencyContexts: new Map(),\n };\n }\n\n const transitiveCounts = external.dependencies.map((dependency) =>\n logScale(dependency.transitiveDependencies.length),\n );\n const dependentCounts = external.dependencies.map((dependency) =>\n logScale(dependency.dependents),\n );\n const chainDepths = external.dependencies.map((dependency) => dependency.dependencyDepth);\n\n const transitiveScale = buildQuantileScale(\n transitiveCounts,\n config.quantileClamp.lower,\n config.quantileClamp.upper,\n );\n const dependentScale = buildQuantileScale(\n dependentCounts,\n config.quantileClamp.lower,\n config.quantileClamp.upper,\n );\n const chainDepthScale = buildQuantileScale(\n chainDepths,\n config.quantileClamp.lower,\n config.quantileClamp.upper,\n );\n\n const dependencyContexts = new Map<\n string,\n {\n signalScore: number;\n stalenessRisk: number;\n maintainerConcentrationRisk: number;\n transitiveBurdenRisk: number;\n centralityRisk: number;\n chainDepthRisk: number;\n busFactorRisk: number;\n popularityDampener: number;\n rawMetrics: {\n daysSinceLastRelease: number | null;\n maintainerCount: number | null;\n transitiveCount: number;\n dependents: number;\n dependencyDepth: number;\n busFactor: number | null;\n weeklyDownloads: number | null;\n };\n confidence: number;\n }\n >();\n\n const metadataConfidence = computeExternalMetadataConfidence(external);\n const dependencyScores = external.dependencies\n .map<DependencyRiskScore>((dependency) => {\n const signalScore = computeDependencySignalScore(\n dependency.ownRiskSignals,\n dependency.inheritedRiskSignals,\n config.dependencySignals.inheritedSignalMultiplier,\n );\n\n const maintainerConcentrationRisk =\n dependency.maintainerCount === null\n ? config.dependencySignals.missingMetadataPenalty\n : toUnitInterval(1 / Math.max(1, dependency.maintainerCount));\n\n const stalenessRisk =\n dependency.daysSinceLastRelease === null\n ? config.dependencySignals.missingMetadataPenalty\n : halfLifeRisk(\n dependency.daysSinceLastRelease,\n config.dependencySignals.abandonedHalfLifeDays,\n );\n\n const transitiveBurdenRisk = normalizeWithScale(\n logScale(dependency.transitiveDependencies.length),\n transitiveScale,\n );\n\n const centralityRisk = normalizeWithScale(logScale(dependency.dependents), dependentScale);\n const chainDepthRisk = normalizeWithScale(dependency.dependencyDepth, chainDepthScale);\n\n const busFactorRisk =\n dependency.busFactor === null\n ? config.dependencySignals.missingMetadataPenalty\n : toUnitInterval(1 / Math.max(1, dependency.busFactor));\n\n const weights = config.dependencyFactorWeights;\n const baseScore = toUnitInterval(\n signalScore * weights.signals +\n stalenessRisk * weights.staleness +\n maintainerConcentrationRisk * weights.maintainerConcentration +\n transitiveBurdenRisk * weights.transitiveBurden +\n centralityRisk * weights.centrality +\n chainDepthRisk * weights.chainDepth +\n busFactorRisk * weights.busFactorRisk,\n );\n\n const hasHardRiskSignal =\n dependency.ownRiskSignals.includes(\"abandoned\") ||\n dependency.ownRiskSignals.includes(\"metadata_unavailable\") ||\n dependency.ownRiskSignals.includes(\"single_maintainer\");\n\n const popularityDampener =\n dependency.weeklyDownloads === null || hasHardRiskSignal\n ? 1\n : 1 -\n halfLifeRisk(\n dependency.weeklyDownloads,\n config.dependencySignals.popularityHalfLifeDownloads,\n ) *\n config.dependencySignals.popularityMaxDampening;\n const normalizedScore = toUnitInterval(baseScore * popularityDampener);\n\n const availableMetricCount = [\n dependency.daysSinceLastRelease,\n dependency.maintainerCount,\n dependency.busFactor,\n dependency.weeklyDownloads,\n ].filter((value) => value !== null).length;\n const confidence = toUnitInterval((0.5 + availableMetricCount * 0.125) * metadataConfidence);\n\n dependencyContexts.set(dependency.name, {\n signalScore: round4(signalScore),\n stalenessRisk: round4(stalenessRisk),\n maintainerConcentrationRisk: round4(maintainerConcentrationRisk),\n transitiveBurdenRisk: round4(transitiveBurdenRisk),\n centralityRisk: round4(centralityRisk),\n chainDepthRisk: round4(chainDepthRisk),\n busFactorRisk: round4(busFactorRisk),\n popularityDampener: round4(popularityDampener),\n rawMetrics: {\n daysSinceLastRelease: dependency.daysSinceLastRelease,\n maintainerCount: dependency.maintainerCount,\n transitiveCount: dependency.transitiveDependencies.length,\n dependents: dependency.dependents,\n dependencyDepth: dependency.dependencyDepth,\n busFactor: dependency.busFactor,\n weeklyDownloads: dependency.weeklyDownloads,\n },\n confidence: round4(confidence),\n });\n\n return {\n dependency: dependency.name,\n score: round4(normalizedScore * 100),\n normalizedScore: round4(normalizedScore),\n ownRiskSignals: dependency.ownRiskSignals,\n inheritedRiskSignals: dependency.inheritedRiskSignals,\n };\n })\n .sort(\n (a, b) => b.normalizedScore - a.normalizedScore || a.dependency.localeCompare(b.dependency),\n );\n\n const normalizedValues = dependencyScores.map((score) => score.normalizedScore);\n const highDependencyRisk =\n dependencyScores.length === 0\n ? 0\n : percentile(normalizedValues, config.externalDimension.topDependencyPercentile);\n const averageDependencyRisk = average(normalizedValues);\n const depthRisk = halfLifeRisk(\n external.metrics.dependencyDepth,\n config.externalDimension.dependencyDepthHalfLife,\n );\n\n const repositoryExternalPressure = toUnitInterval(\n highDependencyRisk * 0.5 + averageDependencyRisk * 0.3 + depthRisk * 0.2,\n );\n\n return {\n dependencyScores,\n repositoryExternalPressure: round4(repositoryExternalPressure),\n dependencyContexts,\n };\n};\n\nconst mapEvolutionByFile = (\n evolution: RepositoryEvolutionSummary,\n): ReadonlyMap<string, FileEvolutionMetrics> => {\n if (!evolution.available) {\n return new Map<string, FileEvolutionMetrics>();\n }\n\n return new Map(\n evolution.files.map((fileMetrics) => [normalizePath(fileMetrics.filePath), fileMetrics]),\n );\n};\n\nconst computeEvolutionScales = (\n evolutionByFile: ReadonlyMap<string, FileEvolutionMetrics>,\n config: RiskEngineConfig,\n): MetricScales => {\n const evolutionFiles = [...evolutionByFile.values()];\n\n return {\n commitCount: buildQuantileScale(\n evolutionFiles.map((metrics) => logScale(metrics.commitCount)),\n config.quantileClamp.lower,\n config.quantileClamp.upper,\n ),\n churnTotal: buildQuantileScale(\n evolutionFiles.map((metrics) => logScale(metrics.churnTotal)),\n config.quantileClamp.lower,\n config.quantileClamp.upper,\n ),\n busFactor: buildQuantileScale(\n evolutionFiles.map((metrics) => metrics.busFactorByCommits),\n config.quantileClamp.lower,\n config.quantileClamp.upper,\n ),\n };\n};\n\nconst inferModuleName = (filePath: string, config: RiskEngineConfig): string => {\n const normalized = normalizePath(filePath);\n const parts = normalized.split(\"/\").filter((part) => part.length > 0);\n\n if (parts.length <= 1) {\n return config.module.rootLabel;\n }\n\n const first = parts[0];\n if (first === undefined) {\n return config.module.rootLabel;\n }\n\n if (!config.module.commonSourceRoots.includes(first)) {\n return first;\n }\n\n if (parts.length <= config.module.maxPrefixSegments) {\n return first;\n }\n\n return parts.slice(0, config.module.maxPrefixSegments).join(\"/\");\n};\n\nconst buildFragileClusters = (\n structural: GraphAnalysisSummary,\n evolution: RepositoryEvolutionSummary,\n fileScoresByFile: ReadonlyMap<string, FileRiskScore>,\n config: RiskEngineConfig,\n): readonly FragileCluster[] => {\n const clusters: FragileCluster[] = [];\n\n let cycleClusterCount = 0;\n for (const cycle of structural.cycles) {\n const files = [...new Set(cycle.nodes.map((node) => normalizePath(node)))].filter((filePath) =>\n fileScoresByFile.has(filePath),\n );\n\n if (files.length < 2) {\n continue;\n }\n\n files.sort((a, b) => a.localeCompare(b));\n\n const averageRisk = average(\n files.map((filePath) => fileScoresByFile.get(filePath)?.normalizedScore ?? 0),\n );\n\n const cycleSizeRisk = toUnitInterval((files.length - 1) / 5);\n const score = round4(toUnitInterval(averageRisk * 0.75 + cycleSizeRisk * 0.25) * 100);\n\n cycleClusterCount += 1;\n clusters.push({\n id: `cycle:${cycleClusterCount}`,\n kind: \"structural_cycle\",\n files,\n score,\n });\n }\n\n if (evolution.available && evolution.coupling.pairs.length > 0) {\n const candidates = evolution.coupling.pairs.filter(\n (pair) => pair.coChangeCommits >= config.couplingCluster.minCoChangeCommits,\n );\n\n const threshold = Math.max(\n config.couplingCluster.floorScore,\n percentile(\n candidates.map((pair) => pair.couplingScore),\n config.couplingCluster.percentileThreshold,\n ),\n );\n\n const selectedPairs = candidates\n .filter((pair) => pair.couplingScore >= threshold)\n .map((pair) => ({\n fileA: normalizePath(pair.fileA),\n fileB: normalizePath(pair.fileB),\n couplingScore: pair.couplingScore,\n }))\n .filter(\n (pair) =>\n pair.fileA !== pair.fileB &&\n fileScoresByFile.has(pair.fileA) &&\n fileScoresByFile.has(pair.fileB),\n );\n\n const adjacency = new Map<string, Set<string>>();\n for (const pair of selectedPairs) {\n const aNeighbors = adjacency.get(pair.fileA) ?? new Set<string>();\n aNeighbors.add(pair.fileB);\n adjacency.set(pair.fileA, aNeighbors);\n\n const bNeighbors = adjacency.get(pair.fileB) ?? new Set<string>();\n bNeighbors.add(pair.fileA);\n adjacency.set(pair.fileB, bNeighbors);\n }\n\n const visited = new Set<string>();\n let couplingClusterCount = 0;\n\n const orderedStarts = [...adjacency.keys()].sort((a, b) => a.localeCompare(b));\n for (const start of orderedStarts) {\n if (visited.has(start)) {\n continue;\n }\n\n const stack = [start];\n const files: string[] = [];\n\n while (stack.length > 0) {\n const current = stack.pop();\n if (current === undefined || visited.has(current)) {\n continue;\n }\n\n visited.add(current);\n files.push(current);\n\n const neighbors = adjacency.get(current);\n if (neighbors === undefined) {\n continue;\n }\n\n for (const neighbor of neighbors) {\n if (!visited.has(neighbor)) {\n stack.push(neighbor);\n }\n }\n }\n\n if (files.length < 2) {\n continue;\n }\n\n files.sort((a, b) => a.localeCompare(b));\n const fileSet = new Set(files);\n const componentPairs = selectedPairs.filter(\n (pair) => fileSet.has(pair.fileA) && fileSet.has(pair.fileB),\n );\n\n const meanFileRisk = average(\n files.map((filePath) => fileScoresByFile.get(filePath)?.normalizedScore ?? 0),\n );\n const meanCoupling = average(componentPairs.map((pair) => pair.couplingScore));\n\n const score = round4(toUnitInterval(meanFileRisk * 0.65 + meanCoupling * 0.35) * 100);\n\n couplingClusterCount += 1;\n clusters.push({\n id: `coupling:${couplingClusterCount}`,\n kind: \"change_coupling\",\n files,\n score,\n });\n }\n }\n\n return clusters.sort(\n (a, b) => b.score - a.score || a.kind.localeCompare(b.kind) || a.id.localeCompare(b.id),\n );\n};\n\nconst buildWorkspaceRiskScores = (\n structural: GraphAnalysisSummary,\n fileScoresByFile: ReadonlyMap<string, FileRiskScore>,\n): readonly WorkspaceRiskScore[] => {\n if (structural.workspaces === undefined || structural.workspaces.length === 0) {\n return [];\n }\n\n const maxIncomingEdges = structural.workspaces.reduce(\n (max, workspace) => Math.max(max, workspace.incomingEdgeCount),\n 0,\n );\n const maxOutgoingEdges = structural.workspaces.reduce(\n (max, workspace) => Math.max(max, workspace.outgoingEdgeCount),\n 0,\n );\n\n return structural.workspaces\n .map((workspace) => {\n const workspaceFileScores = [...fileScoresByFile.values()]\n .filter((fileScore) => fileBelongsToWorkspace(fileScore.file, workspace))\n .sort((a, b) => b.score - a.score || a.file.localeCompare(b.file));\n\n const averageFileRisk = average(\n workspaceFileScores.map((fileScore) => fileScore.normalizedScore),\n );\n const peakFileRisk = workspaceFileScores.reduce(\n (max, fileScore) => Math.max(max, fileScore.normalizedScore),\n 0,\n );\n const incomingPressure =\n maxIncomingEdges <= 0 ? 0 : toUnitInterval(workspace.incomingEdgeCount / maxIncomingEdges);\n const outgoingPressure =\n maxOutgoingEdges <= 0 ? 0 : toUnitInterval(workspace.outgoingEdgeCount / maxOutgoingEdges);\n const structuralPressure = toUnitInterval(incomingPressure * 0.7 + outgoingPressure * 0.3);\n const normalizedScore = toUnitInterval(\n averageFileRisk * 0.5 + peakFileRisk * 0.3 + structuralPressure * 0.2,\n );\n\n return {\n ...workspace,\n score: round4(normalizedScore * 100),\n normalizedScore: round4(normalizedScore),\n averageFileRisk: round4(averageFileRisk),\n peakFileRisk: round4(peakFileRisk),\n topFiles: workspaceFileScores.slice(0, 5).map((fileScore) => ({\n file: fileScore.file,\n score: fileScore.score,\n factors: fileScore.factors,\n })),\n };\n })\n .sort((a, b) => b.score - a.score || a.path.localeCompare(b.path));\n};\n\nexport const computeRiskSummary = (\n structural: GraphAnalysisSummary,\n evolution: RepositoryEvolutionSummary,\n external: ExternalAnalysisSummary,\n config: RiskEngineConfig,\n traceCollector?: TraceCollector,\n): RepositoryRiskSummary => {\n const collector = traceCollector;\n const dependencyComputation = computeDependencyScores(external, config);\n const externalMetadataConfidence = computeExternalMetadataConfidence(external);\n const evolutionByFile = mapEvolutionByFile(evolution);\n const evolutionHistoryConfidence = computeEvolutionHistoryConfidence(\n structural,\n evolution,\n evolutionByFile,\n );\n const evolutionScales = computeEvolutionScales(evolutionByFile, config);\n\n const cycleFileSet = new Set(\n structural.cycles.flatMap((cycle) => cycle.nodes.map((node) => normalizePath(node))),\n );\n\n const fanInScale = buildQuantileScale(\n structural.files.map((file) => logScale(file.fanIn)),\n config.quantileClamp.lower,\n config.quantileClamp.upper,\n );\n const fanOutScale = buildQuantileScale(\n structural.files.map((file) => logScale(file.fanOut)),\n config.quantileClamp.lower,\n config.quantileClamp.upper,\n );\n const depthScale = buildQuantileScale(\n structural.files.map((file) => file.depth),\n config.quantileClamp.lower,\n config.quantileClamp.upper,\n );\n\n const dimensionWeights = normalizeWeights(config.dimensionWeights, {\n structural: true,\n evolution: evolution.available,\n external: external.available,\n });\n\n const fileRiskContexts = structural.files\n .map<FileRiskContext>((file) => {\n const filePath = normalizePath(file.id);\n const inCycle = cycleFileSet.has(filePath) ? 1 : 0;\n\n const fanInRisk = normalizeWithScale(logScale(file.fanIn), fanInScale);\n const fanOutRisk = normalizeWithScale(logScale(file.fanOut), fanOutScale);\n const depthRisk = normalizeWithScale(file.depth, depthScale);\n\n const structuralWeights = config.structuralFactorWeights;\n const structuralFactorRaw = toUnitInterval(\n fanInRisk * structuralWeights.fanIn +\n fanOutRisk * structuralWeights.fanOut +\n depthRisk * structuralWeights.depth +\n inCycle * structuralWeights.cycleParticipation,\n );\n\n const structuralCentralityRaw = toUnitInterval((fanInRisk + fanOutRisk) / 2);\n\n let evolutionFactor = 0;\n let frequencyRisk = 0;\n let churnRisk = 0;\n let volatilityRisk = 0;\n let ownershipConcentrationRisk = 0;\n let busFactorRisk = 0;\n const evolutionMetrics = evolutionByFile.get(filePath);\n if (evolution.available && evolutionMetrics !== undefined) {\n frequencyRisk = normalizeWithScale(\n logScale(evolutionMetrics.commitCount),\n evolutionScales.commitCount,\n );\n churnRisk = normalizeWithScale(\n logScale(evolutionMetrics.churnTotal),\n evolutionScales.churnTotal,\n );\n volatilityRisk = toUnitInterval(evolutionMetrics.recentVolatility);\n ownershipConcentrationRisk = toUnitInterval(evolutionMetrics.topAuthorShareByCommits);\n busFactorRisk = toUnitInterval(\n 1 - normalizeWithScale(evolutionMetrics.busFactorByCommits, evolutionScales.busFactor),\n );\n\n const evolutionWeights = config.evolutionFactorWeights;\n evolutionFactor = toUnitInterval(\n frequencyRisk * evolutionWeights.frequency +\n churnRisk * evolutionWeights.churn +\n volatilityRisk * evolutionWeights.recentVolatility +\n ownershipConcentrationRisk * evolutionWeights.ownershipConcentration +\n busFactorRisk * evolutionWeights.busFactorRisk,\n );\n }\n\n const structuralAttenuation = computeAggregatorAttenuation({\n fanIn: file.fanIn,\n fanOut: file.fanOut,\n inCycle,\n evolutionMetrics,\n config: config.aggregatorAttenuation,\n });\n const structuralFactor = toUnitInterval(structuralFactorRaw * structuralAttenuation);\n const structuralCentrality = toUnitInterval(structuralCentralityRaw * structuralAttenuation);\n\n const dependencyAffinity = toUnitInterval(structuralCentrality * 0.6 + evolutionFactor * 0.4);\n const externalFactor = external.available\n ? toUnitInterval(dependencyComputation.repositoryExternalPressure * dependencyAffinity)\n : 0;\n\n const structuralBase = structuralFactor * dimensionWeights.structural;\n const evolutionBase = evolutionFactor * dimensionWeights.evolution;\n const externalBase = externalFactor * dimensionWeights.external;\n const baseline = structuralBase + evolutionBase + externalBase;\n\n const interactionStructuralEvolution =\n structuralFactor * evolutionFactor * config.interactionWeights.structuralEvolution;\n const interactionCentralInstability =\n structuralCentrality * evolutionFactor * config.interactionWeights.centralInstability;\n const interactionDependencyAmplification =\n externalFactor *\n Math.max(structuralFactor, evolutionFactor) *\n config.interactionWeights.dependencyAmplification;\n\n const interactions = [\n interactionStructuralEvolution,\n interactionCentralInstability,\n interactionDependencyAmplification,\n ];\n\n const normalizedScore = saturatingComposite(baseline, interactions);\n\n return {\n file: filePath,\n score: round4(normalizedScore * 100),\n normalizedScore: round4(normalizedScore),\n factors: {\n structural: round4(structuralFactor),\n evolution: round4(evolutionFactor),\n external: round4(externalFactor),\n },\n structuralCentrality: round4(structuralCentrality),\n traceTerms: {\n structuralBase: round4(structuralBase),\n evolutionBase: round4(evolutionBase),\n externalBase: round4(externalBase),\n interactionStructuralEvolution: round4(interactionStructuralEvolution),\n interactionCentralInstability: round4(interactionCentralInstability),\n interactionDependencyAmplification: round4(interactionDependencyAmplification),\n },\n rawMetrics: {\n fanIn: file.fanIn,\n fanOut: file.fanOut,\n depth: file.depth,\n cycleParticipation: inCycle,\n commitCount: evolutionMetrics?.commitCount ?? null,\n churnTotal: evolutionMetrics?.churnTotal ?? null,\n recentVolatility: evolutionMetrics?.recentVolatility ?? null,\n topAuthorShareByCommits: evolutionMetrics?.topAuthorShareByCommits ?? null,\n busFactorByCommits: evolutionMetrics?.busFactorByCommits ?? null,\n dependencyAffinity: round4(dependencyAffinity),\n repositoryExternalPressure: round4(dependencyComputation.repositoryExternalPressure),\n structuralAttenuation: round4(structuralAttenuation),\n },\n normalizedMetrics: {\n fanInRisk: round4(fanInRisk),\n fanOutRisk: round4(fanOutRisk),\n depthRisk: round4(depthRisk),\n frequencyRisk: round4(frequencyRisk),\n churnRisk: round4(churnRisk),\n volatilityRisk: round4(volatilityRisk),\n ownershipConcentrationRisk: round4(ownershipConcentrationRisk),\n busFactorRisk: round4(busFactorRisk),\n },\n };\n })\n .sort((a, b) => b.score - a.score || a.file.localeCompare(b.file));\n\n const fileScores: FileRiskScore[] = fileRiskContexts.map((context) => ({\n file: context.file,\n score: context.score,\n normalizedScore: context.normalizedScore,\n factors: context.factors,\n }));\n\n if (collector !== undefined) {\n for (const context of fileRiskContexts) {\n const evidence: EvidenceRef[] = [\n { kind: \"file_metric\", target: context.file, metric: \"fanIn\" },\n { kind: \"file_metric\", target: context.file, metric: \"fanOut\" },\n { kind: \"file_metric\", target: context.file, metric: \"depth\" },\n ];\n\n if (context.rawMetrics.cycleParticipation > 0) {\n evidence.push({\n kind: \"graph_cycle\",\n cycleId: `file:${context.file}`,\n files: [context.file],\n });\n }\n\n const fileFactors = buildFactorTraces(context.score, [\n {\n factorId: \"file.structural\",\n family: \"structural\",\n strength: context.traceTerms.structuralBase,\n rawMetrics: {\n fanIn: context.rawMetrics.fanIn,\n fanOut: context.rawMetrics.fanOut,\n depth: context.rawMetrics.depth,\n cycleParticipation: context.rawMetrics.cycleParticipation,\n structuralAttenuation: context.rawMetrics.structuralAttenuation,\n },\n normalizedMetrics: {\n fanInRisk: context.normalizedMetrics.fanInRisk,\n fanOutRisk: context.normalizedMetrics.fanOutRisk,\n depthRisk: context.normalizedMetrics.depthRisk,\n structuralFactor: context.factors.structural,\n },\n weight: dimensionWeights.structural,\n amplification: null,\n evidence,\n confidence: 1,\n },\n {\n factorId: \"file.evolution\",\n family: \"evolution\",\n strength: context.traceTerms.evolutionBase,\n rawMetrics: {\n commitCount: context.rawMetrics.commitCount,\n churnTotal: context.rawMetrics.churnTotal,\n recentVolatility: context.rawMetrics.recentVolatility,\n topAuthorShareByCommits: context.rawMetrics.topAuthorShareByCommits,\n busFactorByCommits: context.rawMetrics.busFactorByCommits,\n },\n normalizedMetrics: {\n frequencyRisk: context.normalizedMetrics.frequencyRisk,\n churnRisk: context.normalizedMetrics.churnRisk,\n volatilityRisk: context.normalizedMetrics.volatilityRisk,\n ownershipConcentrationRisk: context.normalizedMetrics.ownershipConcentrationRisk,\n busFactorRisk: context.normalizedMetrics.busFactorRisk,\n evolutionFactor: context.factors.evolution,\n },\n weight: dimensionWeights.evolution,\n amplification: null,\n evidence: [{ kind: \"file_metric\", target: context.file, metric: \"commitCount\" }],\n confidence: evolution.available\n ? evolutionHistoryConfidence * (context.rawMetrics.commitCount === null ? 0.5 : 1)\n : 0,\n },\n {\n factorId: \"file.external\",\n family: \"external\",\n strength: context.traceTerms.externalBase,\n rawMetrics: {\n repositoryExternalPressure: context.rawMetrics.repositoryExternalPressure,\n dependencyAffinity: context.rawMetrics.dependencyAffinity,\n },\n normalizedMetrics: {\n externalFactor: context.factors.external,\n },\n weight: dimensionWeights.external,\n amplification: null,\n evidence: [{ kind: \"repository_metric\", metric: \"repositoryExternalPressure\" }],\n confidence: external.available ? 0.7 * externalMetadataConfidence : 0,\n },\n {\n factorId: \"file.composite.interactions\",\n family: \"composite\",\n strength:\n context.traceTerms.interactionStructuralEvolution +\n context.traceTerms.interactionCentralInstability +\n context.traceTerms.interactionDependencyAmplification,\n rawMetrics: {\n structuralEvolutionInteraction: context.traceTerms.interactionStructuralEvolution,\n centralInstabilityInteraction: context.traceTerms.interactionCentralInstability,\n dependencyAmplificationInteraction:\n context.traceTerms.interactionDependencyAmplification,\n },\n normalizedMetrics: {},\n weight: null,\n amplification:\n config.interactionWeights.structuralEvolution +\n config.interactionWeights.centralInstability +\n config.interactionWeights.dependencyAmplification,\n evidence: [{ kind: \"repository_metric\", metric: \"interactionWeights\" }],\n confidence: 0.9,\n },\n ]);\n\n collector.record(\n buildTargetTrace(\"file\", context.file, context.score, context.normalizedScore, fileFactors),\n );\n }\n }\n\n const fileScoresByFile = new Map(fileScores.map((fileScore) => [fileScore.file, fileScore]));\n\n const hotspotsCount = Math.min(\n config.hotspotMaxFiles,\n Math.max(config.hotspotMinFiles, Math.ceil(fileScores.length * config.hotspotTopPercent)),\n );\n\n const hotspots = fileScores.slice(0, hotspotsCount).map((fileScore) => ({\n file: fileScore.file,\n score: fileScore.score,\n factors: fileScore.factors,\n }));\n\n const moduleFiles = new Map<string, number[]>();\n for (const fileScore of fileScores) {\n const moduleName = inferModuleName(fileScore.file, config);\n const values = moduleFiles.get(moduleName) ?? [];\n values.push(fileScore.normalizedScore);\n moduleFiles.set(moduleName, values);\n }\n\n const moduleScores: ModuleRiskScore[] = [...moduleFiles.entries()]\n .map(([module, values]) => {\n const averageScore = average(values);\n const peakScore = values.reduce((max, value) => Math.max(max, value), 0);\n const normalizedScore = toUnitInterval(averageScore * 0.65 + peakScore * 0.35);\n\n return {\n module,\n score: round4(normalizedScore * 100),\n normalizedScore: round4(normalizedScore),\n fileCount: values.length,\n };\n })\n .sort((a, b) => b.score - a.score || a.module.localeCompare(b.module));\n\n if (collector !== undefined) {\n for (const [module, values] of moduleFiles.entries()) {\n const averageScore = average(values);\n const peakScore = values.reduce((max, value) => Math.max(max, value), 0);\n const normalizedScore = toUnitInterval(averageScore * 0.65 + peakScore * 0.35);\n const totalScore = round4(normalizedScore * 100);\n const factors = buildFactorTraces(totalScore, [\n {\n factorId: \"module.average_file_risk\",\n family: \"composite\",\n strength: averageScore * 0.65,\n rawMetrics: { averageFileRisk: round4(averageScore), fileCount: values.length },\n normalizedMetrics: { normalizedModuleRisk: round4(normalizedScore) },\n weight: 0.65,\n amplification: null,\n evidence: [{ kind: \"repository_metric\", metric: \"moduleAggregation.average\" }],\n confidence: 1,\n },\n {\n factorId: \"module.peak_file_risk\",\n family: \"composite\",\n strength: peakScore * 0.35,\n rawMetrics: { peakFileRisk: round4(peakScore), fileCount: values.length },\n normalizedMetrics: { normalizedModuleRisk: round4(normalizedScore) },\n weight: 0.35,\n amplification: null,\n evidence: [{ kind: \"repository_metric\", metric: \"moduleAggregation.peak\" }],\n confidence: 1,\n },\n ]);\n\n collector.record(buildTargetTrace(\"module\", module, totalScore, normalizedScore, factors));\n }\n }\n\n const workspaceScores = buildWorkspaceRiskScores(structural, fileScoresByFile);\n\n const fragileClusters = buildFragileClusters(structural, evolution, fileScoresByFile, config);\n\n const externalPressures = fileScores.map((fileScore) => fileScore.factors.external);\n const pressureThreshold = Math.max(\n config.amplificationZone.pressureFloor,\n percentile(externalPressures, config.amplificationZone.percentileThreshold),\n );\n\n const dependencyAmplificationZones = fileScores\n .map((fileScore) => {\n const intensity = toUnitInterval(\n fileScore.factors.external *\n Math.max(fileScore.factors.structural, fileScore.factors.evolution),\n );\n const normalizedZoneScore = toUnitInterval(intensity * 0.7 + fileScore.normalizedScore * 0.3);\n\n return {\n file: fileScore.file,\n score: round4(normalizedZoneScore * 100),\n externalPressure: fileScore.factors.external,\n };\n })\n .filter((zone) => external.available && zone.externalPressure >= pressureThreshold)\n .sort((a, b) => b.score - a.score || a.file.localeCompare(b.file))\n .slice(0, config.amplificationZone.maxZones)\n .map((zone) => ({\n ...zone,\n externalPressure: round4(zone.externalPressure),\n }));\n\n if (collector !== undefined && external.available) {\n const dependencyByName = new Map(\n external.dependencies.map((dependency) => [dependency.name, dependency]),\n );\n for (const dependencyScore of dependencyComputation.dependencyScores) {\n const dependency = dependencyByName.get(dependencyScore.dependency);\n const context = dependencyComputation.dependencyContexts.get(dependencyScore.dependency);\n if (dependency === undefined || context === undefined) {\n continue;\n }\n\n const hasMetadata =\n context.rawMetrics.daysSinceLastRelease !== null &&\n context.rawMetrics.maintainerCount !== null;\n const factors = buildFactorTraces(dependencyScore.score, [\n {\n factorId: \"dependency.signals\",\n family: \"external\",\n strength: context.signalScore * config.dependencyFactorWeights.signals,\n rawMetrics: {\n ownSignals: dependency.ownRiskSignals.length,\n inheritedSignals: dependency.inheritedRiskSignals.length,\n },\n normalizedMetrics: { signalScore: context.signalScore },\n weight: config.dependencyFactorWeights.signals,\n amplification: config.dependencySignals.inheritedSignalMultiplier,\n evidence: [{ kind: \"dependency_metric\", target: dependency.name, metric: \"riskSignals\" }],\n confidence: 0.95 * externalMetadataConfidence,\n },\n {\n factorId: \"dependency.staleness\",\n family: \"external\",\n strength: context.stalenessRisk * config.dependencyFactorWeights.staleness,\n rawMetrics: { daysSinceLastRelease: context.rawMetrics.daysSinceLastRelease },\n normalizedMetrics: { stalenessRisk: context.stalenessRisk },\n weight: config.dependencyFactorWeights.staleness,\n amplification: null,\n evidence: [\n { kind: \"dependency_metric\", target: dependency.name, metric: \"daysSinceLastRelease\" },\n ],\n confidence: (hasMetadata ? 0.9 : 0.5) * externalMetadataConfidence,\n },\n {\n factorId: \"dependency.maintainer_concentration\",\n family: \"external\",\n strength:\n context.maintainerConcentrationRisk *\n config.dependencyFactorWeights.maintainerConcentration,\n rawMetrics: { maintainerCount: context.rawMetrics.maintainerCount },\n normalizedMetrics: {\n maintainerConcentrationRisk: context.maintainerConcentrationRisk,\n },\n weight: config.dependencyFactorWeights.maintainerConcentration,\n amplification: null,\n evidence: [\n { kind: \"dependency_metric\", target: dependency.name, metric: \"maintainerCount\" },\n ],\n confidence: (hasMetadata ? 0.9 : 0.5) * externalMetadataConfidence,\n },\n {\n factorId: \"dependency.topology\",\n family: \"external\",\n strength:\n context.transitiveBurdenRisk * config.dependencyFactorWeights.transitiveBurden +\n context.centralityRisk * config.dependencyFactorWeights.centrality +\n context.chainDepthRisk * config.dependencyFactorWeights.chainDepth,\n rawMetrics: {\n transitiveCount: context.rawMetrics.transitiveCount,\n dependents: context.rawMetrics.dependents,\n dependencyDepth: context.rawMetrics.dependencyDepth,\n },\n normalizedMetrics: {\n transitiveBurdenRisk: context.transitiveBurdenRisk,\n centralityRisk: context.centralityRisk,\n chainDepthRisk: context.chainDepthRisk,\n },\n weight:\n config.dependencyFactorWeights.transitiveBurden +\n config.dependencyFactorWeights.centrality +\n config.dependencyFactorWeights.chainDepth,\n amplification: null,\n evidence: [\n { kind: \"dependency_metric\", target: dependency.name, metric: \"dependencyDepth\" },\n ],\n confidence: 1 * externalMetadataConfidence,\n },\n {\n factorId: \"dependency.bus_factor\",\n family: \"external\",\n strength: context.busFactorRisk * config.dependencyFactorWeights.busFactorRisk,\n rawMetrics: { busFactor: context.rawMetrics.busFactor },\n normalizedMetrics: { busFactorRisk: context.busFactorRisk },\n weight: config.dependencyFactorWeights.busFactorRisk,\n amplification: null,\n evidence: [{ kind: \"dependency_metric\", target: dependency.name, metric: \"busFactor\" }],\n confidence:\n (context.rawMetrics.busFactor === null ? 0.5 : 0.85) * externalMetadataConfidence,\n },\n {\n factorId: \"dependency.popularity_dampening\",\n family: \"composite\",\n strength: 1 - context.popularityDampener,\n rawMetrics: { weeklyDownloads: context.rawMetrics.weeklyDownloads },\n normalizedMetrics: { popularityDampener: context.popularityDampener },\n weight: config.dependencySignals.popularityMaxDampening,\n amplification: null,\n evidence: [\n { kind: \"dependency_metric\", target: dependency.name, metric: \"weeklyDownloads\" },\n ],\n confidence:\n (context.rawMetrics.weeklyDownloads === null ? 0.4 : 0.9) * externalMetadataConfidence,\n },\n ]);\n\n collector.record(\n buildTargetTrace(\n \"dependency\",\n dependencyScore.dependency,\n dependencyScore.score,\n dependencyScore.normalizedScore,\n factors,\n ),\n );\n }\n }\n\n const structuralDimension = average(fileScores.map((fileScore) => fileScore.factors.structural));\n const evolutionDimension = average(fileScores.map((fileScore) => fileScore.factors.evolution));\n const externalDimension = dependencyComputation.repositoryExternalPressure;\n\n const topCentralSlice = Math.max(1, Math.ceil(fileRiskContexts.length * 0.1));\n const criticalInstability = average(\n [...fileRiskContexts]\n .sort(\n (a, b) =>\n b.structuralCentrality * b.factors.evolution -\n a.structuralCentrality * a.factors.evolution || a.file.localeCompare(b.file),\n )\n .slice(0, topCentralSlice)\n .map((context) => context.structuralCentrality * context.factors.evolution),\n );\n\n const dependencyAmplification = average(\n dependencyAmplificationZones.map((zone) =>\n toUnitInterval((zone.externalPressure * zone.score) / 100),\n ),\n );\n\n const repositoryBaseline =\n structuralDimension * dimensionWeights.structural +\n evolutionDimension * dimensionWeights.evolution +\n externalDimension * dimensionWeights.external;\n\n const repositoryNormalizedScore = saturatingComposite(repositoryBaseline, [\n structuralDimension * evolutionDimension * config.interactionWeights.structuralEvolution,\n criticalInstability * config.interactionWeights.centralInstability,\n dependencyAmplification * config.interactionWeights.dependencyAmplification,\n ]);\n\n const riskScore = round4(repositoryNormalizedScore * 100);\n\n if (collector !== undefined) {\n const repositoryFactors = buildFactorTraces(riskScore, [\n {\n factorId: \"repository.structural\",\n family: \"structural\",\n strength: structuralDimension * dimensionWeights.structural,\n rawMetrics: { structuralDimension: round4(structuralDimension) },\n normalizedMetrics: { dimensionWeight: round4(dimensionWeights.structural) },\n weight: dimensionWeights.structural,\n amplification: null,\n evidence: [{ kind: \"repository_metric\", metric: \"structuralDimension\" }],\n confidence: 1,\n },\n {\n factorId: \"repository.evolution\",\n family: \"evolution\",\n strength: evolutionDimension * dimensionWeights.evolution,\n rawMetrics: { evolutionDimension: round4(evolutionDimension) },\n normalizedMetrics: { dimensionWeight: round4(dimensionWeights.evolution) },\n weight: dimensionWeights.evolution,\n amplification: null,\n evidence: [{ kind: \"repository_metric\", metric: \"evolutionDimension\" }],\n confidence: evolution.available ? evolutionHistoryConfidence : 0,\n },\n {\n factorId: \"repository.external\",\n family: \"external\",\n strength: externalDimension * dimensionWeights.external,\n rawMetrics: { externalDimension: round4(externalDimension) },\n normalizedMetrics: { dimensionWeight: round4(dimensionWeights.external) },\n weight: dimensionWeights.external,\n amplification: null,\n evidence: [{ kind: \"repository_metric\", metric: \"externalDimension\" }],\n confidence: external.available ? 0.8 * externalMetadataConfidence : 0,\n },\n {\n factorId: \"repository.composite.interactions\",\n family: \"composite\",\n strength:\n structuralDimension * evolutionDimension * config.interactionWeights.structuralEvolution +\n criticalInstability * config.interactionWeights.centralInstability +\n dependencyAmplification * config.interactionWeights.dependencyAmplification,\n rawMetrics: {\n structuralEvolution: round4(\n structuralDimension *\n evolutionDimension *\n config.interactionWeights.structuralEvolution,\n ),\n centralInstability: round4(\n criticalInstability * config.interactionWeights.centralInstability,\n ),\n dependencyAmplification: round4(\n dependencyAmplification * config.interactionWeights.dependencyAmplification,\n ),\n },\n normalizedMetrics: {\n criticalInstability: round4(criticalInstability),\n dependencyAmplification: round4(dependencyAmplification),\n },\n weight: null,\n amplification:\n config.interactionWeights.structuralEvolution +\n config.interactionWeights.centralInstability +\n config.interactionWeights.dependencyAmplification,\n evidence: [{ kind: \"repository_metric\", metric: \"interactionTerms\" }],\n confidence: 0.9,\n },\n ]);\n\n collector.record(\n buildTargetTrace(\n \"repository\",\n structural.targetPath,\n riskScore,\n repositoryNormalizedScore,\n repositoryFactors,\n ),\n );\n }\n\n return {\n riskScore,\n normalizedScore: round4(repositoryNormalizedScore),\n hotspots,\n fragileClusters,\n dependencyAmplificationZones,\n fileScores,\n moduleScores,\n workspaceScores,\n dependencyScores: dependencyComputation.dependencyScores,\n };\n};\n","export const toUnitInterval = (value: number): number =>\n Number.isFinite(value) ? Math.min(1, Math.max(0, value)) : 0;\n\nexport const round4 = (value: number): number => Number(value.toFixed(4));\n\nexport const average = (values: readonly number[]): number => {\n if (values.length === 0) {\n return 0;\n }\n\n const total = values.reduce((sum, current) => sum + current, 0);\n return total / values.length;\n};\n\nexport const percentile = (values: readonly number[], p: number): number => {\n if (values.length === 0) {\n return 0;\n }\n\n if (values.length === 1) {\n return values[0] ?? 0;\n }\n\n const sorted = [...values].sort((a, b) => a - b);\n const position = toUnitInterval(p) * (sorted.length - 1);\n const lowerIndex = Math.floor(position);\n const upperIndex = Math.ceil(position);\n\n const lower = sorted[lowerIndex] ?? 0;\n const upper = sorted[upperIndex] ?? lower;\n\n if (lowerIndex === upperIndex) {\n return lower;\n }\n\n const ratio = position - lowerIndex;\n return lower + (upper - lower) * ratio;\n};\n\nexport const saturatingComposite = (\n baseline: number,\n amplifications: readonly number[],\n): number => {\n let value = toUnitInterval(baseline);\n\n for (const amplification of amplifications) {\n const boundedAmplification = toUnitInterval(amplification);\n value += (1 - value) * boundedAmplification;\n }\n\n return toUnitInterval(value);\n};\n\nexport const halfLifeRisk = (value: number, halfLife: number): number => {\n if (value <= 0 || halfLife <= 0) {\n return 0;\n }\n\n return toUnitInterval(value / (value + halfLife));\n};\n\nexport const normalizeWeights = <T extends string>(\n weights: Readonly<Record<T, number>>,\n enabled: Readonly<Record<T, boolean>>,\n): Readonly<Record<T, number>> => {\n let total = 0;\n const result: Record<T, number> = { ...weights };\n\n for (const key of Object.keys(result) as T[]) {\n const enabledValue = enabled[key];\n if (!enabledValue) {\n result[key] = 0;\n continue;\n }\n\n const value = Math.max(0, result[key]);\n result[key] = value;\n total += value;\n }\n\n if (total === 0) {\n const activeKeys = (Object.keys(result) as T[]).filter((key) => enabled[key]);\n if (activeKeys.length === 0) {\n return result;\n }\n\n const uniform = 1 / activeKeys.length;\n for (const key of activeKeys) {\n result[key] = uniform;\n }\n\n return result;\n }\n\n for (const key of Object.keys(result) as T[]) {\n if (enabled[key]) {\n result[key] = result[key] / total;\n }\n }\n\n return result;\n};\n","import { toUnitInterval, percentile } from \"./math.js\";\n\nexport type QuantileScale = {\n lower: number;\n upper: number;\n};\n\nexport const logScale = (value: number): number => Math.log1p(Math.max(0, value));\n\nexport const buildQuantileScale = (\n values: readonly number[],\n lowerPercentile: number,\n upperPercentile: number,\n): QuantileScale => {\n if (values.length === 0) {\n return { lower: 0, upper: 0 };\n }\n\n return {\n lower: percentile(values, lowerPercentile),\n upper: percentile(values, upperPercentile),\n };\n};\n\nexport const normalizeWithScale = (value: number, scale: QuantileScale): number => {\n if (scale.upper <= scale.lower) {\n return value > 0 ? 1 : 0;\n }\n\n return toUnitInterval((value - scale.lower) / (scale.upper - scale.lower));\n};\n","import type { RiskTrace, TargetTrace } from \"@codesentinel/core\";\n\nexport interface TraceCollector {\n record(target: TargetTrace): void;\n build(): RiskTrace | undefined;\n}\n\nclass NoopTraceCollector implements TraceCollector {\n record(_target: TargetTrace): void {}\n\n build(): undefined {\n return undefined;\n }\n}\n\nclass RecordingTraceCollector implements TraceCollector {\n private readonly targets: TargetTrace[] = [];\n\n record(target: TargetTrace): void {\n this.targets.push(target);\n }\n\n build(): RiskTrace {\n const orderedTargets = [...this.targets].sort((a, b) => {\n if (a.targetType !== b.targetType) {\n return a.targetType.localeCompare(b.targetType);\n }\n\n if (b.totalScore !== a.totalScore) {\n return b.totalScore - a.totalScore;\n }\n\n return a.targetId.localeCompare(b.targetId);\n });\n\n return {\n schemaVersion: \"1\",\n contributionTolerance: 0.0001,\n targets: orderedTargets,\n };\n }\n}\n\nconst noopCollectorSingleton = new NoopTraceCollector();\n\nexport const createTraceCollector = (enabled: boolean): TraceCollector =>\n enabled ? new RecordingTraceCollector() : noopCollectorSingleton;\n","import type {\n ExternalAnalysisSummary,\n GraphAnalysisSummary,\n RepositoryRiskEvaluation,\n RepositoryEvolutionSummary,\n RepositoryRiskSummary,\n} from \"@codesentinel/core\";\nimport { DEFAULT_RISK_ENGINE_CONFIG, type RiskEngineConfig } from \"../config.js\";\nimport { computeRiskSummary } from \"../domain/risk-model.js\";\nimport { createTraceCollector } from \"../domain/trace-collector.js\";\n\ntype DeepPartial<T> = {\n [K in keyof T]?: T[K] extends readonly unknown[]\n ? T[K]\n : T[K] extends object\n ? DeepPartial<T[K]>\n : T[K];\n};\n\nexport type ComputeRepositoryRiskSummaryInput = {\n structural: GraphAnalysisSummary;\n evolution: RepositoryEvolutionSummary;\n external: ExternalAnalysisSummary;\n config?: DeepPartial<RiskEngineConfig>;\n};\n\nexport type EvaluateRepositoryRiskOptions = {\n explain?: boolean;\n};\n\nconst mergeConfig = (overrides: DeepPartial<RiskEngineConfig> | undefined): RiskEngineConfig => {\n if (overrides === undefined) {\n return DEFAULT_RISK_ENGINE_CONFIG;\n }\n\n return {\n ...DEFAULT_RISK_ENGINE_CONFIG,\n ...overrides,\n dimensionWeights: {\n ...DEFAULT_RISK_ENGINE_CONFIG.dimensionWeights,\n ...overrides.dimensionWeights,\n },\n interactionWeights: {\n ...DEFAULT_RISK_ENGINE_CONFIG.interactionWeights,\n ...overrides.interactionWeights,\n },\n structuralFactorWeights: {\n ...DEFAULT_RISK_ENGINE_CONFIG.structuralFactorWeights,\n ...overrides.structuralFactorWeights,\n },\n evolutionFactorWeights: {\n ...DEFAULT_RISK_ENGINE_CONFIG.evolutionFactorWeights,\n ...overrides.evolutionFactorWeights,\n },\n dependencyFactorWeights: {\n ...DEFAULT_RISK_ENGINE_CONFIG.dependencyFactorWeights,\n ...overrides.dependencyFactorWeights,\n },\n quantileClamp: {\n ...DEFAULT_RISK_ENGINE_CONFIG.quantileClamp,\n ...overrides.quantileClamp,\n },\n couplingCluster: {\n ...DEFAULT_RISK_ENGINE_CONFIG.couplingCluster,\n ...overrides.couplingCluster,\n },\n amplificationZone: {\n ...DEFAULT_RISK_ENGINE_CONFIG.amplificationZone,\n ...overrides.amplificationZone,\n },\n module: {\n ...DEFAULT_RISK_ENGINE_CONFIG.module,\n ...overrides.module,\n },\n dependencySignals: {\n ...DEFAULT_RISK_ENGINE_CONFIG.dependencySignals,\n ...overrides.dependencySignals,\n },\n externalDimension: {\n ...DEFAULT_RISK_ENGINE_CONFIG.externalDimension,\n ...overrides.externalDimension,\n },\n aggregatorAttenuation: {\n ...DEFAULT_RISK_ENGINE_CONFIG.aggregatorAttenuation,\n ...overrides.aggregatorAttenuation,\n },\n };\n};\n\nexport const computeRepositoryRiskSummary = (\n input: ComputeRepositoryRiskSummaryInput,\n): RepositoryRiskSummary => {\n return evaluateRepositoryRisk(input, { explain: false }).summary;\n};\n\nexport const evaluateRepositoryRisk = (\n input: ComputeRepositoryRiskSummaryInput,\n options: EvaluateRepositoryRiskOptions = {},\n): RepositoryRiskEvaluation => {\n const config = mergeConfig(input.config);\n const collector = createTraceCollector(options.explain === true);\n const summary = computeRiskSummary(\n input.structural,\n input.evolution,\n input.external,\n config,\n collector,\n );\n\n const trace = collector.build();\n if (options.explain !== true) {\n return { summary };\n }\n\n if (trace === undefined) {\n return { summary };\n }\n\n return {\n summary,\n trace,\n };\n};\n","import { readFile, writeFile } from \"node:fs/promises\";\nimport {\n GovernanceConfigurationError,\n evaluateGates,\n renderCheckMarkdown,\n renderCheckText,\n type GateConfig,\n type GateEvaluationResult,\n} from \"@codesentinel/governance\";\nimport { compareSnapshots, parseSnapshot, type CodeSentinelSnapshot } from \"@codesentinel/reporter\";\nimport { buildAnalysisSnapshot } from \"./build-analysis-snapshot.js\";\nimport { createSilentLogger, type Logger } from \"./logger.js\";\nimport type { AuthorIdentityCliMode, ScoringProfileCliMode } from \"./run-analyze-command.js\";\n\nexport type CheckOutputFormat = \"json\" | \"text\" | \"md\";\n\nexport type RunCheckCommandOptions = {\n baselinePath?: string;\n includeTrace: boolean;\n recentWindowDays?: number;\n scoringProfile?: ScoringProfileCliMode;\n gateConfig: GateConfig;\n outputFormat: CheckOutputFormat;\n outputPath?: string;\n};\n\nexport type CheckCommandResult = {\n current: CodeSentinelSnapshot;\n baseline?: CodeSentinelSnapshot;\n diff?: ReturnType<typeof compareSnapshots>;\n gateResult: GateEvaluationResult;\n rendered: string;\n};\n\nconst formatCheckResult = (result: CheckCommandResult, format: CheckOutputFormat): string => {\n if (format === \"json\") {\n return JSON.stringify(\n {\n current: result.current,\n ...(result.baseline === undefined ? {} : { baseline: result.baseline }),\n ...(result.diff === undefined ? {} : { diff: result.diff }),\n violations: result.gateResult.violations,\n evaluatedGates: result.gateResult.evaluatedGates,\n highestSeverity: result.gateResult.highestSeverity,\n exitCode: result.gateResult.exitCode,\n },\n null,\n 2,\n );\n }\n\n if (format === \"md\") {\n return renderCheckMarkdown(result.current, result.gateResult);\n }\n\n return renderCheckText(result.current, result.gateResult);\n};\n\nexport const runCheckCommand = async (\n inputPath: string | undefined,\n authorIdentityMode: AuthorIdentityCliMode,\n options: RunCheckCommandOptions,\n logger: Logger = createSilentLogger(),\n): Promise<CheckCommandResult> => {\n logger.info(\"building current snapshot for check\");\n const current = await buildAnalysisSnapshot(\n inputPath,\n authorIdentityMode,\n {\n includeTrace: options.includeTrace,\n ...(options.scoringProfile === undefined ? {} : { scoringProfile: options.scoringProfile }),\n ...(options.recentWindowDays === undefined\n ? {}\n : { recentWindowDays: options.recentWindowDays }),\n },\n logger,\n );\n\n let baseline: CodeSentinelSnapshot | undefined;\n let diff: ReturnType<typeof compareSnapshots> | undefined;\n\n if (options.baselinePath !== undefined) {\n logger.info(`loading baseline snapshot: ${options.baselinePath}`);\n const baselineRaw = await readFile(options.baselinePath, \"utf8\");\n try {\n baseline = parseSnapshot(baselineRaw);\n } catch (error) {\n const message = error instanceof Error ? error.message : \"invalid baseline snapshot\";\n throw new GovernanceConfigurationError(`invalid baseline snapshot: ${message}`);\n }\n diff = compareSnapshots(current, baseline);\n }\n\n const gateResult = evaluateGates({\n current,\n ...(baseline === undefined ? {} : { baseline }),\n ...(diff === undefined ? {} : { diff }),\n gateConfig: options.gateConfig,\n });\n\n const rendered = formatCheckResult(\n {\n current,\n ...(baseline === undefined ? {} : { baseline }),\n ...(diff === undefined ? {} : { diff }),\n gateResult,\n rendered: \"\",\n },\n options.outputFormat,\n );\n\n if (options.outputPath !== undefined) {\n await writeFile(options.outputPath, rendered, \"utf8\");\n logger.info(`check output written: ${options.outputPath}`);\n }\n\n return {\n current,\n ...(baseline === undefined ? {} : { baseline }),\n ...(diff === undefined ? {} : { diff }),\n gateResult,\n rendered,\n };\n};\n\nexport { GovernanceConfigurationError };\n","import type { AnalyzeSummary } from \"@codesentinel/core\";\nimport { computeRepositoryHealthSummary } from \"@codesentinel/health-engine\";\nimport { evaluateRepositoryRisk } from \"@codesentinel/risk-engine\";\nimport { createSnapshot, type CodeSentinelSnapshot } from \"@codesentinel/reporter\";\nimport {\n collectAnalysisInputs,\n resolveHealthConfigForProfile,\n resolveRiskConfigForProfile,\n type AuthorIdentityCliMode,\n type ScoringProfileCliMode,\n} from \"./run-analyze-command.js\";\nimport type { Logger } from \"./logger.js\";\n\nexport type BuildAnalysisSnapshotOptions = {\n includeTrace: boolean;\n recentWindowDays?: number;\n scoringProfile?: ScoringProfileCliMode;\n};\n\nexport const buildAnalysisSnapshot = async (\n inputPath: string | undefined,\n authorIdentityMode: AuthorIdentityCliMode,\n options: BuildAnalysisSnapshotOptions,\n logger: Logger,\n): Promise<CodeSentinelSnapshot> => {\n const analysisInputs = await collectAnalysisInputs(\n inputPath,\n authorIdentityMode,\n {\n ...(options.recentWindowDays === undefined\n ? {}\n : { recentWindowDays: options.recentWindowDays }),\n },\n logger,\n );\n const riskConfig = resolveRiskConfigForProfile(options.scoringProfile);\n const healthConfig = resolveHealthConfigForProfile(options.scoringProfile);\n const evaluation = evaluateRepositoryRisk(\n {\n structural: analysisInputs.structural,\n evolution: analysisInputs.evolution,\n external: analysisInputs.external,\n ...(riskConfig === undefined ? {} : { config: riskConfig }),\n },\n { explain: options.includeTrace },\n );\n\n const summary: AnalyzeSummary = {\n structural: analysisInputs.structural,\n evolution: analysisInputs.evolution,\n external: analysisInputs.external,\n risk: evaluation.summary,\n health: computeRepositoryHealthSummary({\n structural: analysisInputs.structural,\n evolution: analysisInputs.evolution,\n ...(healthConfig === undefined ? {} : { config: healthConfig }),\n }),\n };\n\n return createSnapshot({\n analysis: summary,\n ...(evaluation.trace === undefined ? {} : { trace: evaluation.trace }),\n analysisConfig: {\n authorIdentityMode,\n includeTrace: options.includeTrace,\n scoringProfile: options.scoringProfile ?? \"default\",\n recentWindowDays: analysisInputs.evolution.available\n ? analysisInputs.evolution.metrics.recentWindowDays\n : (options.recentWindowDays ?? null),\n },\n });\n};\n","import { readFile, writeFile } from \"node:fs/promises\";\nimport {\n BaselineRefResolutionError,\n GovernanceConfigurationError,\n evaluateGates,\n renderCheckMarkdown,\n resolveAutoBaselineRef,\n resolveBaselineSnapshotFromRef,\n type GateConfig,\n type GateEvaluationResult,\n type OwnershipGateInput,\n type OwnershipGateMetrics,\n} from \"@codesentinel/governance\";\nimport { relative, resolve } from \"node:path\";\nimport type { OwnershipAudit } from \"@codesentinel/ownership\";\nimport {\n compareSnapshots,\n createReport,\n formatReport,\n parseSnapshot,\n type CodeSentinelSnapshot,\n} from \"@codesentinel/reporter\";\nimport { buildAnalysisSnapshot } from \"./build-analysis-snapshot.js\";\nimport { buildOwnershipAudit, OwnersConfigurationError } from \"./build-ownership-audit.js\";\nimport { createSilentLogger, type Logger } from \"./logger.js\";\nimport type { AuthorIdentityCliMode, ScoringProfileCliMode } from \"./run-analyze-command.js\";\n\nexport type RunCiCommandOptions = {\n baselinePath?: string;\n baselineRef?: string;\n baselineSha?: string;\n mainBranchCandidates?: readonly string[];\n snapshotPath?: string;\n reportPath?: string;\n jsonOutputPath?: string;\n includeTrace: boolean;\n recentWindowDays?: number;\n scoringProfile?: ScoringProfileCliMode;\n gateConfig: GateConfig;\n ownership?: { ref?: string; windowDays?: number; minCommits?: number };\n};\n\nexport type CiOwnershipSummary = {\n available: boolean;\n codeownersSource: string | null;\n metrics: OwnershipGateMetrics | null;\n warnings: readonly string[];\n};\n\nexport type CiCommandResult = {\n current: CodeSentinelSnapshot;\n baseline?: CodeSentinelSnapshot;\n diff?: ReturnType<typeof compareSnapshots>;\n gateResult: GateEvaluationResult;\n markdownSummary: string;\n ownership?: CiOwnershipSummary;\n machineReadable: {\n current: CodeSentinelSnapshot;\n baseline?: CodeSentinelSnapshot;\n diff?: ReturnType<typeof compareSnapshots>;\n violations: GateEvaluationResult[\"violations\"];\n highestSeverity: GateEvaluationResult[\"highestSeverity\"];\n exitCode: GateEvaluationResult[\"exitCode\"];\n ownership?: CiOwnershipSummary;\n };\n};\n\nconst isPathOutsideBase = (value: string): boolean => {\n return value === \"..\" || value.startsWith(\"../\") || value.startsWith(\"..\\\\\");\n};\n\nexport const runCiCommand = async (\n inputPath: string | undefined,\n authorIdentityMode: AuthorIdentityCliMode,\n options: RunCiCommandOptions,\n logger: Logger = createSilentLogger(),\n): Promise<CiCommandResult> => {\n if (options.baselinePath !== undefined && options.baselineRef !== undefined) {\n throw new GovernanceConfigurationError(\n \"baseline configuration is ambiguous: use either --baseline or --baseline-ref\",\n );\n }\n if (options.baselineSha !== undefined && options.baselineRef !== \"auto\") {\n throw new GovernanceConfigurationError(\"baseline-sha requires --baseline-ref auto\");\n }\n\n const resolvedTargetPath = resolve(inputPath ?? process.cwd());\n\n logger.info(\"building current snapshot\");\n const current = await buildAnalysisSnapshot(\n inputPath,\n authorIdentityMode,\n {\n includeTrace: options.includeTrace,\n ...(options.scoringProfile === undefined ? {} : { scoringProfile: options.scoringProfile }),\n ...(options.recentWindowDays === undefined\n ? {}\n : { recentWindowDays: options.recentWindowDays }),\n },\n logger,\n );\n\n if (options.snapshotPath !== undefined) {\n await writeFile(options.snapshotPath, JSON.stringify(current, null, 2), \"utf8\");\n logger.info(`snapshot written: ${options.snapshotPath}`);\n }\n\n let baseline: CodeSentinelSnapshot | undefined;\n let diff: ReturnType<typeof compareSnapshots> | undefined;\n\n if (options.baselineRef !== undefined) {\n let baselineRef = options.baselineRef;\n if (options.baselineRef === \"auto\") {\n logger.info(\"resolving baseline ref using auto strategy\");\n try {\n const autoResolved = await resolveAutoBaselineRef({\n repositoryPath: resolvedTargetPath,\n ...(options.baselineSha === undefined ? {} : { baselineSha: options.baselineSha }),\n ...(options.mainBranchCandidates === undefined\n ? {}\n : { mainBranchCandidates: options.mainBranchCandidates }),\n environment: process.env,\n });\n logger.info(\n `baseline auto strategy selected: ${autoResolved.strategy} (${autoResolved.resolvedRef} -> ${autoResolved.resolvedSha})`,\n );\n for (const attempt of autoResolved.attempts) {\n const detail = attempt.detail === undefined ? \"\" : ` (${attempt.detail})`;\n logger.debug(\n `baseline auto attempt: ${attempt.step} ${attempt.candidate} => ${attempt.outcome}${detail}`,\n );\n }\n baselineRef = autoResolved.resolvedRef;\n } catch (error) {\n if (error instanceof BaselineRefResolutionError) {\n throw new GovernanceConfigurationError(\n `unable to resolve baseline ref 'auto': ${error.message}`,\n );\n }\n throw error;\n }\n }\n\n logger.info(`resolving baseline from git ref: ${baselineRef}`);\n try {\n const resolved = await resolveBaselineSnapshotFromRef({\n repositoryPath: resolvedTargetPath,\n baselineRef,\n analyzeWorktree: async (worktreePath, repositoryRoot) => {\n const relativeTargetPath = relative(repositoryRoot, resolvedTargetPath);\n if (isPathOutsideBase(relativeTargetPath)) {\n throw new GovernanceConfigurationError(\n `target path is outside git repository root: ${resolvedTargetPath}`,\n );\n }\n\n const baselineTargetPath =\n relativeTargetPath.length === 0 || relativeTargetPath === \".\"\n ? worktreePath\n : resolve(worktreePath, relativeTargetPath);\n\n return buildAnalysisSnapshot(\n baselineTargetPath,\n authorIdentityMode,\n {\n includeTrace: options.includeTrace,\n ...(options.scoringProfile === undefined\n ? {}\n : { scoringProfile: options.scoringProfile }),\n ...(options.recentWindowDays === undefined\n ? {}\n : { recentWindowDays: options.recentWindowDays }),\n },\n logger,\n );\n },\n });\n baseline = resolved.baselineSnapshot;\n logger.info(`baseline ref resolved to ${resolved.resolvedSha}`);\n } catch (error) {\n if (error instanceof BaselineRefResolutionError) {\n throw new GovernanceConfigurationError(\n `unable to resolve baseline ref '${baselineRef}': ${error.message}`,\n );\n }\n throw error;\n }\n diff = compareSnapshots(current, baseline);\n } else if (options.baselinePath !== undefined) {\n logger.info(`loading baseline snapshot: ${options.baselinePath}`);\n const baselineRaw = await readFile(options.baselinePath, \"utf8\");\n try {\n baseline = parseSnapshot(baselineRaw);\n } catch (error) {\n const message = error instanceof Error ? error.message : \"invalid baseline snapshot\";\n throw new GovernanceConfigurationError(`invalid baseline snapshot: ${message}`);\n }\n diff = compareSnapshots(current, baseline);\n }\n\n const ownershipConfigured =\n options.gateConfig.maxUnownedCritical !== undefined ||\n options.gateConfig.maxGhostOwners !== undefined ||\n options.gateConfig.maxDrift !== undefined;\n\n let ownershipInput: OwnershipGateInput | undefined;\n let ownershipSummary: CiOwnershipSummary | undefined;\n\n if (ownershipConfigured) {\n logger.info(\"auditing declared ownership for ownership gates\");\n let audit: OwnershipAudit;\n try {\n ({ audit } = await buildOwnershipAudit(\n resolvedTargetPath,\n {\n ...(options.ownership?.ref === undefined ? {} : { ref: options.ownership.ref }),\n ...(options.ownership?.windowDays === undefined\n ? {}\n : { windowDays: options.ownership.windowDays }),\n ...(options.ownership?.minCommits === undefined\n ? {}\n : { minCommits: options.ownership.minCommits }),\n },\n logger,\n ));\n } catch (error) {\n if (error instanceof OwnersConfigurationError) {\n throw new GovernanceConfigurationError(error.message);\n }\n throw error;\n }\n\n if (audit.available) {\n const metrics: OwnershipGateMetrics = {\n declaredCoveragePercent: audit.metrics.declaredCoveragePercent,\n declaredCoverageCriticalPercent: audit.metrics.declaredCoverageCriticalPercent,\n driftPercent: audit.metrics.driftPercent,\n ghostOwnerCount: audit.metrics.ghostOwnerCount,\n unownedCriticalCount: audit.metrics.unownedCriticalCount,\n };\n ownershipInput = {\n available: true,\n source: audit.codeowners.source,\n metrics,\n };\n ownershipSummary = {\n available: true,\n codeownersSource: audit.codeowners.source,\n metrics,\n warnings: [...audit.warnings],\n };\n } else {\n ownershipInput = { available: false, warnings: [...audit.warnings] };\n ownershipSummary = {\n available: false,\n codeownersSource: null,\n metrics: null,\n warnings: [...audit.warnings],\n };\n }\n }\n\n const gateResult = evaluateGates({\n current,\n ...(baseline === undefined ? {} : { baseline }),\n ...(diff === undefined ? {} : { diff }),\n gateConfig: options.gateConfig,\n ...(ownershipInput === undefined ? {} : { ownership: ownershipInput }),\n });\n\n const report = createReport(current, diff);\n const reportMarkdown = formatReport(report, \"md\");\n const ciMarkdown = renderCheckMarkdown(current, gateResult);\n const markdownSummary = `${reportMarkdown}\\n\\n${ciMarkdown}`;\n\n if (options.reportPath !== undefined) {\n await writeFile(options.reportPath, markdownSummary, \"utf8\");\n logger.info(`report written: ${options.reportPath}`);\n }\n\n const machineReadable = {\n current,\n ...(baseline === undefined ? {} : { baseline }),\n ...(diff === undefined ? {} : { diff }),\n violations: gateResult.violations,\n highestSeverity: gateResult.highestSeverity,\n exitCode: gateResult.exitCode,\n ...(ownershipSummary === undefined ? {} : { ownership: ownershipSummary }),\n };\n\n if (options.jsonOutputPath !== undefined) {\n await writeFile(options.jsonOutputPath, JSON.stringify(machineReadable, null, 2), \"utf8\");\n logger.info(`ci machine output written: ${options.jsonOutputPath}`);\n }\n\n return {\n current,\n ...(baseline === undefined ? {} : { baseline }),\n ...(diff === undefined ? {} : { diff }),\n gateResult,\n markdownSummary,\n ...(ownershipSummary === undefined ? {} : { ownership: ownershipSummary }),\n machineReadable,\n };\n};\n\nexport { GovernanceConfigurationError };\n","import { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { buildProjectGraphSummary } from \"@codesentinel/code-graph\";\nimport {\n CODEOWNERS_CANDIDATE_PATHS,\n CodeownersError,\n DEFAULT_MIN_COMMITS,\n auditOwnership,\n discoverCodeowners,\n parseCodeowners,\n parseOwnerAliases,\n type OwnerAliases,\n type OwnershipAudit,\n type OwnershipFileEvidence,\n type ParsedCodeowners,\n} from \"@codesentinel/ownership\";\nimport {\n OwnersGitError,\n collectOwnershipEvidence,\n normalizeRepositoryPath,\n readRepositorySnapshot,\n readTextAtRef,\n type RepositorySnapshot,\n} from \"./owners-git.js\";\nimport type { Logger } from \"./logger.js\";\n\n/**\n * Shared ownership-audit pipeline for the `owners` and `report` commands.\n *\n * The command is offline by contract. The only inputs are the repository at `--ref`, the optional\n * versioned alias map and the structural analysis of the working tree.\n */\n\nexport const DEFAULT_OWNERS_WINDOW_DAYS = 90;\nexport const DEFAULT_OWNERS_REF = \"HEAD\";\nexport const DEFAULT_OWNERS_ALIASES_PATH = \".codesentinel/owners.json\";\n\nexport class OwnersConfigurationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"OwnersConfigurationError\";\n }\n}\n\nexport type BuildOwnershipAuditOptions = {\n codeownersPath?: string;\n ref?: string;\n windowDays?: number;\n minCommits?: number;\n aliasesPath?: string;\n warnings?: readonly string[];\n};\n\nexport type OwnershipAuditResult = {\n audit: OwnershipAudit;\n trackedFileCount: number;\n repositoryPath: string;\n};\n\nconst readSnapshot = (targetPath: string, ref: string): RepositorySnapshot => {\n try {\n return readRepositorySnapshot(targetPath, ref);\n } catch (error) {\n if (error instanceof OwnersGitError) {\n throw new OwnersConfigurationError(error.message);\n }\n throw error;\n }\n};\n\ntype ReadCodeownersInput = {\n snapshot: RepositorySnapshot;\n explicitPath: string | undefined;\n};\n\nconst readCodeowners = (input: ReadCodeownersInput): ParsedCodeowners | null => {\n const trackedFileSet = new Set(input.snapshot.trackedFiles);\n const explicitPath =\n input.explicitPath === undefined ? null : normalizeRepositoryPath(input.explicitPath);\n\n const selection =\n explicitPath === null\n ? discoverCodeowners(\n CODEOWNERS_CANDIDATE_PATHS.filter((candidate) => trackedFileSet.has(candidate)),\n )\n : { source: explicitPath, ignoredSources: [] as readonly string[] };\n\n if (selection === null) {\n return null;\n }\n if (!trackedFileSet.has(selection.source)) {\n throw new OwnersConfigurationError(\n `CODEOWNERS file \"${selection.source}\" is not tracked at ref \"${input.snapshot.ref}\".`,\n );\n }\n\n const text = readTextAtRef(input.snapshot.repositoryPath, input.snapshot.ref, selection.source);\n return parseCodeowners(text, {\n source: selection.source,\n ignoredSources: selection.ignoredSources,\n });\n};\n\ntype OwnerAliasesSource = {\n aliases: OwnerAliases;\n warnings: readonly string[];\n};\n\n/**\n * The alias map is versioned, so it is read from the audited ref when it is tracked there.\n * Otherwise the working-tree copy is used and the degradation is reported, because an alias map\n * that silently changes identity results is exactly the kind of hidden input this command avoids.\n */\nconst readOwnerAliases = async (\n snapshot: RepositorySnapshot,\n aliasesPath: string,\n): Promise<OwnerAliasesSource> => {\n const normalized = normalizeRepositoryPath(aliasesPath);\n const tracked = snapshot.trackedFiles.includes(normalized);\n\n if (tracked) {\n const text = readTextAtRef(snapshot.repositoryPath, snapshot.ref, normalized);\n const parsed = parseOwnerAliases(text);\n return { aliases: parsed.aliases, warnings: parsed.warnings };\n }\n\n const workingTreePath = resolve(snapshot.repositoryPath, normalized);\n if (existsSync(workingTreePath)) {\n const text = await readFile(workingTreePath, \"utf8\");\n const parsed = parseOwnerAliases(text);\n return {\n aliases: parsed.aliases,\n warnings: [\n ...parsed.warnings,\n `Identity aliases were read from the working tree because \"${normalized}\" is not tracked at \"${snapshot.ref}\".`,\n ],\n };\n }\n\n return { aliases: {}, warnings: [] };\n};\n\n/**\n * Structural fan-in is optional enrichment: when the project cannot be parsed the audit degrades to\n * the churn fallback and says so in its warnings rather than inventing criticality.\n */\nconst collectFanInByPath = (\n projectPath: string,\n logger: Logger,\n): ReadonlyMap<string, number> | null => {\n try {\n const structural = buildProjectGraphSummary({ projectPath });\n const fanIn = new Map<string, number>();\n for (const file of structural.files) {\n fanIn.set(normalizeRepositoryPath(file.relativePath), file.fanIn);\n }\n return fanIn;\n } catch (error) {\n logger.warn(\n `structural analysis unavailable, criticality falls back to churn: ${error instanceof Error ? error.message : \"unknown error\"}`,\n );\n return null;\n }\n};\n\nconst withFanIn = (\n evidence: readonly OwnershipFileEvidence[],\n fanInByPath: ReadonlyMap<string, number> | null,\n): readonly OwnershipFileEvidence[] => {\n if (fanInByPath === null) {\n return evidence;\n }\n\n return evidence.map((item) => {\n const fanIn = fanInByPath.get(item.filePath);\n if (fanIn === undefined) {\n return item;\n }\n return { ...item, criticality: { ...item.criticality, fanIn } };\n });\n};\n\nexport const buildOwnershipAudit = async (\n targetPath: string,\n options: BuildOwnershipAuditOptions,\n logger: Logger,\n): Promise<OwnershipAuditResult> => {\n const ref = options.ref ?? DEFAULT_OWNERS_REF;\n const windowDays = options.windowDays ?? DEFAULT_OWNERS_WINDOW_DAYS;\n const minCommits = options.minCommits ?? DEFAULT_MIN_COMMITS;\n\n const snapshot = readSnapshot(targetPath, ref);\n\n let parsedCodeowners: ParsedCodeowners | null;\n try {\n parsedCodeowners = readCodeowners({\n snapshot,\n explicitPath: options.codeownersPath,\n });\n } catch (error) {\n if (error instanceof CodeownersError) {\n throw new OwnersConfigurationError(error.message);\n }\n throw error;\n }\n\n const aliasSource = await readOwnerAliases(\n snapshot,\n options.aliasesPath ?? DEFAULT_OWNERS_ALIASES_PATH,\n );\n\n const collected = collectOwnershipEvidence(snapshot, windowDays);\n logger.debug(\n `ownership evidence: ${collected.files.length} files with history, window since ${collected.sinceUnix} of ${snapshot.trackedFiles.length} tracked`,\n );\n\n const fanInByPath = collectFanInByPath(snapshot.repositoryPath, logger);\n const evidence = withFanIn(collected.files, fanInByPath);\n\n const audit = auditOwnership({\n codeowners: parsedCodeowners,\n trackedFiles: snapshot.trackedFiles,\n evidence,\n aliases: aliasSource.aliases,\n minCommits,\n warnings: [...(options.warnings ?? []), ...aliasSource.warnings],\n });\n\n return {\n audit,\n trackedFileCount: snapshot.trackedFiles.length,\n repositoryPath: snapshot.repositoryPath,\n };\n};\n","export const CODEOWNERS_MAX_BYTES = 3 * 1024 * 1024;\n\nexport type CodeownersErrorCode = \"codeowners_too_large\" | \"codeowners_invalid_pattern\";\n\nexport class CodeownersError extends Error {\n readonly code: CodeownersErrorCode;\n\n constructor(code: CodeownersErrorCode, message: string) {\n super(message);\n this.name = \"CodeownersError\";\n this.code = code;\n }\n}\n\nexport type DeclaredOwner =\n | { kind: \"user\"; handle: string }\n | { kind: \"team\"; org: string; slug: string }\n | { kind: \"email\"; address: string };\n\n/**\n * Stable identity key for a declared owner, used to aggregate owners across files.\n * GitHub treats handles, team slugs and email addresses case-insensitively.\n */\nexport const declaredOwnerKey = (owner: DeclaredOwner): string => {\n if (owner.kind === \"user\") return `@${owner.handle.trim().toLowerCase()}`;\n if (owner.kind === \"team\")\n return `@${owner.org.trim().toLowerCase()}/${owner.slug.trim().toLowerCase()}`;\n return owner.address.trim().toLowerCase();\n};\n\nexport type CodeownersEntry = {\n pattern: string;\n owners: readonly DeclaredOwner[];\n /** 1-based line of the source file, so the report can link to it. */\n line: number;\n /**\n * Invalid lines are preserved for diagnostics but never take part in matching.\n * A line with a pattern and no owners is valid: it clears the ownership of the subtree.\n */\n ignored: boolean;\n};\n\nexport type CodeownersParseError = {\n line: number;\n reason: string;\n};\n\nexport type ParsedCodeowners = {\n source: string;\n entries: readonly CodeownersEntry[];\n errors: readonly CodeownersParseError[];\n ignoredSources: readonly string[];\n};\n\nexport type OwnershipStatus =\n | \"aligned\"\n | \"drifted\"\n | \"ghosted\"\n | \"unowned\"\n | \"unowned-critical\"\n | \"insufficient-evidence\"\n /** Degraded verdict: teams are opaque offline and aliases may be unresolved, so absence is not proof. */\n | \"unknown\";\n\nexport type FileOwnershipAudit = {\n filePath: string;\n declared: readonly DeclaredOwner[];\n matchLine: number | null;\n status: OwnershipStatus;\n observed: {\n /** Lifetime commits touching the file. */\n commits: number;\n /** Commits touching the file inside the activity window. */\n recentCommits: number;\n /** `recentCommits === 0 && commits > 0`: present in history, untouched in the window. */\n dormant: boolean;\n /** Distinct authors over the file's lifetime. */\n authors: number;\n topAuthorId: string | null;\n topAuthorShare: number | null;\n busFactor: number | null;\n lastCommitUnix: number | null;\n };\n criticality: {\n fanIn: number | null;\n isHotspot: boolean;\n riskScore: number | null;\n /**\n * Resolved criticality verdict. Stored so reporters do not have to re-apply the threshold\n * policy, and so `unowned-critical` is auditable from the output alone.\n */\n isCritical: boolean;\n };\n};\n\nexport type OwnershipAuditMetrics = {\n declaredCoveragePercent: number;\n declaredCoverageCriticalPercent: number;\n driftPercent: number;\n ghostOwnerCount: number;\n unownedCriticalCount: number;\n singleOwnerModuleCount: number;\n};\n\nexport type OwnershipAuditAvailable = {\n available: true;\n codeowners: ParsedCodeowners;\n metrics: OwnershipAuditMetrics;\n ghostOwners: readonly { owner: DeclaredOwner; samplePaths: readonly string[] }[];\n files: readonly FileOwnershipAudit[];\n warnings: readonly string[];\n};\n\nexport type OwnershipAuditUnavailable = {\n available: false;\n reason: \"codeowners_not_found\";\n warnings: readonly string[];\n};\n\nexport type OwnershipAudit = OwnershipAuditAvailable | OwnershipAuditUnavailable;\n","import { CodeownersError } from \"./codeowners.js\";\nimport type { CodeownersEntry } from \"./codeowners.js\";\n\nconst REGEX_METACHARACTERS = /[.*+?^${}()|[\\]\\\\]/g;\n\nconst ANY_DEPTH_PREFIX = \"(?:[^/]+/)*\";\n\nexport type CompiledCodeownersPattern = {\n pattern: string;\n regex: RegExp;\n};\n\nexport type CodeownersMatcher = (filePath: string) => CodeownersEntry | null;\n\nconst escapeLiteral = (value: string): string => value.replace(REGEX_METACHARACTERS, \"\\\\$&\");\n\nconst compileSegment = (segment: string): string =>\n [...segment]\n .map((character) => {\n if (character === \"*\") return \"[^/]*\";\n if (character === \"?\") return \"[^/]\";\n return escapeLiteral(character);\n })\n .join(\"\");\n\nconst compileBody = (segments: readonly string[]): string => {\n const parts: string[] = [];\n segments.forEach((segment, index) => {\n const isLast = index === segments.length - 1;\n if (segment === \"**\") {\n parts.push(isLast ? \".*\" : ANY_DEPTH_PREFIX);\n return;\n }\n parts.push(compileSegment(segment));\n if (!isLast) parts.push(\"/\");\n });\n return parts.join(\"\");\n};\n\nconst normalizeFilePath = (filePath: string): string => {\n let normalized = filePath;\n while (normalized.startsWith(\"./\")) normalized = normalized.slice(2);\n return normalized.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\");\n};\n\n/**\n * Compiles a CODEOWNERS pattern into an anchored regular expression over repo-relative paths.\n *\n * Rules, matching GitHub's documented behaviour rather than full gitignore:\n * - A pattern with no internal `/` matches at any depth; `/`-prefixed patterns are root-anchored.\n * - `*` and `?` never cross a `/` separator; `**` crosses segments.\n * - A trailing `/` marks a directory pattern: it owns the directory subtree.\n * - A pattern whose last segment is literal also owns the subtree, so `/apps/github` covers\n * `apps/github/*`. A wildcarded last segment stays exact, so `docs/*` covers one level only.\n * - `!` and `[...]` are literal characters: GitHub does not implement negation or character classes.\n * - Matching is case-sensitive on every platform.\n */\nexport function compileCodeownersPattern(pattern: string): CompiledCodeownersPattern {\n const trimmed = pattern.trim();\n const directoryPattern = trimmed.endsWith(\"/\");\n const withoutTrailingSlashes = trimmed.replace(/\\/+$/, \"\");\n const anchored =\n withoutTrailingSlashes.startsWith(\"/\") || withoutTrailingSlashes.slice(1).includes(\"/\");\n const core = withoutTrailingSlashes.replace(/^\\/+/, \"\");\n\n if (core.length === 0) {\n throw new CodeownersError(\n \"codeowners_invalid_pattern\",\n `CODEOWNERS pattern \"${pattern}\" does not match any path.`,\n );\n }\n\n const segments = core.split(\"/\");\n const lastSegment = segments[segments.length - 1] ?? \"\";\n const lastSegmentIsLiteral =\n lastSegment !== \"**\" && !lastSegment.includes(\"*\") && !lastSegment.includes(\"?\");\n\n const prefix = anchored ? \"\" : ANY_DEPTH_PREFIX;\n const suffix = directoryPattern ? \"(?:/.*)\" : lastSegmentIsLiteral ? \"(?:/.*)?\" : \"\";\n const regex = new RegExp(`^${prefix}${compileBody(segments)}${suffix}$`);\n\n return { pattern: trimmed, regex };\n}\n\nexport function matchCodeownersPattern(pattern: string, filePath: string): boolean {\n const candidate = normalizeFilePath(filePath);\n if (candidate.length === 0) return false;\n return compileCodeownersPattern(pattern).regex.test(candidate);\n}\n\n/**\n * Precompiles every non-ignored entry once and returns a resolver with last-match-wins semantics.\n * A matching entry with no owners is a winner too: it means the subtree is deliberately unowned.\n */\nexport function createCodeownersMatcher(entries: readonly CodeownersEntry[]): CodeownersMatcher {\n const compiled = entries\n .filter((entry) => !entry.ignored)\n .map((entry) => ({ entry, regex: compileCodeownersPattern(entry.pattern).regex }));\n\n return (filePath: string): CodeownersEntry | null => {\n const candidate = normalizeFilePath(filePath);\n if (candidate.length === 0) return null;\n\n let winner: CodeownersEntry | null = null;\n for (const { entry, regex } of compiled) {\n if (regex.test(candidate)) winner = entry;\n }\n return winner;\n };\n}\n\n/** Convenience wrapper. Recompiles the entries on every call; use `createCodeownersMatcher` in loops. */\nexport function findOwningEntry(\n entries: readonly CodeownersEntry[],\n filePath: string,\n): CodeownersEntry | null {\n return createCodeownersMatcher(entries)(filePath);\n}\n","import type { DeclaredOwner } from \"./codeowners.js\";\n\n/**\n * Author evidence for a single file, already reduced to the observation window.\n *\n * `authorId` is expected to be the normalized identity produced by\n * `normalizeAuthorIdentity` in `@codesentinel/git-analyzer`: the numeric prefix of a GitHub\n * noreply address is already stripped, so `<handle>@users.noreply.github.com` is comparable\n * against a CODEOWNERS handle. An unnormalized `123+handle@users.noreply.github.com` will not\n * resolve, by design: the parser is the single place where that normalization happens.\n */\nexport type OwnershipAuthor = {\n authorId: string;\n /** Raw author name, when available. The evolution summary does not keep it. */\n authorName?: string | null;\n /** Commits by this author inside the observation window. */\n commits: number;\n};\n\n/**\n * Identity aliases: handle (with or without `@`) mapping to the author ids that belong to it.\n * The map is versioned in `.codesentinel/owners.json`; reading that file is the caller's job.\n */\nexport type OwnerAliases = Readonly<Record<string, readonly string[]>>;\n\n/**\n * How a declared owner related to the observed authors.\n *\n * - `github_noreply`, `email_local_part`, `author_name`, `alias`: the owner matched at least one\n * author, in cascade order.\n * - `email_owner`: an email owner matched an author id exactly.\n * - `team_unverified`: an unexpanded team. Offline it is opaque, so it is never a ghost.\n * - `no_activity`: no author matched and nothing external could hide the absence.\n * - `alias_unresolved`: no author matched, but the alias map declares identities for this handle\n * that were not observed. The map may be incomplete, so the absence is not proof.\n */\nexport type OwnerResolutionKind =\n | \"github_noreply\"\n | \"email_local_part\"\n | \"author_name\"\n | \"alias\"\n | \"email_owner\"\n | \"team_unverified\"\n | \"no_activity\"\n | \"alias_unresolved\";\n\nexport type OwnerResolution = {\n owner: DeclaredOwner;\n kind: OwnerResolutionKind;\n /** Author ids from the evidence covered by this owner, in evidence order. */\n activeAuthorIds: readonly string[];\n};\n\nexport const isActiveOwnerResolution = (resolution: OwnerResolution): boolean =>\n resolution.activeAuthorIds.length > 0;\n\n/**\n * Whether absence of activity for this owner is evidence: a team that was never expanded, or an\n * alias that never showed up in the window, both mean \"we do not know\" rather than \"ghost\".\n */\nexport const isVerifiableOwnerResolution = (resolution: OwnerResolution): boolean =>\n resolution.kind !== \"team_unverified\" && resolution.kind !== \"alias_unresolved\";\n","import type { OwnershipStatus } from \"./codeowners.js\";\nimport type { OwnerResolution } from \"./identity.js\";\nimport { isActiveOwnerResolution, isVerifiableOwnerResolution } from \"./identity.js\";\n\n/** Criticality defaults from the design: `fanIn >= 5` or hotspot. */\nexport const DEFAULT_FAN_IN_CRITICALITY_THRESHOLD = 5;\n\n/**\n * When no structural analysis exists, criticality falls back to hotspots plus churn. The cutoff is\n * the 90th percentile of the churn seen in the repository, computed with the nearest-rank method so\n * the result does not depend on input order.\n */\nexport const CHURN_CRITICALITY_PERCENTILE = 0.9;\n\n/** Risk score contributes through the upper quartile, as specified in the design. */\nexport const RISK_SCORE_CRITICALITY_PERCENTILE = 0.75;\n\n/** Below this many scores the quartile is noise, so the rule stays off. */\nexport const RISK_SCORE_CRITICALITY_MIN_SAMPLES = 4;\n\nexport type CriticalityEvidence = {\n fanIn?: number | null;\n isHotspot?: boolean | null;\n riskScore?: number | null;\n /** Churn is only used when structural data is missing. */\n churnTotal?: number | null;\n};\n\nexport type CriticalityPolicy = {\n fanInThreshold: number;\n /** Churn cutoff, enabled only when no file carries structural data. */\n churnThreshold: number | null;\n /** Risk score cutoff (upper quartile), `null` when the sample is too small. */\n riskScoreThreshold: number | null;\n structuralDataAvailable: boolean;\n};\n\nexport type CriticalityPolicyOptions = {\n fanInThreshold?: number;\n};\n\nconst finiteNumbers = (values: readonly (number | null | undefined)[]): number[] =>\n values\n .filter((value): value is number => typeof value === \"number\" && Number.isFinite(value))\n .sort((a, b) => a - b);\n\n/** Nearest-rank percentile over an ascending list: no interpolation, so no surprise decimals. */\nconst nearestRank = (sortedAscending: readonly number[], percentile: number): number | null => {\n if (sortedAscending.length === 0) return null;\n const rank = Math.ceil(percentile * sortedAscending.length);\n const index = Math.min(Math.max(rank, 1), sortedAscending.length) - 1;\n return sortedAscending[index] ?? null;\n};\n\n/**\n * Resolves the criticality cutoffs once for the whole audit.\n *\n * `structuralDataAvailable` is false when no file carries a `fanIn`, which is exactly the\n * \"git only, no structural analysis\" mode: criticality then degrades to hotspot + churn and the\n * audit must say so in `warnings` instead of pretending the result means the same thing.\n */\nexport const resolveCriticalityPolicy = (\n evidence: readonly CriticalityEvidence[],\n options: CriticalityPolicyOptions = {},\n): CriticalityPolicy => {\n const fanInThreshold = options.fanInThreshold ?? DEFAULT_FAN_IN_CRITICALITY_THRESHOLD;\n const fanInValues = finiteNumbers(evidence.map((item) => item.fanIn));\n const structuralDataAvailable = fanInValues.length > 0;\n\n const riskScores = finiteNumbers(evidence.map((item) => item.riskScore));\n const riskScoreThreshold =\n riskScores.length >= RISK_SCORE_CRITICALITY_MIN_SAMPLES\n ? nearestRank(riskScores, RISK_SCORE_CRITICALITY_PERCENTILE)\n : null;\n\n if (structuralDataAvailable) {\n return { fanInThreshold, churnThreshold: null, riskScoreThreshold, structuralDataAvailable };\n }\n\n const churnValues = finiteNumbers(evidence.map((item) => item.churnTotal));\n return {\n fanInThreshold,\n churnThreshold: nearestRank(churnValues, CHURN_CRITICALITY_PERCENTILE),\n riskScoreThreshold,\n structuralDataAvailable,\n };\n};\n\nexport const isCriticalFile = (\n evidence: CriticalityEvidence | undefined,\n policy: CriticalityPolicy,\n): boolean => {\n if (evidence === undefined) return false;\n\n const fanIn = typeof evidence.fanIn === \"number\" ? evidence.fanIn : null;\n if (fanIn !== null && Number.isFinite(fanIn) && fanIn >= policy.fanInThreshold) return true;\n if (evidence.isHotspot === true) return true;\n\n const riskScore = typeof evidence.riskScore === \"number\" ? evidence.riskScore : null;\n if (\n policy.riskScoreThreshold !== null &&\n riskScore !== null &&\n Number.isFinite(riskScore) &&\n riskScore >= policy.riskScoreThreshold\n ) {\n return true;\n }\n\n const churnTotal = typeof evidence.churnTotal === \"number\" ? evidence.churnTotal : null;\n return (\n policy.churnThreshold !== null &&\n churnTotal !== null &&\n Number.isFinite(churnTotal) &&\n churnTotal >= policy.churnThreshold\n );\n};\n\n/**\n * Fixed severity order for every report. It is part of the output contract: `files` is sorted by\n * this rank first, so two runs always emit the same bytes.\n *\n * Unowned critical and ghosted come first because they are the findings that need action;\n * `insufficient-evidence` sits near the end because it is the absence of data, not a finding.\n */\nexport const OWNERSHIP_STATUS_ORDER: Readonly<Record<OwnershipStatus, number>> = {\n \"unowned-critical\": 0,\n ghosted: 1,\n drifted: 2,\n unowned: 3,\n unknown: 4,\n \"insufficient-evidence\": 5,\n aligned: 6,\n};\n\nexport const ownershipStatusRank = (status: OwnershipStatus): number =>\n OWNERSHIP_STATUS_ORDER[status];\n\nexport type OwnershipClassificationInput = {\n /** Owners declared by the winning entry. Zero also covers \"no entry matched\" and a reset line. */\n declaredCount: number;\n isCritical: boolean;\n /** Lifetime commits touching the file, used for the evidence threshold. */\n commits: number;\n /** Commits touching the file inside the observation window, used for activity. */\n recentCommits: number;\n minCommits: number;\n /** Highest-commit author of the horizon that produced the verdict, bots excluded. */\n topAuthorId: string | null;\n /** False when the horizon that can produce a verdict has commits but no author breakdown. */\n hasAuthorEvidence: boolean;\n /** Declared owners resolved against the same horizon as `topAuthorId`. */\n resolutions: readonly OwnerResolution[];\n};\n\n/**\n * Classification with two horizons: lifetime history decides whether there is enough evidence,\n * window activity decides whether an owner is still around.\n *\n * Order: no declaration -> insufficient lifetime evidence -> no author evidence -> dormant ->\n * no declared owner active -> top author -> drift.\n *\n * A `ghosted` verdict needs *all* declared owners to be verifiable, so a team that was never\n * expanded or a stale alias map downgrades the file to `unknown` instead of inventing a ghost.\n * A dormant file (no commits in the window) can never be ghosted: it is compared against its\n * lifetime top author instead, because silence in the window is not owner inactivity.\n */\nexport const classifyOwnershipStatus = (input: OwnershipClassificationInput): OwnershipStatus => {\n if (input.declaredCount === 0) {\n return input.isCritical ? \"unowned-critical\" : \"unowned\";\n }\n if (input.commits < input.minCommits) {\n return \"insufficient-evidence\";\n }\n if (!input.hasAuthorEvidence) {\n return \"unknown\";\n }\n\n const topAuthorId = input.topAuthorId;\n\n if (input.recentCommits === 0) {\n return topAuthorId !== null &&\n input.resolutions.some((resolution) => resolution.activeAuthorIds.includes(topAuthorId))\n ? \"aligned\"\n : \"drifted\";\n }\n\n const active = input.resolutions.filter(isActiveOwnerResolution);\n if (active.length === 0) {\n return input.resolutions.every(isVerifiableOwnerResolution) ? \"ghosted\" : \"unknown\";\n }\n\n if (\n topAuthorId !== null &&\n active.some((resolution) => resolution.activeAuthorIds.includes(topAuthorId))\n ) {\n return \"aligned\";\n }\n return \"drifted\";\n};\n","import { declaredOwnerKey } from \"./codeowners.js\";\nimport type { DeclaredOwner, FileOwnershipAudit, OwnershipAuditMetrics } from \"./codeowners.js\";\nimport { ownershipStatusRank } from \"./classify.js\";\n\n/** At most three sample paths per ghost owner, as specified in the design. */\nexport const GHOST_OWNER_SAMPLE_PATHS = 3;\n\nconst roundTo = (value: number, decimals: number): number => {\n const factor = 10 ** decimals;\n return Math.round(value * factor) / factor;\n};\n\n/** Percentages are rounded to two decimals so the JSON stays stable and readable. */\nexport const percentOf = (part: number, total: number): number =>\n total === 0 ? 0 : roundTo((part / total) * 100, 2);\n\nconst compareText = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n\nconst compareNullableDescending = (a: number | null, b: number | null): number => {\n if (a === null && b === null) return 0;\n if (a === null) return 1;\n if (b === null) return -1;\n return b - a;\n};\n\n/**\n * Report order, part of the determinism contract: severity rank, then criticality descending,\n * then `fanIn`, then `riskScore`, then the path as the final tie-breaker.\n */\nexport const compareFileOwnershipAudits = (\n a: FileOwnershipAudit,\n b: FileOwnershipAudit,\n): number => {\n const byStatus = ownershipStatusRank(a.status) - ownershipStatusRank(b.status);\n if (byStatus !== 0) return byStatus;\n\n const byCritical = Number(b.criticality.isCritical) - Number(a.criticality.isCritical);\n if (byCritical !== 0) return byCritical;\n\n const byFanIn = compareNullableDescending(a.criticality.fanIn, b.criticality.fanIn);\n if (byFanIn !== 0) return byFanIn;\n\n const byRiskScore = compareNullableDescending(a.criticality.riskScore, b.criticality.riskScore);\n if (byRiskScore !== 0) return byRiskScore;\n\n return compareText(a.filePath, b.filePath);\n};\n\nexport const sortFileOwnershipAudits = (\n files: readonly FileOwnershipAudit[],\n): readonly FileOwnershipAudit[] => [...files].sort(compareFileOwnershipAudits);\n\n/** Module = first path segment; files at the repository root belong to the \".\" module. */\nexport const moduleOfPath = (filePath: string): string => {\n const separator = filePath.indexOf(\"/\");\n return separator === -1 ? \".\" : filePath.slice(0, separator);\n};\n\nconst countSingleOwnerModules = (files: readonly FileOwnershipAudit[]): number => {\n const ownersByModule = new Map<string, Set<string>>();\n for (const file of files) {\n const module = moduleOfPath(file.filePath);\n const owners = ownersByModule.get(module) ?? new Set<string>();\n for (const owner of file.declared) owners.add(declaredOwnerKey(owner));\n ownersByModule.set(module, owners);\n }\n\n let singleOwnerModules = 0;\n for (const owners of ownersByModule.values()) {\n if (owners.size === 1) singleOwnerModules += 1;\n }\n return singleOwnerModules;\n};\n\nexport type OwnershipMetricsInput = {\n files: readonly FileOwnershipAudit[];\n /** Universe of tracked files, including the ones no CODEOWNERS pattern matches. */\n trackedFileCount: number;\n /** Distinct owners with verified absence of activity. */\n ghostOwnerCount: number;\n};\n\n/**\n * Aggregate metrics. `declaredCoveragePercent` is the headline that GitHub inflates with a single\n * `* @someone`; `declaredCoverageCriticalPercent` is the one that matters.\n *\n * `driftPercent` is measured over files with a declaration, so unowned files cannot hide drift.\n */\nexport const computeOwnershipMetrics = (input: OwnershipMetricsInput): OwnershipAuditMetrics => {\n const declaredFiles = input.files.filter((file) => file.declared.length > 0);\n const criticalFiles = input.files.filter((file) => file.criticality.isCritical);\n const coveredCriticalFiles = criticalFiles.filter((file) => file.declared.length > 0);\n const driftedFiles = declaredFiles.filter((file) => file.status === \"drifted\");\n\n return {\n declaredCoveragePercent: percentOf(declaredFiles.length, input.trackedFileCount),\n declaredCoverageCriticalPercent: percentOf(coveredCriticalFiles.length, criticalFiles.length),\n driftPercent: percentOf(driftedFiles.length, declaredFiles.length),\n ghostOwnerCount: input.ghostOwnerCount,\n unownedCriticalCount: input.files.filter((file) => file.status === \"unowned-critical\").length,\n singleOwnerModuleCount: countSingleOwnerModules(declaredFiles),\n };\n};\n\nexport type GhostOwnerCandidate = {\n owner: DeclaredOwner;\n filePath: string;\n};\n\nexport type GhostOwnerSummary = {\n owner: DeclaredOwner;\n samplePaths: readonly string[];\n};\n\n/**\n * Deduplicates ghost owners across files. Owners are ordered by their identity key and paths\n * ascending, so the list does not depend on traversal order.\n */\nexport const summarizeGhostOwners = (\n candidates: readonly GhostOwnerCandidate[],\n): readonly GhostOwnerSummary[] => {\n const owners = new Map<string, { owner: DeclaredOwner; paths: Set<string> }>();\n for (const candidate of candidates) {\n const key = declaredOwnerKey(candidate.owner);\n const entry = owners.get(key) ?? { owner: candidate.owner, paths: new Set<string>() };\n entry.paths.add(candidate.filePath);\n owners.set(key, entry);\n }\n\n return [...owners.entries()]\n .sort(([a], [b]) => compareText(a, b))\n .map(([, entry]) => ({\n owner: entry.owner,\n samplePaths: [...entry.paths].sort(compareText).slice(0, GHOST_OWNER_SAMPLE_PATHS),\n }));\n};\n","import { CODEOWNERS_MAX_BYTES, CodeownersError } from \"../domain/codeowners.js\";\nimport type {\n CodeownersEntry,\n CodeownersParseError,\n DeclaredOwner,\n ParsedCodeowners,\n} from \"../domain/codeowners.js\";\n\nexport const CODEOWNERS_CANDIDATE_PATHS = [\n \".github/CODEOWNERS\",\n \"CODEOWNERS\",\n \"docs/CODEOWNERS\",\n] as const;\n\nexport const DEFAULT_CODEOWNERS_SOURCE = \"CODEOWNERS\";\n\nexport type CodeownersSourceSelection = {\n source: string;\n ignoredSources: readonly string[];\n};\n\nexport type ParseCodeownersOptions = {\n source?: string;\n ignoredSources?: readonly string[];\n};\n\nconst EMAIL_PATTERN = /^[^@\\s]+@[^@\\s]+$/;\nconst WHITESPACE_PATTERN = /\\s/;\n\nconst hasControlCharacter = (value: string): boolean => {\n for (const character of value) {\n const codePoint = character.codePointAt(0) ?? 0;\n if (codePoint < 0x20 || codePoint === 0x7f) return true;\n }\n return false;\n};\n\nconst parseOwner = (token: string): DeclaredOwner | null => {\n if (!token.startsWith(\"@\")) {\n return EMAIL_PATTERN.test(token) ? { kind: \"email\", address: token } : null;\n }\n\n const reference = token.slice(1);\n if (reference.length === 0 || reference.includes(\"@\")) return null;\n\n const parts = reference.split(\"/\");\n if (parts.length === 1) {\n return { kind: \"user\", handle: reference };\n }\n if (parts.length !== 2) return null;\n\n const [org, slug] = parts;\n if (org === undefined || slug === undefined || org.length === 0 || slug.length === 0) return null;\n return { kind: \"team\", org, slug };\n};\n\nconst isValidPattern = (pattern: string): boolean => {\n if (hasControlCharacter(pattern)) return false;\n return pattern.replace(/^\\/+/, \"\").replace(/\\/+$/, \"\").length > 0;\n};\n\n/**\n * GitHub starts a comment at `#` when it is the first character of the line or follows whitespace,\n * and escaping it is not supported. Any other `#` stays inside the pattern.\n */\nconst commentIndex = (line: string): number => {\n for (let index = 0; index < line.length; index += 1) {\n if (line[index] !== \"#\") continue;\n const previous = index === 0 ? \"\" : (line[index - 1] ?? \"\");\n if (index === 0 || WHITESPACE_PATTERN.test(previous)) return index;\n }\n return -1;\n};\n\nconst stripComment = (line: string): string => {\n const index = commentIndex(line);\n return index === -1 ? line : line.slice(0, index);\n};\n\n/**\n * Parses CODEOWNERS text into entries plus parse errors. Pure: no filesystem, no network.\n *\n * A pattern with no owners is a valid entry that clears ownership of its subtree. A line with an\n * invalid pattern or owner is preserved with `ignored: true` and reported in `errors`; the owners\n * that did parse are kept for diagnostics but never participate in matching.\n */\nexport function parseCodeowners(\n text: string,\n options: ParseCodeownersOptions = {},\n): ParsedCodeowners {\n const byteLength = Buffer.byteLength(text, \"utf8\");\n if (byteLength > CODEOWNERS_MAX_BYTES) {\n throw new CodeownersError(\n \"codeowners_too_large\",\n `CODEOWNERS content is ${byteLength} bytes, above the ${CODEOWNERS_MAX_BYTES} byte limit GitHub accepts.`,\n );\n }\n\n const entries: CodeownersEntry[] = [];\n const errors: CodeownersParseError[] = [];\n const lines = text.replace(/^\\uFEFF/, \"\").split(\"\\n\");\n\n lines.forEach((rawLine, index) => {\n const lineNumber = index + 1;\n const line = rawLine.endsWith(\"\\r\") ? rawLine.slice(0, -1) : rawLine;\n const content = stripComment(line).trim();\n if (content.length === 0) return;\n\n const [pattern, ...ownerTokens] = content.split(/\\s+/);\n if (pattern === undefined) return;\n\n let ignored = !isValidPattern(pattern);\n if (ignored) {\n errors.push({ line: lineNumber, reason: `invalid pattern \"${pattern}\"` });\n }\n\n const owners: DeclaredOwner[] = [];\n for (const token of ownerTokens) {\n const owner = parseOwner(token);\n if (owner === null) {\n ignored = true;\n errors.push({ line: lineNumber, reason: `invalid owner \"${token}\"` });\n continue;\n }\n owners.push(owner);\n }\n\n entries.push({ pattern, owners, line: lineNumber, ignored });\n });\n\n return {\n source: options.source ?? DEFAULT_CODEOWNERS_SOURCE,\n entries,\n errors,\n ignoredSources: options.ignoredSources ?? [],\n };\n}\n\nconst normalizeSourcePath = (source: string): string => {\n let normalized = source;\n while (normalized.startsWith(\"./\")) normalized = normalized.slice(2);\n return normalized.replace(/^\\/+/, \"\");\n};\n\n/**\n * GitHub checks these locations in order and loads only the first one that exists.\n * `existingPaths` is whatever the caller found on disk; the rest become `ignoredSources`.\n */\nexport function discoverCodeowners(\n existingPaths: readonly string[],\n): CodeownersSourceSelection | null {\n const existing = new Set(existingPaths.map(normalizeSourcePath));\n const found = CODEOWNERS_CANDIDATE_PATHS.filter((candidate) => existing.has(candidate));\n const [source, ...ignoredSources] = found;\n if (source === undefined) return null;\n return { source, ignoredSources };\n}\n","import type { DeclaredOwner } from \"../domain/codeowners.js\";\nimport type { OwnerAliases, OwnerResolution, OwnershipAuthor } from \"../domain/identity.js\";\n\nconst BOT_MARKER = /\\[bot\\]/i;\nconst WHITESPACE_PATTERN = /\\s+/g;\n\n/**\n * Bots commit a lot and never own anything. `normalizeAuthorIdentity` keeps `[bot]` in the id,\n * so excluding them here prevents machine accounts from ever being attributed to a human handle.\n */\nexport const isBotAuthor = (author: OwnershipAuthor): boolean => {\n if (BOT_MARKER.test(author.authorId)) return true;\n return typeof author.authorName === \"string\" && BOT_MARKER.test(author.authorName);\n};\n\nconst normalizeHandle = (value: string): string =>\n value.trim().replace(/^@+/, \"\").toLowerCase().replace(WHITESPACE_PATTERN, \"\");\n\nconst normalizeAuthorName = (value: string): string =>\n value.toLowerCase().replace(WHITESPACE_PATTERN, \"\");\n\nconst localPartOf = (authorId: string): string | null => {\n const at = authorId.indexOf(\"@\");\n return at > 0 ? authorId.slice(0, at) : null;\n};\n\nconst uniquify = (values: readonly string[]): readonly string[] => [...new Set(values)];\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport type ParsedOwnerAliases = {\n aliases: OwnerAliases;\n warnings: readonly string[];\n};\n\n/**\n * Parses the versioned alias map (`.codesentinel/owners.json`) from text the caller read.\n *\n * Absence is not a problem: a missing or empty file yields no aliases and no warnings. Anything\n * that cannot be used is dropped with an explicit warning, because silently discarding identity\n * data would turn a configuration mistake into a false ghost-owner report.\n */\nexport const parseOwnerAliases = (raw: string | null | undefined): ParsedOwnerAliases => {\n const warnings: string[] = [];\n if (raw === null || raw === undefined || raw.trim().length === 0) {\n return { aliases: {}, warnings };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return {\n aliases: {},\n warnings: [\"owners.json is not valid JSON: identity aliases were ignored.\"],\n };\n }\n\n if (!isRecord(parsed)) {\n return {\n aliases: {},\n warnings: [\"owners.json must contain a JSON object: identity aliases were ignored.\"],\n };\n }\n\n const rawAliases = parsed[\"aliases\"];\n if (rawAliases === undefined || rawAliases === null) {\n return { aliases: {}, warnings };\n }\n\n if (!isRecord(rawAliases)) {\n return {\n aliases: {},\n warnings: ['owners.json \"aliases\" must be an object: identity aliases were ignored.'],\n };\n }\n\n const aliases: Record<string, readonly string[]> = {};\n for (const [handle, value] of Object.entries(rawAliases)) {\n const key = normalizeHandle(handle);\n if (key.length === 0) {\n warnings.push(\"An alias entry with an empty handle was ignored.\");\n continue;\n }\n if (!Array.isArray(value)) {\n warnings.push(`Alias entry \"${key}\" was ignored: expected an array of author ids.`);\n continue;\n }\n\n const targets = value\n .filter((target): target is string => typeof target === \"string\")\n .map((target) => target.trim().toLowerCase())\n .filter((target) => target.length > 0);\n\n if (targets.length === 0) {\n warnings.push(`Alias entry \"${key}\" was ignored: it contains no usable author id.`);\n continue;\n }\n\n aliases[key] = [...(aliases[key] ?? []), ...targets];\n }\n\n for (const key of Object.keys(aliases)) {\n aliases[key] = uniquify(aliases[key] ?? []);\n }\n\n return { aliases, warnings };\n};\n\nexport type IdentityResolver = (\n owner: DeclaredOwner,\n authors: readonly OwnershipAuthor[],\n) => OwnerResolution;\n\nconst resolveOwner = (\n owner: DeclaredOwner,\n authors: readonly OwnershipAuthor[],\n aliases: ReadonlyMap<string, readonly string[]>,\n): OwnerResolution => {\n if (owner.kind === \"team\") {\n return { owner, kind: \"team_unverified\", activeAuthorIds: [] };\n }\n\n const candidates = authors.filter((author) => !isBotAuthor(author));\n\n if (owner.kind === \"email\") {\n const target = owner.address.trim().toLowerCase();\n const active = candidates\n .filter((author) => author.authorId.trim().toLowerCase() === target)\n .map((author) => author.authorId);\n return { owner, kind: \"email_owner\", activeAuthorIds: uniquify(active) };\n }\n\n const handle = normalizeHandle(owner.handle);\n if (handle.length === 0) {\n return { owner, kind: \"no_activity\", activeAuthorIds: [] };\n }\n\n const noreplyId = `${handle}@users.noreply.github.com`;\n const aliasTargets = aliases.get(handle) ?? [];\n const byNoreply: string[] = [];\n const byLocalPart: string[] = [];\n const byName: string[] = [];\n const byAlias: string[] = [];\n\n for (const author of candidates) {\n const authorId = author.authorId.trim().toLowerCase();\n if (authorId === noreplyId) {\n byNoreply.push(author.authorId);\n continue;\n }\n\n const localPart = localPartOf(authorId);\n if (localPart !== null && localPart === handle) {\n byLocalPart.push(author.authorId);\n continue;\n }\n\n const authorName =\n typeof author.authorName === \"string\" ? normalizeAuthorName(author.authorName) : \"\";\n if (authorName.length > 0 && authorName === handle) {\n byName.push(author.authorId);\n continue;\n }\n\n if (aliasTargets.includes(authorId)) {\n byAlias.push(author.authorId);\n }\n }\n\n if (byNoreply.length > 0) {\n return { owner, kind: \"github_noreply\", activeAuthorIds: uniquify(byNoreply) };\n }\n if (byLocalPart.length > 0) {\n return { owner, kind: \"email_local_part\", activeAuthorIds: uniquify(byLocalPart) };\n }\n if (byName.length > 0) {\n return { owner, kind: \"author_name\", activeAuthorIds: uniquify(byName) };\n }\n if (byAlias.length > 0) {\n return { owner, kind: \"alias\", activeAuthorIds: uniquify(byAlias) };\n }\n if (aliasTargets.length > 0) {\n // The map claims identities for this handle and none of them were observed: the map may be\n // stale, so absence cannot be reported as a ghost.\n return { owner, kind: \"alias_unresolved\", activeAuthorIds: [] };\n }\n return { owner, kind: \"no_activity\", activeAuthorIds: [] };\n};\n\n/**\n * Builds an offline identity resolver from an alias map. Fully deterministic: no network, no clock,\n * and the cascade order is the one documented in the design (noreply, email local part, author\n * name, alias).\n */\nexport const createIdentityResolver = (aliases: OwnerAliases = {}): IdentityResolver => {\n const normalizedAliases = new Map<string, readonly string[]>();\n for (const [handle, targets] of Object.entries(aliases)) {\n const key = normalizeHandle(handle);\n if (key.length === 0) continue;\n normalizedAliases.set(\n key,\n targets.map((target) => target.trim().toLowerCase()).filter((target) => target.length > 0),\n );\n }\n\n return (owner, authors) => resolveOwner(owner, authors, normalizedAliases);\n};\n\nexport const resolveOwnerIdentities = (\n owners: readonly DeclaredOwner[],\n authors: readonly OwnershipAuthor[],\n aliases: OwnerAliases = {},\n): readonly OwnerResolution[] => {\n const resolve = createIdentityResolver(aliases);\n return owners.map((owner) => resolve(owner, authors));\n};\n","import type {\n DeclaredOwner,\n FileOwnershipAudit,\n OwnershipAudit,\n ParsedCodeowners,\n} from \"../domain/codeowners.js\";\nimport { declaredOwnerKey } from \"../domain/codeowners.js\";\nimport {\n classifyOwnershipStatus,\n isCriticalFile,\n resolveCriticalityPolicy,\n} from \"../domain/classify.js\";\nimport type { CriticalityEvidence, CriticalityPolicyOptions } from \"../domain/classify.js\";\nimport { isActiveOwnerResolution, isVerifiableOwnerResolution } from \"../domain/identity.js\";\nimport type { OwnerAliases, OwnershipAuthor } from \"../domain/identity.js\";\nimport {\n computeOwnershipMetrics,\n sortFileOwnershipAudits,\n summarizeGhostOwners,\n} from \"../domain/metrics.js\";\nimport type { GhostOwnerCandidate } from \"../domain/metrics.js\";\nimport { createCodeownersMatcher } from \"../domain/matcher.js\";\nimport { createIdentityResolver, isBotAuthor } from \"./resolve-identities.js\";\n\n/** Design default: at least two lifetime commits touching the file before a verdict is worth anything. */\nexport const DEFAULT_MIN_COMMITS = 2;\n\nconst NO_CODEOWNERS_WARNING = \"No CODEOWNERS file was found; the ownership audit is unavailable.\";\n\nexport type OwnershipFileEvidence = {\n filePath: string;\n /** Lifetime commits touching the file. */\n commits: number;\n /** Commits touching the file inside the activity window. */\n recentCommits: number;\n /** Lifetime commits per author. Bots never count as owner activity. */\n authors?: readonly OwnershipAuthor[];\n /** Commits per author inside the activity window. */\n recentAuthors?: readonly OwnershipAuthor[];\n lastCommitUnix?: number | null;\n busFactor?: number | null;\n /** Structural signals, already computed by the caller. Never imported from `code-graph`. */\n criticality?: CriticalityEvidence;\n};\n\nexport type AuditOwnershipInput = {\n /** `null` when no CODEOWNERS file was found; the audit degrades to `available: false`. */\n codeowners: ParsedCodeowners | null;\n /** Universe of files, from `git ls-files` on the audited ref. */\n trackedFiles: readonly string[];\n /** Per-file history projected onto the lifetime and activity-window horizons. */\n evidence?: readonly OwnershipFileEvidence[];\n /** Identity aliases from `.codesentinel/owners.json`, already parsed by the caller. */\n aliases?: OwnerAliases;\n /** Minimum commits per file before a verdict is emitted. Defaults to `DEFAULT_MIN_COMMITS`. */\n minCommits?: number;\n /** Fan-in threshold for criticality. Defaults to `DEFAULT_FAN_IN_CRITICALITY_THRESHOLD`. */\n fanInCriticalityThreshold?: number;\n /** Warnings produced by the caller (for example, alias file problems), appended as-is. */\n warnings?: readonly string[];\n};\n\nconst compareText = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n\nconst roundTo = (value: number, decimals: number): number => {\n const factor = 10 ** decimals;\n return Math.round(value * factor) / factor;\n};\n\n/** Commits per non-bot author id, so duplicated evidence rows cannot skew the top author. */\nconst aggregateAuthors = (authors: readonly OwnershipAuthor[]): Map<string, number> => {\n const commitsByAuthor = new Map<string, number>();\n for (const author of authors) {\n if (isBotAuthor(author)) continue;\n commitsByAuthor.set(\n author.authorId,\n (commitsByAuthor.get(author.authorId) ?? 0) + author.commits,\n );\n }\n return commitsByAuthor;\n};\n\nconst pickTopAuthor = (\n commitsByAuthor: ReadonlyMap<string, number>,\n): { topAuthorId: string; topAuthorShare: number } | null => {\n let best: { id: string; commits: number } | null = null;\n let total = 0;\n\n for (const [authorId, commits] of commitsByAuthor) {\n total += commits;\n if (\n best === null ||\n commits > best.commits ||\n (commits === best.commits && authorId < best.id)\n ) {\n best = { id: authorId, commits };\n }\n }\n\n if (best === null || total <= 0) return null;\n return { topAuthorId: best.id, topAuthorShare: roundTo(best.commits / total, 4) };\n};\n\nconst countDistinct = (values: readonly string[]): number => new Set(values).size;\n\nconst plural = (count: number, singular: string, pluralForm: string): string =>\n `${count} ${count === 1 ? singular : pluralForm}`;\n\n/**\n * Crosses declared ownership (CODEOWNERS) with observed ownership across two horizons.\n *\n * Lifetime history decides whether there is enough evidence and identifies the owner of a dormant\n * file. Window activity decides whether a declared owner is still active; a file untouched in the\n * window is never a ghost, because silence there is not proof of abandonment. Pure and offline: it\n * receives the tracked file list, per-file history and structural signals already computed\n * elsewhere, and returns a fully ordered, deterministic audit. No filesystem, no network, no clock.\n * Two runs over the same input produce byte-identical JSON.\n *\n * `ghosted` is only emitted for a file with window activity when every declared owner is\n * verifiable (no unexpanded team, no stale alias map) and none of them shows activity in the\n * window. Otherwise the file is `unknown` and the reason appears in `warnings`.\n */\nexport const auditOwnership = (input: AuditOwnershipInput): OwnershipAudit => {\n const callerWarnings = input.warnings ?? [];\n\n if (input.codeowners === null) {\n return {\n available: false,\n reason: \"codeowners_not_found\",\n warnings: [...callerWarnings, NO_CODEOWNERS_WARNING],\n };\n }\n\n const codeowners: ParsedCodeowners = input.codeowners;\n const minCommits = input.minCommits ?? DEFAULT_MIN_COMMITS;\n const criticalityOptions: CriticalityPolicyOptions =\n input.fanInCriticalityThreshold === undefined\n ? {}\n : { fanInThreshold: input.fanInCriticalityThreshold };\n\n const trackedFiles = [...new Set(input.trackedFiles)].sort(compareText);\n const trackedFileSet = new Set(trackedFiles);\n\n const evidenceByPath = new Map<string, OwnershipFileEvidence>();\n const warnings: string[] = [...callerWarnings];\n let duplicatedEvidence = 0;\n let evidenceOutsideUniverse = 0;\n\n for (const item of input.evidence ?? []) {\n if (!trackedFileSet.has(item.filePath)) {\n evidenceOutsideUniverse += 1;\n continue;\n }\n if (evidenceByPath.has(item.filePath)) {\n duplicatedEvidence += 1;\n continue;\n }\n evidenceByPath.set(item.filePath, item);\n }\n\n const evidenceItems = trackedFiles\n .map((filePath) => evidenceByPath.get(filePath))\n .filter((item): item is OwnershipFileEvidence => item !== undefined);\n\n const policy = resolveCriticalityPolicy(\n evidenceItems.map((item) => item.criticality ?? {}),\n criticalityOptions,\n );\n const matcher = createCodeownersMatcher(codeowners.entries);\n const resolveOwner = createIdentityResolver(input.aliases ?? {});\n\n const files: FileOwnershipAudit[] = [];\n const ghostCandidates: GhostOwnerCandidate[] = [];\n const teamKeys = new Set<string>();\n const unresolvedAliasKeys = new Set<string>();\n let filesWithoutAuthorEvidence = 0;\n\n for (const filePath of trackedFiles) {\n const item = evidenceByPath.get(filePath);\n const entry = matcher(filePath);\n const declared: readonly DeclaredOwner[] = entry?.owners ?? [];\n const authors = item?.authors ?? [];\n const recentAuthors = item?.recentAuthors ?? [];\n const commits = item?.commits ?? 0;\n const recentCommits = item?.recentCommits ?? 0;\n\n const lifetimeResolutions = declared.map((owner) => resolveOwner(owner, authors));\n const recentResolutions = declared.map((owner) => resolveOwner(owner, recentAuthors));\n const usesLifetimeHorizon = recentCommits === 0;\n const resolutions = usesLifetimeHorizon ? lifetimeResolutions : recentResolutions;\n const horizonAuthors = usesLifetimeHorizon ? authors : recentAuthors;\n const dormant = usesLifetimeHorizon && commits > 0;\n\n for (const resolution of resolutions) {\n if (resolution.kind === \"team_unverified\") teamKeys.add(declaredOwnerKey(resolution.owner));\n if (resolution.kind === \"alias_unresolved\") {\n unresolvedAliasKeys.add(declaredOwnerKey(resolution.owner));\n }\n }\n\n const commitsByAuthor = aggregateAuthors(horizonAuthors);\n const top = pickTopAuthor(commitsByAuthor);\n const hasAuthorEvidence = commitsByAuthor.size > 0;\n const isCritical = isCriticalFile(item?.criticality, policy);\n\n const status = classifyOwnershipStatus({\n declaredCount: declared.length,\n isCritical,\n commits,\n recentCommits,\n minCommits,\n topAuthorId: top?.topAuthorId ?? null,\n hasAuthorEvidence,\n resolutions,\n });\n\n if (declared.length > 0 && commits >= minCommits && !hasAuthorEvidence) {\n filesWithoutAuthorEvidence += 1;\n }\n\n if (declared.length > 0 && commits >= minCommits && recentCommits > 0) {\n for (const resolution of recentResolutions) {\n if (!isActiveOwnerResolution(resolution) && isVerifiableOwnerResolution(resolution)) {\n ghostCandidates.push({ owner: resolution.owner, filePath });\n }\n }\n }\n\n files.push({\n filePath,\n declared,\n matchLine: entry === null ? null : entry.line,\n status,\n observed: {\n commits,\n recentCommits,\n dormant,\n authors: countDistinct(authors.map((author) => author.authorId)),\n topAuthorId: top?.topAuthorId ?? null,\n topAuthorShare: top?.topAuthorShare ?? null,\n busFactor: item?.busFactor ?? null,\n lastCommitUnix: item?.lastCommitUnix ?? null,\n },\n criticality: {\n fanIn: item?.criticality?.fanIn ?? null,\n isHotspot: item?.criticality?.isHotspot === true,\n riskScore: item?.criticality?.riskScore ?? null,\n isCritical,\n },\n });\n }\n\n const sortedFiles = sortFileOwnershipAudits(files);\n const ghostOwners = summarizeGhostOwners(ghostCandidates);\n\n if (!policy.structuralDataAvailable) {\n warnings.push(\n \"No structural analysis available: criticality falls back to hotspots and churn (p90).\",\n );\n }\n if (teamKeys.size > 0) {\n warnings.push(\n `${plural(teamKeys.size, \"team owner\", \"team owners\")} cannot be verified offline; ` +\n \"teams are never reported as ghost owners.\",\n );\n }\n if (unresolvedAliasKeys.size > 0) {\n warnings.push(\n `${plural(unresolvedAliasKeys.size, \"declared owner has\", \"declared owners have\")} identity ` +\n \"aliases that were not observed in the relevant history; their files are never reported as ghost owners.\",\n );\n }\n if (filesWithoutAuthorEvidence > 0) {\n warnings.push(\n `${plural(filesWithoutAuthorEvidence, \"declared file has\", \"declared files have\")} commits ` +\n \"but no human author evidence; they are reported as unknown.\",\n );\n }\n if (duplicatedEvidence > 0) {\n warnings.push(\n `Ignored ${plural(duplicatedEvidence, \"duplicate file evidence entry\", \"duplicate file evidence entries\")}: ` +\n \"the first entry per path wins.\",\n );\n }\n if (evidenceOutsideUniverse > 0) {\n warnings.push(\n `Ignored ${plural(evidenceOutsideUniverse, \"file evidence entry\", \"file evidence entries\")} ` +\n \"outside the tracked universe.\",\n );\n }\n\n const metrics = computeOwnershipMetrics({\n files: sortedFiles,\n trackedFileCount: trackedFiles.length,\n ghostOwnerCount: ghostOwners.length,\n });\n\n return {\n available: true,\n codeowners,\n metrics,\n ghostOwners,\n files: sortedFiles,\n warnings,\n };\n};\n","import { execFileSync } from \"node:child_process\";\nimport type { OwnershipAuthor, OwnershipFileEvidence } from \"@codesentinel/ownership\";\n\n/**\n * Git access for the `owners` command. Everything read here is pinned to a ref, so the audit\n * measures the revision CI names and not whatever happens to be in the working tree.\n *\n * This is the only place in the command that shells out; the audit itself stays pure.\n */\n\nconst RECORD_SEPARATOR = \"\\u001e\";\nconst FIELD_SEPARATOR = \"\\u001f\";\nconst LOG_FORMAT = `%x1e%at${FIELD_SEPARATOR}%an${FIELD_SEPARATOR}%ae`;\nconst MAX_BUFFER_BYTES = 1024 * 1024 * 256;\n\nexport type OwnersGitErrorCode =\n \"not_a_git_repository\" | \"empty_repository\" | \"unknown_ref\" | \"git_failed\";\n\nexport class OwnersGitError extends Error {\n readonly code: OwnersGitErrorCode;\n\n constructor(code: OwnersGitErrorCode, message: string) {\n super(message);\n this.name = \"OwnersGitError\";\n this.code = code;\n }\n}\n\nexport type RepositorySnapshot = {\n /** Absolute path to the repository root, which is also the CODEOWNERS and path universe root. */\n repositoryPath: string;\n ref: string;\n /** Authored time of the ref commit. Anchors the observation window so runs are reproducible. */\n commitUnix: number;\n /** Tracked files at the ref, in ascending path order. */\n trackedFiles: readonly string[];\n};\n\nconst gitErrorMessage = (error: unknown): string => {\n if (error instanceof Error) {\n const stderr = \"stderr\" in error ? (error as { stderr?: unknown }).stderr : undefined;\n const trimmed = typeof stderr === \"string\" ? stderr.trim() : \"\";\n if (trimmed.length > 0) return trimmed;\n return error.message;\n }\n return \"unknown git execution error\";\n};\n\nconst runGit = (repositoryPath: string, args: readonly string[]): string => {\n try {\n return execFileSync(\"git\", [\"-C\", repositoryPath, ...args], {\n encoding: \"utf8\",\n maxBuffer: MAX_BUFFER_BYTES,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") {\n throw new OwnersGitError(\"git_failed\", \"git is not available on PATH.\");\n }\n throw new OwnersGitError(\"git_failed\", gitErrorMessage(error));\n }\n};\n\nconst splitLines = (value: string): string[] =>\n value\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.length > 0);\n\n/**\n * Mirrors `normalizeAuthorIdentity` in `@codesentinel/git-analyzer` (not exported from that\n * package): numeric-prefixed GitHub noreply addresses collapse to `<handle>@users.noreply.github.com`\n * and bots keep their marker, so declared handles can be compared against history.\n */\nexport const normalizeGitAuthorIdentity = (authorName: string, authorEmail: string): string => {\n const normalizedName = authorName.trim().replace(/\\s+/g, \" \").toLowerCase();\n const normalizedEmail = authorEmail.trim().toLowerCase();\n\n if (/\\[bot\\]/i.test(normalizedName) || /\\[bot\\]/i.test(normalizedEmail)) {\n return normalizedEmail.length > 0 ? normalizedEmail : normalizedName;\n }\n\n const githubNoReplyMatch = normalizedEmail.match(/^\\d+\\+([^@]+)@users\\.noreply\\.github\\.com$/);\n const githubHandle = githubNoReplyMatch?.[1]?.trim().toLowerCase();\n if (githubHandle !== undefined && githubHandle.length > 0) {\n return `${githubHandle}@users.noreply.github.com`;\n }\n\n if (normalizedEmail.length > 0) {\n return normalizedEmail;\n }\n\n return normalizedName;\n};\n\nexport const normalizeRepositoryPath = (value: string): string => {\n let normalized = value.replace(/\\\\/g, \"/\").trim();\n while (normalized.startsWith(\"./\")) normalized = normalized.slice(2);\n return normalized.replace(/^\\/+/, \"\");\n};\n\nconst parseInteger = (value: string): number | null => {\n if (value.length === 0) return null;\n const parsed = Number.parseInt(value, 10);\n return Number.isNaN(parsed) ? null : parsed;\n};\n\n/**\n * A rename in `git log --numstat` arrives as `old => new` or `dir/{old => new}/file`. The\n * destination is what the current tree tracks, so that is the path the audit counts.\n */\nconst parseRenamedPath = (pathSpec: string): string => {\n if (!pathSpec.includes(\" => \")) return pathSpec;\n\n const braceRenameMatch = pathSpec.match(/^(.*)\\{(.+) => (.+)\\}(.*)$/);\n if (braceRenameMatch !== null) {\n const [, prefix, , renamedTo, suffix] = braceRenameMatch;\n return `${prefix}${renamedTo}${suffix}`;\n }\n\n const parts = pathSpec.split(\" => \");\n return parts[parts.length - 1] ?? pathSpec;\n};\n\n/**\n * Resolves the ref and lists the tracked tree at it. `git ls-tree -r` is the ref-pinned\n * equivalent of `git ls-files`: directories, binaries and untracked files are out of scope.\n */\nexport const readRepositorySnapshot = (targetPath: string, ref: string): RepositorySnapshot => {\n const inside = runGit(targetPath, [\"rev-parse\", \"--is-inside-work-tree\"]).trim();\n if (inside !== \"true\") {\n throw new OwnersGitError(\n \"not_a_git_repository\",\n `\"${targetPath}\" is not inside a git work tree.`,\n );\n }\n\n const repositoryPath = runGit(targetPath, [\"rev-parse\", \"--show-toplevel\"]).trim();\n if (repositoryPath.length === 0) {\n throw new OwnersGitError(\"not_a_git_repository\", `\"${targetPath}\" has no git work tree root.`);\n }\n\n const commitUnixRaw = runGit(repositoryPath, [\"log\", \"-1\", \"--format=%ct\", ref]).trim();\n const commitUnix = parseInteger(commitUnixRaw);\n if (commitUnix === null) {\n throw new OwnersGitError(\n \"unknown_ref\",\n `ref \"${ref}\" does not resolve to a commit in \"${repositoryPath}\".`,\n );\n }\n\n const trackedFiles = splitLines(\n runGit(repositoryPath, [\"ls-tree\", \"-r\", \"-z\", \"--name-only\", ref]).split(\"\\u0000\").join(\"\\n\"),\n ).sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n\n if (trackedFiles.length === 0) {\n throw new OwnersGitError(\n \"empty_repository\",\n `ref \"${ref}\" has no tracked files, so there is nothing to audit.`,\n );\n }\n\n return { repositoryPath, ref, commitUnix, trackedFiles };\n};\n\n/** Reads one file exactly as the ref stores it. Callers must have seen the path in the tree. */\nexport const readTextAtRef = (repositoryPath: string, ref: string, filePath: string): string =>\n runGit(repositoryPath, [\"show\", `${ref}:${filePath}`]);\n\nexport type OwnershipEvidence = {\n /** One entry per file with at least one lifetime commit, ascending by path. */\n files: readonly OwnershipFileEvidence[];\n /** Epoch seconds the window starts at, derived from the ref commit. */\n sinceUnix: number;\n};\n\n/** Per-author accumulator for a single file: commits plus the raw name used for identity matching. */\ntype AuthorAccumulator = { authorName: string; commits: number };\n\ntype FileAccumulator = {\n commits: number;\n recentCommits: number;\n churnTotal: number;\n lastCommitUnix: number;\n authors: Map<string, AuthorAccumulator>;\n recentAuthors: Map<string, AuthorAccumulator>;\n};\n\nconst accumulateAuthor = (\n authors: Map<string, AuthorAccumulator>,\n authorId: string,\n authorName: string,\n): void => {\n const author = authors.get(authorId) ?? { authorName, commits: 0 };\n authors.set(authorId, { authorName: author.authorName, commits: author.commits + 1 });\n};\n\nconst toOwnershipAuthors = (\n authors: ReadonlyMap<string, AuthorAccumulator>,\n): readonly OwnershipAuthor[] =>\n [...authors.entries()]\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([authorId, value]) => ({\n authorId,\n authorName: value.authorName,\n commits: value.commits,\n }));\n\n/**\n * Builds per-file authorship evidence for both horizons in a single pass over full history.\n *\n * `commits` and `authors` cover the file's lifetime; `recentCommits` and `recentAuthors` cover\n * `[refCommit - windowDays, refCommit]`. The window is anchored to the ref commit and not to the\n * wall clock: two runs against the same ref therefore see the same commits, which is what makes\n * the JSON reproducible and lets a CI run and a local baseline agree.\n *\n * `criticality.churnTotal` deliberately keeps its window-only semantics, so the criticality\n * fallback still measures recent churn rather than the whole history.\n *\n * Rename detection is disabled so a rename shows up as a delete plus an add instead of a\n * brace-expanded path that would not resolve against the tracked tree.\n */\nexport const collectOwnershipEvidence = (\n snapshot: RepositorySnapshot,\n windowDays: number,\n): OwnershipEvidence => {\n const sinceUnix = snapshot.commitUnix - windowDays * 86_400;\n const rawLog = runGit(snapshot.repositoryPath, [\n \"-c\",\n \"core.quotepath=false\",\n \"log\",\n snapshot.ref,\n \"--no-merges\",\n \"--no-renames\",\n \"--numstat\",\n `--pretty=format:${LOG_FORMAT}`,\n ]);\n\n const trackedFileSet = new Set(snapshot.trackedFiles);\n const filesByPath = new Map<string, FileAccumulator>();\n\n const records = rawLog\n .split(RECORD_SEPARATOR)\n .map((record) => record.trim())\n .filter((record) => record.length > 0);\n\n for (const record of records) {\n const lines = record\n .split(\"\\n\")\n .map((line) => line.trimEnd())\n .filter((line) => line.length > 0);\n const header = lines[0];\n if (header === undefined) continue;\n\n const [authoredAtRaw, authorName, authorEmail] = header.split(FIELD_SEPARATOR);\n if (authoredAtRaw === undefined || authorName === undefined || authorEmail === undefined) {\n continue;\n }\n\n const authoredAtUnix = parseInteger(authoredAtRaw);\n if (authoredAtUnix === null) continue;\n\n const authorId = normalizeGitAuthorIdentity(authorName, authorEmail);\n const insideWindow = authoredAtUnix >= sinceUnix;\n\n for (const line of lines.slice(1)) {\n const parts = line.split(\"\\t\");\n if (parts.length < 3) continue;\n\n const [additionsRaw, deletionsRaw] = parts;\n if (additionsRaw === undefined || deletionsRaw === undefined) continue;\n\n const filePath = parseRenamedPath(parts.slice(2).join(\"\\t\"));\n if (!trackedFileSet.has(filePath)) continue;\n\n const accumulator = filesByPath.get(filePath) ?? {\n commits: 0,\n recentCommits: 0,\n churnTotal: 0,\n lastCommitUnix: authoredAtUnix,\n authors: new Map<string, AuthorAccumulator>(),\n recentAuthors: new Map<string, AuthorAccumulator>(),\n };\n\n accumulator.commits += 1;\n accumulator.lastCommitUnix = Math.max(accumulator.lastCommitUnix, authoredAtUnix);\n accumulateAuthor(accumulator.authors, authorId, authorName);\n\n if (insideWindow) {\n const additions = additionsRaw === \"-\" ? 0 : (parseInteger(additionsRaw) ?? 0);\n const deletions = deletionsRaw === \"-\" ? 0 : (parseInteger(deletionsRaw) ?? 0);\n\n accumulator.recentCommits += 1;\n accumulator.churnTotal += additions + deletions;\n accumulateAuthor(accumulator.recentAuthors, authorId, authorName);\n }\n\n filesByPath.set(filePath, accumulator);\n }\n }\n\n const files: OwnershipFileEvidence[] = [];\n for (const filePath of [...filesByPath.keys()].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))) {\n const accumulator = filesByPath.get(filePath);\n if (accumulator === undefined) continue;\n\n files.push({\n filePath,\n commits: accumulator.commits,\n recentCommits: accumulator.recentCommits,\n authors: toOwnershipAuthors(accumulator.authors),\n recentAuthors: toOwnershipAuthors(accumulator.recentAuthors),\n lastCommitUnix: accumulator.lastCommitUnix,\n criticality: { churnTotal: accumulator.churnTotal },\n });\n }\n\n return { files, sinceUnix };\n};\n","import { join } from \"node:path\";\nimport { readFile, writeFile } from \"node:fs/promises\";\nimport {\n compareSnapshots,\n createReport,\n formatReport,\n parseSnapshot,\n type CodeSentinelReport,\n type ReportFormat,\n} from \"@codesentinel/reporter\";\nimport { type AuthorIdentityCliMode, type ScoringProfileCliMode } from \"./run-analyze-command.js\";\nimport { createSilentLogger, type Logger } from \"./logger.js\";\nimport { buildAnalysisSnapshot } from \"./build-analysis-snapshot.js\";\nimport { writeHtmlReportBundle } from \"./html-report.js\";\nimport { openPath } from \"./open-path.js\";\nimport { buildReportOwnership } from \"./report-ownership.js\";\n\nexport type ReportOutputFormat = ReportFormat | \"html\";\n\nexport type ReportCommandOptions = {\n format: ReportOutputFormat;\n comparePath?: string;\n outputPath?: string;\n snapshotPath?: string;\n open?: boolean;\n includeTrace: boolean;\n recentWindowDays?: number;\n scoringProfile?: ScoringProfileCliMode;\n};\n\nexport const runReportCommand = async (\n inputPath: string | undefined,\n authorIdentityMode: AuthorIdentityCliMode,\n options: ReportCommandOptions,\n logger: Logger = createSilentLogger(),\n): Promise<{ report: CodeSentinelReport; rendered: string; outputPath?: string }> => {\n logger.info(\"building analysis snapshot\");\n const current = await buildAnalysisSnapshot(\n inputPath,\n authorIdentityMode,\n {\n includeTrace: options.includeTrace,\n ...(options.scoringProfile === undefined ? {} : { scoringProfile: options.scoringProfile }),\n ...(options.recentWindowDays === undefined\n ? {}\n : { recentWindowDays: options.recentWindowDays }),\n },\n logger,\n );\n\n if (options.snapshotPath !== undefined) {\n await writeFile(options.snapshotPath, JSON.stringify(current, null, 2), \"utf8\");\n logger.info(`snapshot written: ${options.snapshotPath}`);\n }\n\n const { ownership, webUrl } = await buildReportOwnership(\n current.analysis.structural.targetPath,\n logger,\n );\n const extras = { ownership, repositoryWebUrl: webUrl };\n\n let report: CodeSentinelReport;\n if (options.comparePath === undefined) {\n report = createReport(current, undefined, extras);\n } else {\n logger.info(`loading baseline snapshot: ${options.comparePath}`);\n const baselineRaw = await readFile(options.comparePath, \"utf8\");\n const baseline = parseSnapshot(baselineRaw);\n const diff = compareSnapshots(current, baseline);\n report = createReport(current, diff, extras);\n }\n\n if (options.format === \"html\") {\n const bundlePath = await writeHtmlReportBundle(report, {\n repositoryPath: current.analysis.structural.targetPath,\n ...(options.outputPath === undefined ? {} : { outputPath: options.outputPath }),\n });\n if (options.open === true) {\n const opened = await openPath(join(bundlePath, \"index.html\"));\n if (!opened) {\n logger.warn(\"unable to open html report automatically on this platform\");\n }\n }\n logger.info(`html report written: ${bundlePath}`);\n return {\n report,\n rendered: bundlePath,\n outputPath: bundlePath,\n };\n }\n\n const rendered = formatReport(report, options.format);\n\n if (options.outputPath !== undefined) {\n await writeFile(options.outputPath, rendered, \"utf8\");\n logger.info(`report written: ${options.outputPath}`);\n }\n\n return {\n report,\n rendered,\n ...(options.outputPath === undefined ? {} : { outputPath: options.outputPath }),\n };\n};\n","import { mkdir, readFile, rm, stat, writeFile } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { CodeSentinelReport } from \"@codesentinel/reporter\";\n\nconst HTML_REPORT_DIR = \".codesentinel/report\";\n\nconst getBundledHtmlAppPath = (): string =>\n resolve(dirname(fileURLToPath(import.meta.url)), \"html-report-app\");\n\nconst serializeReportBootstrap = (report: CodeSentinelReport): string =>\n `window.__CODESENTINEL_REPORT__ = ${JSON.stringify(report).replaceAll(\"</\", \"<\\\\/\")};\\n`;\n\nconst escapeInlineScript = (script: string): string =>\n script\n .replaceAll(\"</script\", \"<\\\\/script\")\n .replaceAll(\"<script\", \"\\\\x3Cscript\")\n .replaceAll(\"<!--\", \"\\\\x3C!--\")\n .replaceAll(\"\\u2028\", \"\\\\u2028\")\n .replaceAll(\"\\u2029\", \"\\\\u2029\");\n\nconst ensureDirectory = async (directoryPath: string): Promise<void> => {\n await mkdir(directoryPath, { recursive: true });\n};\n\nconst readReferencedAssets = async (\n appPath: string,\n indexHtml: string,\n): Promise<{ styles: string[]; scripts: string[] }> => {\n const stylesheetPaths = [\n ...indexHtml.matchAll(/<link[^>]+rel=[\"']stylesheet[\"'][^>]+href=[\"']([^\"']+)[\"'][^>]*>/g),\n ]\n .map((match) => match[1])\n .filter(\n (value): value is string =>\n value !== undefined && !/^https?:\\/\\//.test(value) && !value.startsWith(\"//\"),\n );\n\n const styles = await Promise.all(\n stylesheetPaths.map(async (href) => readFile(resolve(appPath, href), \"utf8\")),\n );\n\n const scriptPaths = [...indexHtml.matchAll(/<script[^>]+src=[\"']([^\"']+)[\"'][^>]*><\\/script>/g)]\n .map((match) => match[1])\n .filter(\n (value): value is string =>\n value !== undefined && !/^https?:\\/\\//.test(value) && !value.startsWith(\"//\"),\n );\n\n const scripts = await Promise.all(\n scriptPaths.map(async (src) => readFile(resolve(appPath, src), \"utf8\")),\n );\n\n return { styles, scripts };\n};\n\nconst inlineBuiltHtml = async (appPath: string, report: CodeSentinelReport): Promise<string> => {\n const indexHtml = await readFile(resolve(appPath, \"index.html\"), \"utf8\");\n const { styles, scripts } = await readReferencedAssets(appPath, indexHtml);\n\n const htmlWithoutExternalAssets = indexHtml\n .replace(/\\s*<link[^>]+rel=[\"']stylesheet[\"'][^>]*>\\s*/g, (tag) =>\n /href=[\"'](https?:)?\\/\\//.test(tag) ? tag : \"\",\n )\n .replace(/\\s*<script[^>]+src=[\"'][^\"']+[\"'][^>]*><\\/script>\\s*/g, (tag) =>\n /src=[\"'](https?:)?\\/\\//.test(tag) ? tag : \"\",\n );\n\n const inlineStyles = styles.map((style) => `<style>\\n${style}\\n</style>`).join(\"\\n\");\n const bootstrapScript = `<script>\\n${serializeReportBootstrap(report)}</script>`;\n const inlineScripts = scripts\n .map((script) => `<script>\\n${escapeInlineScript(script)}\\n</script>`)\n .join(\"\\n\");\n\n return htmlWithoutExternalAssets\n .replace(\"</head>\", () => `${inlineStyles === \"\" ? \"\" : `${inlineStyles}\\n`}</head>`)\n .replace(\n \"</body>\",\n () => `${bootstrapScript}\\n${inlineScripts === \"\" ? \"\" : `${inlineScripts}\\n`}</body>`,\n );\n};\n\nconst assertHtmlAppAssets = async (assetPath: string): Promise<void> => {\n const assetStats = await stat(assetPath).catch(() => undefined);\n if (assetStats === undefined || !assetStats.isDirectory()) {\n throw new Error(\n `html_report_assets_missing: expected built app at ${assetPath}. Run the workspace build first.`,\n );\n }\n};\n\nexport type WriteHtmlReportBundleOptions = {\n repositoryPath: string;\n outputPath?: string;\n bundledAppPath?: string;\n};\n\nexport const resolveHtmlReportOutputPath = (\n repositoryPath: string,\n outputPath?: string,\n): string => {\n const invocationCwd = process.env[\"INIT_CWD\"] ?? process.cwd();\n return resolve(invocationCwd, outputPath ?? join(repositoryPath, HTML_REPORT_DIR));\n};\n\nexport const writeHtmlReportBundle = async (\n report: CodeSentinelReport,\n options: WriteHtmlReportBundleOptions,\n): Promise<string> => {\n const bundledAppPath = options.bundledAppPath ?? getBundledHtmlAppPath();\n await assertHtmlAppAssets(bundledAppPath);\n\n const outputPath = resolveHtmlReportOutputPath(options.repositoryPath, options.outputPath);\n await rm(outputPath, { recursive: true, force: true });\n await ensureDirectory(outputPath);\n await writeFile(\n resolve(outputPath, \"index.html\"),\n await inlineBuiltHtml(bundledAppPath, report),\n \"utf8\",\n );\n\n return outputPath;\n};\n","import { spawn } from \"node:child_process\";\nimport { platform } from \"node:os\";\n\nconst openCommandForPlatform = (\n targetPath: string,\n): { command: string; args: string[] } | undefined => {\n switch (platform()) {\n case \"darwin\":\n return { command: \"open\", args: [targetPath] };\n case \"win32\":\n return { command: \"cmd\", args: [\"/c\", \"start\", \"\", targetPath] };\n case \"linux\":\n return { command: \"xdg-open\", args: [targetPath] };\n default:\n return undefined;\n }\n};\n\nexport const openPath = async (targetPath: string): Promise<boolean> => {\n const command = openCommandForPlatform(targetPath);\n if (command === undefined) {\n return false;\n }\n\n return new Promise((resolve) => {\n const child = spawn(command.command, command.args, {\n detached: true,\n stdio: \"ignore\",\n });\n\n child.once(\"error\", () => resolve(false));\n child.once(\"spawn\", () => {\n child.unref();\n resolve(true);\n });\n });\n};\n","import { execFileSync } from \"node:child_process\";\nimport type { OwnershipAudit } from \"@codesentinel/ownership\";\nimport type { OwnershipAuditReport } from \"@codesentinel/reporter\";\nimport { buildOwnershipAudit } from \"./build-ownership-audit.js\";\nimport type { Logger } from \"./logger.js\";\n\nconst stripGitSuffix = (path: string): string => path.replace(/\\.git\\/?$/i, \"\").replace(/\\/+$/, \"\");\n\nexport const normalizeRepositoryWebUrl = (raw: string): string | null => {\n const value = raw.trim();\n if (value.length === 0) {\n return null;\n }\n\n if (!value.includes(\"://\")) {\n const scpMatch = value.match(/^(?:[^@\\s]+@)?([^:/\\s]+):(.+)$/);\n if (scpMatch === null) {\n return null;\n }\n\n const host = scpMatch[1];\n const path = stripGitSuffix(scpMatch[2] ?? \"\").replace(/^\\/+/, \"\");\n if (host === undefined || path.length === 0) {\n return null;\n }\n return `https://${host}/${path}`;\n }\n\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n return null;\n }\n\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\" && url.protocol !== \"ssh:\") {\n return null;\n }\n\n const path = stripGitSuffix(url.pathname).replace(/^\\/+/, \"\");\n if (url.hostname.length === 0 || path.length === 0) {\n return null;\n }\n return `https://${url.hostname}/${path}`;\n};\n\nexport const readRepositoryWebUrl = (repositoryPath: string): string | null => {\n try {\n const raw = execFileSync(\n \"git\",\n [\"-C\", repositoryPath, \"config\", \"--get\", \"remote.origin.url\"],\n {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n },\n );\n return normalizeRepositoryWebUrl(raw);\n } catch {\n return null;\n }\n};\n\nexport const toOwnershipAuditReport = (audit: OwnershipAudit): OwnershipAuditReport => {\n if (!audit.available) {\n return {\n available: false,\n reason: audit.reason,\n warnings: audit.warnings,\n };\n }\n\n return {\n available: true,\n codeowners: {\n source: audit.codeowners.source,\n ignoredSources: audit.codeowners.ignoredSources,\n errors: audit.codeowners.errors,\n },\n metrics: audit.metrics,\n ghostOwners: audit.ghostOwners,\n files: audit.files,\n warnings: audit.warnings,\n };\n};\n\nexport const buildReportOwnership = async (\n repositoryPath: string,\n logger: Logger,\n): Promise<{ ownership: OwnershipAuditReport; webUrl: string | null }> => {\n const webUrl = readRepositoryWebUrl(repositoryPath);\n\n try {\n const { audit } = await buildOwnershipAudit(repositoryPath, {}, logger);\n return { ownership: toOwnershipAuditReport(audit), webUrl };\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown ownership audit error.\";\n logger.warn(`ownership audit unavailable: ${message}`);\n return {\n ownership: {\n available: false,\n reason: \"audit_unavailable\",\n warnings: [message],\n },\n webUrl,\n };\n }\n};\n","import type { AnalyzeSummary, RiskTrace, TargetTrace } from \"@codesentinel/core\";\nimport { computeRepositoryHealthSummary } from \"@codesentinel/health-engine\";\nimport { evaluateRepositoryRisk } from \"@codesentinel/risk-engine\";\nimport {\n collectAnalysisInputs,\n resolveHealthConfigForProfile,\n resolveRiskConfigForProfile,\n type AuthorIdentityCliMode,\n type ScoringProfileCliMode,\n} from \"./run-analyze-command.js\";\nimport { createSilentLogger, type Logger } from \"./logger.js\";\n\nexport type ExplainFormat = \"text\" | \"json\" | \"md\";\n\nexport type ExplainCommandOptions = {\n file?: string;\n module?: string;\n top: number;\n format: ExplainFormat;\n recentWindowDays?: number;\n scoringProfile?: ScoringProfileCliMode;\n};\n\nexport type ExplainResult = {\n summary: AnalyzeSummary;\n trace: RiskTrace;\n selectedTargets: readonly TargetTrace[];\n};\n\nconst selectTargets = (\n trace: RiskTrace,\n summary: AnalyzeSummary,\n options: ExplainCommandOptions,\n): readonly TargetTrace[] => {\n if (options.file !== undefined) {\n const normalized = options.file.replaceAll(\"\\\\\", \"/\");\n return trace.targets.filter(\n (target) => target.targetType === \"file\" && target.targetId === normalized,\n );\n }\n\n if (options.module !== undefined) {\n return trace.targets.filter(\n (target) => target.targetType === \"module\" && target.targetId === options.module,\n );\n }\n\n const top = Math.max(1, options.top);\n const topFiles = summary.risk.hotspots.slice(0, top).map((entry) => entry.file);\n const fileSet = new Set(topFiles);\n return trace.targets.filter(\n (target) =>\n target.targetType === \"repository\" ||\n (target.targetType === \"file\" && fileSet.has(target.targetId)),\n );\n};\n\nexport const runExplainCommand = async (\n inputPath: string | undefined,\n authorIdentityMode: AuthorIdentityCliMode,\n options: ExplainCommandOptions,\n logger: Logger = createSilentLogger(),\n): Promise<ExplainResult> => {\n const analysisInputs = await collectAnalysisInputs(\n inputPath,\n authorIdentityMode,\n {\n ...(options.recentWindowDays === undefined\n ? {}\n : { recentWindowDays: options.recentWindowDays }),\n },\n logger,\n );\n logger.info(\"computing explainable risk summary\");\n\n const riskConfig = resolveRiskConfigForProfile(options.scoringProfile);\n const healthConfig = resolveHealthConfigForProfile(options.scoringProfile);\n const evaluation = evaluateRepositoryRisk(\n {\n structural: analysisInputs.structural,\n evolution: analysisInputs.evolution,\n external: analysisInputs.external,\n ...(riskConfig === undefined ? {} : { config: riskConfig }),\n },\n { explain: true },\n );\n if (evaluation.trace === undefined) {\n throw new Error(\"risk trace unavailable\");\n }\n\n const summary: AnalyzeSummary = {\n structural: analysisInputs.structural,\n evolution: analysisInputs.evolution,\n external: analysisInputs.external,\n risk: evaluation.summary,\n health: computeRepositoryHealthSummary({\n structural: analysisInputs.structural,\n evolution: analysisInputs.evolution,\n ...(healthConfig === undefined ? {} : { config: healthConfig }),\n }),\n };\n logger.info(\n `explanation completed (riskScore=${summary.risk.riskScore}, healthScore=${summary.health.healthScore})`,\n );\n\n return {\n summary,\n trace: evaluation.trace,\n selectedTargets: selectTargets(evaluation.trace, summary, options),\n };\n};\n","import { writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { DEFAULT_MIN_COMMITS, type OwnershipAudit } from \"@codesentinel/ownership\";\nimport {\n buildOwnershipAudit,\n DEFAULT_OWNERS_REF,\n DEFAULT_OWNERS_WINDOW_DAYS,\n} from \"./build-ownership-audit.js\";\nimport {\n buildOwnersReport,\n evaluateOwnersThresholds,\n formatOwnersOutput,\n type OwnersOutputFormat,\n type OwnersReport,\n type OwnersThresholdConfig,\n} from \"./format-owners-output.js\";\nimport { createSilentLogger, type Logger } from \"./logger.js\";\n\nexport {\n DEFAULT_OWNERS_ALIASES_PATH,\n DEFAULT_OWNERS_REF,\n DEFAULT_OWNERS_WINDOW_DAYS,\n OwnersConfigurationError,\n} from \"./build-ownership-audit.js\";\n\n/**\n * Application layer for `codesentinel owners`: reads everything the audit needs from a git ref,\n * runs the pure audit and renders it.\n *\n * The command is offline by contract. The only inputs are the repository at `--ref`, the optional\n * versioned alias map and the structural analysis of the working tree.\n */\n\n/** ESLint-style exit codes fixed by the design, so a gate can tell \"problems\" from \"broken\". */\nexport const OWNERS_EXIT_CODES = {\n ok: 0,\n thresholdExceeded: 1,\n invalidConfiguration: 2,\n} as const;\n\nexport const DEFAULT_OWNERS_TOP = 10;\n\nexport type OwnersCommandOptions = {\n codeownersPath?: string;\n ref?: string;\n windowDays?: number;\n minCommits?: number;\n top?: number;\n format?: OwnersOutputFormat;\n outputPath?: string;\n aliasesPath?: string;\n resolveGithub?: boolean;\n thresholds?: Partial<OwnersThresholdConfig>;\n};\n\nexport type OwnersCommandResult = {\n audit: OwnershipAudit;\n report: OwnersReport;\n rendered: string;\n exitCode: number;\n trackedFileCount: number;\n outputPath?: string;\n};\n\nconst DEFAULT_THRESHOLDS: OwnersThresholdConfig = {\n failOn: \"none\",\n maxUnownedCritical: null,\n maxGhostOwners: null,\n maxDrift: null,\n};\n\nconst resolveTargetPath = (inputPath: string | undefined): string => {\n const invocationCwd = process.env[\"INIT_CWD\"] ?? process.cwd();\n return resolve(invocationCwd, inputPath ?? \".\");\n};\n\nconst normalizeThresholds = (\n input: Partial<OwnersThresholdConfig> | undefined,\n): OwnersThresholdConfig => ({\n failOn: input?.failOn ?? DEFAULT_THRESHOLDS.failOn,\n maxUnownedCritical: input?.maxUnownedCritical ?? DEFAULT_THRESHOLDS.maxUnownedCritical,\n maxGhostOwners: input?.maxGhostOwners ?? DEFAULT_THRESHOLDS.maxGhostOwners,\n maxDrift: input?.maxDrift ?? DEFAULT_THRESHOLDS.maxDrift,\n});\n\nconst resolveExitCode = (\n failOn: OwnersThresholdConfig[\"failOn\"],\n violationCount: number,\n): number => {\n if (failOn === \"none\" || violationCount === 0) {\n return OWNERS_EXIT_CODES.ok;\n }\n return failOn === \"error\" ? OWNERS_EXIT_CODES.thresholdExceeded : OWNERS_EXIT_CODES.ok;\n};\n\nexport const runOwnersCommand = async (\n inputPath: string | undefined,\n options: OwnersCommandOptions = {},\n logger: Logger = createSilentLogger(),\n): Promise<OwnersCommandResult> => {\n const targetPath = resolveTargetPath(inputPath);\n const ref = options.ref ?? DEFAULT_OWNERS_REF;\n const windowDays = options.windowDays ?? DEFAULT_OWNERS_WINDOW_DAYS;\n const minCommits = options.minCommits ?? DEFAULT_MIN_COMMITS;\n const top = options.top ?? DEFAULT_OWNERS_TOP;\n const format = options.format ?? \"console\";\n const thresholds = normalizeThresholds(options.thresholds);\n\n logger.info(`auditing declared ownership at ${ref} in ${targetPath}`);\n\n const callerWarnings: string[] = [];\n if (options.resolveGithub === true) {\n callerWarnings.push(\n \"--resolve-github is not implemented in this iteration; the audit stays offline and declared owners were resolved from local history only.\",\n );\n logger.warn(callerWarnings[callerWarnings.length - 1] ?? \"\");\n }\n\n const { audit, trackedFileCount } = await buildOwnershipAudit(\n targetPath,\n {\n ref,\n windowDays,\n minCommits,\n ...(options.codeownersPath === undefined ? {} : { codeownersPath: options.codeownersPath }),\n ...(options.aliasesPath === undefined ? {} : { aliasesPath: options.aliasesPath }),\n warnings: callerWarnings,\n },\n logger,\n );\n\n const metrics = audit.available ? audit.metrics : null;\n const violations = evaluateOwnersThresholds(metrics, thresholds);\n\n if (metrics === null && hasConfiguredThreshold(thresholds)) {\n logger.warn(\"no CODEOWNERS file was found; thresholds cannot be evaluated.\");\n }\n if (violations.length > 0) {\n for (const violation of violations) {\n logger.warn(`threshold exceeded (${thresholds.failOn}): ${violation.message}`);\n }\n }\n\n const report = buildOwnersReport({\n audit,\n ref,\n windowDays,\n minCommits,\n trackedFileCount,\n thresholds,\n violations,\n });\n const rendered = formatOwnersOutput(report, format, top);\n\n if (options.outputPath !== undefined) {\n await writeFile(options.outputPath, `${rendered}\\n`, \"utf8\");\n logger.info(`owners output written: ${options.outputPath}`);\n }\n\n return {\n audit,\n report,\n rendered,\n exitCode: resolveExitCode(thresholds.failOn, violations.length),\n trackedFileCount,\n ...(options.outputPath === undefined ? {} : { outputPath: options.outputPath }),\n };\n};\n\nconst hasConfiguredThreshold = (thresholds: OwnersThresholdConfig): boolean =>\n thresholds.maxUnownedCritical !== null ||\n thresholds.maxGhostOwners !== null ||\n thresholds.maxDrift !== null;\n","import type {\n DeclaredOwner,\n FileOwnershipAudit,\n OwnershipAudit,\n OwnershipAuditMetrics,\n OwnershipStatus,\n} from \"@codesentinel/ownership\";\n\n/**\n * Report payload and renderers for `codesentinel owners`.\n *\n * The payload is the JSON contract: fixed keys, fixed order, no timestamps, no clock. Console and\n * Markdown are rendered from the same object, so the three formats can never disagree.\n */\n\nexport const OWNERS_SCHEMA_VERSION = \"codesentinel.owners.v1\";\n\nexport type OwnersOutputFormat = \"console\" | \"json\" | \"md\";\n\nexport type OwnersFailOn = \"none\" | \"warn\" | \"error\";\n\nexport type OwnersThresholdConfig = {\n failOn: OwnersFailOn;\n maxUnownedCritical: number | null;\n maxGhostOwners: number | null;\n maxDrift: number | null;\n};\n\nexport type OwnersThresholdViolation = {\n threshold: \"max-unowned-critical\" | \"max-ghost-owners\" | \"max-drift\";\n limit: number;\n actual: number;\n message: string;\n};\n\nexport type OwnersReportCodeowners = {\n source: string;\n ignoredSources: readonly string[];\n entryCount: number;\n errorCount: number;\n errors: readonly { line: number; reason: string }[];\n};\n\nexport type OwnersReportFileCounts = {\n trackedFiles: number;\n declaredFiles: number;\n criticalFiles: number;\n declaredCriticalFiles: number;\n driftedFiles: number;\n};\n\nexport type OwnersReport = {\n schemaVersion: typeof OWNERS_SCHEMA_VERSION;\n available: boolean;\n ref: string;\n windowDays: number;\n minCommits: number;\n codeowners: OwnersReportCodeowners | null;\n fileCounts: OwnersReportFileCounts;\n metrics: OwnershipAuditMetrics | null;\n ghostOwners: readonly { owner: DeclaredOwner; samplePaths: readonly string[] }[];\n files: readonly FileOwnershipAudit[];\n warnings: readonly string[];\n thresholds: OwnersThresholdConfig & {\n violations: readonly OwnersThresholdViolation[];\n };\n};\n\nexport const formatDeclaredOwner = (owner: DeclaredOwner): string => {\n if (owner.kind === \"user\") return `@${owner.handle}`;\n if (owner.kind === \"team\") return `@${owner.org}/${owner.slug}`;\n return owner.address;\n};\n\nexport const formatDeclaredOwners = (owners: readonly DeclaredOwner[]): string =>\n owners.map(formatDeclaredOwner).join(\", \");\n\nconst compareText = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);\n\nconst countFileAudits = (\n files: readonly FileOwnershipAudit[],\n trackedFiles: number,\n): OwnersReportFileCounts => {\n const declaredFiles = files.filter((file) => file.declared.length > 0);\n return {\n trackedFiles,\n declaredFiles: declaredFiles.length,\n criticalFiles: files.filter((file) => file.criticality.isCritical).length,\n declaredCriticalFiles: files.filter(\n (file) => file.declared.length > 0 && file.criticality.isCritical,\n ).length,\n driftedFiles: declaredFiles.filter((file) => file.status === \"drifted\").length,\n };\n};\n\n/**\n * Thresholds are evaluated against the published metrics, never against a recomputed value, so\n * `--fail-on error` fails exactly what the output shows.\n */\nexport const evaluateOwnersThresholds = (\n metrics: OwnershipAuditMetrics | null,\n config: OwnersThresholdConfig,\n): readonly OwnersThresholdViolation[] => {\n if (metrics === null) {\n return [];\n }\n\n const violations: OwnersThresholdViolation[] = [];\n\n if (\n config.maxUnownedCritical !== null &&\n metrics.unownedCriticalCount > config.maxUnownedCritical\n ) {\n violations.push({\n threshold: \"max-unowned-critical\",\n limit: config.maxUnownedCritical,\n actual: metrics.unownedCriticalCount,\n message: `unowned critical files: ${metrics.unownedCriticalCount} (limit ${config.maxUnownedCritical})`,\n });\n }\n\n if (config.maxGhostOwners !== null && metrics.ghostOwnerCount > config.maxGhostOwners) {\n violations.push({\n threshold: \"max-ghost-owners\",\n limit: config.maxGhostOwners,\n actual: metrics.ghostOwnerCount,\n message: `ghost owners: ${metrics.ghostOwnerCount} (limit ${config.maxGhostOwners})`,\n });\n }\n\n if (config.maxDrift !== null) {\n const ratio = metrics.driftPercent / 100;\n if (ratio > config.maxDrift) {\n violations.push({\n threshold: \"max-drift\",\n limit: config.maxDrift,\n actual: ratio,\n message: `drift: ${metrics.driftPercent}% (limit ${formatRatio(config.maxDrift)})`,\n });\n }\n }\n\n return violations;\n};\n\nexport type BuildOwnersReportInput = {\n audit: OwnershipAudit;\n ref: string;\n windowDays: number;\n minCommits: number;\n trackedFileCount: number;\n thresholds: OwnersThresholdConfig;\n violations: readonly OwnersThresholdViolation[];\n};\n\nexport const buildOwnersReport = (input: BuildOwnersReportInput): OwnersReport => {\n const { audit } = input;\n const files = audit.available ? audit.files : [];\n const report: OwnersReport = {\n schemaVersion: OWNERS_SCHEMA_VERSION,\n available: audit.available,\n ref: input.ref,\n windowDays: input.windowDays,\n minCommits: input.minCommits,\n codeowners: audit.available\n ? {\n source: audit.codeowners.source,\n ignoredSources: [...audit.codeowners.ignoredSources].sort(compareText),\n entryCount: audit.codeowners.entries.length,\n errorCount: audit.codeowners.errors.length,\n errors: [...audit.codeowners.errors].sort((a, b) => a.line - b.line),\n }\n : null,\n fileCounts: countFileAudits(files, input.trackedFileCount),\n metrics: audit.available ? audit.metrics : null,\n ghostOwners: audit.available ? audit.ghostOwners : [],\n files,\n warnings: [...audit.warnings],\n thresholds: {\n ...input.thresholds,\n violations: [...input.violations],\n },\n };\n\n return report;\n};\n\nconst formatPercent = (value: number): string => {\n const rounded = Number.isInteger(value) ? value.toString() : value.toFixed(2);\n return `${rounded}%`;\n};\n\nconst formatRatio = (value: number): string => {\n const percent = Math.round(value * 100);\n return `${percent}%`;\n};\n\nconst formatShare = (share: number | null): string =>\n share === null ? \"n/a\" : `${Math.round(share * 100)}%`;\n\nconst plural = (count: number, singular: string, pluralForm: string): string =>\n `${count} ${count === 1 ? singular : pluralForm}`;\n\nconst padLabel = (label: string): string => `${label}:`.padEnd(26, \" \");\n\nconst topLimit = (value: number): number => (Number.isFinite(value) && value > 0 ? value : 0);\n\nconst renderConsoleSection = (\n title: string,\n lines: readonly string[],\n total: number,\n top: number,\n): string[] => {\n if (total === 0) {\n return [`${title}: none`];\n }\n\n const shown = lines.slice(0, topLimit(top));\n const remaining = total - shown.length;\n return [\n title,\n ...shown.map((line) => ` ${line}`),\n ...(remaining > 0 ? [` ... ${plural(remaining, \"more file\", \"more files\")}`] : []),\n ];\n};\n\nconst statusFiles = (\n files: readonly FileOwnershipAudit[],\n status: OwnershipStatus,\n): readonly FileOwnershipAudit[] => files.filter((file) => file.status === status);\n\nconst renderConsole = (report: OwnersReport, top: number): string => {\n const lines: string[] = [];\n lines.push(\n `Ownership audit — ${plural(report.fileCounts.trackedFiles, \"tracked file\", \"tracked files\")}, window ${report.windowDays}d, ref ${report.ref}`,\n );\n\n if (!report.available || report.metrics === null) {\n lines.push(\"\");\n lines.push(`No CODEOWNERS file was found at ${report.ref}.`);\n lines.push(\n \"Looked for .github/CODEOWNERS, CODEOWNERS and docs/CODEOWNERS. The ownership audit is unavailable.\",\n );\n appendWarnings(lines, report.warnings);\n return lines.join(\"\\n\");\n }\n\n const { metrics, fileCounts, codeowners } = report;\n const source = codeowners === null ? \"unknown\" : codeowners.source;\n const errors = codeowners === null ? 0 : codeowners.errorCount;\n lines.push(\n `CODEOWNERS ${source} · ${plural(codeowners?.entryCount ?? 0, \"entry\", \"entries\")} · ${plural(errors, \"invalid line\", \"invalid lines\")}`,\n );\n lines.push(\"\");\n lines.push(\n `${padLabel(\"Declared coverage\")}${formatPercent(metrics.declaredCoveragePercent)} (${fileCounts.declaredFiles}/${fileCounts.trackedFiles})`,\n );\n lines.push(\n `${padLabel(\"Critical coverage\")}${formatPercent(metrics.declaredCoverageCriticalPercent)} (${fileCounts.declaredCriticalFiles}/${fileCounts.criticalFiles})`,\n );\n lines.push(\n `${padLabel(\"Drift\")}${formatPercent(metrics.driftPercent)} (${fileCounts.driftedFiles}/${fileCounts.declaredFiles} declared files)`,\n );\n lines.push(\n `${padLabel(\"Owners without activity\")}${plural(metrics.ghostOwnerCount, \"owner\", \"owners\")}`,\n );\n lines.push(`${padLabel(\"Unowned critical\")}${metrics.unownedCriticalCount}`);\n lines.push(`${padLabel(\"Single-owner modules\")}${metrics.singleOwnerModuleCount}`);\n lines.push(\"\");\n\n const unownedCritical = statusFiles(report.files, \"unowned-critical\");\n lines.push(\n ...renderConsoleSection(\n \"Unowned critical\",\n unownedCritical.map(\n (file) =>\n `${file.filePath} fan-in ${file.criticality.fanIn ?? \"n/a\"} commits ${file.observed.commits} authors ${file.observed.authors}`,\n ),\n unownedCritical.length,\n top,\n ),\n );\n lines.push(\"\");\n\n const drifted = statusFiles(report.files, \"drifted\");\n lines.push(\n ...renderConsoleSection(\n \"Drift — declared owner is not the top recent author\",\n drifted.map(\n (file) =>\n `${file.filePath} declared ${formatDeclaredOwners(file.declared)} observed ${file.observed.topAuthorId ?? \"unknown\"} (${formatShare(file.observed.topAuthorShare)})`,\n ),\n drifted.length,\n top,\n ),\n );\n lines.push(\"\");\n\n const ghosts = report.ghostOwners;\n lines.push(\n ...renderConsoleSection(\n \"Ghost owners — declared, no commits in the window\",\n ghosts.map(\n (entry) =>\n `${formatDeclaredOwner(entry.owner)} ${entry.samplePaths.join(\", \") || \"no sample path\"}`,\n ),\n ghosts.length,\n top,\n ),\n );\n\n appendWarnings(lines, report.warnings);\n return lines.join(\"\\n\");\n};\n\nconst appendWarnings = (lines: string[], warnings: readonly string[]): void => {\n if (warnings.length === 0) return;\n lines.push(\"\");\n lines.push(\"Warnings\");\n for (const warning of warnings) {\n lines.push(` - ${warning}`);\n }\n};\n\nconst escapeTableCell = (value: string): string => value.replace(/\\|/g, \"\\\\|\");\n\nconst renderMarkdownTable = (header: readonly string[], rows: readonly string[][]): string[] => {\n const lines = [`| ${header.join(\" | \")} |`, `| ${header.map(() => \"---\").join(\" | \")} |`];\n for (const row of rows) {\n lines.push(`| ${row.map(escapeTableCell).join(\" | \")} |`);\n }\n return lines;\n};\n\nconst renderMarkdown = (report: OwnersReport, top: number): string => {\n const lines: string[] = [];\n lines.push(\"# Ownership audit\");\n lines.push(\"\");\n lines.push(`- ref: \\`${report.ref}\\``);\n lines.push(`- window: ${report.windowDays} days`);\n lines.push(`- tracked files: ${report.fileCounts.trackedFiles}`);\n lines.push(`- minimum commits per file: ${report.minCommits}`);\n\n if (!report.available || report.metrics === null) {\n lines.push(\"- CODEOWNERS: not found\");\n lines.push(\"\");\n lines.push(\n `No CODEOWNERS file was found at \\`${report.ref}\\` (looked for \\`.github/CODEOWNERS\\`, \\`CODEOWNERS\\` and \\`docs/CODEOWNERS\\`). The ownership audit is unavailable.`,\n );\n if (report.warnings.length > 0) {\n lines.push(\"\");\n lines.push(\"## Warnings\");\n lines.push(\"\");\n for (const warning of report.warnings) {\n lines.push(`- ${warning}`);\n }\n }\n return lines.join(\"\\n\");\n }\n\n const { metrics, fileCounts, codeowners } = report;\n const source = codeowners === null ? \"unknown\" : codeowners.source;\n lines.push(`- CODEOWNERS: \\`${source}\\``);\n if (codeowners !== null && codeowners.ignoredSources.length > 0) {\n lines.push(\n `- ignored sources: ${codeowners.ignoredSources.map((item) => `\\`${item}\\``).join(\", \")}`,\n );\n }\n lines.push(\"\");\n\n lines.push(\"## Metrics\");\n lines.push(\"\");\n lines.push(\n ...renderMarkdownTable(\n [\"Metric\", \"Value\"],\n [\n [\n \"Declared coverage\",\n `${formatPercent(metrics.declaredCoveragePercent)} (${fileCounts.declaredFiles}/${fileCounts.trackedFiles})`,\n ],\n [\n \"Critical coverage\",\n `${formatPercent(metrics.declaredCoverageCriticalPercent)} (${fileCounts.declaredCriticalFiles}/${fileCounts.criticalFiles})`,\n ],\n [\n \"Drift\",\n `${formatPercent(metrics.driftPercent)} (${fileCounts.driftedFiles}/${fileCounts.declaredFiles})`,\n ],\n [\"Owners without activity\", `${metrics.ghostOwnerCount}`],\n [\"Unowned critical\", `${metrics.unownedCriticalCount}`],\n [\"Single-owner modules\", `${metrics.singleOwnerModuleCount}`],\n ],\n ),\n );\n\n const unownedCritical = statusFiles(report.files, \"unowned-critical\").slice(0, topLimit(top));\n lines.push(\"\");\n lines.push(\"## Unowned critical\");\n lines.push(\"\");\n lines.push(\n ...(unownedCritical.length === 0\n ? [\"None.\"]\n : renderMarkdownTable(\n [\"Path\", \"Fan-in\", \"Commits\", \"Authors\"],\n unownedCritical.map((file) => [\n `\\`${file.filePath}\\``,\n `${file.criticality.fanIn ?? \"n/a\"}`,\n `${file.observed.commits}`,\n `${file.observed.authors}`,\n ]),\n )),\n );\n\n const drifted = statusFiles(report.files, \"drifted\").slice(0, topLimit(top));\n lines.push(\"\");\n lines.push(\"## Drift — declared owner is not the top recent author\");\n lines.push(\"\");\n lines.push(\n ...(drifted.length === 0\n ? [\"None.\"]\n : renderMarkdownTable(\n [\"Path\", \"Declared\", \"Observed\", \"Share\"],\n drifted.map((file) => [\n `\\`${file.filePath}\\``,\n formatDeclaredOwners(file.declared),\n file.observed.topAuthorId ?? \"unknown\",\n formatShare(file.observed.topAuthorShare),\n ]),\n )),\n );\n\n const ghosts = report.ghostOwners.slice(0, topLimit(top));\n lines.push(\"\");\n lines.push(\"## Ghost owners — declared, no commits in the window\");\n lines.push(\"\");\n lines.push(\n ...(ghosts.length === 0\n ? [\"None.\"]\n : renderMarkdownTable(\n [\"Owner\", \"Sample paths\"],\n ghosts.map((entry) => [\n formatDeclaredOwner(entry.owner),\n entry.samplePaths.join(\", \") || \"no sample path\",\n ]),\n )),\n );\n\n if (report.thresholds.violations.length > 0) {\n lines.push(\"\");\n lines.push(\"## Threshold violations\");\n lines.push(\"\");\n for (const violation of report.thresholds.violations) {\n lines.push(`- \\`${violation.threshold}\\`: ${violation.message}`);\n }\n }\n\n if (report.warnings.length > 0) {\n lines.push(\"\");\n lines.push(\"## Warnings\");\n lines.push(\"\");\n for (const warning of report.warnings) {\n lines.push(`- ${warning}`);\n }\n }\n\n return lines.join(\"\\n\");\n};\n\nexport const formatOwnersOutput = (\n report: OwnersReport,\n format: OwnersOutputFormat,\n top: number,\n): string => {\n if (format === \"json\") {\n return JSON.stringify(report, null, 2);\n }\n\n return format === \"md\" ? renderMarkdown(report, top) : renderConsole(report, top);\n};\n","import { access, mkdir, writeFile } from \"node:fs/promises\";\nimport { dirname, join, resolve } from \"node:path\";\n\n/**\n * Application layer for `codesentinel init`: plans the CI scaffold for a target repository and\n * writes the missing files. Planning is pure so the rendered output and the writes stay aligned.\n */\n\nexport const CODESENTINEL_WORKFLOW_PATH = \".github/workflows/codesentinel.yml\";\nexport const CODESENTINEL_OWNERS_PATH = \".codesentinel/owners.json\";\n\nexport const CODESENTINEL_WORKFLOW_TEMPLATE = `name: CodeSentinel\n\non:\n push:\n branches: [main]\n pull_request:\n\npermissions:\n contents: read\n\njobs:\n codesentinel:\n runs-on: ubuntu-latest\n steps:\n - name: Checkout\n uses: actions/checkout@v4\n with:\n fetch-depth: 0\n\n - name: Setup Node.js\n uses: actions/setup-node@v4\n with:\n node-version: 24\n\n - name: Run CodeSentinel\n run: npx --yes @getcodesentinel/codesentinel@latest ci --baseline-ref auto --fail-on error --snapshot codesentinel-snapshot.json\n\n - name: Build ownership report\n if: hashFiles('CODEOWNERS', '.github/CODEOWNERS', 'docs/CODEOWNERS') != ''\n run: npx --yes @getcodesentinel/codesentinel@latest owners --format md --output ownership.md\n\n - name: Upload CodeSentinel artifacts\n if: always()\n uses: actions/upload-artifact@v4\n with:\n name: codesentinel\n path: |\n codesentinel-snapshot.json\n ownership.md\n retention-days: 90\n if-no-files-found: warn\n`;\n\nexport const CODESENTINEL_OWNERS_FILE_CONTENT = `{\"aliases\": {}}\\n`;\n\nconst CODEOWNERS_CANDIDATES = [\"CODEOWNERS\", \".github/CODEOWNERS\", \"docs/CODEOWNERS\"] as const;\nconst SKIPPED_REASON = \"already exists (use --force to overwrite)\";\n\nexport type InitCiMode = \"github\" | \"none\";\n\nexport type InitCommandOptions = {\n force?: boolean;\n ci?: InitCiMode;\n dryRun?: boolean;\n};\n\nexport type InitActionStatus = \"created\" | \"updated\" | \"skipped\" | \"disabled\";\n\nexport type InitAction = {\n status: InitActionStatus;\n path: string;\n content?: string;\n reason?: string;\n};\n\nexport type InitPlan = {\n actions: InitAction[];\n};\n\nexport type InitPlanInput = {\n hasCodeownersFile: boolean;\n workflowExists: boolean;\n ownersFileExists: boolean;\n options?: InitCommandOptions;\n};\n\nexport type InitCommandResult = {\n targetPath: string;\n plan: InitPlan;\n rendered: string;\n exitCode: number;\n};\n\nconst action = (\n status: InitActionStatus,\n path: string,\n extra: { content?: string; reason?: string } = {},\n): InitAction => ({\n status,\n path,\n ...(extra.content === undefined ? {} : { content: extra.content }),\n ...(extra.reason === undefined ? {} : { reason: extra.reason }),\n});\n\nexport const buildInitPlan = (input: InitPlanInput): InitPlan => {\n const ci = input.options?.ci ?? \"github\";\n const force = input.options?.force === true;\n const actions: InitAction[] = [];\n\n if (ci === \"none\") {\n actions.push(\n action(\"disabled\", CODESENTINEL_WORKFLOW_PATH, { reason: \"disabled by --ci none\" }),\n );\n } else if (!input.workflowExists) {\n actions.push(\n action(\"created\", CODESENTINEL_WORKFLOW_PATH, { content: CODESENTINEL_WORKFLOW_TEMPLATE }),\n );\n } else if (force) {\n actions.push(\n action(\"updated\", CODESENTINEL_WORKFLOW_PATH, { content: CODESENTINEL_WORKFLOW_TEMPLATE }),\n );\n } else {\n actions.push(action(\"skipped\", CODESENTINEL_WORKFLOW_PATH, { reason: SKIPPED_REASON }));\n }\n\n if (input.hasCodeownersFile) {\n if (!input.ownersFileExists) {\n actions.push(\n action(\"created\", CODESENTINEL_OWNERS_PATH, {\n content: CODESENTINEL_OWNERS_FILE_CONTENT,\n }),\n );\n } else if (force) {\n actions.push(\n action(\"updated\", CODESENTINEL_OWNERS_PATH, {\n content: CODESENTINEL_OWNERS_FILE_CONTENT,\n }),\n );\n } else {\n actions.push(action(\"skipped\", CODESENTINEL_OWNERS_PATH, { reason: SKIPPED_REASON }));\n }\n }\n\n return { actions };\n};\n\nconst SECTION_ORDER: InitActionStatus[] = [\"created\", \"updated\", \"skipped\", \"disabled\"];\nconst SECTION_LABELS: Record<InitActionStatus, string> = {\n created: \"Created\",\n updated: \"Updated\",\n skipped: \"Skipped\",\n disabled: \"Disabled\",\n};\n\nconst indentContent = (content: string): string[] =>\n content\n .replace(/\\n$/, \"\")\n .split(\"\\n\")\n .map((line) => ` ${line}`);\n\nexport const renderInitOutput = (\n plan: InitPlan,\n options: { dryRun?: boolean; ci?: InitCiMode } = {},\n): string => {\n const dryRun = options.dryRun === true;\n const ci = options.ci ?? \"github\";\n const lines: string[] = [];\n lines.push(dryRun ? \"CodeSentinel init (dry run)\" : \"CodeSentinel init\");\n lines.push(\"\");\n\n for (const status of SECTION_ORDER) {\n const actions = plan.actions.filter((entry) => entry.status === status);\n if (actions.length === 0) {\n continue;\n }\n\n lines.push(SECTION_LABELS[status]);\n for (const entry of actions) {\n const suffix = entry.reason === undefined ? \"\" : ` — ${entry.reason}`;\n lines.push(` ${entry.path}${suffix}`);\n if (dryRun && (status === \"created\" || status === \"updated\") && entry.content !== undefined) {\n lines.push(...indentContent(entry.content));\n }\n }\n lines.push(\"\");\n }\n\n lines.push(\"Next steps\");\n lines.push(\" 1. Review and commit the generated files.\");\n lines.push(\n ci === \"none\"\n ? \" 2. Add `codesentinel ci` to your existing CI pipeline.\"\n : \" 2. Push or open a pull request so the workflow runs.\",\n );\n lines.push(\n \" 3. Download the codesentinel artifact with `gh run download` to keep history for `codesentinel trend`.\",\n );\n\n return lines.join(\"\\n\");\n};\n\nconst fileExists = async (absolutePath: string): Promise<boolean> => {\n try {\n await access(absolutePath);\n return true;\n } catch {\n return false;\n }\n};\n\nconst anyFileExists = async (\n targetPath: string,\n candidates: readonly string[],\n): Promise<boolean> => {\n for (const candidate of candidates) {\n if (await fileExists(join(targetPath, candidate))) {\n return true;\n }\n }\n\n return false;\n};\n\nconst resolveTargetPath = (inputPath: string | undefined): string => {\n const invocationCwd = process.env[\"INIT_CWD\"] ?? process.cwd();\n return resolve(invocationCwd, inputPath ?? \".\");\n};\n\nexport const runInitCommand = async (\n inputPath: string | undefined,\n options: InitCommandOptions = {},\n): Promise<InitCommandResult> => {\n const targetPath = resolveTargetPath(inputPath);\n const ci = options.ci ?? \"github\";\n const hasCodeownersFile = await anyFileExists(targetPath, CODEOWNERS_CANDIDATES);\n\n const plan = buildInitPlan({\n hasCodeownersFile,\n workflowExists:\n ci === \"github\" && (await fileExists(join(targetPath, CODESENTINEL_WORKFLOW_PATH))),\n ownersFileExists:\n hasCodeownersFile && (await fileExists(join(targetPath, CODESENTINEL_OWNERS_PATH))),\n options: { ...options, ci },\n });\n\n if (options.dryRun !== true) {\n for (const entry of plan.actions) {\n if (entry.status !== \"created\" && entry.status !== \"updated\") {\n continue;\n }\n\n const absolutePath = join(targetPath, entry.path);\n await mkdir(dirname(absolutePath), { recursive: true });\n await writeFile(absolutePath, entry.content ?? \"\", \"utf8\");\n }\n }\n\n return {\n targetPath,\n plan,\n rendered: renderInitOutput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C7C,gBAAgB;AAAA,MAChB;AAAA,IACF,CAAC;AACD,YAAQ,KAAK,QAAQ,YAAY,CAAC;AAAA,EACpC;AAEA,UAAQ,WAAW;AACnB,UAAQ,KAAK,CAAC;AAChB;AAEA,IAAI,KAAK,CAAC,MAAM,UAAU;AACxB,QAAM,mBAAmB;AAAA,IACvB,aAAa;AAAA,IACb,gBAAgB;AAAA,IAChB,MAAM,QAAQ;AAAA,IACd,KAAK,QAAQ;AAAA,EACf,CAAC;AACH;AAEA,IAAI;AACF,QAAM,QAAQ,WAAW,IAAI;AAC/B,SAAS,OAAO;AACd,MAAI,EAAE,iBAAiB,iBAAiB;AACtC,UAAM;AAAA,EACR;AAGA,MAAI,MAAM,aAAa,GAAG;AACxB,YAAQ,WAAW,kBAAkB;AAAA,EACvC;AACF;","names":["join","existsSync","readFileSync","workspaceSummary","packageJsonPath","version","deletedAny","stripQuotes","withDefaults","splitIndex","name","requested","ONE_DAY_MS","MAX_RETRIES","RETRY_BASE_DELAY_MS","round4","basename","round4","basename","join","resolve","stdout","resolve","readFileSync","readFile","writeFile","dirname","resolve","fileURLToPath","toHealthTier","factorLabelById","repositoryDimensionScores","createSummaryShape","mkdir","readFile","writeFile","homedir","join","parseSemver","resolve","spawn","stderr","stdin","clearScreenDown","cursorTo","emitKeypressEvents","ANSI","action","ANSI","stderr","cursorTo","clearScreenDown","hideCursor","showCursor","stdin","resolve","emitKeypressEvents","scriptPath","spawn","resolve","filePaths","existsSync","readFileSync","join","relative","resolve","readdirSync","statSync","basename","nodeLowLink","createWorkspaceByFile","normalizePath","readPackageJson","packageJsonPath","program","stripQuotes","inferWorkspaceKind","readWorkspacePatternsFromPackageJson","readWorkspacePatternsFromPnpmWorkspace","expandPattern","round4","clamp01","round4","average","normalizePath","ownershipDistributionPenalty","ownershipDistributionFactors","modularityHealth","changeHygieneHealth","testHealthScore","ownershipDistributionHealth","normalizedScore","topIssues","round4","average","normalizePath","resolve","readFile","writeFile","readFile","writeFile","readFile","writeFile","relative","resolve","existsSync","readFile","resolve","percentile","WHITESPACE_PATTERN","compareText","roundTo","resolveOwner","execFileSync","stderr","runGit","parseInteger","parseRenamedPath","resolve","existsSync","readFile","resolve","writeFile","relative","readFile","join","readFile","writeFile","mkdir","readFile","stat","writeFile","dirname","join","resolve","spawn","resolve","execFileSync","path","execFileSync","writeFile","readFile","join","writeFile","resolve","compareText","plural","renderMarkdown","resolveTargetPath","resolve","writeFile","mkdir","writeFile","dirname","join","resolve","resolveTargetPath","resolve","dirname","fileURLToPath","readFileSync","writeFile","readFile"]}