@getcodesentinel/codesentinel 1.40.1 → 1.42.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 CHANGED
@@ -3856,8 +3856,8 @@ var resolveAutoBaselineRef = async (input) => {
3856
3856
 
3857
3857
  // src/index.ts
3858
3858
  import { readFileSync as readFileSync4 } from "fs";
3859
- import { readFile as readFile10, writeFile as writeFile11 } from "fs/promises";
3860
- import { dirname as dirname4, resolve as resolve11 } from "path";
3859
+ import { readFile as readFile11, writeFile as writeFile12 } from "fs/promises";
3860
+ import { dirname as dirname4, resolve as resolve12 } from "path";
3861
3861
  import { fileURLToPath as fileURLToPath2 } from "url";
3862
3862
 
3863
3863
  // src/application/format-analyze-output.ts
@@ -4538,7 +4538,7 @@ var promptInstall = async (packageName, latestVersion, currentVersion) => {
4538
4538
  );
4539
4539
  return "skip";
4540
4540
  }
4541
- return await new Promise((resolve12) => {
4541
+ return await new Promise((resolve13) => {
4542
4542
  emitKeypressEvents(stdin);
4543
4543
  let selectedIndex = 0;
4544
4544
  const previousRawMode = stdin.isRaw;
@@ -4563,7 +4563,7 @@ var promptInstall = async (packageName, latestVersion, currentVersion) => {
4563
4563
  } else {
4564
4564
  stderr.write("\n");
4565
4565
  }
4566
- resolve12(choice);
4566
+ resolve13(choice);
4567
4567
  };
4568
4568
  const onKeypress = (_str, key) => {
4569
4569
  if (key.ctrl === true && key.name === "c") {
@@ -4757,7 +4757,7 @@ var promptSelection = async (currentVersion, actions) => {
4757
4757
  if (!stdin2.isTTY || !stderr2.isTTY || typeof stdin2.setRawMode !== "function") {
4758
4758
  return "exit";
4759
4759
  }
4760
- return await new Promise((resolve12) => {
4760
+ return await new Promise((resolve13) => {
4761
4761
  emitKeypressEvents2(stdin2);
4762
4762
  let selectedIndex = 0;
4763
4763
  const previousRawMode = stdin2.isRaw;
@@ -4772,7 +4772,7 @@ var promptSelection = async (currentVersion, actions) => {
4772
4772
  stdin2.setRawMode(previousRawMode);
4773
4773
  clearTerminal();
4774
4774
  showCursor2();
4775
- resolve12(selection);
4775
+ resolve13(selection);
4776
4776
  };
4777
4777
  const onKeypress = (_str, key) => {
4778
4778
  if (key.ctrl === true && key.name === "c") {
@@ -4865,7 +4865,7 @@ var waitForReturnToMenu = async () => {
4865
4865
  }
4866
4866
  stderr2.write(`
4867
4867
  ${PROMPT_PADDING}Press enter to return to the menu...`);
4868
- await new Promise((resolve12) => {
4868
+ await new Promise((resolve13) => {
4869
4869
  emitKeypressEvents2(stdin2);
4870
4870
  const previousRawMode = stdin2.isRaw;
4871
4871
  const cleanup = () => {
@@ -4874,7 +4874,7 @@ ${PROMPT_PADDING}Press enter to return to the menu...`);
4874
4874
  stdin2.setRawMode(previousRawMode);
4875
4875
  showCursor2();
4876
4876
  stderr2.write("\n");
4877
- resolve12();
4877
+ resolve13();
4878
4878
  };
4879
4879
  const onKeypress = (_str, key) => {
4880
4880
  if (key.ctrl === true && key.name === "c") {
@@ -4892,7 +4892,7 @@ ${PROMPT_PADDING}Press enter to return to the menu...`);
4892
4892
  });
4893
4893
  };
4894
4894
  var runCliCommand = async (scriptPath2, args) => {
4895
- return await new Promise((resolve12, reject) => {
4895
+ return await new Promise((resolve13, reject) => {
4896
4896
  const child = spawn2(process.execPath, [...process.execArgv, scriptPath2, ...args], {
4897
4897
  stdio: ["inherit", "pipe", "pipe"],
4898
4898
  env: {
@@ -4906,7 +4906,7 @@ var runCliCommand = async (scriptPath2, args) => {
4906
4906
  reject(error);
4907
4907
  });
4908
4908
  child.on("close", (code) => {
4909
- resolve12(code ?? 1);
4909
+ resolve13(code ?? 1);
4910
4910
  });
4911
4911
  });
4912
4912
  };
@@ -6002,14 +6002,14 @@ var buildAuthorAliasMap = (commits) => {
6002
6002
  nameCountsByAuthorId.set(commit.authorId, names);
6003
6003
  }
6004
6004
  const profiles = [...commitCountByAuthorId.entries()].map(
6005
- ([authorId, commitCount]) => {
6005
+ ([authorId, commitCount2]) => {
6006
6006
  const names = nameCountsByAuthorId.get(authorId);
6007
6007
  const primaryName = names === void 0 ? "" : [...names.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0]?.[0] ?? "";
6008
6008
  const normalizedAuthorId = authorId.toLowerCase();
6009
6009
  const isBot = normalizedAuthorId.includes("[bot]");
6010
6010
  return {
6011
6011
  authorId,
6012
- commitCount,
6012
+ commitCount: commitCount2,
6013
6013
  primaryName,
6014
6014
  emailStem: isBot ? null : extractEmailStem(authorId),
6015
6015
  isBot
@@ -6405,7 +6405,7 @@ var enrichEvolutionSummaryWithWorkspaces = (structural, evolution) => {
6405
6405
  const files = evolution.files.filter(
6406
6406
  (file) => workspaceByFile.get(normalizeWorkspacePath(file.filePath))?.path === workspace.path
6407
6407
  ).sort((a, b) => a.filePath.localeCompare(b.filePath));
6408
- const commitCount = files.reduce((sum, file) => sum + file.commitCount, 0);
6408
+ const commitCount2 = files.reduce((sum, file) => sum + file.commitCount, 0);
6409
6409
  const recentCommitCount = files.reduce((sum, file) => sum + file.recentCommitCount, 0);
6410
6410
  const churnAdded = files.reduce((sum, file) => sum + file.churnAdded, 0);
6411
6411
  const churnDeleted = files.reduce((sum, file) => sum + file.churnDeleted, 0);
@@ -6420,12 +6420,12 @@ var enrichEvolutionSummaryWithWorkspaces = (structural, evolution) => {
6420
6420
  path: workspace.path,
6421
6421
  kind: workspace.kind,
6422
6422
  fileCount: files.length,
6423
- commitCount,
6423
+ commitCount: commitCount2,
6424
6424
  churnAdded,
6425
6425
  churnDeleted,
6426
6426
  churnTotal,
6427
6427
  recentCommitCount,
6428
- recentVolatility: commitCount === 0 ? 0 : Number((recentCommitCount / commitCount).toFixed(4)),
6428
+ recentVolatility: commitCount2 === 0 ? 0 : Number((recentCommitCount / commitCount2).toFixed(4)),
6429
6429
  topAuthorShareByCommits,
6430
6430
  busFactorByCommits,
6431
6431
  hotspotCount: topHotspots.length,
@@ -8865,7 +8865,7 @@ var createEvolutionProgressReporter = (logger) => {
8865
8865
  }
8866
8866
  };
8867
8867
  };
8868
- var collectAnalysisInputs = async (inputPath, authorIdentityMode, options = {}, logger = createSilentLogger()) => {
8868
+ var collectStructuralEvolutionInputs = (inputPath, authorIdentityMode, options = {}, logger = createSilentLogger()) => {
8869
8869
  const invocationCwd = process.env["INIT_CWD"] ?? process.cwd();
8870
8870
  const targetPath = resolveTargetPath(inputPath, invocationCwd);
8871
8871
  logger.info(`analyzing repository: ${targetPath}`);
@@ -8896,6 +8896,16 @@ var collectAnalysisInputs = async (inputPath, authorIdentityMode, options = {},
8896
8896
  } else {
8897
8897
  logger.warn(`evolution analysis unavailable: ${evolution.reason}`);
8898
8898
  }
8899
+ return { structural, evolution };
8900
+ };
8901
+ var collectAnalysisInputs = async (inputPath, authorIdentityMode, options = {}, logger = createSilentLogger()) => {
8902
+ const { structural, evolution } = collectStructuralEvolutionInputs(
8903
+ inputPath,
8904
+ authorIdentityMode,
8905
+ options,
8906
+ logger
8907
+ );
8908
+ const targetPath = resolveTargetPath(inputPath, process.env["INIT_CWD"] ?? process.cwd());
8899
8909
  logger.info("analyzing external dependencies");
8900
8910
  const external = await analyzeDependencyExposureFromProject(
8901
8911
  { repositoryPath: targetPath },
@@ -9213,15 +9223,15 @@ var classifyOwnershipStatus = (input) => {
9213
9223
  if (!input.hasAuthorEvidence) {
9214
9224
  return "unknown";
9215
9225
  }
9216
- const topAuthorId = input.topAuthorId;
9226
+ const topAuthorId2 = input.topAuthorId;
9217
9227
  if (input.recentCommits === 0) {
9218
- return topAuthorId !== null && input.resolutions.some((resolution) => resolution.activeAuthorIds.includes(topAuthorId)) ? "aligned" : "drifted";
9228
+ return topAuthorId2 !== null && input.resolutions.some((resolution) => resolution.activeAuthorIds.includes(topAuthorId2)) ? "aligned" : "drifted";
9219
9229
  }
9220
9230
  const active = input.resolutions.filter(isActiveOwnerResolution);
9221
9231
  if (active.length === 0) {
9222
9232
  return input.resolutions.every(isVerifiableOwnerResolution) ? "ghosted" : "unknown";
9223
9233
  }
9224
- if (topAuthorId !== null && active.some((resolution) => resolution.activeAuthorIds.includes(topAuthorId))) {
9234
+ if (topAuthorId2 !== null && active.some((resolution) => resolution.activeAuthorIds.includes(topAuthorId2))) {
9225
9235
  return "aligned";
9226
9236
  }
9227
9237
  return "drifted";
@@ -10566,15 +10576,15 @@ var openPath = async (targetPath) => {
10566
10576
  if (command === void 0) {
10567
10577
  return false;
10568
10578
  }
10569
- return new Promise((resolve12) => {
10579
+ return new Promise((resolve13) => {
10570
10580
  const child = spawn3(command.command, command.args, {
10571
10581
  detached: true,
10572
10582
  stdio: "ignore"
10573
10583
  });
10574
- child.once("error", () => resolve12(false));
10584
+ child.once("error", () => resolve13(false));
10575
10585
  child.once("spawn", () => {
10576
10586
  child.unref();
10577
- resolve12(true);
10587
+ resolve13(true);
10578
10588
  });
10579
10589
  });
10580
10590
  };
@@ -11275,6 +11285,981 @@ var runOwnersCommand = async (inputPath, options = {}, logger = createSilentLogg
11275
11285
  };
11276
11286
  var hasConfiguredThreshold = (thresholds) => thresholds.maxUnownedCritical !== null || thresholds.maxGhostOwners !== null || thresholds.maxDrift !== null;
11277
11287
 
11288
+ // src/application/run-path-command.ts
11289
+ import { existsSync as existsSync6, statSync as statSync3 } from "fs";
11290
+ import { readFile as readFile8, writeFile as writeFile8 } from "fs/promises";
11291
+ import { isAbsolute as isAbsolute2, join as join12, relative as relative4, resolve as resolve9 } from "path";
11292
+
11293
+ // ../reading-path/dist/index.js
11294
+ var comparePaths = (a, b) => a < b ? -1 : a > b ? 1 : 0;
11295
+ var createEmptyGraphIndex = () => {
11296
+ const empty = [];
11297
+ return {
11298
+ fanInInternal: () => 0,
11299
+ fanInExternal: () => 0,
11300
+ neighbours: () => empty,
11301
+ importsTo: () => false
11302
+ };
11303
+ };
11304
+ var edgeKey2 = (from, to) => `${from}\0${to}`;
11305
+ var createGraphIndex = (graph, universe) => {
11306
+ if (graph === null || graph === void 0) return createEmptyGraphIndex();
11307
+ const pathById = /* @__PURE__ */ new Map();
11308
+ for (const node of graph.nodes) {
11309
+ const existing = pathById.get(node.id);
11310
+ if (existing === void 0 || comparePaths(node.relativePath, existing) < 0) {
11311
+ pathById.set(node.id, node.relativePath);
11312
+ }
11313
+ }
11314
+ const universeSet = new Set(universe);
11315
+ const internalFanIn = /* @__PURE__ */ new Map();
11316
+ const externalFanIn = /* @__PURE__ */ new Map();
11317
+ const adjacency = /* @__PURE__ */ new Map();
11318
+ const edges = /* @__PURE__ */ new Set();
11319
+ const addAdjacency = (from, to) => {
11320
+ const fromNeighbours = adjacency.get(from);
11321
+ if (fromNeighbours === void 0) {
11322
+ adjacency.set(from, /* @__PURE__ */ new Set([to]));
11323
+ } else {
11324
+ fromNeighbours.add(to);
11325
+ }
11326
+ };
11327
+ for (const edge of graph.edges) {
11328
+ const from = pathById.get(edge.from);
11329
+ const to = pathById.get(edge.to);
11330
+ if (from === void 0 || to === void 0) continue;
11331
+ edges.add(edgeKey2(from, to));
11332
+ addAdjacency(from, to);
11333
+ addAdjacency(to, from);
11334
+ if (universeSet.has(from)) {
11335
+ internalFanIn.set(to, (internalFanIn.get(to) ?? 0) + 1);
11336
+ } else {
11337
+ externalFanIn.set(to, (externalFanIn.get(to) ?? 0) + 1);
11338
+ }
11339
+ }
11340
+ return {
11341
+ fanInInternal: (filePath) => internalFanIn.get(filePath) ?? 0,
11342
+ fanInExternal: (filePath) => externalFanIn.get(filePath) ?? 0,
11343
+ neighbours: (filePath) => {
11344
+ const candidates = adjacency.get(filePath);
11345
+ if (candidates === void 0) return [];
11346
+ return [...candidates].filter((candidate) => universeSet.has(candidate)).sort(comparePaths);
11347
+ },
11348
+ importsTo: (from, to) => edges.has(edgeKey2(from, to))
11349
+ };
11350
+ };
11351
+ var ReadingPathError = class extends Error {
11352
+ code;
11353
+ constructor(code, message) {
11354
+ super(message);
11355
+ this.name = "ReadingPathError";
11356
+ this.code = code;
11357
+ }
11358
+ };
11359
+ var DEFAULT_MAX_STEPS = 8;
11360
+ var MIN_MAX_STEPS = 1;
11361
+ var MAX_MAX_STEPS = 25;
11362
+ var EXCLUDED_SEGMENTS = /* @__PURE__ */ new Set([
11363
+ "dist",
11364
+ "__generated__",
11365
+ "node_modules",
11366
+ "vendor",
11367
+ "vendors",
11368
+ "third_party",
11369
+ "third-party"
11370
+ ]);
11371
+ var LOCKFILE_NAMES = /* @__PURE__ */ new Set([
11372
+ "package-lock.json",
11373
+ "npm-shrinkwrap.json",
11374
+ "pnpm-lock.yaml",
11375
+ "yarn.lock",
11376
+ "bun.lock",
11377
+ "bun.lockb"
11378
+ ]);
11379
+ var TEST_FILE_PATTERN = /\.(test|spec)\.[cm]?[jt]sx?$/;
11380
+ var TEST_SUFFIX_PATTERN = /\.(test|spec)(\.[cm]?[jt]sx?)$/;
11381
+ var TEST_SEGMENTS = /* @__PURE__ */ new Set(["__tests__", "__mocks__"]);
11382
+ var basenameOf = (filePath) => {
11383
+ const separatorIndex = filePath.lastIndexOf("/");
11384
+ return separatorIndex === -1 ? filePath : filePath.slice(separatorIndex + 1);
11385
+ };
11386
+ var normalizeTarget = (target) => {
11387
+ let normalized = target.trim().replaceAll("\\", "/");
11388
+ while (normalized.startsWith("./")) {
11389
+ normalized = normalized.slice(2);
11390
+ }
11391
+ while (normalized.endsWith("/")) {
11392
+ normalized = normalized.slice(0, -1);
11393
+ }
11394
+ if (normalized.length === 0) {
11395
+ throw new ReadingPathError("invalid_target", "target must not be empty");
11396
+ }
11397
+ return normalized;
11398
+ };
11399
+ var isExcludedPath = (relativePath) => {
11400
+ if (relativePath.endsWith(".d.ts")) return true;
11401
+ const segments = relativePath.split("/");
11402
+ if (segments.some((segment) => EXCLUDED_SEGMENTS.has(segment))) return true;
11403
+ const basename6 = basenameOf(relativePath);
11404
+ if (/\.gen\.[^./]+$/.test(basename6)) return true;
11405
+ if (LOCKFILE_NAMES.has(basename6)) return true;
11406
+ return false;
11407
+ };
11408
+ var isTestPath2 = (filePath) => {
11409
+ const segments = filePath.split("/");
11410
+ if (segments.some((segment) => TEST_SEGMENTS.has(segment))) return true;
11411
+ return TEST_FILE_PATTERN.test(basenameOf(filePath));
11412
+ };
11413
+ var stripTestSuffix = (testPath) => {
11414
+ const segments = testPath.split("/").filter((segment) => !TEST_SEGMENTS.has(segment));
11415
+ return segments.join("/").replace(TEST_SUFFIX_PATTERN, "$2");
11416
+ };
11417
+ var stripSourceExtension = (filePath) => {
11418
+ const basename6 = basenameOf(filePath);
11419
+ const extensionIndex = basename6.lastIndexOf(".");
11420
+ if (extensionIndex <= 0) return filePath;
11421
+ return filePath.slice(0, filePath.length - (basename6.length - extensionIndex));
11422
+ };
11423
+ var knownPaths = (graph, evolution) => {
11424
+ let paths;
11425
+ if (graph !== null && graph !== void 0) {
11426
+ paths = graph.files.map((file) => file.relativePath);
11427
+ } else if (evolution !== null && evolution !== void 0 && evolution.available) {
11428
+ paths = evolution.files.map((file) => file.filePath);
11429
+ } else {
11430
+ paths = [];
11431
+ }
11432
+ return [...new Set(paths)].sort(comparePaths);
11433
+ };
11434
+ var inferTargetKind = (target, graph, evolution) => {
11435
+ const paths = knownPaths(graph, evolution);
11436
+ if (paths.includes(target)) return "file";
11437
+ if (paths.some((filePath) => filePath.startsWith(`${target}/`))) return "directory";
11438
+ const basename6 = basenameOf(target);
11439
+ const extensionIndex = basename6.lastIndexOf(".");
11440
+ return extensionIndex >= 0 && extensionIndex < basename6.length - 1 ? "file" : "directory";
11441
+ };
11442
+ var graphNeighbours = (graph, target) => {
11443
+ const pathById = /* @__PURE__ */ new Map();
11444
+ for (const node of graph.nodes) {
11445
+ const existing = pathById.get(node.id);
11446
+ if (existing === void 0 || comparePaths(node.relativePath, existing) < 0) {
11447
+ pathById.set(node.id, node.relativePath);
11448
+ }
11449
+ }
11450
+ const neighbours = /* @__PURE__ */ new Set();
11451
+ for (const edge of graph.edges) {
11452
+ const from = pathById.get(edge.from);
11453
+ const to = pathById.get(edge.to);
11454
+ if (from === void 0 || to === void 0) continue;
11455
+ if (from === target) neighbours.add(to);
11456
+ if (to === target) neighbours.add(from);
11457
+ }
11458
+ return [...neighbours].sort(comparePaths);
11459
+ };
11460
+ var resolveUniverse = (target, graph, evolution) => {
11461
+ const targetKind = inferTargetKind(target, graph, evolution);
11462
+ if (targetKind === "file") {
11463
+ const files = /* @__PURE__ */ new Set([target]);
11464
+ let excludedCount2 = 0;
11465
+ if (graph !== null && graph !== void 0) {
11466
+ const graphFiles = new Set(graph.files.map((file) => file.relativePath));
11467
+ for (const neighbour of graphNeighbours(graph, target)) {
11468
+ if (neighbour === target || !graphFiles.has(neighbour)) continue;
11469
+ if (isExcludedPath(neighbour)) {
11470
+ excludedCount2 += 1;
11471
+ continue;
11472
+ }
11473
+ files.add(neighbour);
11474
+ }
11475
+ }
11476
+ return { targetKind, files: [...files].sort(comparePaths), excludedCount: excludedCount2 };
11477
+ }
11478
+ const included = [];
11479
+ let excludedCount = 0;
11480
+ for (const filePath of knownPaths(graph, evolution)) {
11481
+ if (filePath !== target && !filePath.startsWith(`${target}/`)) continue;
11482
+ if (isExcludedPath(filePath)) {
11483
+ excludedCount += 1;
11484
+ continue;
11485
+ }
11486
+ included.push(filePath);
11487
+ }
11488
+ return { targetKind, files: [...new Set(included)].sort(comparePaths), excludedCount };
11489
+ };
11490
+ var pairKey2 = (fileA, fileB) => comparePaths(fileA, fileB) <= 0 ? `${fileA}\0${fileB}` : `${fileB}\0${fileA}`;
11491
+ var createEvolutionIndex = (evolution) => {
11492
+ if (evolution === null || evolution === void 0 || !evolution.available) {
11493
+ return {
11494
+ available: false,
11495
+ churn: () => 0,
11496
+ commits: () => 0,
11497
+ file: () => null,
11498
+ coupling: () => null
11499
+ };
11500
+ }
11501
+ const files = /* @__PURE__ */ new Map();
11502
+ for (const file of evolution.files) {
11503
+ if (!files.has(file.filePath)) files.set(file.filePath, file);
11504
+ }
11505
+ const pairs = /* @__PURE__ */ new Map();
11506
+ for (const pair of evolution.coupling.pairs) {
11507
+ const key = pairKey2(pair.fileA, pair.fileB);
11508
+ const existing = pairs.get(key);
11509
+ if (existing === void 0 || pair.couplingScore > existing.score || pair.couplingScore === existing.score && pair.coChangeCommits > existing.coChangeCommits) {
11510
+ pairs.set(key, {
11511
+ score: pair.couplingScore,
11512
+ coChangeCommits: pair.coChangeCommits
11513
+ });
11514
+ }
11515
+ }
11516
+ return {
11517
+ available: true,
11518
+ churn: (filePath) => files.get(filePath)?.churnTotal ?? 0,
11519
+ commits: (filePath) => files.get(filePath)?.commitCount ?? 0,
11520
+ file: (filePath) => files.get(filePath) ?? null,
11521
+ coupling: (fileA, fileB) => pairs.get(pairKey2(fileA, fileB)) ?? null
11522
+ };
11523
+ };
11524
+ var resolveMaxSteps = (value) => {
11525
+ if (value === void 0 || !Number.isFinite(value)) return DEFAULT_MAX_STEPS;
11526
+ return Math.min(MAX_MAX_STEPS, Math.max(MIN_MAX_STEPS, Math.trunc(value)));
11527
+ };
11528
+ var medianOf = (values) => {
11529
+ if (values.length === 0) return 0;
11530
+ const sorted = [...values].sort((a, b) => a - b);
11531
+ const middle = Math.floor(sorted.length / 2);
11532
+ if (sorted.length % 2 === 1) return sorted[middle] ?? 0;
11533
+ return ((sorted[middle - 1] ?? 0) + (sorted[middle] ?? 0)) / 2;
11534
+ };
11535
+ var topAuthorId = (shares) => {
11536
+ let top = null;
11537
+ for (const share of shares) {
11538
+ if (share.authorId.length === 0) continue;
11539
+ if (top === null || share.commits > top.commits || share.commits === top.commits && comparePaths(share.authorId, top.authorId) < 0) {
11540
+ top = { authorId: share.authorId, commits: share.commits };
11541
+ }
11542
+ }
11543
+ return top?.authorId ?? null;
11544
+ };
11545
+ var pluralized = (count, singular, plural3) => `${count} ${count === 1 ? singular : plural3}`;
11546
+ var importCount = (count) => pluralized(count, "import", "imports");
11547
+ var importerCount = (count) => pluralized(count, "importer", "importers");
11548
+ var commitCount = (count) => pluralized(count, "commit", "commits");
11549
+ var lineCount = (count) => pluralized(count, "line", "lines");
11550
+ var createStats = (steppableFiles, graphIndex, evolution) => {
11551
+ const steppable = [...new Set(steppableFiles)].sort(comparePaths);
11552
+ const steppableSet = new Set(steppable);
11553
+ let maxFanIn = 0;
11554
+ let maxChurn = 0;
11555
+ for (const filePath of steppable) {
11556
+ maxFanIn = Math.max(maxFanIn, graphIndex.fanInInternal(filePath));
11557
+ maxChurn = Math.max(maxChurn, evolution.churn(filePath));
11558
+ }
11559
+ const internalFanIn = (filePath) => graphIndex.fanInInternal(filePath);
11560
+ const fanInNorm = (filePath) => maxFanIn === 0 ? 0 : internalFanIn(filePath) / maxFanIn;
11561
+ const churnNorm = (filePath) => maxChurn === 0 ? 0 : evolution.churn(filePath) / maxChurn;
11562
+ return {
11563
+ steppable,
11564
+ steppableSet,
11565
+ internalFanIn,
11566
+ fanInNorm,
11567
+ churnNorm,
11568
+ medianFanIn: medianOf(steppable.map(internalFanIn))
11569
+ };
11570
+ };
11571
+ var roleFor = (order, filePath, includeTests, internalFanIn, medianFanIn) => {
11572
+ if (order === 1) return "entry";
11573
+ if (includeTests && isTestPath2(filePath)) return "test";
11574
+ if (internalFanIn > medianFanIn) return "core";
11575
+ return "helper";
11576
+ };
11577
+ var entryReason = (filePath, steppableCount, graphIndex) => {
11578
+ if (steppableCount === 1) return "the module has a single file";
11579
+ const external = graphIndex.fanInExternal(filePath);
11580
+ if (external > 0) {
11581
+ return `external interface: ${importCount(external)} from outside the module`;
11582
+ }
11583
+ const internal = graphIndex.fanInInternal(filePath);
11584
+ if (internal === 0) {
11585
+ return "no imports in or out of the module; first by path";
11586
+ }
11587
+ return `no external importers; ${importerCount(internal)}`;
11588
+ };
11589
+ var chooseGreedyCandidate = (current, candidates, stats, evolution) => {
11590
+ let best = null;
11591
+ for (const filePath of candidates) {
11592
+ const coupling = evolution.coupling(current, filePath);
11593
+ const fanInNorm = stats.fanInNorm(filePath);
11594
+ const churnNorm = stats.churnNorm(filePath);
11595
+ const score = 0.5 * (coupling?.score ?? 0) + 0.3 * fanInNorm + 0.2 * churnNorm;
11596
+ const candidate = { filePath, score, coupling, fanInNorm, churnNorm };
11597
+ if (best === null || score > best.score || score === best.score && comparePaths(filePath, best.filePath) < 0) {
11598
+ best = candidate;
11599
+ }
11600
+ }
11601
+ return best;
11602
+ };
11603
+ var greedyReason = (current, candidate, stats, graphIndex, evolution) => {
11604
+ const couplingContribution = 0.5 * (candidate.coupling?.score ?? 0);
11605
+ const fanInContribution = 0.3 * candidate.fanInNorm;
11606
+ const churnContribution = 0.2 * candidate.churnNorm;
11607
+ if (couplingContribution === 0 && fanInContribution === 0 && churnContribution === 0) {
11608
+ return graphIndex.importsTo(current, candidate.filePath) ? `import of ${current}` : `imported by ${current}`;
11609
+ }
11610
+ if (couplingContribution >= fanInContribution && couplingContribution >= churnContribution && candidate.coupling !== null) {
11611
+ return `most changed together with ${current} (${commitCount(candidate.coupling.coChangeCommits)})`;
11612
+ }
11613
+ if (fanInContribution >= churnContribution) {
11614
+ return `central inside the module: ${importerCount(stats.internalFanIn(candidate.filePath))}`;
11615
+ }
11616
+ return `most churned neighbour (${lineCount(evolution.churn(candidate.filePath))} changed)`;
11617
+ };
11618
+ var chooseExhaustedCandidate = (remaining, stats, evolution) => {
11619
+ let best = null;
11620
+ for (const filePath of remaining) {
11621
+ if (best === null) {
11622
+ best = filePath;
11623
+ continue;
11624
+ }
11625
+ const internal = stats.internalFanIn(filePath);
11626
+ const bestInternal = stats.internalFanIn(best);
11627
+ if (internal > bestInternal) {
11628
+ best = filePath;
11629
+ continue;
11630
+ }
11631
+ if (internal < bestInternal) continue;
11632
+ const churn = evolution.churn(filePath);
11633
+ const bestChurn = evolution.churn(best);
11634
+ if (churn > bestChurn) {
11635
+ best = filePath;
11636
+ continue;
11637
+ }
11638
+ if (churn < bestChurn) continue;
11639
+ if (comparePaths(filePath, best) < 0) best = filePath;
11640
+ }
11641
+ return best;
11642
+ };
11643
+ var exhaustedReason = (filePath, stats, evolution) => {
11644
+ const internal = stats.internalFanIn(filePath);
11645
+ if (internal > 0) {
11646
+ return `central inside the module: ${importerCount(internal)}`;
11647
+ }
11648
+ return `highest churn in the module (${lineCount(evolution.churn(filePath))})`;
11649
+ };
11650
+ var orderGraphReadingPath = (stats, graphIndex, evolution, includeTests, maxSteps, seedFile) => {
11651
+ const firstFile = stats.steppable[0];
11652
+ if (firstFile === void 0) return [];
11653
+ const result = [];
11654
+ const visited = /* @__PURE__ */ new Set();
11655
+ const add = (filePath, reason) => {
11656
+ result.push({
11657
+ filePath,
11658
+ role: roleFor(
11659
+ result.length + 1,
11660
+ filePath,
11661
+ includeTests,
11662
+ stats.internalFanIn(filePath),
11663
+ stats.medianFanIn
11664
+ ),
11665
+ reason
11666
+ });
11667
+ visited.add(filePath);
11668
+ };
11669
+ let entry = firstFile;
11670
+ if (seedFile !== null && stats.steppableSet.has(seedFile)) {
11671
+ entry = seedFile;
11672
+ } else {
11673
+ let entryExternal = graphIndex.fanInExternal(entry);
11674
+ for (const filePath of stats.steppable) {
11675
+ const external = graphIndex.fanInExternal(filePath);
11676
+ if (external > entryExternal || external === entryExternal && (filePath.length < entry.length || filePath.length === entry.length && comparePaths(filePath, entry) < 0)) {
11677
+ entry = filePath;
11678
+ entryExternal = external;
11679
+ }
11680
+ }
11681
+ }
11682
+ add(entry, entryReason(entry, stats.steppable.length, graphIndex));
11683
+ while (result.length < maxSteps) {
11684
+ const current = result[result.length - 1]?.filePath;
11685
+ if (current === void 0) break;
11686
+ const neighbourCandidates = graphIndex.neighbours(current).filter((filePath) => stats.steppableSet.has(filePath) && !visited.has(filePath));
11687
+ if (neighbourCandidates.length > 0) {
11688
+ const candidate2 = chooseGreedyCandidate(current, neighbourCandidates, stats, evolution);
11689
+ if (candidate2 === null) break;
11690
+ add(candidate2.filePath, greedyReason(current, candidate2, stats, graphIndex, evolution));
11691
+ continue;
11692
+ }
11693
+ const remaining = stats.steppable.filter((filePath) => !visited.has(filePath));
11694
+ const candidate = chooseExhaustedCandidate(remaining, stats, evolution);
11695
+ if (candidate === null) break;
11696
+ add(candidate, exhaustedReason(candidate, stats, evolution));
11697
+ }
11698
+ return result;
11699
+ };
11700
+ var chooseGitOnlyCandidate = (remaining, selected, stats, evolution) => {
11701
+ let best = null;
11702
+ for (const filePath of remaining) {
11703
+ let couplingScore = 0;
11704
+ let coChangeCommits = 0;
11705
+ let otherPath = null;
11706
+ for (const selectedFile of selected) {
11707
+ const coupling = evolution.coupling(filePath, selectedFile.filePath);
11708
+ if (coupling === null || coupling.score <= couplingScore) continue;
11709
+ couplingScore = coupling.score;
11710
+ coChangeCommits = coupling.coChangeCommits;
11711
+ otherPath = selectedFile.filePath;
11712
+ }
11713
+ const churn = evolution.churn(filePath);
11714
+ const score = 0.5 * couplingScore + 0.5 * stats.churnNorm(filePath);
11715
+ const candidate = {
11716
+ filePath,
11717
+ score,
11718
+ churn,
11719
+ couplingScore,
11720
+ coChangeCommits,
11721
+ otherPath
11722
+ };
11723
+ if (best === null || score > best.score || score === best.score && (churn > best.churn || churn === best.churn && comparePaths(filePath, best.filePath) < 0)) {
11724
+ best = candidate;
11725
+ }
11726
+ }
11727
+ return best;
11728
+ };
11729
+ var orderGitOnlyReadingPath = (stats, evolution, includeTests, maxSteps, seedFile) => {
11730
+ const result = [];
11731
+ const visited = /* @__PURE__ */ new Set();
11732
+ const add = (filePath, reason) => {
11733
+ result.push({
11734
+ filePath,
11735
+ role: roleFor(
11736
+ result.length + 1,
11737
+ filePath,
11738
+ includeTests,
11739
+ stats.internalFanIn(filePath),
11740
+ stats.medianFanIn
11741
+ ),
11742
+ reason
11743
+ });
11744
+ visited.add(filePath);
11745
+ };
11746
+ if (seedFile !== null && stats.steppableSet.has(seedFile) && result.length < maxSteps) {
11747
+ add(
11748
+ seedFile,
11749
+ `changed ${lineCount(evolution.churn(seedFile))} in ${commitCount(evolution.commits(seedFile))} (no structural graph)`
11750
+ );
11751
+ }
11752
+ while (result.length < maxSteps) {
11753
+ const remaining = stats.steppable.filter((filePath) => !visited.has(filePath));
11754
+ const candidate = chooseGitOnlyCandidate(remaining, result, stats, evolution);
11755
+ if (candidate === null) break;
11756
+ const couplingContribution = 0.5 * candidate.couplingScore;
11757
+ const churnContribution = 0.5 * stats.churnNorm(candidate.filePath);
11758
+ if (candidate.couplingScore > 0 && couplingContribution >= churnContribution && candidate.otherPath !== null) {
11759
+ add(
11760
+ candidate.filePath,
11761
+ `co-changes with ${candidate.otherPath} (${commitCount(candidate.coChangeCommits)}) and changed ${lineCount(candidate.churn)}`
11762
+ );
11763
+ continue;
11764
+ }
11765
+ add(
11766
+ candidate.filePath,
11767
+ `changed ${lineCount(candidate.churn)} in ${commitCount(evolution.commits(candidate.filePath))} (no structural graph)`
11768
+ );
11769
+ }
11770
+ return result;
11771
+ };
11772
+ var orderReadingPath = (params) => {
11773
+ const stats = createStats(params.steppableFiles, params.graphIndex, params.evolution);
11774
+ const seedFile = params.seedFile ?? null;
11775
+ if (!params.hasGraph) {
11776
+ return orderGitOnlyReadingPath(
11777
+ stats,
11778
+ params.evolution,
11779
+ params.includeTests,
11780
+ params.maxSteps,
11781
+ seedFile
11782
+ );
11783
+ }
11784
+ return orderGraphReadingPath(
11785
+ stats,
11786
+ params.graphIndex,
11787
+ params.evolution,
11788
+ params.includeTests,
11789
+ params.maxSteps,
11790
+ seedFile
11791
+ );
11792
+ };
11793
+ var ownerFor = (filePath, ownership) => {
11794
+ if (ownership === null || !ownership.available) return null;
11795
+ return ownership.files.find((file) => file.filePath === filePath)?.declared ?? [];
11796
+ };
11797
+ var ownershipTopAuthor = (filePath, ownership) => {
11798
+ if (ownership === null || !ownership.available) return null;
11799
+ return ownership.files.find((file) => file.filePath === filePath)?.observed.topAuthorId ?? null;
11800
+ };
11801
+ var observedTopAuthorFor = (filePath, evolution, ownership) => {
11802
+ if (evolution.available) {
11803
+ const file = evolution.file(filePath);
11804
+ return topAuthorId(file?.authorDistributionByCommits ?? []);
11805
+ }
11806
+ return ownershipTopAuthor(filePath, ownership);
11807
+ };
11808
+ var buildPeople = (steppedFiles, evolution) => {
11809
+ const commitsByAuthor = /* @__PURE__ */ new Map();
11810
+ const dominantAuthorByFile = /* @__PURE__ */ new Map();
11811
+ for (const filePath of steppedFiles) {
11812
+ const distribution = evolution.file(filePath)?.authorDistributionByCommits ?? [];
11813
+ for (const share of distribution) {
11814
+ if (share.authorId.length === 0) continue;
11815
+ commitsByAuthor.set(
11816
+ share.authorId,
11817
+ (commitsByAuthor.get(share.authorId) ?? 0) + share.commits
11818
+ );
11819
+ }
11820
+ const top = topAuthorId(distribution);
11821
+ if (top !== null) dominantAuthorByFile.set(filePath, top);
11822
+ }
11823
+ return [...commitsByAuthor.entries()].map(([authorId, commits]) => {
11824
+ const files = steppedFiles.filter((filePath) => dominantAuthorByFile.get(filePath) === authorId).sort(comparePaths);
11825
+ return { authorId, files, commits };
11826
+ }).sort((a, b) => b.commits - a.commits || comparePaths(a.authorId, b.authorId)).slice(0, 3);
11827
+ };
11828
+ var attachTestFiles = (steps, testFiles) => {
11829
+ for (const testPath of testFiles) {
11830
+ const sourcePath = stripTestSuffix(testPath);
11831
+ const sourceStem = stripSourceExtension(sourcePath);
11832
+ const target = steps.find(
11833
+ (step) => step.filePath === sourcePath || stripSourceExtension(step.filePath) === sourceStem
11834
+ );
11835
+ if (target !== void 0) target.testFiles.push(testPath);
11836
+ }
11837
+ for (const step of steps) step.testFiles.sort(comparePaths);
11838
+ };
11839
+ var buildReadingPath = (input) => {
11840
+ const target = normalizeTarget(input.target);
11841
+ const maxSteps = resolveMaxSteps(input.maxSteps);
11842
+ const graph = input.graph ?? null;
11843
+ const evolution = input.evolution ?? null;
11844
+ const ownership = input.ownership ?? null;
11845
+ const includeTests = input.includeTests === true;
11846
+ const universe = resolveUniverse(target, graph, evolution);
11847
+ const graphIndex = createGraphIndex(graph, universe.files);
11848
+ const evolutionIndex = createEvolutionIndex(evolution);
11849
+ const steppableFiles = includeTests ? universe.files : universe.files.filter((filePath) => !isTestPath2(filePath));
11850
+ const ordered = orderReadingPath({
11851
+ steppableFiles,
11852
+ graphIndex,
11853
+ evolution: evolutionIndex,
11854
+ hasGraph: graph !== null,
11855
+ includeTests,
11856
+ maxSteps,
11857
+ seedFile: universe.targetKind === "file" ? target : null
11858
+ });
11859
+ const steps = ordered.map((entry) => ({
11860
+ order: 0,
11861
+ filePath: entry.filePath,
11862
+ role: entry.role,
11863
+ reason: entry.reason,
11864
+ owner: ownerFor(entry.filePath, ownership),
11865
+ observedTopAuthor: observedTopAuthorFor(entry.filePath, evolutionIndex, ownership),
11866
+ commits: evolutionIndex.commits(entry.filePath),
11867
+ churn: evolutionIndex.churn(entry.filePath),
11868
+ fanInInternal: graphIndex.fanInInternal(entry.filePath),
11869
+ testFiles: []
11870
+ }));
11871
+ if (!includeTests) {
11872
+ const testFiles = universe.files.filter((filePath) => isTestPath2(filePath)).sort(comparePaths);
11873
+ attachTestFiles(steps, testFiles);
11874
+ }
11875
+ steps.forEach((step, index) => {
11876
+ step.order = index + 1;
11877
+ });
11878
+ const truncated = steps.length === maxSteps && steppableFiles.length > steps.length;
11879
+ const warnings = [];
11880
+ if (graph === null) {
11881
+ warnings.push("no structural graph available: ordered by churn and change coupling");
11882
+ }
11883
+ if (!evolutionIndex.available) {
11884
+ warnings.push("repository evolution is unavailable: churn signals are zero");
11885
+ }
11886
+ if (universe.targetKind === "file" && graph !== null && !knownPaths(graph, evolution).includes(target)) {
11887
+ warnings.push(`target file ${target} has no graph data`);
11888
+ }
11889
+ if (universe.excludedCount > 0) {
11890
+ warnings.push(
11891
+ `excluded ${universe.excludedCount} generated, vendored or lock file(s) from the target`
11892
+ );
11893
+ }
11894
+ if (universe.files.length === 0) {
11895
+ warnings.push(`no files found under ${target}`);
11896
+ }
11897
+ if (truncated) {
11898
+ warnings.push(`showing ${maxSteps} of ${steppableFiles.length} files (truncated)`);
11899
+ }
11900
+ const people = buildPeople(
11901
+ steps.map((step) => step.filePath),
11902
+ evolutionIndex
11903
+ );
11904
+ return {
11905
+ target,
11906
+ targetKind: universe.targetKind,
11907
+ steps,
11908
+ people,
11909
+ commands: [],
11910
+ warnings,
11911
+ truncated
11912
+ };
11913
+ };
11914
+
11915
+ // src/application/format-path-output.ts
11916
+ var PATH_SCHEMA_VERSION = "codesentinel.path.v1";
11917
+ var toPayloadOwner = (owner) => {
11918
+ if (owner.kind === "user") return { kind: "user", handle: owner.handle };
11919
+ if (owner.kind === "team") return { kind: "team", org: owner.org, slug: owner.slug };
11920
+ return { kind: "email", address: owner.address };
11921
+ };
11922
+ var buildPathPayload = (path) => ({
11923
+ schemaVersion: PATH_SCHEMA_VERSION,
11924
+ target: path.target,
11925
+ targetKind: path.targetKind,
11926
+ steps: path.steps.map((step) => ({
11927
+ order: step.order,
11928
+ filePath: step.filePath,
11929
+ role: step.role,
11930
+ reason: step.reason,
11931
+ owner: step.owner === null ? null : step.owner.map(toPayloadOwner),
11932
+ observedTopAuthor: step.observedTopAuthor,
11933
+ commits: step.commits,
11934
+ churn: step.churn,
11935
+ fanInInternal: step.fanInInternal,
11936
+ testFiles: [...step.testFiles]
11937
+ })),
11938
+ people: path.people.map((person) => ({
11939
+ authorId: person.authorId,
11940
+ files: [...person.files],
11941
+ commits: person.commits
11942
+ })),
11943
+ commands: [...path.commands],
11944
+ warnings: [...path.warnings],
11945
+ truncated: path.truncated
11946
+ });
11947
+ var formatOwner = (owner) => {
11948
+ if (owner.kind === "user") return `@${owner.handle}`;
11949
+ if (owner.kind === "team") return `@${owner.org}/${owner.slug}`;
11950
+ return owner.address;
11951
+ };
11952
+ var formatOwnerText = (owner) => {
11953
+ if (owner === null) return "not analysed (no CODEOWNERS)";
11954
+ if (owner.length === 0) return "none declared";
11955
+ return owner.map(formatOwner).join(", ");
11956
+ };
11957
+ var formatStepsCount = (count) => `${count} ${count === 1 ? "step" : "steps"}`;
11958
+ var appendConsoleSection = (lines, title, items) => {
11959
+ if (items.length === 0) return;
11960
+ lines.push("");
11961
+ lines.push(title);
11962
+ for (const item of items) {
11963
+ lines.push(` - ${item}`);
11964
+ }
11965
+ };
11966
+ var renderConsole2 = (path) => {
11967
+ const lines = [];
11968
+ lines.push(`Reading path: ${path.target} (${path.targetKind})`);
11969
+ lines.push(
11970
+ `${formatStepsCount(path.steps.length)}${path.truncated === true ? " (truncated)" : ""}`
11971
+ );
11972
+ lines.push("");
11973
+ if (path.steps.length === 0) {
11974
+ lines.push("No files to read.");
11975
+ } else {
11976
+ for (const step of path.steps) {
11977
+ lines.push(` ${step.order}. ${step.filePath} [${step.role}]`);
11978
+ lines.push(` ${step.reason}`);
11979
+ lines.push(
11980
+ ` owner: ${formatOwnerText(step.owner)} \xB7 observed: ${step.observedTopAuthor ?? "unknown"} \xB7 commits ${step.commits} \xB7 churn ${step.churn} \xB7 fan-in ${step.fanInInternal}`
11981
+ );
11982
+ if (step.testFiles.length > 0) {
11983
+ lines.push(` tests: ${step.testFiles.join(", ")}`);
11984
+ }
11985
+ }
11986
+ }
11987
+ appendConsoleSection(
11988
+ lines,
11989
+ "People to ask",
11990
+ path.people.map(
11991
+ (person) => `${person.authorId} (${person.commits} commits): ${person.files.length > 0 ? person.files.join(", ") : "no single file"}`
11992
+ )
11993
+ );
11994
+ appendConsoleSection(
11995
+ lines,
11996
+ "Suggested commands (not discovered, not run)",
11997
+ path.commands.map((command) => command)
11998
+ );
11999
+ appendConsoleSection(
12000
+ lines,
12001
+ "Warnings",
12002
+ path.warnings.map((warning) => warning)
12003
+ );
12004
+ return lines.join("\n");
12005
+ };
12006
+ var escapeTableCell2 = (value) => value.replace(/\|/g, "\\|");
12007
+ var renderMarkdownTable2 = (header, rows) => {
12008
+ const lines = [`| ${header.join(" | ")} |`, `| ${header.map(() => "---").join(" | ")} |`];
12009
+ for (const row of rows) {
12010
+ lines.push(`| ${row.map(escapeTableCell2).join(" | ")} |`);
12011
+ }
12012
+ return lines;
12013
+ };
12014
+ var formatMarkdownObserved = (value) => value === null ? "unknown" : `\`${value}\``;
12015
+ var formatMarkdownTests = (testFiles) => testFiles.length === 0 ? "none" : testFiles.map((file) => `\`${file}\``).join(", ");
12016
+ var appendMarkdownSection = (lines, title, items) => {
12017
+ if (items.length === 0) return;
12018
+ lines.push("");
12019
+ lines.push(title);
12020
+ lines.push("");
12021
+ for (const item of items) {
12022
+ lines.push(`- ${item}`);
12023
+ }
12024
+ };
12025
+ var renderMarkdown3 = (path) => {
12026
+ const lines = [];
12027
+ lines.push(`## Reading path: \`${path.target}\``);
12028
+ lines.push("");
12029
+ lines.push(`- target kind: \`${path.targetKind}\``);
12030
+ lines.push(`- steps: ${path.steps.length}${path.truncated === true ? " (truncated)" : ""}`);
12031
+ lines.push("");
12032
+ if (path.steps.length === 0) {
12033
+ lines.push("No files to read.");
12034
+ } else {
12035
+ for (const step of path.steps) {
12036
+ lines.push(`${step.order}. **\`${step.filePath}\`** \u2014 \`${step.role}\``);
12037
+ lines.push(` - ${step.reason}`);
12038
+ lines.push(
12039
+ ` - owner: ${formatOwnerText(step.owner)} \xB7 observed: ${formatMarkdownObserved(step.observedTopAuthor)} \xB7 commits \`${step.commits}\` \xB7 churn \`${step.churn}\` \xB7 fan-in \`${step.fanInInternal}\``
12040
+ );
12041
+ if (step.testFiles.length > 0) {
12042
+ lines.push(` - tests: ${formatMarkdownTests(step.testFiles)}`);
12043
+ }
12044
+ }
12045
+ lines.push("");
12046
+ lines.push("### Steps");
12047
+ lines.push("");
12048
+ lines.push(
12049
+ ...renderMarkdownTable2(
12050
+ [
12051
+ "#",
12052
+ "File",
12053
+ "Role",
12054
+ "Commits",
12055
+ "Churn",
12056
+ "Fan-in",
12057
+ "Observed author",
12058
+ "Declared owner",
12059
+ "Tests"
12060
+ ],
12061
+ path.steps.map((step) => [
12062
+ `${step.order}`,
12063
+ `\`${step.filePath}\``,
12064
+ `\`${step.role}\``,
12065
+ `${step.commits}`,
12066
+ `${step.churn}`,
12067
+ `${step.fanInInternal}`,
12068
+ formatMarkdownObserved(step.observedTopAuthor),
12069
+ formatOwnerText(step.owner),
12070
+ formatMarkdownTests(step.testFiles)
12071
+ ])
12072
+ )
12073
+ );
12074
+ }
12075
+ appendMarkdownSection(
12076
+ lines,
12077
+ "### People to ask",
12078
+ path.people.map(
12079
+ (person) => `\`${person.authorId}\` (${person.commits} commits): ${person.files.length > 0 ? person.files.map((file) => `\`${file}\``).join(", ") : "no single file"}`
12080
+ )
12081
+ );
12082
+ appendMarkdownSection(
12083
+ lines,
12084
+ "### Suggested commands (not discovered, not run)",
12085
+ path.commands.map((command) => `\`${command}\``)
12086
+ );
12087
+ appendMarkdownSection(
12088
+ lines,
12089
+ "### Warnings",
12090
+ path.warnings.map((warning) => warning)
12091
+ );
12092
+ return lines.join("\n");
12093
+ };
12094
+ var formatPathOutput = (path, format) => {
12095
+ if (format === "json") {
12096
+ return JSON.stringify(buildPathPayload(path), null, 2);
12097
+ }
12098
+ return format === "md" ? renderMarkdown3(path) : renderConsole2(path);
12099
+ };
12100
+
12101
+ // src/application/run-path-command.ts
12102
+ var PATH_EXIT_CODES = {
12103
+ ok: 0,
12104
+ invalidTarget: 2
12105
+ };
12106
+ var PathConfigurationError = class extends Error {
12107
+ constructor(message) {
12108
+ super(message);
12109
+ this.name = "PathConfigurationError";
12110
+ }
12111
+ };
12112
+ var DEFAULT_PATH_WINDOW_DAYS = DEFAULT_OWNERS_WINDOW_DAYS;
12113
+ var resolveRelativeTarget = (repositoryPath, target, invocationCwd) => {
12114
+ const absoluteTarget = resolve9(invocationCwd, target);
12115
+ const relativeTarget = relative4(repositoryPath, absoluteTarget);
12116
+ if (relativeTarget === "" || relativeTarget === ".") {
12117
+ throw new PathConfigurationError(
12118
+ `target "${target}" is the repository root; pass a module directory or a file.`
12119
+ );
12120
+ }
12121
+ if (relativeTarget.startsWith("..") || isAbsolute2(relativeTarget)) {
12122
+ throw new PathConfigurationError(
12123
+ `target "${target}" is outside the repository at "${repositoryPath}".`
12124
+ );
12125
+ }
12126
+ if (!existsSync6(absoluteTarget)) {
12127
+ throw new PathConfigurationError(`target "${target}" does not exist in the repository.`);
12128
+ }
12129
+ const stats = statSync3(absoluteTarget);
12130
+ if (!stats.isFile() && !stats.isDirectory()) {
12131
+ throw new PathConfigurationError(`target "${target}" is not a regular file or directory.`);
12132
+ }
12133
+ return normalizeRepositoryPath(relativeTarget);
12134
+ };
12135
+ var hasCodeownersFile = (repositoryPath) => CODEOWNERS_CANDIDATE_PATHS.some((candidate) => existsSync6(join12(repositoryPath, candidate)));
12136
+ var resolveOwnership = async (repositoryPath, ref, windowDays, logger) => {
12137
+ if (!hasCodeownersFile(repositoryPath)) {
12138
+ logger.info("ownership skipped: no CODEOWNERS file found");
12139
+ return {
12140
+ ownership: null,
12141
+ warnings: ["no CODEOWNERS file found: declared owners are not reported"]
12142
+ };
12143
+ }
12144
+ let audit;
12145
+ try {
12146
+ const result = await buildOwnershipAudit(repositoryPath, { ref, windowDays }, logger);
12147
+ audit = result.audit;
12148
+ } catch (error) {
12149
+ if (error instanceof OwnersConfigurationError) {
12150
+ throw new PathConfigurationError(error.message);
12151
+ }
12152
+ throw error;
12153
+ }
12154
+ if (!audit.available) {
12155
+ logger.info(`ownership unavailable: CODEOWNERS was not found at ${ref}`);
12156
+ return {
12157
+ ownership: audit,
12158
+ warnings: [`CODEOWNERS was not found at ${ref}: declared owners are not reported`]
12159
+ };
12160
+ }
12161
+ logger.info(`ownership report: CODEOWNERS found for ${audit.files.length} files`);
12162
+ return { ownership: audit, warnings: [] };
12163
+ };
12164
+ var readTestScript = async (repositoryPath) => {
12165
+ let raw;
12166
+ try {
12167
+ raw = await readFile8(join12(repositoryPath, "package.json"), "utf8");
12168
+ } catch {
12169
+ return null;
12170
+ }
12171
+ let parsed;
12172
+ try {
12173
+ parsed = JSON.parse(raw);
12174
+ } catch {
12175
+ return null;
12176
+ }
12177
+ if (typeof parsed !== "object" || parsed === null) return null;
12178
+ const scripts = parsed.scripts;
12179
+ if (typeof scripts !== "object" || scripts === null) return null;
12180
+ const test = scripts.test;
12181
+ if (typeof test !== "string" || test.trim().length === 0) return null;
12182
+ return test;
12183
+ };
12184
+ var resolveTestCommand = (repositoryPath) => {
12185
+ if (existsSync6(join12(repositoryPath, "pnpm-lock.yaml"))) return "pnpm test";
12186
+ if (existsSync6(join12(repositoryPath, "yarn.lock"))) return "yarn test";
12187
+ if (existsSync6(join12(repositoryPath, "bun.lockb")) || existsSync6(join12(repositoryPath, "bun.lock"))) {
12188
+ return "bun test";
12189
+ }
12190
+ return "npm test";
12191
+ };
12192
+ var collectSuggestedCommands = async (repositoryPath) => {
12193
+ const testScript = await readTestScript(repositoryPath);
12194
+ if (testScript === null) return [];
12195
+ const command = resolveTestCommand(repositoryPath);
12196
+ return command === null ? [] : [command];
12197
+ };
12198
+ var runPathCommand = async (target, options = {}, logger = createSilentLogger()) => {
12199
+ const invocationCwd = process.env["INIT_CWD"] ?? process.cwd();
12200
+ const ref = options.ref ?? DEFAULT_OWNERS_REF;
12201
+ const windowDays = options.windowDays ?? DEFAULT_PATH_WINDOW_DAYS;
12202
+ const format = options.format ?? "console";
12203
+ const maxSteps = options.maxSteps ?? DEFAULT_MAX_STEPS;
12204
+ const context = readRepositoryContext(invocationCwd, ref);
12205
+ if (context === null) {
12206
+ throw new PathConfigurationError(
12207
+ `"path" requires a git work tree and a ref that resolves to a commit: could not resolve "${ref}" from "${invocationCwd}".`
12208
+ );
12209
+ }
12210
+ logger.info(`reading path repository: ${context.repositoryPath} at ${ref}`);
12211
+ const relativeTarget = resolveRelativeTarget(context.repositoryPath, target, invocationCwd);
12212
+ logger.info(`reading path target: ${relativeTarget}`);
12213
+ const { structural, evolution } = collectStructuralEvolutionInputs(
12214
+ context.repositoryPath,
12215
+ "likely_merge",
12216
+ { recentWindowDays: windowDays },
12217
+ logger
12218
+ );
12219
+ const ownership = await resolveOwnership(context.repositoryPath, ref, windowDays, logger);
12220
+ let readingPath;
12221
+ try {
12222
+ readingPath = buildReadingPath({
12223
+ target: relativeTarget,
12224
+ graph: structural,
12225
+ evolution,
12226
+ ownership: ownership.ownership,
12227
+ maxSteps,
12228
+ includeTests: options.includeTests === true
12229
+ });
12230
+ } catch (error) {
12231
+ if (error instanceof ReadingPathError) {
12232
+ throw new PathConfigurationError(error.message);
12233
+ }
12234
+ throw error;
12235
+ }
12236
+ const commands = await collectSuggestedCommands(context.repositoryPath);
12237
+ const completedPath = {
12238
+ ...readingPath,
12239
+ commands,
12240
+ warnings: [...readingPath.warnings, ...ownership.warnings]
12241
+ };
12242
+ logger.debug(
12243
+ `reading path built: steps=${completedPath.steps.length}, people=${completedPath.people.length}, commands=${completedPath.commands.length}, truncated=${completedPath.truncated}`
12244
+ );
12245
+ logger.info(`reading path built: ${completedPath.steps.length} steps`);
12246
+ const rendered = formatPathOutput(completedPath, format);
12247
+ const absoluteOutputPath = options.outputPath === void 0 ? void 0 : resolve9(invocationCwd, options.outputPath);
12248
+ if (absoluteOutputPath !== void 0) {
12249
+ await writeFile8(absoluteOutputPath, `${rendered}
12250
+ `, "utf8");
12251
+ logger.info(`reading path output written: ${absoluteOutputPath}`);
12252
+ }
12253
+ return {
12254
+ readingPath: completedPath,
12255
+ rendered,
12256
+ exitCode: PATH_EXIT_CODES.ok,
12257
+ repositoryPath: context.repositoryPath,
12258
+ relativeTarget,
12259
+ ...absoluteOutputPath === void 0 ? {} : { outputPath: absoluteOutputPath }
12260
+ };
12261
+ };
12262
+
11278
12263
  // src/application/format-pr-comment.ts
11279
12264
  var PR_COMMENT_MARKER = "<!-- codesentinel:summary -->";
11280
12265
  var PrCommentConfigurationError = class extends Error {
@@ -11335,7 +12320,7 @@ var formatOffenderOwners = (declared) => {
11335
12320
  return owners.length === 0 ? "\u2014" : owners.join(", ");
11336
12321
  };
11337
12322
  var readEvidence = (status, observed, criticality) => {
11338
- const topAuthorId = observed === null ? null : readString(observed["topAuthorId"]);
12323
+ const topAuthorId2 = observed === null ? null : readString(observed["topAuthorId"]);
11339
12324
  switch (status) {
11340
12325
  case "unowned-critical": {
11341
12326
  const fanIn = criticality === null ? null : readFiniteNumber(criticality["fanIn"]);
@@ -11344,11 +12329,11 @@ var readEvidence = (status, observed, criticality) => {
11344
12329
  return `fan-in ${fanIn ?? "n/a"}, ${commits ?? 0} commits, ${authors ?? 0} authors`;
11345
12330
  }
11346
12331
  case "ghosted":
11347
- return `no commits in the window, top author ${topAuthorId ?? "unknown"}`;
12332
+ return `no commits in the window, top author ${topAuthorId2 ?? "unknown"}`;
11348
12333
  case "drifted": {
11349
12334
  const share = observed === null ? null : readFiniteNumber(observed["topAuthorShare"]);
11350
12335
  const renderedShare = share === null ? "n/a" : `${Math.round(share * 100)}%`;
11351
- return `top author ${topAuthorId ?? "unknown"} (${renderedShare})`;
12336
+ return `top author ${topAuthorId2 ?? "unknown"} (${renderedShare})`;
11352
12337
  }
11353
12338
  default:
11354
12339
  return "ownership cannot be verified offline";
@@ -11401,8 +12386,8 @@ var formatSigned = (value) => {
11401
12386
  var formatCount = (value) => value === null ? "n/a" : String(value);
11402
12387
  var formatPercent2 = (value) => value === null ? "n/a" : `${String(value)}%`;
11403
12388
  var formatPercentagePoints = (value) => value === null ? "n/a" : `${formatSigned(value)} pp`;
11404
- var escapeTableCell2 = (value) => value.replace(/\|/g, "\\|");
11405
- var renderTableRow = (cells) => `| ${cells.map(escapeTableCell2).join(" | ")} |`;
12389
+ var escapeTableCell3 = (value) => value.replace(/\|/g, "\\|");
12390
+ var renderTableRow = (cells) => `| ${cells.map(escapeTableCell3).join(" | ")} |`;
11406
12391
  var parsePrCommentInput = (raw) => {
11407
12392
  if (!isRecord2(raw)) {
11408
12393
  return invalidInput("root", "an object");
@@ -11537,7 +12522,7 @@ var renderPrCommentBody = (input) => {
11537
12522
  };
11538
12523
 
11539
12524
  // src/application/run-comment-command.ts
11540
- import { readFile as readFile8, writeFile as writeFile8 } from "fs/promises";
12525
+ import { readFile as readFile9, writeFile as writeFile9 } from "fs/promises";
11541
12526
 
11542
12527
  // src/application/github-pr-comment-client.ts
11543
12528
  var DEFAULT_API_URL = "https://api.github.com";
@@ -11656,7 +12641,7 @@ var COMMENT_EXIT_CODES = {
11656
12641
  invalidConfiguration: 2
11657
12642
  };
11658
12643
  var readCiJson = async (inputPath) => {
11659
- const raw = await readFile8(inputPath, "utf8");
12644
+ const raw = await readFile9(inputPath, "utf8");
11660
12645
  try {
11661
12646
  return JSON.parse(raw);
11662
12647
  } catch {
@@ -11674,7 +12659,7 @@ var runCommentCommand = async (options, logger = createSilentLogger()) => {
11674
12659
  const body = renderPrCommentBody(input);
11675
12660
  const mode = options.mode ?? "change";
11676
12661
  if (options.outputPath !== void 0) {
11677
- await writeFile8(options.outputPath, `${body}
12662
+ await writeFile9(options.outputPath, `${body}
11678
12663
  `, "utf8");
11679
12664
  logger.info(`comment body written: ${options.outputPath}`);
11680
12665
  }
@@ -11731,7 +12716,7 @@ var runCommentCommand = async (options, logger = createSilentLogger()) => {
11731
12716
  };
11732
12717
 
11733
12718
  // src/application/run-trend-command.ts
11734
- import { writeFile as writeFile9 } from "fs/promises";
12719
+ import { writeFile as writeFile10 } from "fs/promises";
11735
12720
 
11736
12721
  // src/application/format-trend-output.ts
11737
12722
  var TREND_SCHEMA_VERSION = "codesentinel.trend.v1";
@@ -11804,7 +12789,7 @@ var renderAlignedRow = (cells, widths) => cells.map((cell, index) => {
11804
12789
  const width = widths[index] ?? cell.length;
11805
12790
  return index < 2 ? cell.padEnd(width) : cell.padStart(width);
11806
12791
  }).join(" ");
11807
- var renderConsole2 = (report) => {
12792
+ var renderConsole3 = (report) => {
11808
12793
  const rows = report.series.map(pointCells);
11809
12794
  const widths = TREND_HEADERS.map(
11810
12795
  (header, index) => Math.max(header.length, ...rows.map((row) => (row[index] ?? "").length))
@@ -11824,15 +12809,15 @@ var renderConsole2 = (report) => {
11824
12809
  appendWarnings2(lines, report.warnings);
11825
12810
  return lines.join("\n");
11826
12811
  };
11827
- var escapeTableCell3 = (value) => value.replace(/\|/g, "\\|");
11828
- var renderMarkdownTable2 = (header, rows) => {
12812
+ var escapeTableCell4 = (value) => value.replace(/\|/g, "\\|");
12813
+ var renderMarkdownTable3 = (header, rows) => {
11829
12814
  const lines = [`| ${header.join(" | ")} |`, `| ${header.map(() => "---").join(" | ")} |`];
11830
12815
  for (const row of rows) {
11831
- lines.push(`| ${row.map(escapeTableCell3).join(" | ")} |`);
12816
+ lines.push(`| ${row.map(escapeTableCell4).join(" | ")} |`);
11832
12817
  }
11833
12818
  return lines;
11834
12819
  };
11835
- var renderMarkdown3 = (report) => {
12820
+ var renderMarkdown4 = (report) => {
11836
12821
  const lines = ["# Snapshot trend", ""];
11837
12822
  lines.push(`- snapshots: ${report.series.length}`);
11838
12823
  const first = report.series[0];
@@ -11841,7 +12826,7 @@ var renderMarkdown3 = (report) => {
11841
12826
  lines.push(`- window: ${formatDate(first.generatedAt)} \u2192 ${formatDate(last.generatedAt)}`);
11842
12827
  }
11843
12828
  lines.push("");
11844
- lines.push(...renderMarkdownTable2(TREND_HEADERS, report.series.map(pointCells)));
12829
+ lines.push(...renderMarkdownTable3(TREND_HEADERS, report.series.map(pointCells)));
11845
12830
  if (report.deltas === null) {
11846
12831
  lines.push("");
11847
12832
  lines.push("not enough history for a trend");
@@ -11863,12 +12848,12 @@ var formatTrendOutput = (report, format) => {
11863
12848
  if (format === "json") {
11864
12849
  return JSON.stringify(report, null, 2);
11865
12850
  }
11866
- return format === "md" ? renderMarkdown3(report) : renderConsole2(report);
12851
+ return format === "md" ? renderMarkdown4(report) : renderConsole3(report);
11867
12852
  };
11868
12853
 
11869
12854
  // src/application/read-trend-snapshots.ts
11870
- import { glob, readFile as readFile9, readdir as readdir2, stat as stat3 } from "fs/promises";
11871
- import { basename as basename5, join as join12, resolve as resolve9 } from "path";
12855
+ import { glob, readFile as readFile10, readdir as readdir2, stat as stat3 } from "fs/promises";
12856
+ import { basename as basename5, join as join13, resolve as resolve10 } from "path";
11872
12857
  var TrendConfigurationError = class extends Error {
11873
12858
  constructor(message) {
11874
12859
  super(message);
@@ -11966,7 +12951,7 @@ var pathExists = async (absolutePath) => {
11966
12951
  };
11967
12952
  var discoverSnapshotFiles = async (from) => {
11968
12953
  const cwd = process.env["INIT_CWD"] ?? process.cwd();
11969
- const resolved = resolve9(cwd, from);
12954
+ const resolved = resolve10(cwd, from);
11970
12955
  const exists = await pathExists(resolved);
11971
12956
  if (exists) {
11972
12957
  const info = await stat3(resolved);
@@ -11974,7 +12959,7 @@ var discoverSnapshotFiles = async (from) => {
11974
12959
  const entries = await readdir2(resolved, { withFileTypes: true }).catch(() => {
11975
12960
  throw new TrendConfigurationError(`--from directory is not readable: ${from}`);
11976
12961
  });
11977
- const files2 = entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => ({ path: join12(resolved, entry.name), name: entry.name })).sort((a, b) => compareText4(a.name, b.name));
12962
+ const files2 = entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => ({ path: join13(resolved, entry.name), name: entry.name })).sort((a, b) => compareText4(a.name, b.name));
11978
12963
  if (files2.length === 0) {
11979
12964
  throw new TrendConfigurationError(`no snapshot JSON files found in ${from}`);
11980
12965
  }
@@ -11995,7 +12980,7 @@ var discoverSnapshotFiles = async (from) => {
11995
12980
  }
11996
12981
  const files = [];
11997
12982
  for (const match of matches.sort(compareText4)) {
11998
- const absolutePath = resolve9(cwd, match);
12983
+ const absolutePath = resolve10(cwd, match);
11999
12984
  try {
12000
12985
  const info = await stat3(absolutePath);
12001
12986
  if (!info.isFile() || !absolutePath.endsWith(".json")) {
@@ -12066,7 +13051,7 @@ var readTrendSnapshots = async (options) => {
12066
13051
  for (const file of files) {
12067
13052
  let content;
12068
13053
  try {
12069
- content = await readFile9(file.path, "utf8");
13054
+ content = await readFile10(file.path, "utf8");
12070
13055
  } catch {
12071
13056
  warnings.push(`skipped ${file.name}: invalid JSON`);
12072
13057
  continue;
@@ -12111,7 +13096,7 @@ var runTrendCommand = async (options, logger = createSilentLogger()) => {
12111
13096
  const rendered = formatTrendOutput(report, format);
12112
13097
  logger.debug(`trend series: ${report.series.length} snapshot(s)`);
12113
13098
  if (options.outputPath !== void 0) {
12114
- await writeFile9(options.outputPath, `${rendered}
13099
+ await writeFile10(options.outputPath, `${rendered}
12115
13100
  `, "utf8");
12116
13101
  logger.info(`trend output written: ${options.outputPath}`);
12117
13102
  }
@@ -12124,8 +13109,8 @@ var runTrendCommand = async (options, logger = createSilentLogger()) => {
12124
13109
  };
12125
13110
 
12126
13111
  // src/application/run-init-command.ts
12127
- import { access, mkdir as mkdir4, writeFile as writeFile10 } from "fs/promises";
12128
- import { dirname as dirname3, join as join13, resolve as resolve10 } from "path";
13112
+ import { access, mkdir as mkdir4, writeFile as writeFile11 } from "fs/promises";
13113
+ import { dirname as dirname3, join as join14, resolve as resolve11 } from "path";
12129
13114
  var CODESENTINEL_WORKFLOW_PATH = ".github/workflows/codesentinel.yml";
12130
13115
  var CODESENTINEL_OWNERS_PATH = ".codesentinel/owners.json";
12131
13116
  var CODESENTINEL_WORKFLOW_TEMPLATE = `name: CodeSentinel
@@ -12286,7 +13271,7 @@ var fileExists = async (absolutePath) => {
12286
13271
  };
12287
13272
  var anyFileExists = async (targetPath, candidates) => {
12288
13273
  for (const candidate of candidates) {
12289
- if (await fileExists(join13(targetPath, candidate))) {
13274
+ if (await fileExists(join14(targetPath, candidate))) {
12290
13275
  return true;
12291
13276
  }
12292
13277
  }
@@ -12294,16 +13279,16 @@ var anyFileExists = async (targetPath, candidates) => {
12294
13279
  };
12295
13280
  var resolveTargetPath3 = (inputPath) => {
12296
13281
  const invocationCwd = process.env["INIT_CWD"] ?? process.cwd();
12297
- return resolve10(invocationCwd, inputPath ?? ".");
13282
+ return resolve11(invocationCwd, inputPath ?? ".");
12298
13283
  };
12299
13284
  var runInitCommand = async (inputPath, options = {}) => {
12300
13285
  const targetPath = resolveTargetPath3(inputPath);
12301
13286
  const ci = options.ci ?? "github";
12302
- const hasCodeownersFile = await anyFileExists(targetPath, CODEOWNERS_CANDIDATES);
13287
+ const hasCodeownersFile2 = await anyFileExists(targetPath, CODEOWNERS_CANDIDATES);
12303
13288
  const plan = buildInitPlan({
12304
- hasCodeownersFile,
12305
- workflowExists: ci === "github" && await fileExists(join13(targetPath, CODESENTINEL_WORKFLOW_PATH)),
12306
- ownersFileExists: hasCodeownersFile && await fileExists(join13(targetPath, CODESENTINEL_OWNERS_PATH)),
13289
+ hasCodeownersFile: hasCodeownersFile2,
13290
+ workflowExists: ci === "github" && await fileExists(join14(targetPath, CODESENTINEL_WORKFLOW_PATH)),
13291
+ ownersFileExists: hasCodeownersFile2 && await fileExists(join14(targetPath, CODESENTINEL_OWNERS_PATH)),
12307
13292
  options: { ...options, ci }
12308
13293
  });
12309
13294
  if (options.dryRun !== true) {
@@ -12311,9 +13296,9 @@ var runInitCommand = async (inputPath, options = {}) => {
12311
13296
  if (entry.status !== "created" && entry.status !== "updated") {
12312
13297
  continue;
12313
13298
  }
12314
- const absolutePath = join13(targetPath, entry.path);
13299
+ const absolutePath = join14(targetPath, entry.path);
12315
13300
  await mkdir4(dirname3(absolutePath), { recursive: true });
12316
- await writeFile10(absolutePath, entry.content ?? "", "utf8");
13301
+ await writeFile11(absolutePath, entry.content ?? "", "utf8");
12317
13302
  }
12318
13303
  }
12319
13304
  return {
@@ -12326,7 +13311,7 @@ var runInitCommand = async (inputPath, options = {}) => {
12326
13311
 
12327
13312
  // src/index.ts
12328
13313
  var program = new Command();
12329
- var packageJsonPath = resolve11(dirname4(fileURLToPath2(import.meta.url)), "../package.json");
13314
+ var packageJsonPath = resolve12(dirname4(fileURLToPath2(import.meta.url)), "../package.json");
12330
13315
  var { version } = JSON.parse(readFileSync4(packageJsonPath, "utf8"));
12331
13316
  var parseRecentWindowDays = (value) => {
12332
13317
  const parsed = Number.parseInt(value, 10);
@@ -12650,12 +13635,12 @@ program.command("run").argument("[path]", "path to the project to analyze").addO
12650
13635
  ...options.trace === true ? { trace: explain.trace } : {}
12651
13636
  });
12652
13637
  if (options.snapshot !== void 0) {
12653
- await writeFile11(options.snapshot, JSON.stringify(snapshot, null, 2), "utf8");
13638
+ await writeFile12(options.snapshot, JSON.stringify(snapshot, null, 2), "utf8");
12654
13639
  logger.info(`snapshot written: ${options.snapshot}`);
12655
13640
  }
12656
13641
  const report = options.compare === void 0 ? createReport(snapshot) : createReport(
12657
13642
  snapshot,
12658
- compareSnapshots(snapshot, parseSnapshot(await readFile10(options.compare, "utf8")))
13643
+ compareSnapshots(snapshot, parseSnapshot(await readFile11(options.compare, "utf8")))
12659
13644
  );
12660
13645
  if (options.report === "html") {
12661
13646
  const htmlOutputPath = await writeHtmlReportBundle(report, {
@@ -13102,6 +14087,18 @@ var parseCommentPullRequest = (value) => {
13102
14087
  }
13103
14088
  return parsed;
13104
14089
  };
14090
+ var parsePathInteger = (value, optionName, minimum, maximum) => {
14091
+ if (value === void 0) {
14092
+ return void 0;
14093
+ }
14094
+ const trimmed = value.trim();
14095
+ const parsed = Number.parseInt(trimmed, 10);
14096
+ if (!/^\d+$/.test(trimmed) || !Number.isInteger(parsed) || parsed < minimum || maximum !== void 0 && parsed > maximum) {
14097
+ const range = maximum === void 0 ? `an integer greater than or equal to ${minimum}` : `an integer between ${minimum} and ${maximum}`;
14098
+ throw new PathConfigurationError(`${optionName} must be ${range}`);
14099
+ }
14100
+ return parsed;
14101
+ };
13105
14102
  program.command("owners").alias("ownership").exitOverride().argument("[path]", "path to the repository to audit").option(
13106
14103
  "--codeowners <file>",
13107
14104
  "explicit CODEOWNERS path, relative to the repository root (default: auto-discovery)"
@@ -13169,6 +14166,47 @@ program.command("owners").alias("ownership").exitOverride().argument("[path]", "
13169
14166
  }
13170
14167
  }
13171
14168
  );
14169
+ program.command("path").description("show which files to read first for a target, in order").exitOverride().argument("<target>", "file or directory to read, relative to the repository root").option("--max-steps <count>", "maximum number of files in the reading path (1..25)", "8").addOption(
14170
+ new Option("--format <mode>", "output format: console (default), md or json").choices(["console", "md", "json"]).default("console")
14171
+ ).option("--output <file>", "write the rendered output to a file instead of stdout").option("--window-days <days>", "ownership observation window in days", "90").option(
14172
+ "--include-tests",
14173
+ "include test files as their own steps instead of attaching them to their source"
14174
+ ).option("--ref <ref>", "git ref to read CODEOWNERS and the tracked history from", "HEAD").addOption(
14175
+ new Option(
14176
+ "--log-level <level>",
14177
+ "log verbosity: silent, error, warn, info, debug (logs are written to stderr)"
14178
+ ).choices(["silent", "error", "warn", "info", "debug"]).default(parseLogLevel(process.env["CODESENTINEL_LOG_LEVEL"]))
14179
+ ).action(
14180
+ async (target, options) => {
14181
+ const logger = createStderrLogger(options.logLevel);
14182
+ try {
14183
+ const maxSteps = parsePathInteger(options.maxSteps, "--max-steps", 1, 25) ?? 8;
14184
+ const windowDays = parsePathInteger(options.windowDays, "--window-days", 1) ?? 90;
14185
+ const commandOptions = {
14186
+ maxSteps,
14187
+ format: options.format,
14188
+ ...options.output === void 0 ? {} : { outputPath: options.output },
14189
+ windowDays,
14190
+ ...options.includeTests === true ? { includeTests: true } : {},
14191
+ ref: options.ref
14192
+ };
14193
+ const result = await runPathCommand(target, commandOptions, logger);
14194
+ if (result.outputPath === void 0) {
14195
+ process.stdout.write(`${result.rendered}
14196
+ `);
14197
+ }
14198
+ process.exitCode = result.exitCode;
14199
+ } catch (error) {
14200
+ if (error instanceof PathConfigurationError) {
14201
+ logger.error(error.message);
14202
+ process.exitCode = PATH_EXIT_CODES.invalidTarget;
14203
+ return;
14204
+ }
14205
+ logger.error(error instanceof Error ? error.message : "internal error");
14206
+ process.exitCode = PATH_EXIT_CODES.invalidTarget;
14207
+ }
14208
+ }
14209
+ );
13172
14210
  program.command("comment").exitOverride().description("render or upsert the sticky CodeSentinel pull request summary comment").requiredOption("--input <file>", "CI JSON input written by `codesentinel ci --json-output`").option("--pr <number>", "pull request number to comment on").addOption(
13173
14211
  new Option(
13174
14212
  "--comment-on <mode>",