@getcodesentinel/codesentinel 1.41.0 → 1.42.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
@@ -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,1072 @@ 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
+ fanOutInternal: () => 0,
11301
+ neighbours: () => empty,
11302
+ importsTo: () => false
11303
+ };
11304
+ };
11305
+ var edgeKey2 = (from, to) => `${from}\0${to}`;
11306
+ var createGraphIndex = (graph, universe) => {
11307
+ if (graph === null || graph === void 0) return createEmptyGraphIndex();
11308
+ const pathById = /* @__PURE__ */ new Map();
11309
+ for (const node of graph.nodes) {
11310
+ const existing = pathById.get(node.id);
11311
+ if (existing === void 0 || comparePaths(node.relativePath, existing) < 0) {
11312
+ pathById.set(node.id, node.relativePath);
11313
+ }
11314
+ }
11315
+ const universeSet = new Set(universe);
11316
+ const internalFanIn = /* @__PURE__ */ new Map();
11317
+ const externalFanIn = /* @__PURE__ */ new Map();
11318
+ const internalFanOut = /* @__PURE__ */ new Map();
11319
+ const adjacency = /* @__PURE__ */ new Map();
11320
+ const edges = /* @__PURE__ */ new Set();
11321
+ const addAdjacency = (from, to) => {
11322
+ const fromNeighbours = adjacency.get(from);
11323
+ if (fromNeighbours === void 0) {
11324
+ adjacency.set(from, /* @__PURE__ */ new Set([to]));
11325
+ } else {
11326
+ fromNeighbours.add(to);
11327
+ }
11328
+ };
11329
+ for (const edge of graph.edges) {
11330
+ const from = pathById.get(edge.from);
11331
+ const to = pathById.get(edge.to);
11332
+ if (from === void 0 || to === void 0) continue;
11333
+ edges.add(edgeKey2(from, to));
11334
+ addAdjacency(from, to);
11335
+ addAdjacency(to, from);
11336
+ if (universeSet.has(from)) {
11337
+ internalFanIn.set(to, (internalFanIn.get(to) ?? 0) + 1);
11338
+ } else {
11339
+ externalFanIn.set(to, (externalFanIn.get(to) ?? 0) + 1);
11340
+ }
11341
+ if (universeSet.has(to)) {
11342
+ const targets = internalFanOut.get(from);
11343
+ if (targets === void 0) {
11344
+ internalFanOut.set(from, /* @__PURE__ */ new Set([to]));
11345
+ } else {
11346
+ targets.add(to);
11347
+ }
11348
+ }
11349
+ }
11350
+ return {
11351
+ fanInInternal: (filePath) => internalFanIn.get(filePath) ?? 0,
11352
+ fanInExternal: (filePath) => externalFanIn.get(filePath) ?? 0,
11353
+ fanOutInternal: (filePath) => internalFanOut.get(filePath)?.size ?? 0,
11354
+ neighbours: (filePath) => {
11355
+ const candidates = adjacency.get(filePath);
11356
+ if (candidates === void 0) return [];
11357
+ return [...candidates].filter((candidate) => universeSet.has(candidate)).sort(comparePaths);
11358
+ },
11359
+ importsTo: (from, to) => edges.has(edgeKey2(from, to))
11360
+ };
11361
+ };
11362
+ var ReadingPathError = class extends Error {
11363
+ code;
11364
+ constructor(code, message) {
11365
+ super(message);
11366
+ this.name = "ReadingPathError";
11367
+ this.code = code;
11368
+ }
11369
+ };
11370
+ var DEFAULT_MAX_STEPS = 8;
11371
+ var MIN_MAX_STEPS = 1;
11372
+ var MAX_MAX_STEPS = 25;
11373
+ var EXCLUDED_SEGMENTS = /* @__PURE__ */ new Set([
11374
+ "dist",
11375
+ "__generated__",
11376
+ "node_modules",
11377
+ "vendor",
11378
+ "vendors",
11379
+ "third_party",
11380
+ "third-party"
11381
+ ]);
11382
+ var LOCKFILE_NAMES = /* @__PURE__ */ new Set([
11383
+ "package-lock.json",
11384
+ "npm-shrinkwrap.json",
11385
+ "pnpm-lock.yaml",
11386
+ "yarn.lock",
11387
+ "bun.lock",
11388
+ "bun.lockb"
11389
+ ]);
11390
+ var TEST_FILE_PATTERN = /\.(test|spec)\.[cm]?[jt]sx?$/;
11391
+ var TEST_SUFFIX_PATTERN = /\.(test|spec)(\.[cm]?[jt]sx?)$/;
11392
+ var TEST_SEGMENTS = /* @__PURE__ */ new Set(["__tests__", "__mocks__"]);
11393
+ var basenameOf = (filePath) => {
11394
+ const separatorIndex = filePath.lastIndexOf("/");
11395
+ return separatorIndex === -1 ? filePath : filePath.slice(separatorIndex + 1);
11396
+ };
11397
+ var normalizeTarget = (target) => {
11398
+ let normalized = target.trim().replaceAll("\\", "/");
11399
+ while (normalized.startsWith("./")) {
11400
+ normalized = normalized.slice(2);
11401
+ }
11402
+ while (normalized.endsWith("/")) {
11403
+ normalized = normalized.slice(0, -1);
11404
+ }
11405
+ if (normalized.length === 0) {
11406
+ throw new ReadingPathError("invalid_target", "target must not be empty");
11407
+ }
11408
+ return normalized;
11409
+ };
11410
+ var isExcludedPath = (relativePath) => {
11411
+ if (relativePath.endsWith(".d.ts")) return true;
11412
+ const segments = relativePath.split("/");
11413
+ if (segments.some((segment) => EXCLUDED_SEGMENTS.has(segment))) return true;
11414
+ const basename6 = basenameOf(relativePath);
11415
+ if (/\.gen\.[^./]+$/.test(basename6)) return true;
11416
+ if (LOCKFILE_NAMES.has(basename6)) return true;
11417
+ return false;
11418
+ };
11419
+ var isTestPath2 = (filePath) => {
11420
+ const segments = filePath.split("/");
11421
+ if (segments.some((segment) => TEST_SEGMENTS.has(segment))) return true;
11422
+ return TEST_FILE_PATTERN.test(basenameOf(filePath));
11423
+ };
11424
+ var stripTestSuffix = (testPath) => {
11425
+ const segments = testPath.split("/").filter((segment) => !TEST_SEGMENTS.has(segment));
11426
+ return segments.join("/").replace(TEST_SUFFIX_PATTERN, "$2");
11427
+ };
11428
+ var stripSourceExtension = (filePath) => {
11429
+ const basename6 = basenameOf(filePath);
11430
+ const extensionIndex = basename6.lastIndexOf(".");
11431
+ if (extensionIndex <= 0) return filePath;
11432
+ return filePath.slice(0, filePath.length - (basename6.length - extensionIndex));
11433
+ };
11434
+ var knownPaths = (graph, evolution) => {
11435
+ let paths;
11436
+ if (graph !== null && graph !== void 0) {
11437
+ paths = graph.files.map((file) => file.relativePath);
11438
+ } else if (evolution !== null && evolution !== void 0 && evolution.available) {
11439
+ paths = evolution.files.map((file) => file.filePath);
11440
+ } else {
11441
+ paths = [];
11442
+ }
11443
+ return [...new Set(paths)].sort(comparePaths);
11444
+ };
11445
+ var inferTargetKind = (target, graph, evolution) => {
11446
+ const paths = knownPaths(graph, evolution);
11447
+ if (paths.includes(target)) return "file";
11448
+ if (paths.some((filePath) => filePath.startsWith(`${target}/`))) return "directory";
11449
+ const basename6 = basenameOf(target);
11450
+ const extensionIndex = basename6.lastIndexOf(".");
11451
+ return extensionIndex >= 0 && extensionIndex < basename6.length - 1 ? "file" : "directory";
11452
+ };
11453
+ var graphNeighbours = (graph, target) => {
11454
+ const pathById = /* @__PURE__ */ new Map();
11455
+ for (const node of graph.nodes) {
11456
+ const existing = pathById.get(node.id);
11457
+ if (existing === void 0 || comparePaths(node.relativePath, existing) < 0) {
11458
+ pathById.set(node.id, node.relativePath);
11459
+ }
11460
+ }
11461
+ const neighbours = /* @__PURE__ */ new Set();
11462
+ for (const edge of graph.edges) {
11463
+ const from = pathById.get(edge.from);
11464
+ const to = pathById.get(edge.to);
11465
+ if (from === void 0 || to === void 0) continue;
11466
+ if (from === target) neighbours.add(to);
11467
+ if (to === target) neighbours.add(from);
11468
+ }
11469
+ return [...neighbours].sort(comparePaths);
11470
+ };
11471
+ var resolveUniverse = (target, graph, evolution) => {
11472
+ const targetKind = inferTargetKind(target, graph, evolution);
11473
+ if (targetKind === "file") {
11474
+ const files = /* @__PURE__ */ new Set([target]);
11475
+ let excludedCount2 = 0;
11476
+ if (graph !== null && graph !== void 0) {
11477
+ const graphFiles = new Set(graph.files.map((file) => file.relativePath));
11478
+ for (const neighbour of graphNeighbours(graph, target)) {
11479
+ if (neighbour === target || !graphFiles.has(neighbour)) continue;
11480
+ if (isExcludedPath(neighbour)) {
11481
+ excludedCount2 += 1;
11482
+ continue;
11483
+ }
11484
+ files.add(neighbour);
11485
+ }
11486
+ }
11487
+ return { targetKind, files: [...files].sort(comparePaths), excludedCount: excludedCount2 };
11488
+ }
11489
+ const included = [];
11490
+ let excludedCount = 0;
11491
+ for (const filePath of knownPaths(graph, evolution)) {
11492
+ if (filePath !== target && !filePath.startsWith(`${target}/`)) continue;
11493
+ if (isExcludedPath(filePath)) {
11494
+ excludedCount += 1;
11495
+ continue;
11496
+ }
11497
+ included.push(filePath);
11498
+ }
11499
+ return { targetKind, files: [...new Set(included)].sort(comparePaths), excludedCount };
11500
+ };
11501
+ var pairKey2 = (fileA, fileB) => comparePaths(fileA, fileB) <= 0 ? `${fileA}\0${fileB}` : `${fileB}\0${fileA}`;
11502
+ var createEvolutionIndex = (evolution) => {
11503
+ if (evolution === null || evolution === void 0 || !evolution.available) {
11504
+ return {
11505
+ available: false,
11506
+ churn: () => 0,
11507
+ commits: () => 0,
11508
+ file: () => null,
11509
+ coupling: () => null
11510
+ };
11511
+ }
11512
+ const files = /* @__PURE__ */ new Map();
11513
+ for (const file of evolution.files) {
11514
+ if (!files.has(file.filePath)) files.set(file.filePath, file);
11515
+ }
11516
+ const pairs = /* @__PURE__ */ new Map();
11517
+ for (const pair of evolution.coupling.pairs) {
11518
+ const key = pairKey2(pair.fileA, pair.fileB);
11519
+ const existing = pairs.get(key);
11520
+ if (existing === void 0 || pair.couplingScore > existing.score || pair.couplingScore === existing.score && pair.coChangeCommits > existing.coChangeCommits) {
11521
+ pairs.set(key, {
11522
+ score: pair.couplingScore,
11523
+ coChangeCommits: pair.coChangeCommits
11524
+ });
11525
+ }
11526
+ }
11527
+ return {
11528
+ available: true,
11529
+ churn: (filePath) => files.get(filePath)?.churnTotal ?? 0,
11530
+ commits: (filePath) => files.get(filePath)?.commitCount ?? 0,
11531
+ file: (filePath) => files.get(filePath) ?? null,
11532
+ coupling: (fileA, fileB) => pairs.get(pairKey2(fileA, fileB)) ?? null
11533
+ };
11534
+ };
11535
+ var resolveMaxSteps = (value) => {
11536
+ if (value === void 0 || !Number.isFinite(value)) return DEFAULT_MAX_STEPS;
11537
+ return Math.min(MAX_MAX_STEPS, Math.max(MIN_MAX_STEPS, Math.trunc(value)));
11538
+ };
11539
+ var medianOf = (values) => {
11540
+ if (values.length === 0) return 0;
11541
+ const sorted = [...values].sort((a, b) => a - b);
11542
+ const middle = Math.floor(sorted.length / 2);
11543
+ if (sorted.length % 2 === 1) return sorted[middle] ?? 0;
11544
+ return ((sorted[middle - 1] ?? 0) + (sorted[middle] ?? 0)) / 2;
11545
+ };
11546
+ var topAuthorId = (shares) => {
11547
+ let top = null;
11548
+ for (const share of shares) {
11549
+ if (share.authorId.length === 0) continue;
11550
+ if (top === null || share.commits > top.commits || share.commits === top.commits && comparePaths(share.authorId, top.authorId) < 0) {
11551
+ top = { authorId: share.authorId, commits: share.commits };
11552
+ }
11553
+ }
11554
+ return top?.authorId ?? null;
11555
+ };
11556
+ var pluralized = (count, singular, plural3) => `${count} ${count === 1 ? singular : plural3}`;
11557
+ var importCount = (count) => pluralized(count, "import", "imports");
11558
+ var importerCount = (count) => pluralized(count, "importer", "importers");
11559
+ var commitCount = (count) => pluralized(count, "commit", "commits");
11560
+ var lineCount = (count) => pluralized(count, "line", "lines");
11561
+ var createStats = (steppableFiles, graphIndex, evolution) => {
11562
+ const steppable = [...new Set(steppableFiles)].sort(comparePaths);
11563
+ const steppableSet = new Set(steppable);
11564
+ let maxFanIn = 0;
11565
+ let maxChurn = 0;
11566
+ for (const filePath of steppable) {
11567
+ maxFanIn = Math.max(maxFanIn, graphIndex.fanInInternal(filePath));
11568
+ maxChurn = Math.max(maxChurn, evolution.churn(filePath));
11569
+ }
11570
+ const internalFanIn = (filePath) => graphIndex.fanInInternal(filePath);
11571
+ const fanInNorm = (filePath) => maxFanIn === 0 ? 0 : internalFanIn(filePath) / maxFanIn;
11572
+ const churnNorm = (filePath) => maxChurn === 0 ? 0 : evolution.churn(filePath) / maxChurn;
11573
+ return {
11574
+ steppable,
11575
+ steppableSet,
11576
+ internalFanIn,
11577
+ fanInNorm,
11578
+ churnNorm,
11579
+ medianFanIn: medianOf(steppable.map(internalFanIn))
11580
+ };
11581
+ };
11582
+ var roleFor = (order, filePath, includeTests, internalFanIn, medianFanIn) => {
11583
+ if (order === 1) return "entry";
11584
+ if (includeTests && isTestPath2(filePath)) return "test";
11585
+ if (internalFanIn > medianFanIn) return "core";
11586
+ return "helper";
11587
+ };
11588
+ var INDEX_FILE_NAMES = ["index.ts", "index.tsx", "main.ts", "mod.ts", "public-api.ts"];
11589
+ var chooseEntryByFanIn = (stats, fanIn) => {
11590
+ const firstFile = stats.steppable[0];
11591
+ if (firstFile === void 0) return null;
11592
+ let best = firstFile;
11593
+ let bestFanIn = fanIn(best);
11594
+ for (const filePath of stats.steppable) {
11595
+ const count = fanIn(filePath);
11596
+ if (count > bestFanIn || count === bestFanIn && (filePath.length < best.length || filePath.length === best.length && comparePaths(filePath, best) < 0)) {
11597
+ best = filePath;
11598
+ bestFanIn = count;
11599
+ }
11600
+ }
11601
+ return best;
11602
+ };
11603
+ var chooseShortestPath = (files) => {
11604
+ let best = null;
11605
+ for (const filePath of files) {
11606
+ if (best === null || filePath.length < best.length || filePath.length === best.length && comparePaths(filePath, best) < 0) {
11607
+ best = filePath;
11608
+ }
11609
+ }
11610
+ return best;
11611
+ };
11612
+ var maxOf = (files, value) => {
11613
+ let max = Number.NEGATIVE_INFINITY;
11614
+ for (const filePath of files) {
11615
+ const current = value(filePath);
11616
+ if (current > max) max = current;
11617
+ }
11618
+ return max;
11619
+ };
11620
+ var selectEntry = (stats, graphIndex, targetRoot, seedFile) => {
11621
+ const firstFile = stats.steppable[0];
11622
+ if (firstFile === void 0) return null;
11623
+ if (seedFile !== null && stats.steppableSet.has(seedFile)) {
11624
+ return { filePath: seedFile, rule: "seed" };
11625
+ }
11626
+ if (stats.steppable.length === 1) {
11627
+ return { filePath: firstFile, rule: "single" };
11628
+ }
11629
+ if (targetRoot !== null) {
11630
+ for (const name of INDEX_FILE_NAMES) {
11631
+ const candidate = `${targetRoot}/${name}`;
11632
+ if (stats.steppableSet.has(candidate)) {
11633
+ return { filePath: candidate, rule: "index" };
11634
+ }
11635
+ }
11636
+ }
11637
+ const externalMax = maxOf(stats.steppable, (filePath) => graphIndex.fanInExternal(filePath));
11638
+ if (externalMax > 0) {
11639
+ const externallyTied = stats.steppable.filter(
11640
+ (filePath) => graphIndex.fanInExternal(filePath) === externalMax
11641
+ );
11642
+ if (externallyTied.length > 1) {
11643
+ const fanOutMax = maxOf(externallyTied, (filePath) => graphIndex.fanOutInternal(filePath));
11644
+ if (fanOutMax > 0) {
11645
+ const fanOutTied = externallyTied.filter(
11646
+ (filePath) => graphIndex.fanOutInternal(filePath) === fanOutMax
11647
+ );
11648
+ const fanOutEntry = chooseShortestPath(fanOutTied);
11649
+ if (fanOutEntry !== null) return { filePath: fanOutEntry, rule: "fanout" };
11650
+ }
11651
+ }
11652
+ const externalEntry = chooseShortestPath(externallyTied);
11653
+ if (externalEntry !== null) return { filePath: externalEntry, rule: "external" };
11654
+ }
11655
+ const internalEntry = chooseEntryByFanIn(stats, (filePath) => graphIndex.fanInInternal(filePath));
11656
+ if (internalEntry === null) return null;
11657
+ return { filePath: internalEntry, rule: "internal" };
11658
+ };
11659
+ var entryReason = (selection, steppableCount, graphIndex) => {
11660
+ if (steppableCount === 1) return "the module has a single file";
11661
+ const { filePath, rule } = selection;
11662
+ if (rule === "seed") {
11663
+ const external = graphIndex.fanInExternal(filePath);
11664
+ if (external > 0) {
11665
+ return `external interface: ${importCount(external)} from outside the module`;
11666
+ }
11667
+ const internal2 = graphIndex.fanInInternal(filePath);
11668
+ if (internal2 === 0) {
11669
+ return "no imports in or out of the module; first by path";
11670
+ }
11671
+ return `no external importers; ${importerCount(internal2)}`;
11672
+ }
11673
+ if (rule === "index") {
11674
+ const external = graphIndex.fanInExternal(filePath);
11675
+ return external > 0 ? `entry: package index (${importCount(external)} from outside the module)` : "entry: package index";
11676
+ }
11677
+ if (rule === "external") {
11678
+ return `entry: highest external fan-in (${importCount(graphIndex.fanInExternal(filePath))} from outside the module)`;
11679
+ }
11680
+ if (rule === "fanout") {
11681
+ return `entry: highest internal fan-out (${importCount(graphIndex.fanOutInternal(filePath))} inside the module)`;
11682
+ }
11683
+ const internal = graphIndex.fanInInternal(filePath);
11684
+ if (internal === 0) {
11685
+ return "no imports in or out of the module; first by path";
11686
+ }
11687
+ return `entry: highest internal fan-in (${importerCount(internal)})`;
11688
+ };
11689
+ var chooseGreedyCandidate = (current, candidates, stats, evolution) => {
11690
+ let best = null;
11691
+ for (const filePath of candidates) {
11692
+ const coupling = evolution.coupling(current, filePath);
11693
+ const fanInNorm = stats.fanInNorm(filePath);
11694
+ const churnNorm = stats.churnNorm(filePath);
11695
+ const score = 0.5 * (coupling?.score ?? 0) + 0.3 * fanInNorm + 0.2 * churnNorm;
11696
+ const candidate = { filePath, score, coupling, fanInNorm, churnNorm };
11697
+ if (best === null || score > best.score || score === best.score && comparePaths(filePath, best.filePath) < 0) {
11698
+ best = candidate;
11699
+ }
11700
+ }
11701
+ return best;
11702
+ };
11703
+ var greedyReason = (current, candidate, stats, graphIndex, evolution) => {
11704
+ const couplingContribution = 0.5 * (candidate.coupling?.score ?? 0);
11705
+ const fanInContribution = 0.3 * candidate.fanInNorm;
11706
+ const churnContribution = 0.2 * candidate.churnNorm;
11707
+ if (couplingContribution === 0 && fanInContribution === 0 && churnContribution === 0) {
11708
+ return graphIndex.importsTo(current, candidate.filePath) ? `import of ${current}` : `imported by ${current}`;
11709
+ }
11710
+ if (couplingContribution >= fanInContribution && couplingContribution >= churnContribution && candidate.coupling !== null) {
11711
+ return `most changed together with ${current} (${commitCount(candidate.coupling.coChangeCommits)})`;
11712
+ }
11713
+ if (fanInContribution >= churnContribution) {
11714
+ return `central inside the module: ${importerCount(stats.internalFanIn(candidate.filePath))}`;
11715
+ }
11716
+ return `most churned neighbour (${lineCount(evolution.churn(candidate.filePath))} changed)`;
11717
+ };
11718
+ var chooseExhaustedCandidate = (remaining, stats, evolution) => {
11719
+ let best = null;
11720
+ for (const filePath of remaining) {
11721
+ if (best === null) {
11722
+ best = filePath;
11723
+ continue;
11724
+ }
11725
+ const internal = stats.internalFanIn(filePath);
11726
+ const bestInternal = stats.internalFanIn(best);
11727
+ if (internal > bestInternal) {
11728
+ best = filePath;
11729
+ continue;
11730
+ }
11731
+ if (internal < bestInternal) continue;
11732
+ const churn = evolution.churn(filePath);
11733
+ const bestChurn = evolution.churn(best);
11734
+ if (churn > bestChurn) {
11735
+ best = filePath;
11736
+ continue;
11737
+ }
11738
+ if (churn < bestChurn) continue;
11739
+ if (comparePaths(filePath, best) < 0) best = filePath;
11740
+ }
11741
+ return best;
11742
+ };
11743
+ var exhaustedReason = (filePath, stats, evolution) => {
11744
+ const internal = stats.internalFanIn(filePath);
11745
+ if (internal > 0) {
11746
+ return `central inside the module: ${importerCount(internal)}`;
11747
+ }
11748
+ return `highest churn in the module (${lineCount(evolution.churn(filePath))})`;
11749
+ };
11750
+ var orderGraphReadingPath = (stats, graphIndex, evolution, includeTests, maxSteps, seedFile, targetRoot) => {
11751
+ const firstFile = stats.steppable[0];
11752
+ if (firstFile === void 0) return [];
11753
+ const result = [];
11754
+ const visited = /* @__PURE__ */ new Set();
11755
+ const add = (filePath, reason) => {
11756
+ result.push({
11757
+ filePath,
11758
+ role: roleFor(
11759
+ result.length + 1,
11760
+ filePath,
11761
+ includeTests,
11762
+ stats.internalFanIn(filePath),
11763
+ stats.medianFanIn
11764
+ ),
11765
+ reason
11766
+ });
11767
+ visited.add(filePath);
11768
+ };
11769
+ const selection = selectEntry(stats, graphIndex, targetRoot, seedFile);
11770
+ if (selection === null) return [];
11771
+ add(selection.filePath, entryReason(selection, stats.steppable.length, graphIndex));
11772
+ while (result.length < maxSteps) {
11773
+ const current = result[result.length - 1]?.filePath;
11774
+ if (current === void 0) break;
11775
+ const neighbourCandidates = graphIndex.neighbours(current).filter((filePath) => stats.steppableSet.has(filePath) && !visited.has(filePath));
11776
+ if (neighbourCandidates.length > 0) {
11777
+ const candidate2 = chooseGreedyCandidate(current, neighbourCandidates, stats, evolution);
11778
+ if (candidate2 === null) break;
11779
+ add(candidate2.filePath, greedyReason(current, candidate2, stats, graphIndex, evolution));
11780
+ continue;
11781
+ }
11782
+ const remaining = stats.steppable.filter((filePath) => !visited.has(filePath));
11783
+ const candidate = chooseExhaustedCandidate(remaining, stats, evolution);
11784
+ if (candidate === null) break;
11785
+ add(candidate, exhaustedReason(candidate, stats, evolution));
11786
+ }
11787
+ return result;
11788
+ };
11789
+ var chooseGitOnlyCandidate = (remaining, selected, stats, evolution) => {
11790
+ let best = null;
11791
+ for (const filePath of remaining) {
11792
+ let couplingScore = 0;
11793
+ let coChangeCommits = 0;
11794
+ let otherPath = null;
11795
+ for (const selectedFile of selected) {
11796
+ const coupling = evolution.coupling(filePath, selectedFile.filePath);
11797
+ if (coupling === null || coupling.score <= couplingScore) continue;
11798
+ couplingScore = coupling.score;
11799
+ coChangeCommits = coupling.coChangeCommits;
11800
+ otherPath = selectedFile.filePath;
11801
+ }
11802
+ const churn = evolution.churn(filePath);
11803
+ const score = 0.5 * couplingScore + 0.5 * stats.churnNorm(filePath);
11804
+ const candidate = {
11805
+ filePath,
11806
+ score,
11807
+ churn,
11808
+ couplingScore,
11809
+ coChangeCommits,
11810
+ otherPath
11811
+ };
11812
+ if (best === null || score > best.score || score === best.score && (churn > best.churn || churn === best.churn && comparePaths(filePath, best.filePath) < 0)) {
11813
+ best = candidate;
11814
+ }
11815
+ }
11816
+ return best;
11817
+ };
11818
+ var orderGitOnlyReadingPath = (stats, evolution, includeTests, maxSteps, seedFile) => {
11819
+ const result = [];
11820
+ const visited = /* @__PURE__ */ new Set();
11821
+ const add = (filePath, reason) => {
11822
+ result.push({
11823
+ filePath,
11824
+ role: roleFor(
11825
+ result.length + 1,
11826
+ filePath,
11827
+ includeTests,
11828
+ stats.internalFanIn(filePath),
11829
+ stats.medianFanIn
11830
+ ),
11831
+ reason
11832
+ });
11833
+ visited.add(filePath);
11834
+ };
11835
+ if (seedFile !== null && stats.steppableSet.has(seedFile) && result.length < maxSteps) {
11836
+ add(
11837
+ seedFile,
11838
+ `changed ${lineCount(evolution.churn(seedFile))} in ${commitCount(evolution.commits(seedFile))} (no structural graph)`
11839
+ );
11840
+ }
11841
+ while (result.length < maxSteps) {
11842
+ const remaining = stats.steppable.filter((filePath) => !visited.has(filePath));
11843
+ const candidate = chooseGitOnlyCandidate(remaining, result, stats, evolution);
11844
+ if (candidate === null) break;
11845
+ const couplingContribution = 0.5 * candidate.couplingScore;
11846
+ const churnContribution = 0.5 * stats.churnNorm(candidate.filePath);
11847
+ if (candidate.couplingScore > 0 && couplingContribution >= churnContribution && candidate.otherPath !== null) {
11848
+ add(
11849
+ candidate.filePath,
11850
+ `co-changes with ${candidate.otherPath} (${commitCount(candidate.coChangeCommits)}) and changed ${lineCount(candidate.churn)}`
11851
+ );
11852
+ continue;
11853
+ }
11854
+ add(
11855
+ candidate.filePath,
11856
+ `changed ${lineCount(candidate.churn)} in ${commitCount(evolution.commits(candidate.filePath))} (no structural graph)`
11857
+ );
11858
+ }
11859
+ return result;
11860
+ };
11861
+ var orderReadingPath = (params) => {
11862
+ const stats = createStats(params.steppableFiles, params.graphIndex, params.evolution);
11863
+ const seedFile = params.seedFile ?? null;
11864
+ if (!params.hasGraph) {
11865
+ return orderGitOnlyReadingPath(
11866
+ stats,
11867
+ params.evolution,
11868
+ params.includeTests,
11869
+ params.maxSteps,
11870
+ seedFile
11871
+ );
11872
+ }
11873
+ return orderGraphReadingPath(
11874
+ stats,
11875
+ params.graphIndex,
11876
+ params.evolution,
11877
+ params.includeTests,
11878
+ params.maxSteps,
11879
+ seedFile,
11880
+ params.targetRoot ?? null
11881
+ );
11882
+ };
11883
+ var ownerFor = (filePath, ownership) => {
11884
+ if (ownership === null || !ownership.available) return null;
11885
+ return ownership.files.find((file) => file.filePath === filePath)?.declared ?? [];
11886
+ };
11887
+ var ownershipTopAuthor = (filePath, ownership) => {
11888
+ if (ownership === null || !ownership.available) return null;
11889
+ return ownership.files.find((file) => file.filePath === filePath)?.observed.topAuthorId ?? null;
11890
+ };
11891
+ var observedTopAuthorFor = (filePath, evolution, ownership) => {
11892
+ if (evolution.available) {
11893
+ const file = evolution.file(filePath);
11894
+ return topAuthorId(file?.authorDistributionByCommits ?? []);
11895
+ }
11896
+ return ownershipTopAuthor(filePath, ownership);
11897
+ };
11898
+ var buildPeople = (steppedFiles, evolution) => {
11899
+ const commitsByAuthor = /* @__PURE__ */ new Map();
11900
+ const dominantAuthorByFile = /* @__PURE__ */ new Map();
11901
+ for (const filePath of steppedFiles) {
11902
+ const distribution = evolution.file(filePath)?.authorDistributionByCommits ?? [];
11903
+ for (const share of distribution) {
11904
+ if (share.authorId.length === 0) continue;
11905
+ commitsByAuthor.set(
11906
+ share.authorId,
11907
+ (commitsByAuthor.get(share.authorId) ?? 0) + share.commits
11908
+ );
11909
+ }
11910
+ const top = topAuthorId(distribution);
11911
+ if (top !== null) dominantAuthorByFile.set(filePath, top);
11912
+ }
11913
+ return [...commitsByAuthor.entries()].map(([authorId, commits]) => {
11914
+ const files = steppedFiles.filter((filePath) => dominantAuthorByFile.get(filePath) === authorId).sort(comparePaths);
11915
+ return { authorId, files, commits };
11916
+ }).sort((a, b) => b.commits - a.commits || comparePaths(a.authorId, b.authorId)).slice(0, 3);
11917
+ };
11918
+ var attachTestFiles = (steps, testFiles) => {
11919
+ for (const testPath of testFiles) {
11920
+ const sourcePath = stripTestSuffix(testPath);
11921
+ const sourceStem = stripSourceExtension(sourcePath);
11922
+ const target = steps.find(
11923
+ (step) => step.filePath === sourcePath || stripSourceExtension(step.filePath) === sourceStem
11924
+ );
11925
+ if (target !== void 0) target.testFiles.push(testPath);
11926
+ }
11927
+ for (const step of steps) step.testFiles.sort(comparePaths);
11928
+ };
11929
+ var buildReadingPath = (input) => {
11930
+ const target = normalizeTarget(input.target);
11931
+ const maxSteps = resolveMaxSteps(input.maxSteps);
11932
+ const graph = input.graph ?? null;
11933
+ const evolution = input.evolution ?? null;
11934
+ const ownership = input.ownership ?? null;
11935
+ const includeTests = input.includeTests === true;
11936
+ const universe = resolveUniverse(target, graph, evolution);
11937
+ const graphIndex = createGraphIndex(graph, universe.files);
11938
+ const evolutionIndex = createEvolutionIndex(evolution);
11939
+ const steppableFiles = includeTests ? universe.files : universe.files.filter((filePath) => !isTestPath2(filePath));
11940
+ const ordered = orderReadingPath({
11941
+ steppableFiles,
11942
+ graphIndex,
11943
+ evolution: evolutionIndex,
11944
+ hasGraph: graph !== null,
11945
+ includeTests,
11946
+ maxSteps,
11947
+ seedFile: universe.targetKind === "file" ? target : null,
11948
+ targetRoot: universe.targetKind === "directory" ? target : null
11949
+ });
11950
+ const steps = ordered.map((entry) => ({
11951
+ order: 0,
11952
+ filePath: entry.filePath,
11953
+ role: entry.role,
11954
+ reason: entry.reason,
11955
+ owner: ownerFor(entry.filePath, ownership),
11956
+ observedTopAuthor: observedTopAuthorFor(entry.filePath, evolutionIndex, ownership),
11957
+ commits: evolutionIndex.commits(entry.filePath),
11958
+ churn: evolutionIndex.churn(entry.filePath),
11959
+ fanInInternal: graphIndex.fanInInternal(entry.filePath),
11960
+ testFiles: []
11961
+ }));
11962
+ if (!includeTests) {
11963
+ const testFiles = universe.files.filter((filePath) => isTestPath2(filePath)).sort(comparePaths);
11964
+ attachTestFiles(steps, testFiles);
11965
+ }
11966
+ steps.forEach((step, index) => {
11967
+ step.order = index + 1;
11968
+ });
11969
+ const truncated = steps.length === maxSteps && steppableFiles.length > steps.length;
11970
+ const warnings = [];
11971
+ if (graph === null) {
11972
+ warnings.push("no structural graph available: ordered by churn and change coupling");
11973
+ }
11974
+ if (!evolutionIndex.available) {
11975
+ warnings.push("repository evolution is unavailable: churn signals are zero");
11976
+ }
11977
+ if (universe.targetKind === "file" && graph !== null && !knownPaths(graph, evolution).includes(target)) {
11978
+ warnings.push(`target file ${target} has no graph data`);
11979
+ }
11980
+ if (universe.excludedCount > 0) {
11981
+ warnings.push(
11982
+ `excluded ${universe.excludedCount} generated, vendored or lock file(s) from the target`
11983
+ );
11984
+ }
11985
+ if (universe.files.length === 0) {
11986
+ warnings.push(`no files found under ${target}`);
11987
+ }
11988
+ if (truncated) {
11989
+ warnings.push(`showing ${maxSteps} of ${steppableFiles.length} files (truncated)`);
11990
+ }
11991
+ const people = buildPeople(
11992
+ steps.map((step) => step.filePath),
11993
+ evolutionIndex
11994
+ );
11995
+ return {
11996
+ target,
11997
+ targetKind: universe.targetKind,
11998
+ steps,
11999
+ people,
12000
+ commands: [],
12001
+ warnings,
12002
+ truncated
12003
+ };
12004
+ };
12005
+
12006
+ // src/application/format-path-output.ts
12007
+ var PATH_SCHEMA_VERSION = "codesentinel.path.v1";
12008
+ var toPayloadOwner = (owner) => {
12009
+ if (owner.kind === "user") return { kind: "user", handle: owner.handle };
12010
+ if (owner.kind === "team") return { kind: "team", org: owner.org, slug: owner.slug };
12011
+ return { kind: "email", address: owner.address };
12012
+ };
12013
+ var buildPathPayload = (path) => ({
12014
+ schemaVersion: PATH_SCHEMA_VERSION,
12015
+ target: path.target,
12016
+ targetKind: path.targetKind,
12017
+ steps: path.steps.map((step) => ({
12018
+ order: step.order,
12019
+ filePath: step.filePath,
12020
+ role: step.role,
12021
+ reason: step.reason,
12022
+ owner: step.owner === null ? null : step.owner.map(toPayloadOwner),
12023
+ observedTopAuthor: step.observedTopAuthor,
12024
+ commits: step.commits,
12025
+ churn: step.churn,
12026
+ fanInInternal: step.fanInInternal,
12027
+ testFiles: [...step.testFiles]
12028
+ })),
12029
+ people: path.people.map((person) => ({
12030
+ authorId: person.authorId,
12031
+ files: [...person.files],
12032
+ commits: person.commits
12033
+ })),
12034
+ commands: [...path.commands],
12035
+ warnings: [...path.warnings],
12036
+ truncated: path.truncated
12037
+ });
12038
+ var formatOwner = (owner) => {
12039
+ if (owner.kind === "user") return `@${owner.handle}`;
12040
+ if (owner.kind === "team") return `@${owner.org}/${owner.slug}`;
12041
+ return owner.address;
12042
+ };
12043
+ var formatOwnerText = (owner) => {
12044
+ if (owner === null) return "not analysed (no CODEOWNERS)";
12045
+ if (owner.length === 0) return "none declared";
12046
+ return owner.map(formatOwner).join(", ");
12047
+ };
12048
+ var formatStepsCount = (count) => `${count} ${count === 1 ? "step" : "steps"}`;
12049
+ var appendConsoleSection = (lines, title, items) => {
12050
+ if (items.length === 0) return;
12051
+ lines.push("");
12052
+ lines.push(title);
12053
+ for (const item of items) {
12054
+ lines.push(` - ${item}`);
12055
+ }
12056
+ };
12057
+ var renderConsole2 = (path) => {
12058
+ const lines = [];
12059
+ lines.push(`Reading path: ${path.target} (${path.targetKind})`);
12060
+ lines.push(
12061
+ `${formatStepsCount(path.steps.length)}${path.truncated === true ? " (truncated)" : ""}`
12062
+ );
12063
+ lines.push("");
12064
+ if (path.steps.length === 0) {
12065
+ lines.push("No files to read.");
12066
+ } else {
12067
+ for (const step of path.steps) {
12068
+ lines.push(` ${step.order}. ${step.filePath} [${step.role}]`);
12069
+ lines.push(` ${step.reason}`);
12070
+ lines.push(
12071
+ ` owner: ${formatOwnerText(step.owner)} \xB7 observed: ${step.observedTopAuthor ?? "unknown"} \xB7 commits ${step.commits} \xB7 churn ${step.churn} \xB7 fan-in ${step.fanInInternal}`
12072
+ );
12073
+ if (step.testFiles.length > 0) {
12074
+ lines.push(` tests: ${step.testFiles.join(", ")}`);
12075
+ }
12076
+ }
12077
+ }
12078
+ appendConsoleSection(
12079
+ lines,
12080
+ "People to ask",
12081
+ path.people.map(
12082
+ (person) => `${person.authorId} (${person.commits} commits): ${person.files.length > 0 ? person.files.join(", ") : "no single file"}`
12083
+ )
12084
+ );
12085
+ appendConsoleSection(
12086
+ lines,
12087
+ "Suggested commands (not discovered, not run)",
12088
+ path.commands.map((command) => command)
12089
+ );
12090
+ appendConsoleSection(
12091
+ lines,
12092
+ "Warnings",
12093
+ path.warnings.map((warning) => warning)
12094
+ );
12095
+ return lines.join("\n");
12096
+ };
12097
+ var escapeTableCell2 = (value) => value.replace(/\|/g, "\\|");
12098
+ var renderMarkdownTable2 = (header, rows) => {
12099
+ const lines = [`| ${header.join(" | ")} |`, `| ${header.map(() => "---").join(" | ")} |`];
12100
+ for (const row of rows) {
12101
+ lines.push(`| ${row.map(escapeTableCell2).join(" | ")} |`);
12102
+ }
12103
+ return lines;
12104
+ };
12105
+ var formatMarkdownObserved = (value) => value === null ? "unknown" : `\`${value}\``;
12106
+ var formatMarkdownTests = (testFiles) => testFiles.length === 0 ? "none" : testFiles.map((file) => `\`${file}\``).join(", ");
12107
+ var appendMarkdownSection = (lines, title, items) => {
12108
+ if (items.length === 0) return;
12109
+ lines.push("");
12110
+ lines.push(title);
12111
+ lines.push("");
12112
+ for (const item of items) {
12113
+ lines.push(`- ${item}`);
12114
+ }
12115
+ };
12116
+ var renderMarkdown3 = (path) => {
12117
+ const lines = [];
12118
+ lines.push(`## Reading path: \`${path.target}\``);
12119
+ lines.push("");
12120
+ lines.push(`- target kind: \`${path.targetKind}\``);
12121
+ lines.push(`- steps: ${path.steps.length}${path.truncated === true ? " (truncated)" : ""}`);
12122
+ lines.push("");
12123
+ if (path.steps.length === 0) {
12124
+ lines.push("No files to read.");
12125
+ } else {
12126
+ for (const step of path.steps) {
12127
+ lines.push(`${step.order}. **\`${step.filePath}\`** \u2014 \`${step.role}\``);
12128
+ lines.push(` - ${step.reason}`);
12129
+ lines.push(
12130
+ ` - owner: ${formatOwnerText(step.owner)} \xB7 observed: ${formatMarkdownObserved(step.observedTopAuthor)} \xB7 commits \`${step.commits}\` \xB7 churn \`${step.churn}\` \xB7 fan-in \`${step.fanInInternal}\``
12131
+ );
12132
+ if (step.testFiles.length > 0) {
12133
+ lines.push(` - tests: ${formatMarkdownTests(step.testFiles)}`);
12134
+ }
12135
+ }
12136
+ lines.push("");
12137
+ lines.push("### Steps");
12138
+ lines.push("");
12139
+ lines.push(
12140
+ ...renderMarkdownTable2(
12141
+ [
12142
+ "#",
12143
+ "File",
12144
+ "Role",
12145
+ "Commits",
12146
+ "Churn",
12147
+ "Fan-in",
12148
+ "Observed author",
12149
+ "Declared owner",
12150
+ "Tests"
12151
+ ],
12152
+ path.steps.map((step) => [
12153
+ `${step.order}`,
12154
+ `\`${step.filePath}\``,
12155
+ `\`${step.role}\``,
12156
+ `${step.commits}`,
12157
+ `${step.churn}`,
12158
+ `${step.fanInInternal}`,
12159
+ formatMarkdownObserved(step.observedTopAuthor),
12160
+ formatOwnerText(step.owner),
12161
+ formatMarkdownTests(step.testFiles)
12162
+ ])
12163
+ )
12164
+ );
12165
+ }
12166
+ appendMarkdownSection(
12167
+ lines,
12168
+ "### People to ask",
12169
+ path.people.map(
12170
+ (person) => `\`${person.authorId}\` (${person.commits} commits): ${person.files.length > 0 ? person.files.map((file) => `\`${file}\``).join(", ") : "no single file"}`
12171
+ )
12172
+ );
12173
+ appendMarkdownSection(
12174
+ lines,
12175
+ "### Suggested commands (not discovered, not run)",
12176
+ path.commands.map((command) => `\`${command}\``)
12177
+ );
12178
+ appendMarkdownSection(
12179
+ lines,
12180
+ "### Warnings",
12181
+ path.warnings.map((warning) => warning)
12182
+ );
12183
+ return lines.join("\n");
12184
+ };
12185
+ var formatPathOutput = (path, format) => {
12186
+ if (format === "json") {
12187
+ return JSON.stringify(buildPathPayload(path), null, 2);
12188
+ }
12189
+ return format === "md" ? renderMarkdown3(path) : renderConsole2(path);
12190
+ };
12191
+
12192
+ // src/application/run-path-command.ts
12193
+ var PATH_EXIT_CODES = {
12194
+ ok: 0,
12195
+ invalidTarget: 2
12196
+ };
12197
+ var PathConfigurationError = class extends Error {
12198
+ constructor(message) {
12199
+ super(message);
12200
+ this.name = "PathConfigurationError";
12201
+ }
12202
+ };
12203
+ var DEFAULT_PATH_WINDOW_DAYS = DEFAULT_OWNERS_WINDOW_DAYS;
12204
+ var resolveRelativeTarget = (repositoryPath, target, invocationCwd) => {
12205
+ const absoluteTarget = resolve9(invocationCwd, target);
12206
+ const relativeTarget = relative4(repositoryPath, absoluteTarget);
12207
+ if (relativeTarget === "" || relativeTarget === ".") {
12208
+ throw new PathConfigurationError(
12209
+ `target "${target}" is the repository root; pass a module directory or a file.`
12210
+ );
12211
+ }
12212
+ if (relativeTarget.startsWith("..") || isAbsolute2(relativeTarget)) {
12213
+ throw new PathConfigurationError(
12214
+ `target "${target}" is outside the repository at "${repositoryPath}".`
12215
+ );
12216
+ }
12217
+ if (!existsSync6(absoluteTarget)) {
12218
+ throw new PathConfigurationError(`target "${target}" does not exist in the repository.`);
12219
+ }
12220
+ const stats = statSync3(absoluteTarget);
12221
+ if (!stats.isFile() && !stats.isDirectory()) {
12222
+ throw new PathConfigurationError(`target "${target}" is not a regular file or directory.`);
12223
+ }
12224
+ return normalizeRepositoryPath(relativeTarget);
12225
+ };
12226
+ var hasCodeownersFile = (repositoryPath) => CODEOWNERS_CANDIDATE_PATHS.some((candidate) => existsSync6(join12(repositoryPath, candidate)));
12227
+ var resolveOwnership = async (repositoryPath, ref, windowDays, logger) => {
12228
+ if (!hasCodeownersFile(repositoryPath)) {
12229
+ logger.info("ownership skipped: no CODEOWNERS file found");
12230
+ return {
12231
+ ownership: null,
12232
+ warnings: ["no CODEOWNERS file found: declared owners are not reported"]
12233
+ };
12234
+ }
12235
+ let audit;
12236
+ try {
12237
+ const result = await buildOwnershipAudit(repositoryPath, { ref, windowDays }, logger);
12238
+ audit = result.audit;
12239
+ } catch (error) {
12240
+ if (error instanceof OwnersConfigurationError) {
12241
+ throw new PathConfigurationError(error.message);
12242
+ }
12243
+ throw error;
12244
+ }
12245
+ if (!audit.available) {
12246
+ logger.info(`ownership unavailable: CODEOWNERS was not found at ${ref}`);
12247
+ return {
12248
+ ownership: audit,
12249
+ warnings: [`CODEOWNERS was not found at ${ref}: declared owners are not reported`]
12250
+ };
12251
+ }
12252
+ logger.info(`ownership report: CODEOWNERS found for ${audit.files.length} files`);
12253
+ return { ownership: audit, warnings: [] };
12254
+ };
12255
+ var readTestScript = async (repositoryPath) => {
12256
+ let raw;
12257
+ try {
12258
+ raw = await readFile8(join12(repositoryPath, "package.json"), "utf8");
12259
+ } catch {
12260
+ return null;
12261
+ }
12262
+ let parsed;
12263
+ try {
12264
+ parsed = JSON.parse(raw);
12265
+ } catch {
12266
+ return null;
12267
+ }
12268
+ if (typeof parsed !== "object" || parsed === null) return null;
12269
+ const scripts = parsed.scripts;
12270
+ if (typeof scripts !== "object" || scripts === null) return null;
12271
+ const test = scripts.test;
12272
+ if (typeof test !== "string" || test.trim().length === 0) return null;
12273
+ return test;
12274
+ };
12275
+ var resolveTestCommand = (repositoryPath) => {
12276
+ if (existsSync6(join12(repositoryPath, "pnpm-lock.yaml"))) return "pnpm test";
12277
+ if (existsSync6(join12(repositoryPath, "yarn.lock"))) return "yarn test";
12278
+ if (existsSync6(join12(repositoryPath, "bun.lockb")) || existsSync6(join12(repositoryPath, "bun.lock"))) {
12279
+ return "bun test";
12280
+ }
12281
+ return "npm test";
12282
+ };
12283
+ var collectSuggestedCommands = async (repositoryPath) => {
12284
+ const testScript = await readTestScript(repositoryPath);
12285
+ if (testScript === null) return [];
12286
+ const command = resolveTestCommand(repositoryPath);
12287
+ return command === null ? [] : [command];
12288
+ };
12289
+ var runPathCommand = async (target, options = {}, logger = createSilentLogger()) => {
12290
+ const invocationCwd = process.env["INIT_CWD"] ?? process.cwd();
12291
+ const ref = options.ref ?? DEFAULT_OWNERS_REF;
12292
+ const windowDays = options.windowDays ?? DEFAULT_PATH_WINDOW_DAYS;
12293
+ const format = options.format ?? "console";
12294
+ const maxSteps = options.maxSteps ?? DEFAULT_MAX_STEPS;
12295
+ const context = readRepositoryContext(invocationCwd, ref);
12296
+ if (context === null) {
12297
+ throw new PathConfigurationError(
12298
+ `"path" requires a git work tree and a ref that resolves to a commit: could not resolve "${ref}" from "${invocationCwd}".`
12299
+ );
12300
+ }
12301
+ logger.info(`reading path repository: ${context.repositoryPath} at ${ref}`);
12302
+ const relativeTarget = resolveRelativeTarget(context.repositoryPath, target, invocationCwd);
12303
+ logger.info(`reading path target: ${relativeTarget}`);
12304
+ const { structural, evolution } = collectStructuralEvolutionInputs(
12305
+ context.repositoryPath,
12306
+ "likely_merge",
12307
+ { recentWindowDays: windowDays },
12308
+ logger
12309
+ );
12310
+ const ownership = await resolveOwnership(context.repositoryPath, ref, windowDays, logger);
12311
+ let readingPath;
12312
+ try {
12313
+ readingPath = buildReadingPath({
12314
+ target: relativeTarget,
12315
+ graph: structural,
12316
+ evolution,
12317
+ ownership: ownership.ownership,
12318
+ maxSteps,
12319
+ includeTests: options.includeTests === true
12320
+ });
12321
+ } catch (error) {
12322
+ if (error instanceof ReadingPathError) {
12323
+ throw new PathConfigurationError(error.message);
12324
+ }
12325
+ throw error;
12326
+ }
12327
+ const commands = await collectSuggestedCommands(context.repositoryPath);
12328
+ const completedPath = {
12329
+ ...readingPath,
12330
+ commands,
12331
+ warnings: [...readingPath.warnings, ...ownership.warnings]
12332
+ };
12333
+ logger.debug(
12334
+ `reading path built: steps=${completedPath.steps.length}, people=${completedPath.people.length}, commands=${completedPath.commands.length}, truncated=${completedPath.truncated}`
12335
+ );
12336
+ logger.info(`reading path built: ${completedPath.steps.length} steps`);
12337
+ const rendered = formatPathOutput(completedPath, format);
12338
+ const absoluteOutputPath = options.outputPath === void 0 ? void 0 : resolve9(invocationCwd, options.outputPath);
12339
+ if (absoluteOutputPath !== void 0) {
12340
+ await writeFile8(absoluteOutputPath, `${rendered}
12341
+ `, "utf8");
12342
+ logger.info(`reading path output written: ${absoluteOutputPath}`);
12343
+ }
12344
+ return {
12345
+ readingPath: completedPath,
12346
+ rendered,
12347
+ exitCode: PATH_EXIT_CODES.ok,
12348
+ repositoryPath: context.repositoryPath,
12349
+ relativeTarget,
12350
+ ...absoluteOutputPath === void 0 ? {} : { outputPath: absoluteOutputPath }
12351
+ };
12352
+ };
12353
+
11278
12354
  // src/application/format-pr-comment.ts
