@getcodesentinel/codesentinel 1.32.0 → 1.33.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -13,6 +13,16 @@ import { join as join2 } from "path";
13
13
  import { createHash } from "crypto";
14
14
  import { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from "fs/promises";
15
15
  import { join as join3 } from "path";
16
+ import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2, statSync } from "fs";
17
+ import { basename, join as join5, relative, resolve } from "path";
18
+ var DEFAULT_EXTERNAL_ANALYSIS_CONFIG = {
19
+ abandonedDaysThreshold: 540,
20
+ deepChainThreshold: 6,
21
+ fanOutHighThreshold: 25,
22
+ centralityTopN: 20,
23
+ maxHighRiskDependencies: 100,
24
+ metadataRequestConcurrency: 8
25
+ };
16
26
  var round4 = (value) => Number(value.toFixed(4));
17
27
  var normalizeNodes = (nodes) => {
18
28
  const byName = /* @__PURE__ */ new Map();
@@ -115,7 +125,81 @@ var collectTransitiveDependencies = (rootName, nodeByName) => {
115
125
  }
116
126
  return [...seen].sort((a, b) => a.localeCompare(b));
117
127
  };
118
- var buildExternalAnalysisSummary = (targetPath, extraction, metadataByKey, config) => {
128
+ var hasHighRiskSignals = (dependency, config) => dependency.ownRiskSignals.includes("abandoned") || dependency.ownRiskSignals.filter(
129
+ (signal) => signal === "high_centrality" || signal === "deep_chain" || signal === "high_fanout"
130
+ ).length >= 2 || dependency.ownRiskSignals.includes("single_maintainer") && ((dependency.daysSinceLastRelease ?? 0) >= config.abandonedDaysThreshold / 2 || (dependency.repositoryActivity30d ?? 1) <= 0);
131
+ var buildWorkspaceExposureSummaries = (workspaceManifests, allByName, nodeByName, config) => {
132
+ if (workspaceManifests.length === 0) {
133
+ return [];
134
+ }
135
+ const workspaceNames = new Set(workspaceManifests.map((workspace) => workspace.name));
136
+ const externalDependencyNamesByWorkspace = /* @__PURE__ */ new Map();
137
+ const workspaceCountByDependency = /* @__PURE__ */ new Map();
138
+ for (const workspace of workspaceManifests) {
139
+ const dependencyNames = [
140
+ ...new Set(
141
+ workspace.directDependencies.map((dependency) => dependency.name).filter((dependencyName) => !workspaceNames.has(dependencyName))
142
+ )
143
+ ].sort((a, b) => a.localeCompare(b));
144
+ externalDependencyNamesByWorkspace.set(workspace.path, dependencyNames);
145
+ for (const dependencyName of dependencyNames) {
146
+ workspaceCountByDependency.set(
147
+ dependencyName,
148
+ (workspaceCountByDependency.get(dependencyName) ?? 0) + 1
149
+ );
150
+ }
151
+ }
152
+ return [...workspaceManifests].map((workspace) => {
153
+ const dependencyNames = externalDependencyNamesByWorkspace.get(workspace.path) ?? [];
154
+ const directSpecByName = new Map(
155
+ workspace.directDependencies.map((dependency) => [dependency.name, dependency])
156
+ );
157
+ const resolvedDependencies = dependencyNames.map((dependencyName) => allByName.get(dependencyName)).filter((dependency) => dependency !== void 0);
158
+ const unresolvedDependencies = dependencyNames.filter(
159
+ (dependencyName) => !allByName.has(dependencyName)
160
+ );
161
+ const highRiskDependencies = resolvedDependencies.filter(
162
+ (dependency) => (directSpecByName.get(dependency.name)?.scope ?? dependency.dependencyScope) === "prod" && hasHighRiskSignals(dependency, config)
163
+ ).map((dependency) => dependency.name).sort((a, b) => a.localeCompare(b));
164
+ const highRiskDevelopmentDependencies = resolvedDependencies.filter(
165
+ (dependency) => (directSpecByName.get(dependency.name)?.scope ?? dependency.dependencyScope) === "dev" && hasHighRiskSignals(dependency, config)
166
+ ).map((dependency) => dependency.name).sort((a, b) => a.localeCompare(b));
167
+ const transitiveExposureDependencies = resolvedDependencies.filter((dependency) => {
168
+ const transitiveDependencies = collectTransitiveDependencies(dependency.name, nodeByName);
169
+ return transitiveDependencies.some((transitiveName) => {
170
+ const transitive = allByName.get(transitiveName);
171
+ return transitive?.riskSignals.some(canPropagateSignal) ?? false;
172
+ });
173
+ }).map((dependency) => dependency.name).sort((a, b) => a.localeCompare(b));
174
+ const singleMaintainerDependencies = resolvedDependencies.filter((dependency) => dependency.ownRiskSignals.includes("single_maintainer")).map((dependency) => dependency.name).sort((a, b) => a.localeCompare(b));
175
+ const abandonedDependencies = resolvedDependencies.filter((dependency) => dependency.ownRiskSignals.includes("abandoned")).map((dependency) => dependency.name).sort((a, b) => a.localeCompare(b));
176
+ return {
177
+ name: workspace.name,
178
+ path: workspace.path,
179
+ kind: workspace.kind,
180
+ directDependencies: dependencyNames.length,
181
+ directProductionDependencies: dependencyNames.filter(
182
+ (dependencyName) => directSpecByName.get(dependencyName)?.scope === "prod"
183
+ ).length,
184
+ directDevelopmentDependencies: dependencyNames.filter(
185
+ (dependencyName) => directSpecByName.get(dependencyName)?.scope === "dev"
186
+ ).length,
187
+ unresolvedDependencies,
188
+ dependencyNames,
189
+ sharedDependencies: dependencyNames.filter(
190
+ (dependencyName) => (workspaceCountByDependency.get(dependencyName) ?? 0) > 1
191
+ ),
192
+ highRiskDependencies,
193
+ highRiskDevelopmentDependencies,
194
+ transitiveExposureDependencies,
195
+ singleMaintainerDependencies,
196
+ abandonedDependencies
197
+ };
198
+ }).sort(
199
+ (a, b) => b.highRiskDependencies.length - a.highRiskDependencies.length || b.transitiveExposureDependencies.length - a.transitiveExposureDependencies.length || b.directDependencies - a.directDependencies || a.path.localeCompare(b.path)
200
+ );
201
+ };
202
+ var buildExternalAnalysisSummary = (targetPath, extraction, metadataByKey, config, workspaceManifests = []) => {
119
203
  const nodes = normalizeNodes(extraction.nodes);
120
204
  const directNames = new Set(extraction.directDependencies.map((dep) => dep.name));
121
205
  const directSpecByName = new Map(extraction.directDependencies.map((dep) => [dep.name, dep]));
@@ -235,6 +319,13 @@ var buildExternalAnalysisSummary = (targetPath, extraction, metadataByKey, confi
235
319
  ).map((dep) => dep.name);
236
320
  const singleMaintainerDependencies = dependencies.filter((dep) => dep.ownRiskSignals.includes("single_maintainer")).map((dep) => dep.name).sort((a, b) => a.localeCompare(b));
237
321
  const abandonedDependencies = dependencies.filter((dep) => dep.ownRiskSignals.includes("abandoned")).map((dep) => dep.name).sort((a, b) => a.localeCompare(b));
322
+ const workspaces = buildWorkspaceExposureSummaries(
323
+ workspaceManifests,
324
+ allByName,
325
+ nodeByName,
326
+ config
327
+ );
328
+ const workspaceSummary2 = workspaces.length > 0 ? { workspaces } : {};
238
329
  return {
239
330
  targetPath,
240
331
  available: true,
@@ -253,6 +344,7 @@ var buildExternalAnalysisSummary = (targetPath, extraction, metadataByKey, confi
253
344
  metadataCoverage: allDependencies.length === 0 ? 0 : round4(metadataAvailableCount / allDependencies.length)
254
345
  },
255
346
  dependencies,
347
+ ...workspaceSummary2,
256
348
  highRiskDependencies,
257
349
  highRiskDevelopmentDependencies,
258
350
  transitiveExposureDependencies,
@@ -261,14 +353,6 @@ var buildExternalAnalysisSummary = (targetPath, extraction, metadataByKey, confi
261
353
  centralityRanking
262
354
  };
263
355
  };
264
- var DEFAULT_EXTERNAL_ANALYSIS_CONFIG = {
265
- abandonedDaysThreshold: 540,
266
- deepChainThreshold: 6,
267
- fanOutHighThreshold: 25,
268
- centralityTopN: 20,
269
- maxHighRiskDependencies: 100,
270
- metadataRequestConcurrency: 8
271
- };
272
356
  var mapWithConcurrency = async (values, limit, handler) => {
273
357
  const effectiveLimit = Math.max(1, limit);
274
358
  const workerCount = Math.min(effectiveLimit, values.length);
@@ -311,6 +395,25 @@ var collectDependencyMetadata = async (extraction, metadataProvider, concurrency
311
395
  return result;
312
396
  });
313
397
  };
398
+ var buildDependencyExposureSummary = async (input) => {
399
+ const metadataEntries = await collectDependencyMetadata(
400
+ input.extraction,
401
+ input.metadataProvider,
402
+ input.config.metadataRequestConcurrency,
403
+ input.onMetadataProgress
404
+ );
405
+ const metadataByKey = /* @__PURE__ */ new Map();
406
+ for (const entry of metadataEntries) {
407
+ metadataByKey.set(entry.key, entry.metadata);
408
+ }
409
+ return buildExternalAnalysisSummary(
410
+ input.targetPath,
411
+ input.extraction,
412
+ metadataByKey,
413
+ input.config,
414
+ input.workspaceManifests ?? []
415
+ );
416
+ };
314
417
  var LOCKFILE_CANDIDATES = [
315
418
  { fileName: "pnpm-lock.yaml", kind: "pnpm" },
316
419
  { fileName: "package-lock.json", kind: "npm" },
@@ -1423,11 +1526,141 @@ var prepareDependencyExtraction = async (repositoryPath) => {
1423
1526
  extraction: parseLockfileExtraction(lockfile.kind, lockfile.raw, directSpecs)
1424
1527
  };
1425
1528
  };
1529
+ var normalizePath = (pathValue) => pathValue.replaceAll("\\", "/");
1530
+ var stripQuotes2 = (value) => value.replace(/^['"]|['"]$/g, "");
1531
+ var readPackageJson = (path) => {
1532
+ try {
1533
+ return JSON.parse(readFileSync2(path, "utf8"));
1534
+ } catch {
1535
+ return null;
1536
+ }
1537
+ };
1538
+ var inferWorkspaceKind = (workspacePath) => {
1539
+ const segments = workspacePath.split("/");
1540
+ const first = segments[0] ?? "";
1541
+ if (first === "apps" || first === "app") {
1542
+ return "app";
1543
+ }
1544
+ if (first === "packages" || first === "package") {
1545
+ return "package";
1546
+ }
1547
+ if (first === "docs" || first === "documentation") {
1548
+ return "docs";
1549
+ }
1550
+ if (first === "examples" || first === "example-apps" || first === "playground") {
1551
+ return "example";
1552
+ }
1553
+ if (first === "tooling" || first === "tools") {
1554
+ return "tooling";
1555
+ }
1556
+ return "unknown";
1557
+ };
1558
+ var readWorkspacePatternsFromPackageJson = (projectRoot) => {
1559
+ const packageJson = readPackageJson(join5(projectRoot, "package.json"));
1560
+ if (packageJson?.workspaces === void 0) {
1561
+ return [];
1562
+ }
1563
+ const workspaces = packageJson.workspaces;
1564
+ if (Array.isArray(workspaces)) {
1565
+ const workspaceArray = workspaces;
1566
+ return workspaceArray.filter((workspace) => typeof workspace === "string");
1567
+ }
1568
+ const workspaceObject = workspaces;
1569
+ return workspaceObject.packages ?? [];
1570
+ };
1571
+ var readWorkspacePatternsFromPnpmWorkspace = (projectRoot) => {
1572
+ const workspacePath = join5(projectRoot, "pnpm-workspace.yaml");
1573
+ if (!existsSync2(workspacePath)) {
1574
+ return [];
1575
+ }
1576
+ const patterns = [];
1577
+ const lines = readFileSync2(workspacePath, "utf8").split("\n");
1578
+ let readingPackages = false;
1579
+ for (const line of lines) {
1580
+ const trimmed = line.trim();
1581
+ if (trimmed.length === 0 || trimmed.startsWith("#")) {
1582
+ continue;
1583
+ }
1584
+ if (!line.startsWith(" ") && !line.startsWith("-")) {
1585
+ readingPackages = trimmed === "packages:";
1586
+ continue;
1587
+ }
1588
+ if (!readingPackages) {
1589
+ continue;
1590
+ }
1591
+ const match = trimmed.match(/^-\s+(.+)$/);
1592
+ if (match?.[1] !== void 0) {
1593
+ patterns.push(stripQuotes2(match[1].trim()));
1594
+ }
1595
+ }
1596
+ return patterns;
1597
+ };
1598
+ var expandPattern = (projectRoot, pattern) => {
1599
+ const segments = normalizePath(pattern).split("/").filter((segment) => segment.length > 0);
1600
+ let current = [projectRoot];
1601
+ for (const segment of segments) {
1602
+ const next = [];
1603
+ if (segment === "*") {
1604
+ for (const directory of current) {
1605
+ if (!existsSync2(directory)) {
1606
+ continue;
1607
+ }
1608
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
1609
+ if (entry.isDirectory()) {
1610
+ next.push(join5(directory, entry.name));
1611
+ }
1612
+ }
1613
+ }
1614
+ } else {
1615
+ for (const directory of current) {
1616
+ const candidate = join5(directory, segment);
1617
+ if (existsSync2(candidate) && statSync(candidate).isDirectory()) {
1618
+ next.push(candidate);
1619
+ }
1620
+ }
1621
+ }
1622
+ current = next;
1623
+ }
1624
+ return current;
1625
+ };
1626
+ var loadWorkspaceDependencyManifests = (projectRoot) => {
1627
+ const absoluteRoot = resolve(projectRoot);
1628
+ const packageJsonPatterns = readWorkspacePatternsFromPackageJson(absoluteRoot);
1629
+ const pnpmPatterns = readWorkspacePatternsFromPnpmWorkspace(absoluteRoot);
1630
+ const patterns = packageJsonPatterns.length > 0 ? packageJsonPatterns : pnpmPatterns;
1631
+ const includePatterns = patterns.filter((pattern) => !pattern.startsWith("!"));
1632
+ const excludePatterns = patterns.filter((pattern) => pattern.startsWith("!")).map((pattern) => pattern.slice(1));
1633
+ const excludedPaths = new Set(
1634
+ excludePatterns.flatMap((pattern) => expandPattern(absoluteRoot, pattern)).map((path) => normalizePath(relative(absoluteRoot, path)))
1635
+ );
1636
+ const manifestsByPath = /* @__PURE__ */ new Map();
1637
+ for (const pattern of includePatterns) {
1638
+ for (const absoluteWorkspacePath of expandPattern(absoluteRoot, pattern)) {
1639
+ const relativePath = normalizePath(relative(absoluteRoot, absoluteWorkspacePath));
1640
+ if (relativePath.length === 0 || relativePath.startsWith("..") || excludedPaths.has(relativePath)) {
1641
+ continue;
1642
+ }
1643
+ const packageJsonPath2 = join5(absoluteWorkspacePath, "package.json");
1644
+ if (!existsSync2(packageJsonPath2)) {
1645
+ continue;
1646
+ }
1647
+ const rawPackageJson = readFileSync2(packageJsonPath2, "utf8");
1648
+ const packageJson = readPackageJson(packageJsonPath2);
1649
+ manifestsByPath.set(relativePath, {
1650
+ name: packageJson?.name ?? basename(absoluteWorkspacePath),
1651
+ path: relativePath,
1652
+ kind: inferWorkspaceKind(relativePath),
1653
+ directDependencies: parsePackageJson(rawPackageJson)
1654
+ });
1655
+ }
1656
+ }
1657
+ return [...manifestsByPath.values()].sort((a, b) => a.path.localeCompare(b.path));
1658
+ };
1426
1659
  var withDefaults = (overrides) => ({
1427
1660
  ...DEFAULT_EXTERNAL_ANALYSIS_CONFIG,
1428
1661
  ...overrides
1429
1662
  });
1430
- var analyzeDependencyExposure = async (input, metadataProvider, onProgress) => {
1663
+ var analyzeDependencyExposure = async (input, metadataProvider, onProgress, loadWorkspaceManifests = loadWorkspaceDependencyManifests) => {
1431
1664
  const config = withDefaults(input.config);
1432
1665
  try {
1433
1666
  const prepared = await prepareDependencyExtraction(input.repositoryPath);
@@ -1447,28 +1680,20 @@ var analyzeDependencyExposure = async (input, metadataProvider, onProgress) => {
1447
1680
  directDependencies: extraction.directDependencies.length
1448
1681
  });
1449
1682
  onProgress?.({ stage: "metadata_fetch_started", total: extraction.nodes.length });
1450
- const metadataEntries = await collectDependencyMetadata(
1683
+ const summary = await buildDependencyExposureSummary({
1684
+ targetPath: input.repositoryPath,
1451
1685
  extraction,
1452
1686
  metadataProvider,
1453
- config.metadataRequestConcurrency,
1454
- (event) => onProgress?.({
1687
+ config,
1688
+ workspaceManifests: loadWorkspaceManifests(input.repositoryPath),
1689
+ onMetadataProgress: (event) => onProgress?.({
1455
1690
  stage: "metadata_fetch_progress",
1456
1691
  completed: event.completed,
1457
1692
  total: event.total,
1458
1693
  packageName: event.packageName
1459
1694
  })
1460
- );
1695
+ });
1461
1696
  onProgress?.({ stage: "metadata_fetch_completed", total: extraction.nodes.length });
1462
- const metadataByKey = /* @__PURE__ */ new Map();
1463
- for (const entry of metadataEntries) {
1464
- metadataByKey.set(entry.key, entry.metadata);
1465
- }
1466
- const summary = buildExternalAnalysisSummary(
1467
- input.repositoryPath,
1468
- extraction,
1469
- metadataByKey,
1470
- config
1471
- );
1472
1697
  if (summary.available) {
1473
1698
  onProgress?.({
1474
1699
  stage: "summary_built",
@@ -1527,29 +1752,6 @@ var parseDependencySpec = (value) => {
1527
1752
  }
1528
1753
  return { name, requested };
1529
1754
  };
1530
- var mapWithConcurrency2 = async (values, limit, handler) => {
1531
- const effectiveLimit = Math.max(1, limit);
1532
- const workerCount = Math.min(effectiveLimit, values.length);
1533
- const UNSET = /* @__PURE__ */ Symbol("map_with_concurrency_unset");
1534
- const results = new Array(values.length).fill(UNSET);
1535
- let index = 0;
1536
- const workers = Array.from({ length: workerCount }, async () => {
1537
- while (true) {
1538
- const current = index;
1539
- index += 1;
1540
- if (current >= values.length) {
1541
- return;
1542
- }
1543
- const value = values[current];
1544
- results[current] = await handler(value);
1545
- }
1546
- });
1547
- await Promise.all(workers);
1548
- if (results.some((value) => value === UNSET)) {
1549
- throw new Error("map_with_concurrency_incomplete_results");
1550
- }
1551
- return results;
1552
- };
1553
1755
  var analyzeDependencyCandidate = async (input, metadataProvider) => {
1554
1756
  const parsed = parseDependencySpec(input.dependency);
1555
1757
  if (parsed === null) {
@@ -1580,20 +1782,6 @@ var analyzeDependencyCandidate = async (input, metadataProvider) => {
1580
1782
  dependency: input.dependency
1581
1783
  };
1582
1784
  }
1583
- const metadataEntries = await mapWithConcurrency2(
1584
- graph.nodes,
1585
- config.metadataRequestConcurrency,
1586
- async (node) => ({
1587
- key: `${node.name}@${node.version}`,
1588
- metadata: await metadataProvider.getMetadata(node.name, node.version, {
1589
- directDependency: node.name === parsed.name
1590
- })
1591
- })
1592
- );
1593
- const metadataByKey = /* @__PURE__ */ new Map();
1594
- for (const entry of metadataEntries) {
1595
- metadataByKey.set(entry.key, entry.metadata);
1596
- }
1597
1785
  const extraction = {
1598
1786
  kind: "npm",
1599
1787
  directDependencies: [
@@ -1605,12 +1793,12 @@ var analyzeDependencyCandidate = async (input, metadataProvider) => {
1605
1793
  ],
1606
1794
  nodes: graph.nodes
1607
1795
  };
1608
- const external = buildExternalAnalysisSummary(
1609
- `npm:${parsed.name}`,
1796
+ const external = await buildDependencyExposureSummary({
1797
+ targetPath: `npm:${parsed.name}`,
1610
1798
  extraction,
1611
- metadataByKey,
1799
+ metadataProvider,
1612
1800
  config
1613
- );
1801
+ });
1614
1802
  return {
1615
1803
  available: true,
1616
1804
  dependency: {
@@ -1753,7 +1941,7 @@ var analyzeDependencyCandidateFromRegistry = async (input) => {
1753
1941
  };
1754
1942
 
1755
1943
  // ../reporter/dist/index.js
1756
- import { basename, posix } from "path";
1944
+ import { basename as basename2, posix } from "path";
1757
1945
  var SNAPSHOT_SCHEMA_VERSION = "codesentinel.snapshot.v1";
1758
1946
  var REPORT_SCHEMA_VERSION = "codesentinel.report.v1";
1759
1947
  var RISK_MODEL_VERSION = "deterministic-v1";
@@ -2391,13 +2579,97 @@ var repositoryDimensionScores = (snapshot) => {
2391
2579
  interactions: interactionScore
2392
2580
  };
2393
2581
  };
2582
+ var workspaceSummary = (snapshot) => ({
2583
+ structural: [...snapshot.analysis.structural.workspaces ?? []].sort(
2584
+ (a, b) => b.incomingEdgeCount + b.outgoingEdgeCount + b.internalEdgeCount - (a.incomingEdgeCount + a.outgoingEdgeCount + a.internalEdgeCount) || b.fileCount - a.fileCount || a.path.localeCompare(b.path)
2585
+ ).map((workspace) => ({
2586
+ name: workspace.name,
2587
+ path: workspace.path,
2588
+ kind: workspace.kind,
2589
+ fileCount: workspace.fileCount,
2590
+ internalEdgeCount: workspace.internalEdgeCount,
2591
+ incomingEdgeCount: workspace.incomingEdgeCount,
2592
+ outgoingEdgeCount: workspace.outgoingEdgeCount
2593
+ })),
2594
+ risk: [...snapshot.analysis.risk.workspaceScores].sort((a, b) => b.score - a.score || a.path.localeCompare(b.path)).map((workspace) => ({
2595
+ name: workspace.name,
2596
+ path: workspace.path,
2597
+ kind: workspace.kind,
2598
+ score: workspace.score,
2599
+ normalizedScore: workspace.normalizedScore,
2600
+ fileCount: workspace.fileCount,
2601
+ averageFileRisk: workspace.averageFileRisk,
2602
+ peakFileRisk: workspace.peakFileRisk,
2603
+ internalEdgeCount: workspace.internalEdgeCount,
2604
+ incomingEdgeCount: workspace.incomingEdgeCount,
2605
+ outgoingEdgeCount: workspace.outgoingEdgeCount,
2606
+ topFiles: workspace.topFiles.slice(0, 5).map((file) => ({
2607
+ file: file.file,
2608
+ score: file.score
2609
+ }))
2610
+ })),
2611
+ evolution: snapshot.analysis.evolution.available ? [...snapshot.analysis.evolution.workspaces ?? []].sort(
2612
+ (a, b) => b.recentVolatility - a.recentVolatility || b.churnTotal - a.churnTotal || b.commitCount - a.commitCount || a.path.localeCompare(b.path)
2613
+ ).map((workspace) => ({
2614
+ name: workspace.name,
2615
+ path: workspace.path,
2616
+ kind: workspace.kind,
2617
+ fileCount: workspace.fileCount,
2618
+ commitCount: workspace.commitCount,
2619
+ churnTotal: workspace.churnTotal,
2620
+ recentCommitCount: workspace.recentCommitCount,
2621
+ recentVolatility: workspace.recentVolatility,
2622
+ topAuthorShareByCommits: workspace.topAuthorShareByCommits,
2623
+ busFactorByCommits: workspace.busFactorByCommits,
2624
+ hotspotCount: workspace.hotspotCount,
2625
+ topHotspots: workspace.topHotspots.slice(0, 5).map((hotspot) => ({
2626
+ filePath: hotspot.filePath,
2627
+ rank: hotspot.rank,
2628
+ commitCount: hotspot.commitCount,
2629
+ churnTotal: hotspot.churnTotal
2630
+ })),
2631
+ internalCouplingPairCount: workspace.internalCouplingPairCount,
2632
+ incomingCouplingPairCount: workspace.incomingCouplingPairCount,
2633
+ outgoingCouplingPairCount: workspace.outgoingCouplingPairCount
2634
+ })) : [],
2635
+ external: snapshot.analysis.external.available ? [...snapshot.analysis.external.workspaces ?? []].sort(
2636
+ (a, b) => b.highRiskDependencies.length - a.highRiskDependencies.length || b.transitiveExposureDependencies.length - a.transitiveExposureDependencies.length || b.directDependencies - a.directDependencies || a.path.localeCompare(b.path)
2637
+ ).map((workspace) => ({
2638
+ name: workspace.name,
2639
+ path: workspace.path,
2640
+ kind: workspace.kind,
2641
+ directDependencies: workspace.directDependencies,
2642
+ directProductionDependencies: workspace.directProductionDependencies,
2643
+ directDevelopmentDependencies: workspace.directDevelopmentDependencies,
2644
+ unresolvedDependencies: [...workspace.unresolvedDependencies].sort(
2645
+ (a, b) => a.localeCompare(b)
2646
+ ),
2647
+ dependencyNames: [...workspace.dependencyNames].sort((a, b) => a.localeCompare(b)),
2648
+ sharedDependencies: [...workspace.sharedDependencies].sort((a, b) => a.localeCompare(b)),
2649
+ highRiskDependencies: [...workspace.highRiskDependencies].sort(
2650
+ (a, b) => a.localeCompare(b)
2651
+ ),
2652
+ highRiskDevelopmentDependencies: [...workspace.highRiskDevelopmentDependencies].sort(
2653
+ (a, b) => a.localeCompare(b)
2654
+ ),
2655
+ transitiveExposureDependencies: [...workspace.transitiveExposureDependencies].sort(
2656
+ (a, b) => a.localeCompare(b)
2657
+ ),
2658
+ singleMaintainerDependencies: [...workspace.singleMaintainerDependencies].sort(
2659
+ (a, b) => a.localeCompare(b)
2660
+ ),
2661
+ abandonedDependencies: [...workspace.abandonedDependencies].sort(
2662
+ (a, b) => a.localeCompare(b)
2663
+ )
2664
+ })) : []
2665
+ });
2394
2666
  var createReport = (snapshot, diff) => {
2395
2667
  const external = snapshot.analysis.external;
2396
2668
  return {
2397
2669
  schemaVersion: REPORT_SCHEMA_VERSION,
2398
2670
  generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2399
2671
  repository: {
2400
- name: basename(snapshot.analysis.structural.targetPath) || snapshot.analysis.structural.targetPath,
2672
+ name: basename2(snapshot.analysis.structural.targetPath) || snapshot.analysis.structural.targetPath,
2401
2673
  targetPath: snapshot.analysis.structural.targetPath,
2402
2674
  riskScore: snapshot.analysis.risk.riskScore,
2403
2675
  normalizedScore: snapshot.analysis.risk.normalizedScore,
@@ -2407,6 +2679,7 @@ var createReport = (snapshot, diff) => {
2407
2679
  dimensionScores: repositoryDimensionScores(snapshot)
2408
2680
  },
2409
2681
  health: snapshot.analysis.health,
2682
+ workspaces: workspaceSummary(snapshot),
2410
2683
  hotspots: hotspotItems(snapshot),
2411
2684
  structural: {
2412
2685
  cycleCount: snapshot.analysis.structural.metrics.cycleCount,
@@ -2480,6 +2753,55 @@ var renderTextDiff = (report) => {
2480
2753
  ` resolvedCycles: ${report.diff.resolvedCycles.join(", ") || "none"}`
2481
2754
  ];
2482
2755
  };
2756
+ var renderTextWorkspaceSummary = (report) => {
2757
+ const workspaceCount = Math.max(
2758
+ report.workspaces.structural.length,
2759
+ report.workspaces.risk.length,
2760
+ report.workspaces.evolution.length,
2761
+ report.workspaces.external.length
2762
+ );
2763
+ if (workspaceCount === 0) {
2764
+ return [];
2765
+ }
2766
+ const lines = ["", "Workspace Summary"];
2767
+ lines.push(" topRisk:");
2768
+ for (const workspace of report.workspaces.risk.slice(0, 5)) {
2769
+ lines.push(
2770
+ ` - ${workspace.path} | score=${workspace.score} files=${workspace.fileCount} peakFileRisk=${workspace.peakFileRisk}`
2771
+ );
2772
+ }
2773
+ if (report.workspaces.risk.length === 0) {
2774
+ lines.push(" - none");
2775
+ }
2776
+ lines.push(" structuralCoupling:");
2777
+ for (const workspace of report.workspaces.structural.slice(0, 5)) {
2778
+ lines.push(
2779
+ ` - ${workspace.path} | internal=${workspace.internalEdgeCount} incoming=${workspace.incomingEdgeCount} outgoing=${workspace.outgoingEdgeCount}`
2780
+ );
2781
+ }
2782
+ if (report.workspaces.structural.length === 0) {
2783
+ lines.push(" - none");
2784
+ }
2785
+ lines.push(" evolutionHotspots:");
2786
+ for (const workspace of report.workspaces.evolution.slice(0, 5)) {
2787
+ lines.push(
2788
+ ` - ${workspace.path} | commits=${workspace.commitCount} churn=${workspace.churnTotal} recentVolatility=${workspace.recentVolatility}`
2789
+ );
2790
+ }
2791
+ if (report.workspaces.evolution.length === 0) {
2792
+ lines.push(" - none");
2793
+ }
2794
+ lines.push(" dependencyExposure:");
2795
+ for (const workspace of report.workspaces.external.slice(0, 5)) {
2796
+ lines.push(
2797
+ ` - ${workspace.path} | direct=${workspace.directDependencies} shared=${workspace.sharedDependencies.length} highRisk=${workspace.highRiskDependencies.length} transitiveExposure=${workspace.transitiveExposureDependencies.length}`
2798
+ );
2799
+ }
2800
+ if (report.workspaces.external.length === 0) {
2801
+ lines.push(" - none");
2802
+ }
2803
+ return lines;
2804
+ };
2483
2805
  var renderTextReport = (report) => {
2484
2806
  const lines = [];
2485
2807
  lines.push("Repository Summary");
@@ -2545,6 +2867,7 @@ var renderTextReport = (report) => {
2545
2867
  lines.push(` cycleCount: ${report.structural.cycleCount}`);
2546
2868
  lines.push(` cycles: ${report.structural.cycles.join(" ; ") || "none"}`);
2547
2869
  lines.push(` fragileClusters: ${report.structural.fragileClusters.length}`);
2870
+ lines.push(...renderTextWorkspaceSummary(report));
2548
2871
  lines.push("");
2549
2872
  lines.push("External Exposure");
2550
2873
  if (!report.external.available) {
@@ -2587,6 +2910,59 @@ var renderMarkdownDiff = (report) => {
2587
2910
  `- resolvedCycles: ${report.diff.resolvedCycles.map((item) => `\`${item}\``).join(", ") || "none"}`
2588
2911
  ];
2589
2912
  };
2913
+ var renderMarkdownWorkspaceSummary = (report) => {
2914
+ const workspaceCount = Math.max(
2915
+ report.workspaces.structural.length,
2916
+ report.workspaces.risk.length,
2917
+ report.workspaces.evolution.length,
2918
+ report.workspaces.external.length
2919
+ );
2920
+ if (workspaceCount === 0) {
2921
+ return [];
2922
+ }
2923
+ const lines = ["", "## Workspace Summary"];
2924
+ lines.push("- top risk:");
2925
+ if (report.workspaces.risk.length === 0) {
2926
+ lines.push(" - none");
2927
+ } else {
2928
+ for (const workspace of report.workspaces.risk.slice(0, 5)) {
2929
+ lines.push(
2930
+ ` - \`${workspace.path}\`: score=\`${workspace.score}\`, files=\`${workspace.fileCount}\`, peak file risk=\`${workspace.peakFileRisk}\``
2931
+ );
2932
+ }
2933
+ }
2934
+ lines.push("- structural coupling:");
2935
+ if (report.workspaces.structural.length === 0) {
2936
+ lines.push(" - none");
2937
+ } else {
2938
+ for (const workspace of report.workspaces.structural.slice(0, 5)) {
2939
+ lines.push(
2940
+ ` - \`${workspace.path}\`: internal=\`${workspace.internalEdgeCount}\`, incoming=\`${workspace.incomingEdgeCount}\`, outgoing=\`${workspace.outgoingEdgeCount}\``
2941
+ );
2942
+ }
2943
+ }
2944
+ lines.push("- evolution hotspots:");
2945
+ if (report.workspaces.evolution.length === 0) {
2946
+ lines.push(" - none");
2947
+ } else {
2948
+ for (const workspace of report.workspaces.evolution.slice(0, 5)) {
2949
+ lines.push(
2950
+ ` - \`${workspace.path}\`: commits=\`${workspace.commitCount}\`, churn=\`${workspace.churnTotal}\`, recent volatility=\`${workspace.recentVolatility}\``
2951
+ );
2952
+ }
2953
+ }
2954
+ lines.push("- dependency exposure:");
2955
+ if (report.workspaces.external.length === 0) {
2956
+ lines.push(" - none");
2957
+ } else {
2958
+ for (const workspace of report.workspaces.external.slice(0, 5)) {
2959
+ lines.push(
2960
+ ` - \`${workspace.path}\`: direct=\`${workspace.directDependencies}\`, shared=\`${workspace.sharedDependencies.length}\`, high risk=\`${workspace.highRiskDependencies.length}\`, transitive exposure=\`${workspace.transitiveExposureDependencies.length}\``
2961
+ );
2962
+ }
2963
+ }
2964
+ return lines;
2965
+ };
2590
2966
  var renderMarkdownReport = (report) => {
2591
2967
  const lines = [];
2592
2968
  lines.push("# CodeSentinel Report");
@@ -2658,6 +3034,7 @@ var renderMarkdownReport = (report) => {
2658
3034
  `- cycles: ${report.structural.cycles.map((cycle) => `\`${cycle}\``).join(", ") || "none"}`
2659
3035
  );
2660
3036
  lines.push(`- fragile clusters: \`${report.structural.fragileClusters.length}\``);
3037
+ lines.push(...renderMarkdownWorkspaceSummary(report));
2661
3038
  lines.push("");
2662
3039
  lines.push("## External Exposure Summary");
2663
3040
  if (!report.external.available) {
@@ -2724,7 +3101,7 @@ var formatReport = (report, format) => {
2724
3101
 
2725
3102
  // ../governance/dist/index.js
2726
3103
  import { mkdirSync, rmSync } from "fs";
2727
- import { basename as basename2, join as join5, resolve } from "path";
3104
+ import { basename as basename3, join as join6, resolve as resolve2 } from "path";
2728
3105
  import { execFile } from "child_process";
2729
3106
  import { promisify } from "util";
2730
3107
  var EXIT_CODES = {
@@ -3245,10 +3622,10 @@ var tryRunGit = async (repositoryPath, args) => {
3245
3622
  }
3246
3623
  };
3247
3624
  var buildWorktreePath = (repoRoot, sha) => {
3248
- const tmpRoot = join5(repoRoot, SENTINEL_TMP_DIR, WORKTREE_DIR);
3625
+ const tmpRoot = join6(repoRoot, SENTINEL_TMP_DIR, WORKTREE_DIR);
3249
3626
  mkdirSync(tmpRoot, { recursive: true });
3250
3627
  const baseName = `baseline-${sha.slice(0, 12)}-${process.pid}`;
3251
- const candidate = resolve(tmpRoot, baseName);
3628
+ const candidate = resolve2(tmpRoot, baseName);
3252
3629
  return candidate;
3253
3630
  };
3254
3631
  var sanitizeSnapshotForWorktree = (snapshot, worktreePath, canonicalPath) => {
@@ -3281,7 +3658,7 @@ var sanitizeSnapshotForWorktree = (snapshot, worktreePath, canonicalPath) => {
3281
3658
  };
3282
3659
  };
3283
3660
  var resolveBaselineSnapshotFromRef = async (input) => {
3284
- const repositoryPath = resolve(input.repositoryPath);
3661
+ const repositoryPath = resolve2(input.repositoryPath);
3285
3662
  const ref = input.baselineRef.trim();
3286
3663
  if (ref.length === 0) {
3287
3664
  throw new BaselineRefResolutionError("baseline-ref cannot be empty");
@@ -3313,7 +3690,7 @@ var resolveBaselineSnapshotFromRef = async (input) => {
3313
3690
  }
3314
3691
  };
3315
3692
  var resolveAutoBaselineRef = async (input) => {
3316
- const repositoryPath = resolve(input.repositoryPath);
3693
+ const repositoryPath = resolve2(input.repositoryPath);
3317
3694
  const repoRoot = await runGit(repositoryPath, ["rev-parse", "--show-toplevel"]);
3318
3695
  try {
3319
3696
  return await resolveAutoBaseline({
@@ -3336,9 +3713,9 @@ var resolveAutoBaselineRef = async (input) => {
3336
3713
  };
3337
3714
 
3338
3715
  // src/index.ts
3339
- import { readFileSync as readFileSync3 } from "fs";
3716
+ import { readFileSync as readFileSync4 } from "fs";
3340
3717
  import { readFile as readFile7, writeFile as writeFile7 } from "fs/promises";
3341
- import { dirname as dirname3, resolve as resolve6 } from "path";
3718
+ import { dirname as dirname3, resolve as resolve7 } from "path";
3342
3719
  import { fileURLToPath as fileURLToPath2 } from "url";
3343
3720
 
3344
3721
  // src/application/format-analyze-output.ts
@@ -3357,6 +3734,40 @@ var toHealthTier2 = (score) => {
3357
3734
  }
3358
3735
  return "excellent";
3359
3736
  };
3737
+ var createWorkspaceSummaryShape = (summary) => ({
3738
+ structuralTop: [...summary.structural.workspaces ?? []].sort(
3739
+ (a, b) => b.incomingEdgeCount + b.outgoingEdgeCount + b.internalEdgeCount - (a.incomingEdgeCount + a.outgoingEdgeCount + a.internalEdgeCount) || b.fileCount - a.fileCount || a.path.localeCompare(b.path)
3740
+ ).slice(0, 5).map((workspace) => ({
3741
+ path: workspace.path,
3742
+ fileCount: workspace.fileCount,
3743
+ internalEdgeCount: workspace.internalEdgeCount,
3744
+ incomingEdgeCount: workspace.incomingEdgeCount,
3745
+ outgoingEdgeCount: workspace.outgoingEdgeCount
3746
+ })),
3747
+ riskTop: [...summary.risk.workspaceScores].sort((a, b) => b.score - a.score || a.path.localeCompare(b.path)).slice(0, 5).map((workspace) => ({
3748
+ path: workspace.path,
3749
+ score: workspace.score,
3750
+ fileCount: workspace.fileCount,
3751
+ peakFileRisk: workspace.peakFileRisk
3752
+ })),
3753
+ evolutionTop: summary.evolution.available ? [...summary.evolution.workspaces ?? []].sort(
3754
+ (a, b) => b.recentVolatility - a.recentVolatility || b.churnTotal - a.churnTotal || b.commitCount - a.commitCount || a.path.localeCompare(b.path)
3755
+ ).slice(0, 5).map((workspace) => ({
3756
+ path: workspace.path,
3757
+ commitCount: workspace.commitCount,
3758
+ churnTotal: workspace.churnTotal,
3759
+ recentVolatility: workspace.recentVolatility
3760
+ })) : [],
3761
+ dependencyExposureTop: summary.external.available ? [...summary.external.workspaces ?? []].sort(
3762
+ (a, b) => b.highRiskDependencies.length - a.highRiskDependencies.length || b.transitiveExposureDependencies.length - a.transitiveExposureDependencies.length || b.directDependencies - a.directDependencies || a.path.localeCompare(b.path)
3763
+ ).slice(0, 5).map((workspace) => ({
3764
+ path: workspace.path,
3765
+ directDependencies: workspace.directDependencies,
3766
+ sharedDependencies: workspace.sharedDependencies.length,
3767
+ highRiskDependencies: workspace.highRiskDependencies.length,
3768
+ transitiveExposureDependencies: workspace.transitiveExposureDependencies.length
3769
+ })) : []
3770
+ });
3360
3771
  var createSummaryShape = (summary) => ({
3361
3772
  targetPath: summary.structural.targetPath,
3362
3773
  structural: summary.structural.metrics,
@@ -3394,6 +3805,7 @@ var createSummaryShape = (summary) => ({
3394
3805
  fragileClusterCount: summary.risk.fragileClusters.length,
3395
3806
  dependencyAmplificationZoneCount: summary.risk.dependencyAmplificationZones.length
3396
3807
  },
3808
+ workspaces: createWorkspaceSummaryShape(summary),
3397
3809
  health: {
3398
3810
  healthScore: summary.health.healthScore,
3399
3811
  healthTier: toHealthTier2(summary.health.healthScore),
@@ -3748,11 +4160,11 @@ var parseLogLevel = (value) => {
3748
4160
  import { spawn } from "child_process";
3749
4161
  import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
3750
4162
  import { homedir as homedir2 } from "os";
3751
- import { dirname, join as join6 } from "path";
4163
+ import { dirname, join as join7 } from "path";
3752
4164
  import { stderr, stdin } from "process";
3753
4165
  import { clearScreenDown, cursorTo, emitKeypressEvents } from "readline";
3754
4166
  var UPDATE_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
3755
- var UPDATE_CACHE_PATH = join6(homedir2(), ".cache", "codesentinel", "update-check.json");
4167
+ var UPDATE_CACHE_PATH = join7(homedir2(), ".cache", "codesentinel", "update-check.json");
3756
4168
  var SEMVER_PATTERN = /^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)(?:-(?<prerelease>[0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
3757
4169
  var ANSI = {
3758
4170
  reset: "\x1B[0m",
@@ -3984,7 +4396,7 @@ var promptInstall = async (packageName, latestVersion, currentVersion) => {
3984
4396
  );
3985
4397
  return "skip";
3986
4398
  }
3987
- return await new Promise((resolve7) => {
4399
+ return await new Promise((resolve8) => {
3988
4400
  emitKeypressEvents(stdin);
3989
4401
  let selectedIndex = 0;
3990
4402
  const previousRawMode = stdin.isRaw;
@@ -4009,7 +4421,7 @@ var promptInstall = async (packageName, latestVersion, currentVersion) => {
4009
4421
  } else {
4010
4422
  stderr.write("\n");
4011
4423
  }
4012
- resolve7(choice);
4424
+ resolve8(choice);
4013
4425
  };
4014
4426
  const onKeypress = (_str, key) => {
4015
4427
  if (key.ctrl === true && key.name === "c") {
@@ -4203,7 +4615,7 @@ var promptSelection = async (currentVersion, actions) => {
4203
4615
  if (!stdin2.isTTY || !stderr2.isTTY || typeof stdin2.setRawMode !== "function") {
4204
4616
  return "exit";
4205
4617
  }
4206
- return await new Promise((resolve7) => {
4618
+ return await new Promise((resolve8) => {
4207
4619
  emitKeypressEvents2(stdin2);
4208
4620
  let selectedIndex = 0;
4209
4621
  const previousRawMode = stdin2.isRaw;
@@ -4218,7 +4630,7 @@ var promptSelection = async (currentVersion, actions) => {
4218
4630
  stdin2.setRawMode(previousRawMode);
4219
4631
  clearTerminal();
4220
4632
  showCursor2();
4221
- resolve7(selection);
4633
+ resolve8(selection);
4222
4634
  };
4223
4635
  const onKeypress = (_str, key) => {
4224
4636
  if (key.ctrl === true && key.name === "c") {
@@ -4311,7 +4723,7 @@ var waitForReturnToMenu = async () => {
4311
4723
  }
4312
4724
  stderr2.write(`
4313
4725
  ${PROMPT_PADDING}Press enter to return to the menu...`);
4314
- await new Promise((resolve7) => {
4726
+ await new Promise((resolve8) => {
4315
4727
  emitKeypressEvents2(stdin2);
4316
4728
  const previousRawMode = stdin2.isRaw;
4317
4729
  const cleanup = () => {
@@ -4320,7 +4732,7 @@ ${PROMPT_PADDING}Press enter to return to the menu...`);
4320
4732
  stdin2.setRawMode(previousRawMode);
4321
4733
  showCursor2();
4322
4734
  stderr2.write("\n");
4323
- resolve7();
4735
+ resolve8();
4324
4736
  };
4325
4737
  const onKeypress = (_str, key) => {
4326
4738
  if (key.ctrl === true && key.name === "c") {
@@ -4338,7 +4750,7 @@ ${PROMPT_PADDING}Press enter to return to the menu...`);
4338
4750
  });
4339
4751
  };
4340
4752
  var runCliCommand = async (scriptPath2, args) => {
4341
- return await new Promise((resolve7, reject) => {
4753
+ return await new Promise((resolve8, reject) => {
4342
4754
  const child = spawn2(process.execPath, [...process.execArgv, scriptPath2, ...args], {
4343
4755
  stdio: ["inherit", "pipe", "pipe"],
4344
4756
  env: {
@@ -4352,7 +4764,7 @@ var runCliCommand = async (scriptPath2, args) => {
4352
4764
  reject(error);
4353
4765
  });
4354
4766
  child.on("close", (code) => {
4355
- resolve7(code ?? 1);
4767
+ resolve8(code ?? 1);
4356
4768
  });
4357
4769
  });
4358
4770
  };
@@ -4423,14 +4835,43 @@ ${PROMPT_PADDING}Command exited with code ${exitCode}.
4423
4835
  };
4424
4836
 
4425
4837
  // src/application/run-analyze-command.ts
4426
- import { resolve as resolve3 } from "path";
4838
+ import { resolve as resolve4 } from "path";
4839
+
4840
+ // ../core/dist/index.js
4841
+ var normalizeWorkspacePath = (pathValue) => pathValue.replaceAll("\\", "/");
4842
+ var fileBelongsToWorkspace = (filePath, workspace) => {
4843
+ const normalizedFilePath = normalizeWorkspacePath(filePath);
4844
+ const normalizedWorkspacePath = normalizeWorkspacePath(workspace.path);
4845
+ return normalizedFilePath === normalizedWorkspacePath || normalizedFilePath.startsWith(`${normalizedWorkspacePath}/`);
4846
+ };
4847
+ var findWorkspaceForFile = (filePath, workspaces) => {
4848
+ let match = null;
4849
+ for (const workspace of workspaces) {
4850
+ if (fileBelongsToWorkspace(filePath, workspace)) {
4851
+ if (match === null || workspace.path.length > match.path.length) {
4852
+ match = workspace;
4853
+ }
4854
+ }
4855
+ }
4856
+ return match;
4857
+ };
4858
+ var createWorkspaceByFile = (filePaths2, workspaces) => {
4859
+ const workspaceByFile = /* @__PURE__ */ new Map();
4860
+ for (const filePath of filePaths2) {
4861
+ const workspace = findWorkspaceForFile(filePath, workspaces);
4862
+ if (workspace !== null) {
4863
+ workspaceByFile.set(filePath, workspace);
4864
+ }
4865
+ }
4866
+ return workspaceByFile;
4867
+ };
4427
4868
 
4428
4869
  // ../code-graph/dist/index.js
4429
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
4430
- import { extname, isAbsolute, join as join7, relative, resolve as resolve2 } from "path";
4870
+ import { existsSync as existsSync3, readFileSync as readFileSync3 } from "fs";
4871
+ import { extname, isAbsolute, join as join8, relative as relative2, resolve as resolve3 } from "path";
4431
4872
  import * as ts from "typescript";
4432
- import { existsSync as existsSync22, readdirSync, readFileSync as readFileSync22, statSync } from "fs";
4433
- import { basename as basename3, join as join22, relative as relative2, resolve as resolve22 } from "path";
4873
+ import { existsSync as existsSync22, readdirSync as readdirSync2, readFileSync as readFileSync22, statSync as statSync2 } from "fs";
4874
+ import { basename as basename4, join as join22, relative as relative22, resolve as resolve22 } from "path";
4434
4875
  var edgeKey = (from, to) => `${from}\0${to}`;
4435
4876
  var createGraphData = (nodes, rawEdges) => {
4436
4877
  const sortedNodes = [...nodes].sort((a, b) => a.id.localeCompare(b.id));
@@ -4625,26 +5066,11 @@ var computeCyclesAndDepth = (graph) => {
4625
5066
  cycles
4626
5067
  };
4627
5068
  };
4628
- var findWorkspaceForFile = (filePath, workspaces) => {
4629
- let match = null;
4630
- for (const workspace of workspaces) {
4631
- if (filePath === workspace.path || filePath.startsWith(`${workspace.path}/`)) {
4632
- if (match === null || workspace.path.length > match.path.length) {
4633
- match = workspace;
4634
- }
4635
- }
4636
- }
4637
- return match;
4638
- };
4639
- var createWorkspaceByFile = (graph, workspaces) => {
4640
- const workspaceByFile = /* @__PURE__ */ new Map();
4641
- for (const node of graph.nodes) {
4642
- const workspace = findWorkspaceForFile(node.id, workspaces);
4643
- if (workspace !== null) {
4644
- workspaceByFile.set(node.id, workspace);
4645
- }
4646
- }
4647
- return workspaceByFile;
5069
+ var createWorkspaceByFile2 = (graph, workspaces) => {
5070
+ return createWorkspaceByFile(
5071
+ graph.nodes.map((node) => node.id),
5072
+ workspaces
5073
+ );
4648
5074
  };
4649
5075
  var createCrossWorkspaceEdges = (graph, workspaceByFile) => {
4650
5076
  const edges = [];
@@ -4760,7 +5186,7 @@ var createGraphAnalysisSummary = (targetPath, graph, workspaces = []) => {
4760
5186
  maxFanIn,
4761
5187
  maxFanOut
4762
5188
  };
4763
- const workspaceByFile = createWorkspaceByFile(graph, workspaces);
5189
+ const workspaceByFile = createWorkspaceByFile2(graph, workspaces);
4764
5190
  return {
4765
5191
  targetPath,
4766
5192
  nodes: graph.nodes,
@@ -4798,10 +5224,10 @@ var IGNORED_SEGMENTS = /* @__PURE__ */ new Set([
4798
5224
  ".cache",
4799
5225
  "out"
4800
5226
  ]);
4801
- var normalizePath = (pathValue) => pathValue.replaceAll("\\", "/");
4802
- var readPackageJson = (packageJsonPath2) => {
5227
+ var normalizePath2 = (pathValue) => pathValue.replaceAll("\\", "/");
5228
+ var readPackageJson2 = (packageJsonPath2) => {
4803
5229
  try {
4804
- return JSON.parse(readFileSync2(packageJsonPath2, "utf8"));
5230
+ return JSON.parse(readFileSync3(packageJsonPath2, "utf8"));
4805
5231
  } catch {
4806
5232
  return null;
4807
5233
  }
@@ -4811,11 +5237,11 @@ var isProjectSourceFile = (filePath, projectRoot) => {
4811
5237
  if (!SOURCE_EXTENSIONS.has(extension)) {
4812
5238
  return false;
4813
5239
  }
4814
- const relativePath = relative(projectRoot, filePath);
5240
+ const relativePath = relative2(projectRoot, filePath);
4815
5241
  if (relativePath.startsWith("..")) {
4816
5242
  return false;
4817
5243
  }
4818
- const normalizedRelativePath = normalizePath(relativePath);
5244
+ const normalizedRelativePath = normalizePath2(relativePath);
4819
5245
  const segments = normalizedRelativePath.split("/");
4820
5246
  return !segments.some((segment) => IGNORED_SEGMENTS.has(segment));
4821
5247
  };
@@ -4826,7 +5252,7 @@ var discoverSourceFilesByScan = (projectRoot) => {
4826
5252
  SCAN_EXCLUDES,
4827
5253
  SCAN_INCLUDES
4828
5254
  );
4829
- return files.map((filePath) => resolve2(filePath));
5255
+ return files.map((filePath) => resolve3(filePath));
4830
5256
  };
4831
5257
  var parseTsConfigFile = (configPath) => {
4832
5258
  const parsedCommandLine = ts.getParsedCommandLineOfConfigFile(
@@ -4857,7 +5283,7 @@ var collectFilesFromTsConfigGraph = (projectRoot) => {
4857
5283
  const collectedFiles = /* @__PURE__ */ new Set();
4858
5284
  let rootOptions = null;
4859
5285
  const visitConfig = (configPath) => {
4860
- const absoluteConfigPath = resolve2(configPath);
5286
+ const absoluteConfigPath = resolve3(configPath);
4861
5287
  if (visitedConfigPaths.has(absoluteConfigPath)) {
4862
5288
  return;
4863
5289
  }
@@ -4867,10 +5293,10 @@ var collectFilesFromTsConfigGraph = (projectRoot) => {
4867
5293
  rootOptions = parsed.options;
4868
5294
  }
4869
5295
  for (const filePath of parsed.fileNames) {
4870
- collectedFiles.add(resolve2(filePath));
5296
+ collectedFiles.add(resolve3(filePath));
4871
5297
  }
4872
5298
  for (const reference of parsed.projectReferences ?? []) {
4873
- const referencePath = resolve2(reference.path);
5299
+ const referencePath = resolve3(reference.path);
4874
5300
  const referenceConfigPath = ts.sys.directoryExists(referencePath) ? ts.findConfigFile(
4875
5301
  referencePath,
4876
5302
  (filePath) => ts.sys.fileExists(filePath),
@@ -5013,7 +5439,7 @@ var parseWorkspaceSpecifier = (specifier, workspaceNames) => {
5013
5439
  var expandFileCandidates = (pathWithoutExtension) => [
5014
5440
  pathWithoutExtension,
5015
5441
  ...[...SOURCE_EXTENSIONS].map((extension) => `${pathWithoutExtension}${extension}`),
5016
- ...[...SOURCE_EXTENSIONS].map((extension) => join7(pathWithoutExtension, `index${extension}`))
5442
+ ...[...SOURCE_EXTENSIONS].map((extension) => join8(pathWithoutExtension, `index${extension}`))
5017
5443
  ];
5018
5444
  var isExportArray = (value) => Array.isArray(value);
5019
5445
  var isExportMap = (value) => typeof value !== "string" && !isExportArray(value);
@@ -5074,8 +5500,8 @@ var collectPackageExportCandidates = (packageJson, subpath) => {
5074
5500
  var resolveFirstAnalyzedCandidate = (candidates, sourceFilePathSet) => {
5075
5501
  for (const candidate of candidates) {
5076
5502
  for (const expanded of expandFileCandidates(candidate)) {
5077
- const normalized = normalizePath(expanded);
5078
- if (sourceFilePathSet.has(normalized) && existsSync2(normalized)) {
5503
+ const normalized = normalizePath2(expanded);
5504
+ if (sourceFilePathSet.has(normalized) && existsSync3(normalized)) {
5079
5505
  return normalized;
5080
5506
  }
5081
5507
  }
@@ -5094,8 +5520,8 @@ var createWorkspaceResolver = (projectRoot, workspaces, sourceFilePathSet) => {
5094
5520
  if (workspace === void 0) {
5095
5521
  return void 0;
5096
5522
  }
5097
- const workspaceRoot = resolve2(projectRoot, workspace.path);
5098
- const packageJson = readPackageJson(join7(workspaceRoot, "package.json"));
5523
+ const workspaceRoot = resolve3(projectRoot, workspace.path);
5524
+ const packageJson = readPackageJson2(join8(workspaceRoot, "package.json"));
5099
5525
  const candidates = parsed.subpath === null ? [
5100
5526
  ...collectPackageExportCandidates(packageJson, null),
5101
5527
  packageJson?.source,
@@ -5108,10 +5534,10 @@ var createWorkspaceResolver = (projectRoot, workspaces, sourceFilePathSet) => {
5108
5534
  ].filter((candidate) => candidate !== void 0) : [
5109
5535
  ...collectPackageExportCandidates(packageJson, parsed.subpath),
5110
5536
  parsed.subpath,
5111
- join7("src", parsed.subpath)
5537
+ join8("src", parsed.subpath)
5112
5538
  ];
5113
5539
  return resolveFirstAnalyzedCandidate(
5114
- candidates.map((candidate) => resolve2(workspaceRoot, candidate)),
5540
+ candidates.map((candidate) => resolve3(workspaceRoot, candidate)),
5115
5541
  sourceFilePathSet
5116
5542
  );
5117
5543
  };
@@ -5140,7 +5566,7 @@ var createTsPathAliasResolver = (projectRoot, options, sourceFilePathSet) => {
5140
5566
  }
5141
5567
  const replacement = hasWildcard ? specifier.slice(prefix.length, specifier.length - suffix.length) : "";
5142
5568
  const candidates = substitutions.map(
5143
- (substitution) => resolve2(baseUrl, hasWildcard ? substitution.replaceAll("*", replacement) : substitution)
5569
+ (substitution) => resolve3(baseUrl, hasWildcard ? substitution.replaceAll("*", replacement) : substitution)
5144
5570
  );
5145
5571
  const resolved = resolveFirstAnalyzedCandidate(candidates, sourceFilePathSet);
5146
5572
  if (resolved !== void 0) {
@@ -5151,10 +5577,10 @@ var createTsPathAliasResolver = (projectRoot, options, sourceFilePathSet) => {
5151
5577
  };
5152
5578
  };
5153
5579
  var parseTypescriptProject = (projectPath, onProgress, workspaces = []) => {
5154
- const projectRoot = isAbsolute(projectPath) ? projectPath : resolve2(projectPath);
5580
+ const projectRoot = isAbsolute(projectPath) ? projectPath : resolve3(projectPath);
5155
5581
  const { fileNames, options, tsconfigCount, usedFallbackScan } = parseTsConfig(projectRoot);
5156
5582
  onProgress?.({ stage: "config_resolved", tsconfigCount, usedFallbackScan });
5157
- const sourceFilePaths = fileNames.filter((filePath) => isProjectSourceFile(filePath, projectRoot)).map((filePath) => normalizePath(resolve2(filePath)));
5583
+ const sourceFilePaths = fileNames.filter((filePath) => isProjectSourceFile(filePath, projectRoot)).map((filePath) => normalizePath2(resolve3(filePath)));
5158
5584
  const uniqueSourceFilePaths = [...new Set(sourceFilePaths)].sort((a, b) => a.localeCompare(b));
5159
5585
  const sourceFilePathSet = new Set(uniqueSourceFilePaths);
5160
5586
  onProgress?.({ stage: "files_discovered", totalSourceFiles: uniqueSourceFilePaths.length });
@@ -5165,7 +5591,7 @@ var parseTypescriptProject = (projectPath, onProgress, workspaces = []) => {
5165
5591
  onProgress?.({ stage: "program_created", totalSourceFiles: uniqueSourceFilePaths.length });
5166
5592
  const nodeByAbsolutePath = /* @__PURE__ */ new Map();
5167
5593
  for (const sourcePath of uniqueSourceFilePaths) {
5168
- const relativePath = normalizePath(relative(projectRoot, sourcePath));
5594
+ const relativePath = normalizePath2(relative2(projectRoot, sourcePath));
5169
5595
  const nodeId = relativePath;
5170
5596
  nodeByAbsolutePath.set(sourcePath, {
5171
5597
  id: nodeId,
@@ -5202,7 +5628,7 @@ var parseTypescriptProject = (projectPath, onProgress, workspaces = []) => {
5202
5628
  ts.sys
5203
5629
  ).resolvedModule;
5204
5630
  if (resolved !== void 0) {
5205
- resolvedPath = normalizePath(resolve2(resolved.resolvedFileName));
5631
+ resolvedPath = normalizePath2(resolve3(resolved.resolvedFileName));
5206
5632
  }
5207
5633
  if (resolvedPath === void 0 || !sourceFilePathSet.has(resolvedPath)) {
5208
5634
  resolvedPath = resolveTsPathAlias(specifier);
@@ -5237,16 +5663,16 @@ var parseTypescriptProject = (projectPath, onProgress, workspaces = []) => {
5237
5663
  edges
5238
5664
  };
5239
5665
  };
5240
- var normalizePath2 = (pathValue) => pathValue.replaceAll("\\", "/");
5241
- var stripQuotes2 = (value) => value.replace(/^['"]|['"]$/g, "");
5242
- var readPackageJson2 = (path) => {
5666
+ var normalizePath22 = (pathValue) => pathValue.replaceAll("\\", "/");
5667
+ var stripQuotes3 = (value) => value.replace(/^['"]|['"]$/g, "");
5668
+ var readPackageJson22 = (path) => {
5243
5669
  try {
5244
5670
  return JSON.parse(readFileSync22(path, "utf8"));
5245
5671
  } catch {
5246
5672
  return null;
5247
5673
  }
5248
5674
  };
5249
- var inferWorkspaceKind = (workspacePath) => {
5675
+ var inferWorkspaceKind2 = (workspacePath) => {
5250
5676
  const segments = workspacePath.split("/");
5251
5677
  const first = segments[0] ?? "";
5252
5678
  if (first === "apps" || first === "app") {
@@ -5266,8 +5692,8 @@ var inferWorkspaceKind = (workspacePath) => {
5266
5692
  }
5267
5693
  return "unknown";
5268
5694
  };
5269
- var readWorkspacePatternsFromPackageJson = (projectRoot) => {
5270
- const packageJson = readPackageJson2(join22(projectRoot, "package.json"));
5695
+ var readWorkspacePatternsFromPackageJson2 = (projectRoot) => {
5696
+ const packageJson = readPackageJson22(join22(projectRoot, "package.json"));
5271
5697
  if (packageJson?.workspaces === void 0) {
5272
5698
  return [];
5273
5699
  }
@@ -5279,7 +5705,7 @@ var readWorkspacePatternsFromPackageJson = (projectRoot) => {
5279
5705
  const workspaceObject = workspaces;
5280
5706
  return workspaceObject.packages ?? [];
5281
5707
  };
5282
- var readWorkspacePatternsFromPnpmWorkspace = (projectRoot) => {
5708
+ var readWorkspacePatternsFromPnpmWorkspace2 = (projectRoot) => {
5283
5709
  const workspacePath = join22(projectRoot, "pnpm-workspace.yaml");
5284
5710
  if (!existsSync22(workspacePath)) {
5285
5711
  return [];
@@ -5301,13 +5727,13 @@ var readWorkspacePatternsFromPnpmWorkspace = (projectRoot) => {
5301
5727
  }
5302
5728
  const match = trimmed.match(/^-\s+(.+)$/);
5303
5729
  if (match?.[1] !== void 0) {
5304
- patterns.push(stripQuotes2(match[1].trim()));
5730
+ patterns.push(stripQuotes3(match[1].trim()));
5305
5731
  }
5306
5732
  }
5307
5733
  return patterns;
5308
5734
  };
5309
- var expandPattern = (projectRoot, pattern) => {
5310
- const segments = normalizePath2(pattern).split("/").filter((segment) => segment.length > 0);
5735
+ var expandPattern2 = (projectRoot, pattern) => {
5736
+ const segments = normalizePath22(pattern).split("/").filter((segment) => segment.length > 0);
5311
5737
  let current = [projectRoot];
5312
5738
  for (const segment of segments) {
5313
5739
  const next = [];
@@ -5316,7 +5742,7 @@ var expandPattern = (projectRoot, pattern) => {
5316
5742
  if (!existsSync22(directory)) {
5317
5743
  continue;
5318
5744
  }
5319
- for (const entry of readdirSync(directory, { withFileTypes: true })) {
5745
+ for (const entry of readdirSync2(directory, { withFileTypes: true })) {
5320
5746
  if (entry.isDirectory()) {
5321
5747
  next.push(join22(directory, entry.name));
5322
5748
  }
@@ -5325,7 +5751,7 @@ var expandPattern = (projectRoot, pattern) => {
5325
5751
  } else {
5326
5752
  for (const directory of current) {
5327
5753
  const candidate = join22(directory, segment);
5328
- if (existsSync22(candidate) && statSync(candidate).isDirectory()) {
5754
+ if (existsSync22(candidate) && statSync2(candidate).isDirectory()) {
5329
5755
  next.push(candidate);
5330
5756
  }
5331
5757
  }
@@ -5336,18 +5762,18 @@ var expandPattern = (projectRoot, pattern) => {
5336
5762
  };
5337
5763
  var discoverWorkspacePackages = (projectRoot) => {
5338
5764
  const absoluteRoot = resolve22(projectRoot);
5339
- const packageJsonPatterns = readWorkspacePatternsFromPackageJson(absoluteRoot);
5340
- const pnpmPatterns = readWorkspacePatternsFromPnpmWorkspace(absoluteRoot);
5765
+ const packageJsonPatterns = readWorkspacePatternsFromPackageJson2(absoluteRoot);
5766
+ const pnpmPatterns = readWorkspacePatternsFromPnpmWorkspace2(absoluteRoot);
5341
5767
  const patterns = packageJsonPatterns.length > 0 ? packageJsonPatterns : pnpmPatterns;
5342
5768
  const includePatterns = patterns.filter((pattern) => !pattern.startsWith("!"));
5343
5769
  const excludePatterns = patterns.filter((pattern) => pattern.startsWith("!")).map((pattern) => pattern.slice(1));
5344
5770
  const excludedPaths = new Set(
5345
- excludePatterns.flatMap((pattern) => expandPattern(absoluteRoot, pattern)).map((path) => normalizePath2(relative2(absoluteRoot, path)))
5771
+ excludePatterns.flatMap((pattern) => expandPattern2(absoluteRoot, pattern)).map((path) => normalizePath22(relative22(absoluteRoot, path)))
5346
5772
  );
5347
5773
  const packagesByPath = /* @__PURE__ */ new Map();
5348
5774
  for (const pattern of includePatterns) {
5349
- for (const absoluteWorkspacePath of expandPattern(absoluteRoot, pattern)) {
5350
- const relativePath = normalizePath2(relative2(absoluteRoot, absoluteWorkspacePath));
5775
+ for (const absoluteWorkspacePath of expandPattern2(absoluteRoot, pattern)) {
5776
+ const relativePath = normalizePath22(relative22(absoluteRoot, absoluteWorkspacePath));
5351
5777
  if (relativePath.length === 0 || relativePath.startsWith("..") || excludedPaths.has(relativePath)) {
5352
5778
  continue;
5353
5779
  }
@@ -5355,11 +5781,11 @@ var discoverWorkspacePackages = (projectRoot) => {
5355
5781
  if (!existsSync22(packageJsonPath2)) {
5356
5782
  continue;
5357
5783
  }
5358
- const packageJson = readPackageJson2(packageJsonPath2);
5784
+ const packageJson = readPackageJson22(packageJsonPath2);
5359
5785
  packagesByPath.set(relativePath, {
5360
- name: packageJson?.name ?? basename3(absoluteWorkspacePath),
5786
+ name: packageJson?.name ?? basename4(absoluteWorkspacePath),
5361
5787
  path: relativePath,
5362
- kind: inferWorkspaceKind(relativePath)
5788
+ kind: inferWorkspaceKind2(relativePath)
5363
5789
  });
5364
5790
  }
5365
5791
  }
@@ -5794,37 +6220,22 @@ var analyzeRepositoryEvolution = (input, historyProvider, onProgress) => {
5794
6220
  onProgress?.({ stage: "analysis_completed", available: summary.available });
5795
6221
  return summary;
5796
6222
  };
5797
- var normalizePath3 = (pathValue) => pathValue.replaceAll("\\", "/");
5798
- var findWorkspaceForFile2 = (filePath, workspaces) => {
5799
- let match = null;
5800
- for (const workspace of workspaces) {
5801
- if (filePath === workspace.path || filePath.startsWith(`${workspace.path}/`)) {
5802
- if (match === null || workspace.path.length > match.path.length) {
5803
- match = workspace;
5804
- }
5805
- }
5806
- }
5807
- return match;
5808
- };
5809
6223
  var enrichEvolutionSummaryWithWorkspaces = (structural, evolution) => {
5810
6224
  if (!evolution.available || structural.workspaces === void 0) {
5811
6225
  return evolution;
5812
6226
  }
5813
6227
  const workspaces = structural.workspaces;
5814
- const workspaceByFile = /* @__PURE__ */ new Map();
6228
+ const workspaceByFile = createWorkspaceByFile(
6229
+ evolution.files.map((file) => normalizeWorkspacePath(file.filePath)),
6230
+ workspaces
6231
+ );
5815
6232
  const structuralWorkspacePaths = new Set(workspaces.map((workspace) => workspace.path));
5816
- for (const file of evolution.files) {
5817
- const workspace = findWorkspaceForFile2(normalizePath3(file.filePath), workspaces);
5818
- if (workspace !== null) {
5819
- workspaceByFile.set(normalizePath3(file.filePath), workspace);
5820
- }
5821
- }
5822
6233
  const internalCouplingPairCountByWorkspace = /* @__PURE__ */ new Map();
5823
6234
  const incomingCouplingPairCountByWorkspace = /* @__PURE__ */ new Map();
5824
6235
  const outgoingCouplingPairCountByWorkspace = /* @__PURE__ */ new Map();
5825
6236
  for (const pair of evolution.coupling.pairs) {
5826
- const fromWorkspace = workspaceByFile.get(normalizePath3(pair.fileA));
5827
- const toWorkspace = workspaceByFile.get(normalizePath3(pair.fileB));
6237
+ const fromWorkspace = workspaceByFile.get(normalizeWorkspacePath(pair.fileA));
6238
+ const toWorkspace = workspaceByFile.get(normalizeWorkspacePath(pair.fileB));
5828
6239
  if (fromWorkspace === void 0 && toWorkspace === void 0) {
5829
6240
  continue;
5830
6241
  }
@@ -5850,7 +6261,7 @@ var enrichEvolutionSummaryWithWorkspaces = (structural, evolution) => {
5850
6261
  }
5851
6262
  const workspaceSummaries = workspaces.filter((workspace) => structuralWorkspacePaths.has(workspace.path)).map((workspace) => {
5852
6263
  const files = evolution.files.filter(
5853
- (file) => workspaceByFile.get(normalizePath3(file.filePath))?.path === workspace.path
6264
+ (file) => workspaceByFile.get(normalizeWorkspacePath(file.filePath))?.path === workspace.path
5854
6265
  ).sort((a, b) => a.filePath.localeCompare(b.filePath));
5855
6266
  const commitCount = files.reduce((sum, file) => sum + file.commitCount, 0);
5856
6267
  const recentCommitCount = files.reduce((sum, file) => sum + file.recentCommitCount, 0);
@@ -5860,7 +6271,7 @@ var enrichEvolutionSummaryWithWorkspaces = (structural, evolution) => {
5860
6271
  const topAuthorShareByCommits = files.length === 0 ? 0 : Math.max(...files.map((file) => file.topAuthorShareByCommits));
5861
6272
  const busFactorByCommits = files.length === 0 ? 0 : Math.min(...files.map((file) => file.busFactorByCommits));
5862
6273
  const topHotspots = evolution.hotspots.filter(
5863
- (hotspot) => workspaceByFile.get(normalizePath3(hotspot.filePath))?.path === workspace.path
6274
+ (hotspot) => workspaceByFile.get(normalizeWorkspacePath(hotspot.filePath))?.path === workspace.path
5864
6275
  );
5865
6276
  return {
5866
6277
  name: workspace.name,
@@ -6165,9 +6576,9 @@ var createDimensionTrace = (dimension, health, factors) => ({
6165
6576
  factors: factors.map((factor) => toFactorTrace(factor))
6166
6577
  });
6167
6578
  var filePaths = (structural) => structural.files.map((file) => file.relativePath);
6168
- var normalizePath4 = (value) => value.replaceAll("\\", "/").toLowerCase();
6579
+ var normalizePath3 = (value) => value.replaceAll("\\", "/").toLowerCase();
6169
6580
  var isTestPath = (path) => {
6170
- const normalized = normalizePath4(path);
6581
+ const normalized = normalizePath3(path);
6171
6582
  return normalized.includes("/__tests__/") || normalized.includes("/tests/") || normalized.includes("/test/") || normalized.includes(".test.") || normalized.includes(".spec.");
6172
6583
  };
6173
6584
  var isSourcePath = (path) => {
@@ -6177,7 +6588,7 @@ var isSourcePath = (path) => {
6177
6588
  return !isTestPath(path);
6178
6589
  };
6179
6590
  var hasTestDirectory = (paths) => paths.some((path) => {
6180
- const normalized = normalizePath4(path);
6591
+ const normalized = normalizePath3(path);
6181
6592
  return normalized.includes("/__tests__/") || normalized.includes("/tests/") || normalized.includes("/test/");
6182
6593
  });
6183
6594
  var moduleNameFromPath = (path) => {
@@ -7067,7 +7478,7 @@ var normalizeWithScale = (value, scale) => {
7067
7478
  }
7068
7479
  return toUnitInterval((value - scale.lower) / (scale.upper - scale.lower));
7069
7480
  };
7070
- var normalizePath5 = (path) => path.replaceAll("\\", "/");
7481
+ var normalizePath4 = (path) => path.replaceAll("\\", "/");
7071
7482
  var computeAggregatorAttenuation = (input) => {
7072
7483
  const { fanIn, fanOut, inCycle, evolutionMetrics, config } = input;
7073
7484
  if (!config.enabled || inCycle > 0) {
@@ -7142,7 +7553,7 @@ var computeEvolutionHistoryConfidence = (structural, evolution, evolutionByFile)
7142
7553
  }
7143
7554
  let coveredFiles = 0;
7144
7555
  for (const file of structural.files) {
7145
- if (evolutionByFile.has(normalizePath5(file.id))) {
7556
+ if (evolutionByFile.has(normalizePath4(file.id))) {
7146
7557
  coveredFiles += 1;
7147
7558
  }
7148
7559
  }
@@ -7336,7 +7747,7 @@ var mapEvolutionByFile = (evolution) => {
7336
7747
  return /* @__PURE__ */ new Map();
7337
7748
  }
7338
7749
  return new Map(
7339
- evolution.files.map((fileMetrics) => [normalizePath5(fileMetrics.filePath), fileMetrics])
7750
+ evolution.files.map((fileMetrics) => [normalizePath4(fileMetrics.filePath), fileMetrics])
7340
7751
  );
7341
7752
  };
7342
7753
  var computeEvolutionScales = (evolutionByFile, config) => {
@@ -7360,7 +7771,7 @@ var computeEvolutionScales = (evolutionByFile, config) => {
7360
7771
  };
7361
7772
  };
7362
7773
  var inferModuleName = (filePath, config) => {
7363
- const normalized = normalizePath5(filePath);
7774
+ const normalized = normalizePath4(filePath);
7364
7775
  const parts = normalized.split("/").filter((part) => part.length > 0);
7365
7776
  if (parts.length <= 1) {
7366
7777
  return config.module.rootLabel;
@@ -7381,7 +7792,7 @@ var buildFragileClusters = (structural, evolution, fileScoresByFile, config) =>
7381
7792
  const clusters = [];
7382
7793
  let cycleClusterCount = 0;
7383
7794
  for (const cycle of structural.cycles) {
7384
- const files = [...new Set(cycle.nodes.map((node) => normalizePath5(node)))].filter(
7795
+ const files = [...new Set(cycle.nodes.map((node) => normalizePath4(node)))].filter(
7385
7796
  (filePath) => fileScoresByFile.has(filePath)
7386
7797
  );
7387
7798
  if (files.length < 2) {
@@ -7413,8 +7824,8 @@ var buildFragileClusters = (structural, evolution, fileScoresByFile, config) =>
7413
7824
  )
7414
7825
  );
7415
7826
  const selectedPairs = candidates.filter((pair) => pair.couplingScore >= threshold).map((pair) => ({
7416
- fileA: normalizePath5(pair.fileA),
7417
- fileB: normalizePath5(pair.fileB),
7827
+ fileA: normalizePath4(pair.fileA),
7828
+ fileB: normalizePath4(pair.fileB),
7418
7829
  couplingScore: pair.couplingScore
7419
7830
  })).filter(
7420
7831
  (pair) => pair.fileA !== pair.fileB && fileScoresByFile.has(pair.fileA) && fileScoresByFile.has(pair.fileB)
@@ -7493,9 +7904,7 @@ var buildWorkspaceRiskScores = (structural, fileScoresByFile) => {
7493
7904
  0
7494
7905
  );
7495
7906
  return structural.workspaces.map((workspace) => {
7496
- const workspaceFileScores = [...fileScoresByFile.values()].filter(
7497
- (fileScore) => fileScore.file === workspace.path || fileScore.file.startsWith(`${workspace.path}/`)
7498
- ).sort((a, b) => b.score - a.score || a.file.localeCompare(b.file));
7907
+ const workspaceFileScores = [...fileScoresByFile.values()].filter((fileScore) => fileBelongsToWorkspace(fileScore.file, workspace)).sort((a, b) => b.score - a.score || a.file.localeCompare(b.file));
7499
7908
  const averageFileRisk = average3(
7500
7909
  workspaceFileScores.map((fileScore) => fileScore.normalizedScore)
7501
7910
  );
@@ -7535,7 +7944,7 @@ var computeRiskSummary = (structural, evolution, external, config, traceCollecto
7535
7944
  );
7536
7945
  const evolutionScales = computeEvolutionScales(evolutionByFile, config);
7537
7946
  const cycleFileSet = new Set(
7538
- structural.cycles.flatMap((cycle) => cycle.nodes.map((node) => normalizePath5(node)))
7947
+ structural.cycles.flatMap((cycle) => cycle.nodes.map((node) => normalizePath4(node)))
7539
7948
  );
7540
7949
  const fanInScale = buildQuantileScale(
7541
7950
  structural.files.map((file) => logScale(file.fanIn)),
@@ -7558,7 +7967,7 @@ var computeRiskSummary = (structural, evolution, external, config, traceCollecto
7558
7967
  external: external.available
7559
7968
  });
7560
7969
  const fileRiskContexts = structural.files.map((file) => {
7561
- const filePath = normalizePath5(file.id);
7970
+ const filePath = normalizePath4(file.id);
7562
7971
  const inCycle = cycleFileSet.has(filePath) ? 1 : 0;
7563
7972
  const fanInRisk = normalizeWithScale(logScale(file.fanIn), fanInScale);
7564
7973
  const fanOutRisk = normalizeWithScale(logScale(file.fanOut), fanOutScale);
@@ -8177,7 +8586,7 @@ var evaluateRepositoryRisk = (input, options = {}) => {
8177
8586
  };
8178
8587
 
8179
8588
  // src/application/run-analyze-command.ts
8180
- var resolveTargetPath = (inputPath, cwd) => resolve3(cwd, inputPath ?? ".");
8589
+ var resolveTargetPath = (inputPath, cwd) => resolve4(cwd, inputPath ?? ".");
8181
8590
  var scoringProfileConfig = {
8182
8591
  default: void 0,
8183
8592
  personal: {
@@ -8520,7 +8929,7 @@ var runCheckCommand = async (inputPath, authorIdentityMode, options, logger = cr
8520
8929
 
8521
8930
  // src/application/run-ci-command.ts
8522
8931
  import { readFile as readFile4, writeFile as writeFile4 } from "fs/promises";
8523
- import { relative as relative3, resolve as resolve4 } from "path";
8932
+ import { relative as relative3, resolve as resolve5 } from "path";
8524
8933
  var isPathOutsideBase = (value) => {
8525
8934
  return value === ".." || value.startsWith("../") || value.startsWith("..\\");
8526
8935
  };
@@ -8533,7 +8942,7 @@ var runCiCommand = async (inputPath, authorIdentityMode, options, logger = creat
8533
8942
  if (options.baselineSha !== void 0 && options.baselineRef !== "auto") {
8534
8943
  throw new GovernanceConfigurationError("baseline-sha requires --baseline-ref auto");
8535
8944
  }
8536
- const resolvedTargetPath = resolve4(inputPath ?? process.cwd());
8945
+ const resolvedTargetPath = resolve5(inputPath ?? process.cwd());
8537
8946
  logger.info("building current snapshot");
8538
8947
  const current = await buildAnalysisSnapshot(
8539
8948
  inputPath,
@@ -8593,7 +9002,7 @@ var runCiCommand = async (inputPath, authorIdentityMode, options, logger = creat
8593
9002
  `target path is outside git repository root: ${resolvedTargetPath}`
8594
9003
  );
8595
9004
  }
8596
- const baselineTargetPath = relativeTargetPath.length === 0 || relativeTargetPath === "." ? worktreePath : resolve4(worktreePath, relativeTargetPath);
9005
+ const baselineTargetPath = relativeTargetPath.length === 0 || relativeTargetPath === "." ? worktreePath : resolve5(worktreePath, relativeTargetPath);
8597
9006
  return buildAnalysisSnapshot(
8598
9007
  baselineTargetPath,
8599
9008
  authorIdentityMode,
@@ -8667,15 +9076,15 @@ ${ciMarkdown}`;
8667
9076
  };
8668
9077
 
8669
9078
  // src/application/run-report-command.ts
8670
- import { join as join9 } from "path";
9079
+ import { join as join10 } from "path";
8671
9080
  import { readFile as readFile6, writeFile as writeFile6 } from "fs/promises";
8672
9081
 
8673
9082
  // src/application/html-report.ts
8674
9083
  import { mkdir as mkdir3, readFile as readFile5, rm, stat as stat2, writeFile as writeFile5 } from "fs/promises";
8675
- import { dirname as dirname2, join as join8, resolve as resolve5 } from "path";
9084
+ import { dirname as dirname2, join as join9, resolve as resolve6 } from "path";
8676
9085
  import { fileURLToPath } from "url";
8677
9086
  var HTML_REPORT_DIR = ".codesentinel/report";
8678
- var getBundledHtmlAppPath = () => resolve5(dirname2(fileURLToPath(import.meta.url)), "html-report-app");
9087
+ var getBundledHtmlAppPath = () => resolve6(dirname2(fileURLToPath(import.meta.url)), "html-report-app");
8679
9088
  var serializeReportBootstrap = (report) => `window.__CODESENTINEL_REPORT__ = ${JSON.stringify(report).replaceAll("</", "<\\/")};
8680
9089
  `;
8681
9090
  var escapeInlineScript = (script) => script.replaceAll("</script", "<\\/script").replaceAll("<script", "\\x3Cscript").replaceAll("<!--", "\\x3C!--").replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
@@ -8689,18 +9098,18 @@ var readReferencedAssets = async (appPath, indexHtml) => {
8689
9098
  (value) => value !== void 0 && !/^https?:\/\//.test(value) && !value.startsWith("//")
8690
9099
  );
8691
9100
  const styles = await Promise.all(
8692
- stylesheetPaths.map(async (href) => readFile5(resolve5(appPath, href), "utf8"))
9101
+ stylesheetPaths.map(async (href) => readFile5(resolve6(appPath, href), "utf8"))
8693
9102
  );
8694
9103
  const scriptPaths = [...indexHtml.matchAll(/<script[^>]+src=["']([^"']+)["'][^>]*><\/script>/g)].map((match) => match[1]).filter(
8695
9104
  (value) => value !== void 0 && !/^https?:\/\//.test(value) && !value.startsWith("//")
8696
9105
  );
8697
9106
  const scripts = await Promise.all(
8698
- scriptPaths.map(async (src) => readFile5(resolve5(appPath, src), "utf8"))
9107
+ scriptPaths.map(async (src) => readFile5(resolve6(appPath, src), "utf8"))
8699
9108
  );
8700
9109
  return { styles, scripts };
8701
9110
  };
8702
9111
  var inlineBuiltHtml = async (appPath, report) => {
8703
- const indexHtml = await readFile5(resolve5(appPath, "index.html"), "utf8");
9112
+ const indexHtml = await readFile5(resolve6(appPath, "index.html"), "utf8");
8704
9113
  const { styles, scripts } = await readReferencedAssets(appPath, indexHtml);
8705
9114
  const htmlWithoutExternalAssets = indexHtml.replace(
8706
9115
  /\s*<link[^>]+rel=["']stylesheet["'][^>]*>\s*/g,
@@ -8735,7 +9144,7 @@ var assertHtmlAppAssets = async (assetPath) => {
8735
9144
  };
8736
9145
  var resolveHtmlReportOutputPath = (repositoryPath, outputPath) => {
8737
9146
  const invocationCwd = process.env["INIT_CWD"] ?? process.cwd();
8738
- return resolve5(invocationCwd, outputPath ?? join8(repositoryPath, HTML_REPORT_DIR));
9147
+ return resolve6(invocationCwd, outputPath ?? join9(repositoryPath, HTML_REPORT_DIR));
8739
9148
  };
8740
9149
  var writeHtmlReportBundle = async (report, options) => {
8741
9150
  const bundledAppPath = options.bundledAppPath ?? getBundledHtmlAppPath();
@@ -8744,7 +9153,7 @@ var writeHtmlReportBundle = async (report, options) => {
8744
9153
  await rm(outputPath, { recursive: true, force: true });
8745
9154
  await ensureDirectory(outputPath);
8746
9155
  await writeFile5(
8747
- resolve5(outputPath, "index.html"),
9156
+ resolve6(outputPath, "index.html"),
8748
9157
  await inlineBuiltHtml(bundledAppPath, report),
8749
9158
  "utf8"
8750
9159
  );
@@ -8771,15 +9180,15 @@ var openPath = async (targetPath) => {
8771
9180
  if (command === void 0) {
8772
9181
  return false;
8773
9182
  }
8774
- return new Promise((resolve7) => {
9183
+ return new Promise((resolve8) => {
8775
9184
  const child = spawn3(command.command, command.args, {
8776
9185
  detached: true,
8777
9186
  stdio: "ignore"
8778
9187
  });
8779
- child.once("error", () => resolve7(false));
9188
+ child.once("error", () => resolve8(false));
8780
9189
  child.once("spawn", () => {
8781
9190
  child.unref();
8782
- resolve7(true);
9191
+ resolve8(true);
8783
9192
  });
8784
9193
  });
8785
9194
  };
@@ -8817,7 +9226,7 @@ var runReportCommand = async (inputPath, authorIdentityMode, options, logger = c
8817
9226
  ...options.outputPath === void 0 ? {} : { outputPath: options.outputPath }
8818
9227
  });
8819
9228
  if (options.open === true) {
8820
- const opened = await openPath(join9(bundlePath, "index.html"));
9229
+ const opened = await openPath(join10(bundlePath, "index.html"));
8821
9230
  if (!opened) {
8822
9231
  logger.warn("unable to open html report automatically on this platform");
8823
9232
  }
@@ -8908,8 +9317,8 @@ var runExplainCommand = async (inputPath, authorIdentityMode, options, logger =
8908
9317
 
8909
9318
  // src/index.ts
8910
9319
  var program = new Command();
8911
- var packageJsonPath = resolve6(dirname3(fileURLToPath2(import.meta.url)), "../package.json");
8912
- var { version } = JSON.parse(readFileSync3(packageJsonPath, "utf8"));
9320
+ var packageJsonPath = resolve7(dirname3(fileURLToPath2(import.meta.url)), "../package.json");
9321
+ var { version } = JSON.parse(readFileSync4(packageJsonPath, "utf8"));
8913
9322
  var parseRecentWindowDays = (value) => {
8914
9323
  const parsed = Number.parseInt(value, 10);
8915
9324
  if (!Number.isInteger(parsed) || parsed <= 0) {