11279
12355
  var PR_COMMENT_MARKER = "<!-- codesentinel:summary -->";
11280
12356
  var PrCommentConfigurationError = class extends Error {
@@ -11335,7 +12411,7 @@ var formatOffenderOwners = (declared) => {
11335
12411
  return owners.length === 0 ? "\u2014" : owners.join(", ");
11336
12412
  };
11337
12413
  var readEvidence = (status, observed, criticality) => {
11338
- const topAuthorId = observed === null ? null : readString(observed["topAuthorId"]);
12414
+ const topAuthorId2 = observed === null ? null : readString(observed["topAuthorId"]);
11339
12415
  switch (status) {
11340
12416
  case "unowned-critical": {
11341
12417
  const fanIn = criticality === null ? null : readFiniteNumber(criticality["fanIn"]);
@@ -11344,11 +12420,11 @@ var readEvidence = (status, observed, criticality) => {
11344
12420
  return `fan-in ${fanIn ?? "n/a"}, ${commits ?? 0} commits, ${authors ?? 0} authors`;
11345
12421
  }
11346
12422
  case "ghosted":
11347
- return `no commits in the window, top author ${topAuthorId ?? "unknown"}`;
12423
+ return `no commits in the window, top author ${topAuthorId2 ?? "unknown"}`;
11348
12424
  case "drifted": {
11349
12425
  const share = observed === null ? null : readFiniteNumber(observed["topAuthorShare"]);
11350
12426
  const renderedShare = share === null ? "n/a" : `${Math.round(share * 100)}%`;
11351
- return `top author ${topAuthorId ?? "unknown"} (${renderedShare})`;
12427
+ return `top author ${topAuthorId2 ?? "unknown"} (${renderedShare})`;
11352
12428
  }
11353
12429
  default:
11354
12430
  return "ownership cannot be verified offline";
@@ -11401,8 +12477,8 @@ var formatSigned = (value) => {
11401
12477
  var formatCount = (value) => value === null ? "n/a" : String(value);
11402
12478
  var formatPercent2 = (value) => value === null ? "n/a" : `${String(value)}%`;
11403
12479
  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(" | ")} |`;
12480
+ var escapeTableCell3 = (value) => value.replace(/\|/g, "\\|");
12481
+ var renderTableRow = (cells) => `| ${cells.map(escapeTableCell3).join(" | ")} |`;
11406
12482
  var parsePrCommentInput = (raw) => {
11407
12483
  if (!isRecord2(raw)) {
11408
12484
  return invalidInput("root", "an object");
@@ -11537,7 +12613,7 @@ var renderPrCommentBody = (input) => {
11537
12613
  };
11538
12614
 
11539
12615
  // src/application/run-comment-command.ts
11540
- import { readFile as readFile8, writeFile as writeFile8 } from "fs/promises";
12616
+ import { readFile as readFile9, writeFile as writeFile9 } from "fs/promises";
11541
12617
 
11542
12618
  // src/application/github-pr-comment-client.ts
11543
12619
  var DEFAULT_API_URL = "https://api.github.com";
@@ -11656,7 +12732,7 @@ var COMMENT_EXIT_CODES = {
11656
12732
  invalidConfiguration: 2
11657
12733
  };
11658
12734
  var readCiJson = async (inputPath) => {
11659
- const raw = await readFile8(inputPath, "utf8");
12735
+ const raw = await readFile9(inputPath, "utf8");
11660
12736
  try {
11661
12737
  return JSON.parse(raw);
11662
12738
  } catch {
@@ -11674,7 +12750,7 @@ var runCommentCommand = async (options, logger = createSilentLogger()) => {
11674
12750
  const body = renderPrCommentBody(input);
11675
12751
  const mode = options.mode ?? "change";
11676
12752
  if (options.outputPath !== void 0) {
11677
- await writeFile8(options.outputPath, `${body}
12753
+ await writeFile9(options.outputPath, `${body}
11678
12754
  `, "utf8");
11679
12755
  logger.info(`comment body written: ${options.outputPath}`);
11680
12756
  }
@@ -11731,7 +12807,7 @@ var runCommentCommand = async (options, logger = createSilentLogger()) => {
11731
12807
  };
11732
12808
 
11733
12809
  // src/application/run-trend-command.ts
11734
- import { writeFile as writeFile9 } from "fs/promises";
12810
+ import { writeFile as writeFile10 } from "fs/promises";
11735
12811
 
11736
12812
  // src/application/format-trend-output.ts
11737
12813
  var TREND_SCHEMA_VERSION = "codesentinel.trend.v1";
@@ -11804,7 +12880,7 @@ var renderAlignedRow = (cells, widths) => cells.map((cell, index) => {
11804
12880
  const width = widths[index] ?? cell.length;
11805
12881
  return index < 2 ? cell.padEnd(width) : cell.padStart(width);
11806
12882
  }).join(" ");
11807
- var renderConsole2 = (report) => {
12883
+ var renderConsole3 = (report) => {
11808
12884
  const rows = report.series.map(pointCells);
11809
12885
  const widths = TREND_HEADERS.map(
11810
12886
  (header, index) => Math.max(header.length, ...rows.map((row) => (row[index] ?? "").length))
@@ -11824,15 +12900,15 @@ var renderConsole2 = (report) => {
11824
12900
  appendWarnings2(lines, report.warnings);
11825
12901
  return lines.join("\n");
11826
12902
  };
11827
- var escapeTableCell3 = (value) => value.replace(/\|/g, "\\|");
11828
- var renderMarkdownTable2 = (header, rows) => {
12903
+ var escapeTableCell4 = (value) => value.replace(/\|/g, "\\|");
12904
+ var renderMarkdownTable3 = (header, rows) => {
11829
12905
  const lines = [`| ${header.join(" | ")} |`, `| ${header.map(() => "---").join(" | ")} |`];
11830
12906
  for (const row of rows) {
11831
- lines.push(`| ${row.map(escapeTableCell3).join(" | ")} |`);
12907
+ lines.push(`| ${row.map(escapeTableCell4).join(" | ")} |`);
11832
12908
  }
11833
12909
  return lines;
11834
12910
  };
11835
- var renderMarkdown3 = (report) => {
12911
+ var renderMarkdown4 = (report) => {
11836
12912
  const lines = ["# Snapshot trend", ""];
11837
12913
  lines.push(`- snapshots: ${report.series.length}`);
11838
12914
  const first = report.series[0];
@@ -11841,7 +12917,7 @@ var renderMarkdown3 = (report) => {
11841
12917
  lines.push(`- window: ${formatDate(first.generatedAt)} \u2192 ${formatDate(last.generatedAt)}`);
11842
12918
  }
11843
12919
  lines.push("");
11844
- lines.push(...renderMarkdownTable2(TREND_HEADERS, report.series.map(pointCells)));
12920
+ lines.push(...renderMarkdownTable3(TREND_HEADERS, report.series.map(pointCells)));
11845
12921
  if (report.deltas === null) {
11846
12922
  lines.push("");
11847
12923
  lines.push("not enough history for a trend");
@@ -11863,12 +12939,12 @@ var formatTrendOutput = (report, format) => {
11863
12939
  if (format === "json") {
11864
12940
  return JSON.stringify(report, null, 2);
11865
12941
  }
11866
- return format === "md" ? renderMarkdown3(report) : renderConsole2(report);
12942
+ return format === "md" ? renderMarkdown4(report) : renderConsole3(report);
11867
12943
  };
11868
12944
 
11869
12945
  // 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";
12946
+ import { glob, readFile as readFile10, readdir as readdir2, stat as stat3 } from "fs/promises";
12947
+ import { basename as basename5, join as join13, resolve as resolve10 } from "path";
11872
12948
  var TrendConfigurationError = class extends Error {
11873
12949
  constructor(message) {
11874
12950
  super(message);
@@ -11966,7 +13042,7 @@ var pathExists = async (absolutePath) => {
11966
13042
  };
11967
13043
  var discoverSnapshotFiles = async (from) => {
11968
13044
  const cwd = process.env["INIT_CWD"] ?? process.cwd();
11969
- const resolved = resolve9(cwd, from);
13045
+ const resolved = resolve10(cwd, from);
11970
13046
  const exists = await pathExists(resolved);
11971
13047
  if (exists) {
11972
13048
  const info = await stat3(resolved);
@@ -11974,7 +13050,7 @@ var discoverSnapshotFiles = async (from) => {
11974
13050
  const entries = await readdir2(resolved, { withFileTypes: true }).catch(() => {
11975
13051
  throw new TrendConfigurationError(`--from directory is not readable: ${from}`);
11976
13052
  });
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));
13053
+ 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
13054
  if (files2.length === 0) {
11979
13055
  throw new TrendConfigurationError(`no snapshot JSON files found in ${from}`);
11980
13056
  }
@@ -11995,7 +13071,7 @@ var discoverSnapshotFiles = async (from) => {
11995
13071
  }
11996
13072
  const files = [];
11997
13073
  for (const match of matches.sort(compareText4)) {
11998
- const absolutePath = resolve9(cwd, match);
13074
+ const absolutePath = resolve10(cwd, match);
11999
13075
  try {
12000
13076
  const info = await stat3(absolutePath);
12001
13077
  if (!info.isFile() || !absolutePath.endsWith(".json")) {
@@ -12066,7 +13142,7 @@ var readTrendSnapshots = async (options) => {
12066
13142
  for (const file of files) {
12067
13143
  let content;
12068
13144
  try {
12069
- content = await readFile9(file.path, "utf8");
13145
+ content = await readFile10(file.path, "utf8");
12070
13146
  } catch {
12071
13147
  warnings.push(`skipped ${file.name}: invalid JSON`);
12072
13148
  continue;
@@ -12111,7 +13187,7 @@ var runTrendCommand = async (options, logger = createSilentLogger()) => {
12111
13187
  const rendered = formatTrendOutput(report, format);
12112
13188
  logger.debug(`trend series: ${report.series.length} snapshot(s)`);
12113
13189
  if (options.outputPath !== void 0) {
12114
- await writeFile9(options.outputPath, `${rendered}
13190
+ await writeFile10(options.outputPath, `${rendered}
12115
13191
  `, "utf8");
12116
13192
  logger.info(`trend output written: ${options.outputPath}`);
12117
13193
  }
@@ -12124,8 +13200,8 @@ var runTrendCommand = async (options, logger = createSilentLogger()) => {
12124
13200
  };
12125
13201
 
12126
13202
  // 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";
13203
+ import { access, mkdir as mkdir4, writeFile as writeFile11 } from "fs/promises";
13204
+ import { dirname as dirname3, join as join14, resolve as resolve11 } from "path";
12129
13205
  var CODESENTINEL_WORKFLOW_PATH = ".github/workflows/codesentinel.yml";
12130
13206
  var CODESENTINEL_OWNERS_PATH = ".codesentinel/owners.json";
12131
13207
  var CODESENTINEL_WORKFLOW_TEMPLATE = `name: CodeSentinel
@@ -12286,7 +13362,7 @@ var fileExists = async (absolutePath) => {
12286
13362
  };
12287
13363
  var anyFileExists = async (targetPath, candidates) => {
12288
13364
  for (const candidate of candidates) {
12289
- if (await fileExists(join13(targetPath, candidate))) {
13365
+ if (await fileExists(join14(targetPath, candidate))) {
12290
13366
  return true;
12291
13367
  }
12292
13368
  }
@@ -12294,16 +13370,16 @@ var anyFileExists = async (targetPath, candidates) => {
12294
13370
  };
12295
13371
  var resolveTargetPath3 = (inputPath) => {
12296
13372
  const invocationCwd = process.env["INIT_CWD"] ?? process.cwd();
12297
- return resolve10(invocationCwd, inputPath ?? ".");
13373
+ return resolve11(invocationCwd, inputPath ?? ".");
12298
13374
  };
12299
13375
  var runInitCommand = async (inputPath, options = {}) => {
12300
13376
  const targetPath = resolveTargetPath3(inputPath);
12301
13377
  const ci = options.ci ?? "github";
12302
- const hasCodeownersFile = await anyFileExists(targetPath, CODEOWNERS_CANDIDATES);
13378
+ const hasCodeownersFile2 = await anyFileExists(targetPath, CODEOWNERS_CANDIDATES);
12303
13379
  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)),
13380
+ hasCodeownersFile: hasCodeownersFile2,
13381
+ workflowExists: ci === "github" && await fileExists(join14(targetPath, CODESENTINEL_WORKFLOW_PATH)),
13382
+ ownersFileExists: hasCodeownersFile2 && await fileExists(join14(targetPath, CODESENTINEL_OWNERS_PATH)),
12307
13383
  options: { ...options, ci }
12308
13384
  });
12309
13385
  if (options.dryRun !== true) {
@@ -12311,9 +13387,9 @@ var runInitCommand = async (inputPath, options = {}) => {
12311
13387
  if (entry.status !== "created" && entry.status !== "updated") {
12312
13388
  continue;
12313
13389
  }
12314
- const absolutePath = join13(targetPath, entry.path);
13390
+ const absolutePath = join14(targetPath, entry.path);
12315
13391
  await mkdir4(dirname3(absolutePath), { recursive: true });
12316
- await writeFile10(absolutePath, entry.content ?? "", "utf8");
13392
+ await writeFile11(absolutePath, entry.content ?? "", "utf8");
12317
13393
  }
12318
13394
  }
12319
13395
  return {
@@ -12326,7 +13402,7 @@ var runInitCommand = async (inputPath, options = {}) => {
12326
13402
 
12327
13403
  // src/index.ts
12328
13404
  var program = new Command();
12329
- var packageJsonPath = resolve11(dirname4(fileURLToPath2(import.meta.url)), "../package.json");
13405
+ var packageJsonPath = resolve12(dirname4(fileURLToPath2(import.meta.url)), "../package.json");
12330
13406
  var { version } = JSON.parse(readFileSync4(packageJsonPath, "utf8"));
12331
13407
  var parseRecentWindowDays = (value) => {
12332
13408
  const parsed = Number.parseInt(value, 10);
@@ -12650,12 +13726,12 @@ program.command("run").argument("[path]", "path to the project to analyze").addO
12650
13726
  ...options.trace === true ? { trace: explain.trace } : {}
12651
13727
  });
12652
13728
  if (options.snapshot !== void 0) {
12653
- await writeFile11(options.snapshot, JSON.stringify(snapshot, null, 2), "utf8");
13729
+ await writeFile12(options.snapshot, JSON.stringify(snapshot, null, 2), "utf8");
12654
13730
  logger.info(`snapshot written: ${options.snapshot}`);
12655
13731
  }
12656
13732
  const report = options.compare === void 0 ? createReport(snapshot) : createReport(
12657
13733
  snapshot,
12658
- compareSnapshots(snapshot, parseSnapshot(await readFile10(options.compare, "utf8")))
13734
+ compareSnapshots(snapshot, parseSnapshot(await readFile11(options.compare, "utf8")))
12659
13735
  );
12660
13736
  if (options.report === "html") {
12661
13737
  const htmlOutputPath = await writeHtmlReportBundle(report, {
@@ -13102,6 +14178,18 @@ var parseCommentPullRequest = (value) => {
13102
14178
  }
13103
14179
  return parsed;
13104
14180
  };
14181
+ var parsePathInteger = (value, optionName, minimum, maximum) => {
14182
+ if (value === void 0) {
14183
+ return void 0;
14184
+ }
14185
+ const trimmed = value.trim();
14186
+ const parsed = Number.parseInt(trimmed, 10);
14187
+ if (!/^\d+$/.test(trimmed) || !Number.isInteger(parsed) || parsed < minimum || maximum !== void 0 && parsed > maximum) {
14188
+ const range = maximum === void 0 ? `an integer greater than or equal to ${minimum}` : `an integer between ${minimum} and ${maximum}`;
14189
+ throw new PathConfigurationError(`${optionName} must be ${range}`);
14190
+ }
14191
+ return parsed;
14192
+ };
13105
14193
  program.command("owners").alias("ownership").exitOverride().argument("[path]", "path to the repository to audit").option(
13106
14194
  "--codeowners <file>",
13107
14195
  "explicit CODEOWNERS path, relative to the repository root (default: auto-discovery)"
@@ -13169,6 +14257,47 @@ program.command("owners").alias("ownership").exitOverride().argument("[path]", "
13169
14257
  }
13170
14258
  }
13171
14259
  );
14260
+ 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(
14261
+ new Option("--format <mode>", "output format: console (default), md or json").choices(["console", "md", "json"]).default("console")
14262
+ ).option("--output <file>", "write the rendered output to a file instead of stdout").option("--window-days <days>", "ownership observation window in days", "90").option(
14263
+ "--include-tests",
14264
+ "include test files as their own steps instead of attaching them to their source"
14265
+ ).option("--ref <ref>", "git ref to read CODEOWNERS and the tracked history from", "HEAD").addOption(
14266
+ new Option(
14267
+ "--log-level <level>",
14268
+ "log verbosity: silent, error, warn, info, debug (logs are written to stderr)"
14269
+ ).choices(["silent", "error", "warn", "info", "debug"]).default(parseLogLevel(process.env["CODESENTINEL_LOG_LEVEL"]))
14270
+ ).action(
14271
+ async (target, options) => {
14272
+ const logger = createStderrLogger(options.logLevel);
14273
+ try {
14274
+ const maxSteps = parsePathInteger(options.maxSteps, "--max-steps", 1, 25) ?? 8;
14275
+ const windowDays = parsePathInteger(options.windowDays, "--window-days", 1) ?? 90;
14276
+ const commandOptions = {
14277
+ maxSteps,
14278
+ format: options.format,
14279
+ ...options.output === void 0 ? {} : { outputPath: options.output },
14280
+ windowDays,
14281
+ ...options.includeTests === true ? { includeTests: true } : {},
14282
+ ref: options.ref
14283
+ };
14284
+ const result = await runPathCommand(target, commandOptions, logger);
14285
+ if (result.outputPath === void 0) {
14286
+ process.stdout.write(`${result.rendered}
14287
+ `);
14288
+ }
14289
+ process.exitCode = result.exitCode;
14290
+ } catch (error) {
14291
+ if (error instanceof PathConfigurationError) {
14292
+ logger.error(error.message);
14293
+ process.exitCode = PATH_EXIT_CODES.invalidTarget;
14294
+ return;
14295
+ }
14296
+ logger.error(error instanceof Error ? error.message : "internal error");
14297
+ process.exitCode = PATH_EXIT_CODES.invalidTarget;
14298
+ }
14299
+ }
14300
+ );
13172
14301
  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
14302
  new Option(
13174
14303
  "--comment-on <mode>",