@getcodesentinel/codesentinel 1.33.1 → 1.34.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
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/index.ts
4
- import { Command, Option } from "commander";
4
+ import { Command, CommanderError, Option } from "commander";
5
5
 
6
6
  // ../dependency-firewall/dist/index.js
7
7
  import { existsSync, readFileSync } from "fs";
@@ -819,6 +819,8 @@ var FileCacheStore = class {
819
819
  this.directoryPath = directoryPath;
820
820
  this.options = options;
821
821
  }
822
+ directoryPath;
823
+ options;
822
824
  byKey = /* @__PURE__ */ new Map();
823
825
  inFlightWrites = /* @__PURE__ */ new Map();
824
826
  writesSinceSweep = 0;
@@ -2663,7 +2665,7 @@ var workspaceSummary = (snapshot) => ({
2663
2665
  )
2664
2666
  })) : []
2665
2667
  });
2666
- var createReport = (snapshot, diff) => {
2668
+ var createReport = (snapshot, diff, extras = {}) => {
2667
2669
  const external = snapshot.analysis.external;
2668
2670
  return {
2669
2671
  schemaVersion: REPORT_SCHEMA_VERSION,
@@ -2676,7 +2678,8 @@ var createReport = (snapshot, diff) => {
2676
2678
  riskTier: toRiskTier(snapshot.analysis.risk.riskScore),
2677
2679
  healthTier: toHealthTier(snapshot.analysis.health.healthScore),
2678
2680
  confidence: repositoryConfidence(snapshot),
2679
- dimensionScores: repositoryDimensionScores(snapshot)
2681
+ dimensionScores: repositoryDimensionScores(snapshot),
2682
+ webUrl: extras.repositoryWebUrl ?? null
2680
2683
  },
2681
2684
  health: snapshot.analysis.health,
2682
2685
  workspaces: workspaceSummary(snapshot),
@@ -2728,6 +2731,7 @@ var createReport = (snapshot, diff) => {
2728
2731
  ),
2729
2732
  riskyDependencies: riskyDependencies(snapshot)
2730
2733
  },
2734
+ ...extras.ownership === void 0 ? {} : { ownership: extras.ownership },
2731
2735
  appendix: {
2732
2736
  snapshotSchemaVersion: snapshot.schemaVersion,
2733
2737
  riskModelVersion: snapshot.riskModelVersion,
@@ -3181,12 +3185,22 @@ var validateGateConfig = (input) => {
3181
3185
  "new-hotspot-score-threshold must be a number in [0, 100]"
3182
3186
  );
3183
3187
  }
3188
+ if (config.maxUnownedCritical !== void 0 && (!Number.isInteger(config.maxUnownedCritical) || config.maxUnownedCritical < 0)) {
3189
+ throw new GovernanceConfigurationError("max-unowned-critical must be an integer >= 0");
3190
+ }
3191
+ if (config.maxGhostOwners !== void 0 && (!Number.isInteger(config.maxGhostOwners) || config.maxGhostOwners < 0)) {
3192
+ throw new GovernanceConfigurationError("max-ghost-owners must be an integer >= 0");
3193
+ }
3194
+ if (config.maxDrift !== void 0 && (!Number.isFinite(config.maxDrift) || config.maxDrift < 0 || config.maxDrift > 1)) {
3195
+ throw new GovernanceConfigurationError("max-drift must be a ratio between 0 and 1");
3196
+ }
3184
3197
  };
3185
3198
  var evaluateGates = (input) => {
3186
3199
  validateGateConfig(input);
3187
3200
  const config = input.gateConfig;
3188
3201
  const violations = [];
3189
3202
  const evaluatedGates = [];
3203
+ const warnings = [];
3190
3204
  if (config.maxRiskScore !== void 0) {
3191
3205
  evaluatedGates.push("max-risk-score");
3192
3206
  const current = input.current.analysis.risk.riskScore;
@@ -3323,6 +3337,69 @@ var evaluateGates = (input) => {
3323
3337
  );
3324
3338
  }
3325
3339
  }
3340
+ const ownershipConfigured = config.maxUnownedCritical !== void 0 || config.maxGhostOwners !== void 0 || config.maxDrift !== void 0;
3341
+ let ownership;
3342
+ if (ownershipConfigured) {
3343
+ const ownershipInput = input.ownership;
3344
+ if (ownershipInput === void 0) {
3345
+ warnings.push("ownership gates were not evaluated: no ownership input was provided.");
3346
+ ownership = { evaluated: false, source: null, metrics: null };
3347
+ } else if (!ownershipInput.available) {
3348
+ warnings.push(...ownershipInput.warnings);
3349
+ warnings.push("ownership gates were not evaluated: no CODEOWNERS file was found.");
3350
+ ownership = { evaluated: false, source: null, metrics: null };
3351
+ } else {
3352
+ const metrics = ownershipInput.metrics;
3353
+ ownership = {
3354
+ evaluated: true,
3355
+ source: ownershipInput.source,
3356
+ metrics
3357
+ };
3358
+ if (config.maxUnownedCritical !== void 0) {
3359
+ evaluatedGates.push("max-unowned-critical");
3360
+ if (metrics.unownedCriticalCount > config.maxUnownedCritical) {
3361
+ violations.push(
3362
+ makeViolation(
3363
+ "max-unowned-critical",
3364
+ "error",
3365
+ `Unowned critical files ${metrics.unownedCriticalCount} exceeds configured max ${config.maxUnownedCritical}.`,
3366
+ [],
3367
+ [{ kind: "repository_metric", metric: "unownedCriticalCount" }]
3368
+ )
3369
+ );
3370
+ }
3371
+ }
3372
+ if (config.maxGhostOwners !== void 0) {
3373
+ evaluatedGates.push("max-ghost-owners");
3374
+ if (metrics.ghostOwnerCount > config.maxGhostOwners) {
3375
+ violations.push(
3376
+ makeViolation(
3377
+ "max-ghost-owners",
3378
+ "error",
3379
+ `Ghost owners ${metrics.ghostOwnerCount} exceeds configured max ${config.maxGhostOwners}.`,
3380
+ [],
3381
+ [{ kind: "repository_metric", metric: "ghostOwnerCount" }]
3382
+ )
3383
+ );
3384
+ }
3385
+ }
3386
+ if (config.maxDrift !== void 0) {
3387
+ evaluatedGates.push("max-drift");
3388
+ const ratio = metrics.driftPercent / 100;
3389
+ if (ratio > config.maxDrift) {
3390
+ violations.push(
3391
+ makeViolation(
3392
+ "max-drift",
3393
+ "error",
3394
+ `Ownership drift ratio ${ratio.toFixed(4)} exceeds configured max ${config.maxDrift}.`,
3395
+ [],
3396
+ [{ kind: "repository_metric", metric: "driftPercent" }]
3397
+ )
3398
+ );
3399
+ }
3400
+ }
3401
+ }
3402
+ }
3326
3403
  const ordered = stableSortViolations(violations);
3327
3404
  const highestSeverity = ordered.reduce(
3328
3405
  (current, violation) => compareSeverity(current, violation.severity),
@@ -3333,7 +3410,9 @@ var evaluateGates = (input) => {
3333
3410
  violations: ordered,
3334
3411
  highestSeverity,
3335
3412
  exitCode,
3336
- evaluatedGates: [...evaluatedGates].sort((a, b) => a.localeCompare(b))
3413
+ evaluatedGates: [...evaluatedGates].sort((a, b) => a.localeCompare(b)),
3414
+ warnings: [...warnings],
3415
+ ...ownership === void 0 ? {} : { ownership }
3337
3416
  };
3338
3417
  };
3339
3418
  var renderViolationText = (violation) => {
@@ -3357,6 +3436,27 @@ var renderCheckText = (snapshot, result) => {
3357
3436
  lines.push(renderViolationText(violation));
3358
3437
  }
3359
3438
  }
3439
+ if (result.ownership !== void 0) {
3440
+ lines.push("");
3441
+ lines.push("Ownership");
3442
+ lines.push(`evaluated: ${result.ownership.evaluated}`);
3443
+ lines.push(`source: ${result.ownership.source ?? "none"}`);
3444
+ if (result.ownership.metrics !== null) {
3445
+ const metrics = result.ownership.metrics;
3446
+ lines.push(`declaredCoverage: ${metrics.declaredCoveragePercent}`);
3447
+ lines.push(`declaredCoverageCritical: ${metrics.declaredCoverageCriticalPercent}`);
3448
+ lines.push(`unownedCritical: ${metrics.unownedCriticalCount}`);
3449
+ lines.push(`ghostOwners: ${metrics.ghostOwnerCount}`);
3450
+ lines.push(`driftPercent: ${metrics.driftPercent}`);
3451
+ }
3452
+ }
3453
+ if (result.warnings.length > 0) {
3454
+ lines.push("");
3455
+ lines.push("Warnings");
3456
+ for (const warning of result.warnings) {
3457
+ lines.push(`- ${warning}`);
3458
+ }
3459
+ }
3360
3460
  return lines.join("\n");
3361
3461
  };
3362
3462
  var renderCheckMarkdown = (snapshot, result) => {
@@ -3382,6 +3482,30 @@ var renderCheckMarkdown = (snapshot, result) => {
3382
3482
  );
3383
3483
  }
3384
3484
  }
3485
+ if (result.ownership !== void 0) {
3486
+ lines.push("");
3487
+ lines.push("### Ownership");
3488
+ lines.push(
3489
+ `- codeowners: ${result.ownership.source === null ? "none" : `\`${result.ownership.source}\``}`
3490
+ );
3491
+ lines.push(`- evaluated: \`${result.ownership.evaluated}\``);
3492
+ if (result.ownership.metrics !== null) {
3493
+ const metrics = result.ownership.metrics;
3494
+ lines.push(
3495
+ `- declared coverage: \`${metrics.declaredCoveragePercent}%\` (critical \`${metrics.declaredCoverageCriticalPercent}%\`)`
3496
+ );
3497
+ lines.push(`- unowned critical: \`${metrics.unownedCriticalCount}\``);
3498
+ lines.push(`- ghost owners: \`${metrics.ghostOwnerCount}\``);
3499
+ lines.push(`- drift: \`${metrics.driftPercent}%\``);
3500
+ }
3501
+ }
3502
+ if (result.warnings.length > 0) {
3503
+ lines.push("");
3504
+ lines.push("### Warnings");
3505
+ for (const warning of result.warnings) {
3506
+ lines.push(`- ${warning}`);
3507
+ }
3508
+ }
3385
3509
  lines.push("");
3386
3510
  lines.push("### Violations");
3387
3511
  if (result.violations.length === 0) {
@@ -3714,8 +3838,8 @@ var resolveAutoBaselineRef = async (input) => {
3714
3838
 
3715
3839
  // src/index.ts
3716
3840
  import { readFileSync as readFileSync4 } from "fs";
3717
- import { readFile as readFile7, writeFile as writeFile7 } from "fs/promises";
3718
- import { dirname as dirname3, resolve as resolve7 } from "path";
3841
+ import { readFile as readFile8, writeFile as writeFile8 } from "fs/promises";
3842
+ import { dirname as dirname3, resolve as resolve9 } from "path";
3719
3843
  import { fileURLToPath as fileURLToPath2 } from "url";
3720
3844
 
3721
3845
  // src/application/format-analyze-output.ts
@@ -4396,7 +4520,7 @@ var promptInstall = async (packageName, latestVersion, currentVersion) => {
4396
4520
  );
4397
4521
  return "skip";
4398
4522
  }
4399
- return await new Promise((resolve8) => {
4523
+ return await new Promise((resolve10) => {
4400
4524
  emitKeypressEvents(stdin);
4401
4525
  let selectedIndex = 0;
4402
4526
  const previousRawMode = stdin.isRaw;
@@ -4421,7 +4545,7 @@ var promptInstall = async (packageName, latestVersion, currentVersion) => {
4421
4545
  } else {
4422
4546
  stderr.write("\n");
4423
4547
  }
4424
- resolve8(choice);
4548
+ resolve10(choice);
4425
4549
  };
4426
4550
  const onKeypress = (_str, key) => {
4427
4551
  if (key.ctrl === true && key.name === "c") {
@@ -4615,7 +4739,7 @@ var promptSelection = async (currentVersion, actions) => {
4615
4739
  if (!stdin2.isTTY || !stderr2.isTTY || typeof stdin2.setRawMode !== "function") {
4616
4740
  return "exit";
4617
4741
  }
4618
- return await new Promise((resolve8) => {
4742
+ return await new Promise((resolve10) => {
4619
4743
  emitKeypressEvents2(stdin2);
4620
4744
  let selectedIndex = 0;
4621
4745
  const previousRawMode = stdin2.isRaw;
@@ -4630,7 +4754,7 @@ var promptSelection = async (currentVersion, actions) => {
4630
4754
  stdin2.setRawMode(previousRawMode);
4631
4755
  clearTerminal();
4632
4756
  showCursor2();
4633
- resolve8(selection);
4757
+ resolve10(selection);
4634
4758
  };
4635
4759
  const onKeypress = (_str, key) => {
4636
4760
  if (key.ctrl === true && key.name === "c") {
@@ -4723,7 +4847,7 @@ var waitForReturnToMenu = async () => {
4723
4847
  }
4724
4848
  stderr2.write(`
4725
4849
  ${PROMPT_PADDING}Press enter to return to the menu...`);
4726
- await new Promise((resolve8) => {
4850
+ await new Promise((resolve10) => {
4727
4851
  emitKeypressEvents2(stdin2);
4728
4852
  const previousRawMode = stdin2.isRaw;
4729
4853
  const cleanup = () => {
@@ -4732,7 +4856,7 @@ ${PROMPT_PADDING}Press enter to return to the menu...`);
4732
4856
  stdin2.setRawMode(previousRawMode);
4733
4857
  showCursor2();
4734
4858
  stderr2.write("\n");
4735
- resolve8();
4859
+ resolve10();
4736
4860
  };
4737
4861
  const onKeypress = (_str, key) => {
4738
4862
  if (key.ctrl === true && key.name === "c") {
@@ -4750,7 +4874,7 @@ ${PROMPT_PADDING}Press enter to return to the menu...`);
4750
4874
  });
4751
4875
  };
4752
4876
  var runCliCommand = async (scriptPath2, args) => {
4753
- return await new Promise((resolve8, reject) => {
4877
+ return await new Promise((resolve10, reject) => {
4754
4878
  const child = spawn2(process.execPath, [...process.execArgv, scriptPath2, ...args], {
4755
4879
  stdio: ["inherit", "pipe", "pipe"],
4756
4880
  env: {
@@ -4764,7 +4888,7 @@ var runCliCommand = async (scriptPath2, args) => {
4764
4888
  reject(error);
4765
4889
  });
4766
4890
  child.on("close", (code) => {
4767
- resolve8(code ?? 1);
4891
+ resolve10(code ?? 1);
4768
4892
  });
4769
4893
  });
4770
4894
  };
@@ -6443,6 +6567,7 @@ var GitCliHistoryProvider = class {
6443
6567
  constructor(gitClient) {
6444
6568
  this.gitClient = gitClient;
6445
6569
  }
6570
+ gitClient;
6446
6571
  isGitRepository(repositoryPath) {
6447
6572
  try {
6448
6573
  const output = this.gitClient.run(repositoryPath, ["rev-parse", "--is-inside-work-tree"]);
@@ -8928,8 +9053,975 @@ var runCheckCommand = async (inputPath, authorIdentityMode, options, logger = cr
8928
9053
  };
8929
9054
 
8930
9055
  // src/application/run-ci-command.ts
8931
- import { readFile as readFile4, writeFile as writeFile4 } from "fs/promises";
8932
- import { relative as relative3, resolve as resolve5 } from "path";
9056
+ import { readFile as readFile5, writeFile as writeFile4 } from "fs/promises";
9057
+ import { relative as relative3, resolve as resolve6 } from "path";
9058
+
9059
+ // src/application/build-ownership-audit.ts
9060
+ import { existsSync as existsSync4 } from "fs";
9061
+ import { readFile as readFile4 } from "fs/promises";
9062
+ import { resolve as resolve5 } from "path";
9063
+
9064
+ // ../ownership/dist/index.js
9065
+ var CODEOWNERS_MAX_BYTES = 3 * 1024 * 1024;
9066
+ var CodeownersError = class extends Error {
9067
+ code;
9068
+ constructor(code, message) {
9069
+ super(message);
9070
+ this.name = "CodeownersError";
9071
+ this.code = code;
9072
+ }
9073
+ };
9074
+ var declaredOwnerKey = (owner) => {
9075
+ if (owner.kind === "user") return `@${owner.handle.trim().toLowerCase()}`;
9076
+ if (owner.kind === "team")
9077
+ return `@${owner.org.trim().toLowerCase()}/${owner.slug.trim().toLowerCase()}`;
9078
+ return owner.address.trim().toLowerCase();
9079
+ };
9080
+ var REGEX_METACHARACTERS = /[.*+?^${}()|[\]\\]/g;
9081
+ var ANY_DEPTH_PREFIX = "(?:[^/]+/)*";
9082
+ var escapeLiteral = (value) => value.replace(REGEX_METACHARACTERS, "\\$&");
9083
+ var compileSegment = (segment) => [...segment].map((character) => {
9084
+ if (character === "*") return "[^/]*";
9085
+ if (character === "?") return "[^/]";
9086
+ return escapeLiteral(character);
9087
+ }).join("");
9088
+ var compileBody = (segments) => {
9089
+ const parts = [];
9090
+ segments.forEach((segment, index) => {
9091
+ const isLast = index === segments.length - 1;
9092
+ if (segment === "**") {
9093
+ parts.push(isLast ? ".*" : ANY_DEPTH_PREFIX);
9094
+ return;
9095
+ }
9096
+ parts.push(compileSegment(segment));
9097
+ if (!isLast) parts.push("/");
9098
+ });
9099
+ return parts.join("");
9100
+ };
9101
+ var normalizeFilePath = (filePath) => {
9102
+ let normalized = filePath;
9103
+ while (normalized.startsWith("./")) normalized = normalized.slice(2);
9104
+ return normalized.replace(/^\/+/, "").replace(/\/+$/, "");
9105
+ };
9106
+ function compileCodeownersPattern(pattern) {
9107
+ const trimmed = pattern.trim();
9108
+ const directoryPattern = trimmed.endsWith("/");
9109
+ const withoutTrailingSlashes = trimmed.replace(/\/+$/, "");
9110
+ const anchored = withoutTrailingSlashes.startsWith("/") || withoutTrailingSlashes.slice(1).includes("/");
9111
+ const core = withoutTrailingSlashes.replace(/^\/+/, "");
9112
+ if (core.length === 0) {
9113
+ throw new CodeownersError(
9114
+ "codeowners_invalid_pattern",
9115
+ `CODEOWNERS pattern "${pattern}" does not match any path.`
9116
+ );
9117
+ }
9118
+ const segments = core.split("/");
9119
+ const lastSegment = segments[segments.length - 1] ?? "";
9120
+ const lastSegmentIsLiteral = lastSegment !== "**" && !lastSegment.includes("*") && !lastSegment.includes("?");
9121
+ const prefix = anchored ? "" : ANY_DEPTH_PREFIX;
9122
+ const suffix = directoryPattern ? "(?:/.*)" : lastSegmentIsLiteral ? "(?:/.*)?" : "";
9123
+ const regex = new RegExp(`^${prefix}${compileBody(segments)}${suffix}$`);
9124
+ return { pattern: trimmed, regex };
9125
+ }
9126
+ function createCodeownersMatcher(entries) {
9127
+ const compiled = entries.filter((entry) => !entry.ignored).map((entry) => ({ entry, regex: compileCodeownersPattern(entry.pattern).regex }));
9128
+ return (filePath) => {
9129
+ const candidate = normalizeFilePath(filePath);
9130
+ if (candidate.length === 0) return null;
9131
+ let winner = null;
9132
+ for (const { entry, regex } of compiled) {
9133
+ if (regex.test(candidate)) winner = entry;
9134
+ }
9135
+ return winner;
9136
+ };
9137
+ }
9138
+ var isActiveOwnerResolution = (resolution) => resolution.activeAuthorIds.length > 0;
9139
+ var isVerifiableOwnerResolution = (resolution) => resolution.kind !== "team_unverified" && resolution.kind !== "alias_unresolved";
9140
+ var DEFAULT_FAN_IN_CRITICALITY_THRESHOLD = 5;
9141
+ var CHURN_CRITICALITY_PERCENTILE = 0.9;
9142
+ var RISK_SCORE_CRITICALITY_PERCENTILE = 0.75;
9143
+ var RISK_SCORE_CRITICALITY_MIN_SAMPLES = 4;
9144
+ var finiteNumbers = (values) => values.filter((value) => typeof value === "number" && Number.isFinite(value)).sort((a, b) => a - b);
9145
+ var nearestRank = (sortedAscending, percentile2) => {
9146
+ if (sortedAscending.length === 0) return null;
9147
+ const rank = Math.ceil(percentile2 * sortedAscending.length);
9148
+ const index = Math.min(Math.max(rank, 1), sortedAscending.length) - 1;
9149
+ return sortedAscending[index] ?? null;
9150
+ };
9151
+ var resolveCriticalityPolicy = (evidence, options = {}) => {
9152
+ const fanInThreshold = options.fanInThreshold ?? DEFAULT_FAN_IN_CRITICALITY_THRESHOLD;
9153
+ const fanInValues = finiteNumbers(evidence.map((item) => item.fanIn));
9154
+ const structuralDataAvailable = fanInValues.length > 0;
9155
+ const riskScores = finiteNumbers(evidence.map((item) => item.riskScore));
9156
+ const riskScoreThreshold = riskScores.length >= RISK_SCORE_CRITICALITY_MIN_SAMPLES ? nearestRank(riskScores, RISK_SCORE_CRITICALITY_PERCENTILE) : null;
9157
+ if (structuralDataAvailable) {
9158
+ return { fanInThreshold, churnThreshold: null, riskScoreThreshold, structuralDataAvailable };
9159
+ }
9160
+ const churnValues = finiteNumbers(evidence.map((item) => item.churnTotal));
9161
+ return {
9162
+ fanInThreshold,
9163
+ churnThreshold: nearestRank(churnValues, CHURN_CRITICALITY_PERCENTILE),
9164
+ riskScoreThreshold,
9165
+ structuralDataAvailable
9166
+ };
9167
+ };
9168
+ var isCriticalFile = (evidence, policy) => {
9169
+ if (evidence === void 0) return false;
9170
+ const fanIn = typeof evidence.fanIn === "number" ? evidence.fanIn : null;
9171
+ if (fanIn !== null && Number.isFinite(fanIn) && fanIn >= policy.fanInThreshold) return true;
9172
+ if (evidence.isHotspot === true) return true;
9173
+ const riskScore = typeof evidence.riskScore === "number" ? evidence.riskScore : null;
9174
+ if (policy.riskScoreThreshold !== null && riskScore !== null && Number.isFinite(riskScore) && riskScore >= policy.riskScoreThreshold) {
9175
+ return true;
9176
+ }
9177
+ const churnTotal = typeof evidence.churnTotal === "number" ? evidence.churnTotal : null;
9178
+ return policy.churnThreshold !== null && churnTotal !== null && Number.isFinite(churnTotal) && churnTotal >= policy.churnThreshold;
9179
+ };
9180
+ var OWNERSHIP_STATUS_ORDER = {
9181
+ "unowned-critical": 0,
9182
+ ghosted: 1,
9183
+ drifted: 2,
9184
+ unowned: 3,
9185
+ unknown: 4,
9186
+ "insufficient-evidence": 5,
9187
+ aligned: 6
9188
+ };
9189
+ var ownershipStatusRank = (status) => OWNERSHIP_STATUS_ORDER[status];
9190
+ var classifyOwnershipStatus = (input) => {
9191
+ if (input.declaredCount === 0) {
9192
+ return input.isCritical ? "unowned-critical" : "unowned";
9193
+ }
9194
+ if (input.commits < input.minCommits) {
9195
+ return "insufficient-evidence";
9196
+ }
9197
+ if (!input.hasAuthorEvidence) {
9198
+ return "unknown";
9199
+ }
9200
+ const topAuthorId = input.topAuthorId;
9201
+ if (input.recentCommits === 0) {
9202
+ return topAuthorId !== null && input.resolutions.some((resolution) => resolution.activeAuthorIds.includes(topAuthorId)) ? "aligned" : "drifted";
9203
+ }
9204
+ const active = input.resolutions.filter(isActiveOwnerResolution);
9205
+ if (active.length === 0) {
9206
+ return input.resolutions.every(isVerifiableOwnerResolution) ? "ghosted" : "unknown";
9207
+ }
9208
+ if (topAuthorId !== null && active.some((resolution) => resolution.activeAuthorIds.includes(topAuthorId))) {
9209
+ return "aligned";
9210
+ }
9211
+ return "drifted";
9212
+ };
9213
+ var GHOST_OWNER_SAMPLE_PATHS = 3;
9214
+ var roundTo = (value, decimals) => {
9215
+ const factor = 10 ** decimals;
9216
+ return Math.round(value * factor) / factor;
9217
+ };
9218
+ var percentOf = (part, total) => total === 0 ? 0 : roundTo(part / total * 100, 2);
9219
+ var compareText = (a, b) => a < b ? -1 : a > b ? 1 : 0;
9220
+ var compareNullableDescending = (a, b) => {
9221
+ if (a === null && b === null) return 0;
9222
+ if (a === null) return 1;
9223
+ if (b === null) return -1;
9224
+ return b - a;
9225
+ };
9226
+ var compareFileOwnershipAudits = (a, b) => {
9227
+ const byStatus = ownershipStatusRank(a.status) - ownershipStatusRank(b.status);
9228
+ if (byStatus !== 0) return byStatus;
9229
+ const byCritical = Number(b.criticality.isCritical) - Number(a.criticality.isCritical);
9230
+ if (byCritical !== 0) return byCritical;
9231
+ const byFanIn = compareNullableDescending(a.criticality.fanIn, b.criticality.fanIn);
9232
+ if (byFanIn !== 0) return byFanIn;
9233
+ const byRiskScore = compareNullableDescending(a.criticality.riskScore, b.criticality.riskScore);
9234
+ if (byRiskScore !== 0) return byRiskScore;
9235
+ return compareText(a.filePath, b.filePath);
9236
+ };
9237
+ var sortFileOwnershipAudits = (files) => [...files].sort(compareFileOwnershipAudits);
9238
+ var moduleOfPath = (filePath) => {
9239
+ const separator = filePath.indexOf("/");
9240
+ return separator === -1 ? "." : filePath.slice(0, separator);
9241
+ };
9242
+ var countSingleOwnerModules = (files) => {
9243
+ const ownersByModule = /* @__PURE__ */ new Map();
9244
+ for (const file of files) {
9245
+ const module = moduleOfPath(file.filePath);
9246
+ const owners = ownersByModule.get(module) ?? /* @__PURE__ */ new Set();
9247
+ for (const owner of file.declared) owners.add(declaredOwnerKey(owner));
9248
+ ownersByModule.set(module, owners);
9249
+ }
9250
+ let singleOwnerModules = 0;
9251
+ for (const owners of ownersByModule.values()) {
9252
+ if (owners.size === 1) singleOwnerModules += 1;
9253
+ }
9254
+ return singleOwnerModules;
9255
+ };
9256
+ var computeOwnershipMetrics = (input) => {
9257
+ const declaredFiles = input.files.filter((file) => file.declared.length > 0);
9258
+ const criticalFiles = input.files.filter((file) => file.criticality.isCritical);
9259
+ const coveredCriticalFiles = criticalFiles.filter((file) => file.declared.length > 0);
9260
+ const driftedFiles = declaredFiles.filter((file) => file.status === "drifted");
9261
+ return {
9262
+ declaredCoveragePercent: percentOf(declaredFiles.length, input.trackedFileCount),
9263
+ declaredCoverageCriticalPercent: percentOf(coveredCriticalFiles.length, criticalFiles.length),
9264
+ driftPercent: percentOf(driftedFiles.length, declaredFiles.length),
9265
+ ghostOwnerCount: input.ghostOwnerCount,
9266
+ unownedCriticalCount: input.files.filter((file) => file.status === "unowned-critical").length,
9267
+ singleOwnerModuleCount: countSingleOwnerModules(declaredFiles)
9268
+ };
9269
+ };
9270
+ var summarizeGhostOwners = (candidates) => {
9271
+ const owners = /* @__PURE__ */ new Map();
9272
+ for (const candidate of candidates) {
9273
+ const key = declaredOwnerKey(candidate.owner);
9274
+ const entry = owners.get(key) ?? { owner: candidate.owner, paths: /* @__PURE__ */ new Set() };
9275
+ entry.paths.add(candidate.filePath);
9276
+ owners.set(key, entry);
9277
+ }
9278
+ return [...owners.entries()].sort(([a], [b]) => compareText(a, b)).map(([, entry]) => ({
9279
+ owner: entry.owner,
9280
+ samplePaths: [...entry.paths].sort(compareText).slice(0, GHOST_OWNER_SAMPLE_PATHS)
9281
+ }));
9282
+ };
9283
+ var CODEOWNERS_CANDIDATE_PATHS = [
9284
+ ".github/CODEOWNERS",
9285
+ "CODEOWNERS",
9286
+ "docs/CODEOWNERS"
9287
+ ];
9288
+ var DEFAULT_CODEOWNERS_SOURCE = "CODEOWNERS";
9289
+ var EMAIL_PATTERN = /^[^@\s]+@[^@\s]+$/;
9290
+ var WHITESPACE_PATTERN = /\s/;
9291
+ var hasControlCharacter = (value) => {
9292
+ for (const character of value) {
9293
+ const codePoint = character.codePointAt(0) ?? 0;
9294
+ if (codePoint < 32 || codePoint === 127) return true;
9295
+ }
9296
+ return false;
9297
+ };
9298
+ var parseOwner = (token) => {
9299
+ if (!token.startsWith("@")) {
9300
+ return EMAIL_PATTERN.test(token) ? { kind: "email", address: token } : null;
9301
+ }
9302
+ const reference = token.slice(1);
9303
+ if (reference.length === 0 || reference.includes("@")) return null;
9304
+ const parts = reference.split("/");
9305
+ if (parts.length === 1) {
9306
+ return { kind: "user", handle: reference };
9307
+ }
9308
+ if (parts.length !== 2) return null;
9309
+ const [org, slug] = parts;
9310
+ if (org === void 0 || slug === void 0 || org.length === 0 || slug.length === 0) return null;
9311
+ return { kind: "team", org, slug };
9312
+ };
9313
+ var isValidPattern = (pattern) => {
9314
+ if (hasControlCharacter(pattern)) return false;
9315
+ return pattern.replace(/^\/+/, "").replace(/\/+$/, "").length > 0;
9316
+ };
9317
+ var commentIndex = (line) => {
9318
+ for (let index = 0; index < line.length; index += 1) {
9319
+ if (line[index] !== "#") continue;
9320
+ const previous = index === 0 ? "" : line[index - 1] ?? "";
9321
+ if (index === 0 || WHITESPACE_PATTERN.test(previous)) return index;
9322
+ }
9323
+ return -1;
9324
+ };
9325
+ var stripComment = (line) => {
9326
+ const index = commentIndex(line);
9327
+ return index === -1 ? line : line.slice(0, index);
9328
+ };
9329
+ function parseCodeowners(text, options = {}) {
9330
+ const byteLength = Buffer.byteLength(text, "utf8");
9331
+ if (byteLength > CODEOWNERS_MAX_BYTES) {
9332
+ throw new CodeownersError(
9333
+ "codeowners_too_large",
9334
+ `CODEOWNERS content is ${byteLength} bytes, above the ${CODEOWNERS_MAX_BYTES} byte limit GitHub accepts.`
9335
+ );
9336
+ }
9337
+ const entries = [];
9338
+ const errors = [];
9339
+ const lines = text.replace(/^\uFEFF/, "").split("\n");
9340
+ lines.forEach((rawLine, index) => {
9341
+ const lineNumber = index + 1;
9342
+ const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
9343
+ const content = stripComment(line).trim();
9344
+ if (content.length === 0) return;
9345
+ const [pattern, ...ownerTokens] = content.split(/\s+/);
9346
+ if (pattern === void 0) return;
9347
+ let ignored = !isValidPattern(pattern);
9348
+ if (ignored) {
9349
+ errors.push({ line: lineNumber, reason: `invalid pattern "${pattern}"` });
9350
+ }
9351
+ const owners = [];
9352
+ for (const token of ownerTokens) {
9353
+ const owner = parseOwner(token);
9354
+ if (owner === null) {
9355
+ ignored = true;
9356
+ errors.push({ line: lineNumber, reason: `invalid owner "${token}"` });
9357
+ continue;
9358
+ }
9359
+ owners.push(owner);
9360
+ }
9361
+ entries.push({ pattern, owners, line: lineNumber, ignored });
9362
+ });
9363
+ return {
9364
+ source: options.source ?? DEFAULT_CODEOWNERS_SOURCE,
9365
+ entries,
9366
+ errors,
9367
+ ignoredSources: options.ignoredSources ?? []
9368
+ };
9369
+ }
9370
+ var normalizeSourcePath = (source) => {
9371
+ let normalized = source;
9372
+ while (normalized.startsWith("./")) normalized = normalized.slice(2);
9373
+ return normalized.replace(/^\/+/, "");
9374
+ };
9375
+ function discoverCodeowners(existingPaths) {
9376
+ const existing = new Set(existingPaths.map(normalizeSourcePath));
9377
+ const found = CODEOWNERS_CANDIDATE_PATHS.filter((candidate) => existing.has(candidate));
9378
+ const [source, ...ignoredSources] = found;
9379
+ if (source === void 0) return null;
9380
+ return { source, ignoredSources };
9381
+ }
9382
+ var BOT_MARKER = /\[bot\]/i;
9383
+ var WHITESPACE_PATTERN2 = /\s+/g;
9384
+ var isBotAuthor = (author) => {
9385
+ if (BOT_MARKER.test(author.authorId)) return true;
9386
+ return typeof author.authorName === "string" && BOT_MARKER.test(author.authorName);
9387
+ };
9388
+ var normalizeHandle = (value) => value.trim().replace(/^@+/, "").toLowerCase().replace(WHITESPACE_PATTERN2, "");
9389
+ var normalizeAuthorName = (value) => value.toLowerCase().replace(WHITESPACE_PATTERN2, "");
9390
+ var localPartOf = (authorId) => {
9391
+ const at = authorId.indexOf("@");
9392
+ return at > 0 ? authorId.slice(0, at) : null;
9393
+ };
9394
+ var uniquify = (values) => [...new Set(values)];
9395
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
9396
+ var parseOwnerAliases = (raw) => {
9397
+ const warnings = [];
9398
+ if (raw === null || raw === void 0 || raw.trim().length === 0) {
9399
+ return { aliases: {}, warnings };
9400
+ }
9401
+ let parsed;
9402
+ try {
9403
+ parsed = JSON.parse(raw);
9404
+ } catch {
9405
+ return {
9406
+ aliases: {},
9407
+ warnings: ["owners.json is not valid JSON: identity aliases were ignored."]
9408
+ };
9409
+ }
9410
+ if (!isRecord(parsed)) {
9411
+ return {
9412
+ aliases: {},
9413
+ warnings: ["owners.json must contain a JSON object: identity aliases were ignored."]
9414
+ };
9415
+ }
9416
+ const rawAliases = parsed["aliases"];
9417
+ if (rawAliases === void 0 || rawAliases === null) {
9418
+ return { aliases: {}, warnings };
9419
+ }
9420
+ if (!isRecord(rawAliases)) {
9421
+ return {
9422
+ aliases: {},
9423
+ warnings: ['owners.json "aliases" must be an object: identity aliases were ignored.']
9424
+ };
9425
+ }
9426
+ const aliases = {};
9427
+ for (const [handle, value] of Object.entries(rawAliases)) {
9428
+ const key = normalizeHandle(handle);
9429
+ if (key.length === 0) {
9430
+ warnings.push("An alias entry with an empty handle was ignored.");
9431
+ continue;
9432
+ }
9433
+ if (!Array.isArray(value)) {
9434
+ warnings.push(`Alias entry "${key}" was ignored: expected an array of author ids.`);
9435
+ continue;
9436
+ }
9437
+ const targets = value.filter((target) => typeof target === "string").map((target) => target.trim().toLowerCase()).filter((target) => target.length > 0);
9438
+ if (targets.length === 0) {
9439
+ warnings.push(`Alias entry "${key}" was ignored: it contains no usable author id.`);
9440
+ continue;
9441
+ }
9442
+ aliases[key] = [...aliases[key] ?? [], ...targets];
9443
+ }
9444
+ for (const key of Object.keys(aliases)) {
9445
+ aliases[key] = uniquify(aliases[key] ?? []);
9446
+ }
9447
+ return { aliases, warnings };
9448
+ };
9449
+ var resolveOwner = (owner, authors, aliases) => {
9450
+ if (owner.kind === "team") {
9451
+ return { owner, kind: "team_unverified", activeAuthorIds: [] };
9452
+ }
9453
+ const candidates = authors.filter((author) => !isBotAuthor(author));
9454
+ if (owner.kind === "email") {
9455
+ const target = owner.address.trim().toLowerCase();
9456
+ const active = candidates.filter((author) => author.authorId.trim().toLowerCase() === target).map((author) => author.authorId);
9457
+ return { owner, kind: "email_owner", activeAuthorIds: uniquify(active) };
9458
+ }
9459
+ const handle = normalizeHandle(owner.handle);
9460
+ if (handle.length === 0) {
9461
+ return { owner, kind: "no_activity", activeAuthorIds: [] };
9462
+ }
9463
+ const noreplyId = `${handle}@users.noreply.github.com`;
9464
+ const aliasTargets = aliases.get(handle) ?? [];
9465
+ const byNoreply = [];
9466
+ const byLocalPart = [];
9467
+ const byName = [];
9468
+ const byAlias = [];
9469
+ for (const author of candidates) {
9470
+ const authorId = author.authorId.trim().toLowerCase();
9471
+ if (authorId === noreplyId) {
9472
+ byNoreply.push(author.authorId);
9473
+ continue;
9474
+ }
9475
+ const localPart = localPartOf(authorId);
9476
+ if (localPart !== null && localPart === handle) {
9477
+ byLocalPart.push(author.authorId);
9478
+ continue;
9479
+ }
9480
+ const authorName = typeof author.authorName === "string" ? normalizeAuthorName(author.authorName) : "";
9481
+ if (authorName.length > 0 && authorName === handle) {
9482
+ byName.push(author.authorId);
9483
+ continue;
9484
+ }
9485
+ if (aliasTargets.includes(authorId)) {
9486
+ byAlias.push(author.authorId);
9487
+ }
9488
+ }
9489
+ if (byNoreply.length > 0) {
9490
+ return { owner, kind: "github_noreply", activeAuthorIds: uniquify(byNoreply) };
9491
+ }
9492
+ if (byLocalPart.length > 0) {
9493
+ return { owner, kind: "email_local_part", activeAuthorIds: uniquify(byLocalPart) };
9494
+ }
9495
+ if (byName.length > 0) {
9496
+ return { owner, kind: "author_name", activeAuthorIds: uniquify(byName) };
9497
+ }
9498
+ if (byAlias.length > 0) {
9499
+ return { owner, kind: "alias", activeAuthorIds: uniquify(byAlias) };
9500
+ }
9501
+ if (aliasTargets.length > 0) {
9502
+ return { owner, kind: "alias_unresolved", activeAuthorIds: [] };
9503
+ }
9504
+ return { owner, kind: "no_activity", activeAuthorIds: [] };
9505
+ };
9506
+ var createIdentityResolver = (aliases = {}) => {
9507
+ const normalizedAliases = /* @__PURE__ */ new Map();
9508
+ for (const [handle, targets] of Object.entries(aliases)) {
9509
+ const key = normalizeHandle(handle);
9510
+ if (key.length === 0) continue;
9511
+ normalizedAliases.set(
9512
+ key,
9513
+ targets.map((target) => target.trim().toLowerCase()).filter((target) => target.length > 0)
9514
+ );
9515
+ }
9516
+ return (owner, authors) => resolveOwner(owner, authors, normalizedAliases);
9517
+ };
9518
+ var DEFAULT_MIN_COMMITS = 2;
9519
+ var NO_CODEOWNERS_WARNING = "No CODEOWNERS file was found; the ownership audit is unavailable.";
9520
+ var compareText2 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
9521
+ var roundTo2 = (value, decimals) => {
9522
+ const factor = 10 ** decimals;
9523
+ return Math.round(value * factor) / factor;
9524
+ };
9525
+ var aggregateAuthors = (authors) => {
9526
+ const commitsByAuthor = /* @__PURE__ */ new Map();
9527
+ for (const author of authors) {
9528
+ if (isBotAuthor(author)) continue;
9529
+ commitsByAuthor.set(
9530
+ author.authorId,
9531
+ (commitsByAuthor.get(author.authorId) ?? 0) + author.commits
9532
+ );
9533
+ }
9534
+ return commitsByAuthor;
9535
+ };
9536
+ var pickTopAuthor = (commitsByAuthor) => {
9537
+ let best = null;
9538
+ let total = 0;
9539
+ for (const [authorId, commits] of commitsByAuthor) {
9540
+ total += commits;
9541
+ if (best === null || commits > best.commits || commits === best.commits && authorId < best.id) {
9542
+ best = { id: authorId, commits };
9543
+ }
9544
+ }
9545
+ if (best === null || total <= 0) return null;
9546
+ return { topAuthorId: best.id, topAuthorShare: roundTo2(best.commits / total, 4) };
9547
+ };
9548
+ var countDistinct = (values) => new Set(values).size;
9549
+ var plural = (count, singular, pluralForm) => `${count} ${count === 1 ? singular : pluralForm}`;
9550
+ var auditOwnership = (input) => {
9551
+ const callerWarnings = input.warnings ?? [];
9552
+ if (input.codeowners === null) {
9553
+ return {
9554
+ available: false,
9555
+ reason: "codeowners_not_found",
9556
+ warnings: [...callerWarnings, NO_CODEOWNERS_WARNING]
9557
+ };
9558
+ }
9559
+ const codeowners = input.codeowners;
9560
+ const minCommits = input.minCommits ?? DEFAULT_MIN_COMMITS;
9561
+ const criticalityOptions = input.fanInCriticalityThreshold === void 0 ? {} : { fanInThreshold: input.fanInCriticalityThreshold };
9562
+ const trackedFiles = [...new Set(input.trackedFiles)].sort(compareText2);
9563
+ const trackedFileSet = new Set(trackedFiles);
9564
+ const evidenceByPath = /* @__PURE__ */ new Map();
9565
+ const warnings = [...callerWarnings];
9566
+ let duplicatedEvidence = 0;
9567
+ let evidenceOutsideUniverse = 0;
9568
+ for (const item of input.evidence ?? []) {
9569
+ if (!trackedFileSet.has(item.filePath)) {
9570
+ evidenceOutsideUniverse += 1;
9571
+ continue;
9572
+ }
9573
+ if (evidenceByPath.has(item.filePath)) {
9574
+ duplicatedEvidence += 1;
9575
+ continue;
9576
+ }
9577
+ evidenceByPath.set(item.filePath, item);
9578
+ }
9579
+ const evidenceItems = trackedFiles.map((filePath) => evidenceByPath.get(filePath)).filter((item) => item !== void 0);
9580
+ const policy = resolveCriticalityPolicy(
9581
+ evidenceItems.map((item) => item.criticality ?? {}),
9582
+ criticalityOptions
9583
+ );
9584
+ const matcher = createCodeownersMatcher(codeowners.entries);
9585
+ const resolveOwner2 = createIdentityResolver(input.aliases ?? {});
9586
+ const files = [];
9587
+ const ghostCandidates = [];
9588
+ const teamKeys = /* @__PURE__ */ new Set();
9589
+ const unresolvedAliasKeys = /* @__PURE__ */ new Set();
9590
+ let filesWithoutAuthorEvidence = 0;
9591
+ for (const filePath of trackedFiles) {
9592
+ const item = evidenceByPath.get(filePath);
9593
+ const entry = matcher(filePath);
9594
+ const declared = entry?.owners ?? [];
9595
+ const authors = item?.authors ?? [];
9596
+ const recentAuthors = item?.recentAuthors ?? [];
9597
+ const commits = item?.commits ?? 0;
9598
+ const recentCommits = item?.recentCommits ?? 0;
9599
+ const lifetimeResolutions = declared.map((owner) => resolveOwner2(owner, authors));
9600
+ const recentResolutions = declared.map((owner) => resolveOwner2(owner, recentAuthors));
9601
+ const usesLifetimeHorizon = recentCommits === 0;
9602
+ const resolutions = usesLifetimeHorizon ? lifetimeResolutions : recentResolutions;
9603
+ const horizonAuthors = usesLifetimeHorizon ? authors : recentAuthors;
9604
+ const dormant = usesLifetimeHorizon && commits > 0;
9605
+ for (const resolution of resolutions) {
9606
+ if (resolution.kind === "team_unverified") teamKeys.add(declaredOwnerKey(resolution.owner));
9607
+ if (resolution.kind === "alias_unresolved") {
9608
+ unresolvedAliasKeys.add(declaredOwnerKey(resolution.owner));
9609
+ }
9610
+ }
9611
+ const commitsByAuthor = aggregateAuthors(horizonAuthors);
9612
+ const top = pickTopAuthor(commitsByAuthor);
9613
+ const hasAuthorEvidence = commitsByAuthor.size > 0;
9614
+ const isCritical = isCriticalFile(item?.criticality, policy);
9615
+ const status = classifyOwnershipStatus({
9616
+ declaredCount: declared.length,
9617
+ isCritical,
9618
+ commits,
9619
+ recentCommits,
9620
+ minCommits,
9621
+ topAuthorId: top?.topAuthorId ?? null,
9622
+ hasAuthorEvidence,
9623
+ resolutions
9624
+ });
9625
+ if (declared.length > 0 && commits >= minCommits && !hasAuthorEvidence) {
9626
+ filesWithoutAuthorEvidence += 1;
9627
+ }
9628
+ if (declared.length > 0 && commits >= minCommits && recentCommits > 0) {
9629
+ for (const resolution of recentResolutions) {
9630
+ if (!isActiveOwnerResolution(resolution) && isVerifiableOwnerResolution(resolution)) {
9631
+ ghostCandidates.push({ owner: resolution.owner, filePath });
9632
+ }
9633
+ }
9634
+ }
9635
+ files.push({
9636
+ filePath,
9637
+ declared,
9638
+ matchLine: entry === null ? null : entry.line,
9639
+ status,
9640
+ observed: {
9641
+ commits,
9642
+ recentCommits,
9643
+ dormant,
9644
+ authors: countDistinct(authors.map((author) => author.authorId)),
9645
+ topAuthorId: top?.topAuthorId ?? null,
9646
+ topAuthorShare: top?.topAuthorShare ?? null,
9647
+ busFactor: item?.busFactor ?? null,
9648
+ lastCommitUnix: item?.lastCommitUnix ?? null
9649
+ },
9650
+ criticality: {
9651
+ fanIn: item?.criticality?.fanIn ?? null,
9652
+ isHotspot: item?.criticality?.isHotspot === true,
9653
+ riskScore: item?.criticality?.riskScore ?? null,
9654
+ isCritical
9655
+ }
9656
+ });
9657
+ }
9658
+ const sortedFiles = sortFileOwnershipAudits(files);
9659
+ const ghostOwners = summarizeGhostOwners(ghostCandidates);
9660
+ if (!policy.structuralDataAvailable) {
9661
+ warnings.push(
9662
+ "No structural analysis available: criticality falls back to hotspots and churn (p90)."
9663
+ );
9664
+ }
9665
+ if (teamKeys.size > 0) {
9666
+ warnings.push(
9667
+ `${plural(teamKeys.size, "team owner", "team owners")} cannot be verified offline; teams are never reported as ghost owners.`
9668
+ );
9669
+ }
9670
+ if (unresolvedAliasKeys.size > 0) {
9671
+ warnings.push(
9672
+ `${plural(unresolvedAliasKeys.size, "declared owner has", "declared owners have")} identity aliases that were not observed in the relevant history; their files are never reported as ghost owners.`
9673
+ );
9674
+ }
9675
+ if (filesWithoutAuthorEvidence > 0) {
9676
+ warnings.push(
9677
+ `${plural(filesWithoutAuthorEvidence, "declared file has", "declared files have")} commits but no human author evidence; they are reported as unknown.`
9678
+ );
9679
+ }
9680
+ if (duplicatedEvidence > 0) {
9681
+ warnings.push(
9682
+ `Ignored ${plural(duplicatedEvidence, "duplicate file evidence entry", "duplicate file evidence entries")}: the first entry per path wins.`
9683
+ );
9684
+ }
9685
+ if (evidenceOutsideUniverse > 0) {
9686
+ warnings.push(
9687
+ `Ignored ${plural(evidenceOutsideUniverse, "file evidence entry", "file evidence entries")} outside the tracked universe.`
9688
+ );
9689
+ }
9690
+ const metrics = computeOwnershipMetrics({
9691
+ files: sortedFiles,
9692
+ trackedFileCount: trackedFiles.length,
9693
+ ghostOwnerCount: ghostOwners.length
9694
+ });
9695
+ return {
9696
+ available: true,
9697
+ codeowners,
9698
+ metrics,
9699
+ ghostOwners,
9700
+ files: sortedFiles,
9701
+ warnings
9702
+ };
9703
+ };
9704
+
9705
+ // src/application/owners-git.ts
9706
+ import { execFileSync as execFileSync2 } from "child_process";
9707
+ var RECORD_SEPARATOR = "";
9708
+ var FIELD_SEPARATOR = "";
9709
+ var LOG_FORMAT = `%x1e%at${FIELD_SEPARATOR}%an${FIELD_SEPARATOR}%ae`;
9710
+ var MAX_BUFFER_BYTES = 1024 * 1024 * 256;
9711
+ var OwnersGitError = class extends Error {
9712
+ code;
9713
+ constructor(code, message) {
9714
+ super(message);
9715
+ this.name = "OwnersGitError";
9716
+ this.code = code;
9717
+ }
9718
+ };
9719
+ var gitErrorMessage = (error) => {
9720
+ if (error instanceof Error) {
9721
+ const stderr3 = "stderr" in error ? error.stderr : void 0;
9722
+ const trimmed = typeof stderr3 === "string" ? stderr3.trim() : "";
9723
+ if (trimmed.length > 0) return trimmed;
9724
+ return error.message;
9725
+ }
9726
+ return "unknown git execution error";
9727
+ };
9728
+ var runGit2 = (repositoryPath, args) => {
9729
+ try {
9730
+ return execFileSync2("git", ["-C", repositoryPath, ...args], {
9731
+ encoding: "utf8",
9732
+ maxBuffer: MAX_BUFFER_BYTES,
9733
+ stdio: ["ignore", "pipe", "pipe"]
9734
+ });
9735
+ } catch (error) {
9736
+ const code = error.code;
9737
+ if (code === "ENOENT") {
9738
+ throw new OwnersGitError("git_failed", "git is not available on PATH.");
9739
+ }
9740
+ throw new OwnersGitError("git_failed", gitErrorMessage(error));
9741
+ }
9742
+ };
9743
+ var splitLines = (value) => value.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
9744
+ var normalizeGitAuthorIdentity = (authorName, authorEmail) => {
9745
+ const normalizedName = authorName.trim().replace(/\s+/g, " ").toLowerCase();
9746
+ const normalizedEmail = authorEmail.trim().toLowerCase();
9747
+ if (/\[bot\]/i.test(normalizedName) || /\[bot\]/i.test(normalizedEmail)) {
9748
+ return normalizedEmail.length > 0 ? normalizedEmail : normalizedName;
9749
+ }
9750
+ const githubNoReplyMatch = normalizedEmail.match(/^\d+\+([^@]+)@users\.noreply\.github\.com$/);
9751
+ const githubHandle = githubNoReplyMatch?.[1]?.trim().toLowerCase();
9752
+ if (githubHandle !== void 0 && githubHandle.length > 0) {
9753
+ return `${githubHandle}@users.noreply.github.com`;
9754
+ }
9755
+ if (normalizedEmail.length > 0) {
9756
+ return normalizedEmail;
9757
+ }
9758
+ return normalizedName;
9759
+ };
9760
+ var normalizeRepositoryPath = (value) => {
9761
+ let normalized = value.replace(/\\/g, "/").trim();
9762
+ while (normalized.startsWith("./")) normalized = normalized.slice(2);
9763
+ return normalized.replace(/^\/+/, "");
9764
+ };
9765
+ var parseInteger2 = (value) => {
9766
+ if (value.length === 0) return null;
9767
+ const parsed = Number.parseInt(value, 10);
9768
+ return Number.isNaN(parsed) ? null : parsed;
9769
+ };
9770
+ var parseRenamedPath2 = (pathSpec) => {
9771
+ if (!pathSpec.includes(" => ")) return pathSpec;
9772
+ const braceRenameMatch = pathSpec.match(/^(.*)\{(.+) => (.+)\}(.*)$/);
9773
+ if (braceRenameMatch !== null) {
9774
+ const [, prefix, , renamedTo, suffix] = braceRenameMatch;
9775
+ return `${prefix}${renamedTo}${suffix}`;
9776
+ }
9777
+ const parts = pathSpec.split(" => ");
9778
+ return parts[parts.length - 1] ?? pathSpec;
9779
+ };
9780
+ var readRepositorySnapshot = (targetPath, ref) => {
9781
+ const inside = runGit2(targetPath, ["rev-parse", "--is-inside-work-tree"]).trim();
9782
+ if (inside !== "true") {
9783
+ throw new OwnersGitError(
9784
+ "not_a_git_repository",
9785
+ `"${targetPath}" is not inside a git work tree.`
9786
+ );
9787
+ }
9788
+ const repositoryPath = runGit2(targetPath, ["rev-parse", "--show-toplevel"]).trim();
9789
+ if (repositoryPath.length === 0) {
9790
+ throw new OwnersGitError("not_a_git_repository", `"${targetPath}" has no git work tree root.`);
9791
+ }
9792
+ const commitUnixRaw = runGit2(repositoryPath, ["log", "-1", "--format=%ct", ref]).trim();
9793
+ const commitUnix = parseInteger2(commitUnixRaw);
9794
+ if (commitUnix === null) {
9795
+ throw new OwnersGitError(
9796
+ "unknown_ref",
9797
+ `ref "${ref}" does not resolve to a commit in "${repositoryPath}".`
9798
+ );
9799
+ }
9800
+ const trackedFiles = splitLines(
9801
+ runGit2(repositoryPath, ["ls-tree", "-r", "-z", "--name-only", ref]).split("\0").join("\n")
9802
+ ).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
9803
+ if (trackedFiles.length === 0) {
9804
+ throw new OwnersGitError(
9805
+ "empty_repository",
9806
+ `ref "${ref}" has no tracked files, so there is nothing to audit.`
9807
+ );
9808
+ }
9809
+ return { repositoryPath, ref, commitUnix, trackedFiles };
9810
+ };
9811
+ var readTextAtRef = (repositoryPath, ref, filePath) => runGit2(repositoryPath, ["show", `${ref}:${filePath}`]);
9812
+ var accumulateAuthor = (authors, authorId, authorName) => {
9813
+ const author = authors.get(authorId) ?? { authorName, commits: 0 };
9814
+ authors.set(authorId, { authorName: author.authorName, commits: author.commits + 1 });
9815
+ };
9816
+ var toOwnershipAuthors = (authors) => [...authors.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([authorId, value]) => ({
9817
+ authorId,
9818
+ authorName: value.authorName,
9819
+ commits: value.commits
9820
+ }));
9821
+ var collectOwnershipEvidence = (snapshot, windowDays) => {
9822
+ const sinceUnix = snapshot.commitUnix - windowDays * 86400;
9823
+ const rawLog = runGit2(snapshot.repositoryPath, [
9824
+ "-c",
9825
+ "core.quotepath=false",
9826
+ "log",
9827
+ snapshot.ref,
9828
+ "--no-merges",
9829
+ "--no-renames",
9830
+ "--numstat",
9831
+ `--pretty=format:${LOG_FORMAT}`
9832
+ ]);
9833
+ const trackedFileSet = new Set(snapshot.trackedFiles);
9834
+ const filesByPath = /* @__PURE__ */ new Map();
9835
+ const records = rawLog.split(RECORD_SEPARATOR).map((record) => record.trim()).filter((record) => record.length > 0);
9836
+ for (const record of records) {
9837
+ const lines = record.split("\n").map((line) => line.trimEnd()).filter((line) => line.length > 0);
9838
+ const header = lines[0];
9839
+ if (header === void 0) continue;
9840
+ const [authoredAtRaw, authorName, authorEmail] = header.split(FIELD_SEPARATOR);
9841
+ if (authoredAtRaw === void 0 || authorName === void 0 || authorEmail === void 0) {
9842
+ continue;
9843
+ }
9844
+ const authoredAtUnix = parseInteger2(authoredAtRaw);
9845
+ if (authoredAtUnix === null) continue;
9846
+ const authorId = normalizeGitAuthorIdentity(authorName, authorEmail);
9847
+ const insideWindow = authoredAtUnix >= sinceUnix;
9848
+ for (const line of lines.slice(1)) {
9849
+ const parts = line.split(" ");
9850
+ if (parts.length < 3) continue;
9851
+ const [additionsRaw, deletionsRaw] = parts;
9852
+ if (additionsRaw === void 0 || deletionsRaw === void 0) continue;
9853
+ const filePath = parseRenamedPath2(parts.slice(2).join(" "));
9854
+ if (!trackedFileSet.has(filePath)) continue;
9855
+ const accumulator = filesByPath.get(filePath) ?? {
9856
+ commits: 0,
9857
+ recentCommits: 0,
9858
+ churnTotal: 0,
9859
+ lastCommitUnix: authoredAtUnix,
9860
+ authors: /* @__PURE__ */ new Map(),
9861
+ recentAuthors: /* @__PURE__ */ new Map()
9862
+ };
9863
+ accumulator.commits += 1;
9864
+ accumulator.lastCommitUnix = Math.max(accumulator.lastCommitUnix, authoredAtUnix);
9865
+ accumulateAuthor(accumulator.authors, authorId, authorName);
9866
+ if (insideWindow) {
9867
+ const additions = additionsRaw === "-" ? 0 : parseInteger2(additionsRaw) ?? 0;
9868
+ const deletions = deletionsRaw === "-" ? 0 : parseInteger2(deletionsRaw) ?? 0;
9869
+ accumulator.recentCommits += 1;
9870
+ accumulator.churnTotal += additions + deletions;
9871
+ accumulateAuthor(accumulator.recentAuthors, authorId, authorName);
9872
+ }
9873
+ filesByPath.set(filePath, accumulator);
9874
+ }
9875
+ }
9876
+ const files = [];
9877
+ for (const filePath of [...filesByPath.keys()].sort((a, b) => a < b ? -1 : a > b ? 1 : 0)) {
9878
+ const accumulator = filesByPath.get(filePath);
9879
+ if (accumulator === void 0) continue;
9880
+ files.push({
9881
+ filePath,
9882
+ commits: accumulator.commits,
9883
+ recentCommits: accumulator.recentCommits,
9884
+ authors: toOwnershipAuthors(accumulator.authors),
9885
+ recentAuthors: toOwnershipAuthors(accumulator.recentAuthors),
9886
+ lastCommitUnix: accumulator.lastCommitUnix,
9887
+ criticality: { churnTotal: accumulator.churnTotal }
9888
+ });
9889
+ }
9890
+ return { files, sinceUnix };
9891
+ };
9892
+
9893
+ // src/application/build-ownership-audit.ts
9894
+ var DEFAULT_OWNERS_WINDOW_DAYS = 90;
9895
+ var DEFAULT_OWNERS_REF = "HEAD";
9896
+ var DEFAULT_OWNERS_ALIASES_PATH = ".codesentinel/owners.json";
9897
+ var OwnersConfigurationError = class extends Error {
9898
+ constructor(message) {
9899
+ super(message);
9900
+ this.name = "OwnersConfigurationError";
9901
+ }
9902
+ };
9903
+ var readSnapshot = (targetPath, ref) => {
9904
+ try {
9905
+ return readRepositorySnapshot(targetPath, ref);
9906
+ } catch (error) {
9907
+ if (error instanceof OwnersGitError) {
9908
+ throw new OwnersConfigurationError(error.message);
9909
+ }
9910
+ throw error;
9911
+ }
9912
+ };
9913
+ var readCodeowners = (input) => {
9914
+ const trackedFileSet = new Set(input.snapshot.trackedFiles);
9915
+ const explicitPath = input.explicitPath === void 0 ? null : normalizeRepositoryPath(input.explicitPath);
9916
+ const selection = explicitPath === null ? discoverCodeowners(
9917
+ CODEOWNERS_CANDIDATE_PATHS.filter((candidate) => trackedFileSet.has(candidate))
9918
+ ) : { source: explicitPath, ignoredSources: [] };
9919
+ if (selection === null) {
9920
+ return null;
9921
+ }
9922
+ if (!trackedFileSet.has(selection.source)) {
9923
+ throw new OwnersConfigurationError(
9924
+ `CODEOWNERS file "${selection.source}" is not tracked at ref "${input.snapshot.ref}".`
9925
+ );
9926
+ }
9927
+ const text = readTextAtRef(input.snapshot.repositoryPath, input.snapshot.ref, selection.source);
9928
+ return parseCodeowners(text, {
9929
+ source: selection.source,
9930
+ ignoredSources: selection.ignoredSources
9931
+ });
9932
+ };
9933
+ var readOwnerAliases = async (snapshot, aliasesPath) => {
9934
+ const normalized = normalizeRepositoryPath(aliasesPath);
9935
+ const tracked = snapshot.trackedFiles.includes(normalized);
9936
+ if (tracked) {
9937
+ const text = readTextAtRef(snapshot.repositoryPath, snapshot.ref, normalized);
9938
+ const parsed = parseOwnerAliases(text);
9939
+ return { aliases: parsed.aliases, warnings: parsed.warnings };
9940
+ }
9941
+ const workingTreePath = resolve5(snapshot.repositoryPath, normalized);
9942
+ if (existsSync4(workingTreePath)) {
9943
+ const text = await readFile4(workingTreePath, "utf8");
9944
+ const parsed = parseOwnerAliases(text);
9945
+ return {
9946
+ aliases: parsed.aliases,
9947
+ warnings: [
9948
+ ...parsed.warnings,
9949
+ `Identity aliases were read from the working tree because "${normalized}" is not tracked at "${snapshot.ref}".`
9950
+ ]
9951
+ };
9952
+ }
9953
+ return { aliases: {}, warnings: [] };
9954
+ };
9955
+ var collectFanInByPath = (projectPath, logger) => {
9956
+ try {
9957
+ const structural = buildProjectGraphSummary({ projectPath });
9958
+ const fanIn = /* @__PURE__ */ new Map();
9959
+ for (const file of structural.files) {
9960
+ fanIn.set(normalizeRepositoryPath(file.relativePath), file.fanIn);
9961
+ }
9962
+ return fanIn;
9963
+ } catch (error) {
9964
+ logger.warn(
9965
+ `structural analysis unavailable, criticality falls back to churn: ${error instanceof Error ? error.message : "unknown error"}`
9966
+ );
9967
+ return null;
9968
+ }
9969
+ };
9970
+ var withFanIn = (evidence, fanInByPath) => {
9971
+ if (fanInByPath === null) {
9972
+ return evidence;
9973
+ }
9974
+ return evidence.map((item) => {
9975
+ const fanIn = fanInByPath.get(item.filePath);
9976
+ if (fanIn === void 0) {
9977
+ return item;
9978
+ }
9979
+ return { ...item, criticality: { ...item.criticality, fanIn } };
9980
+ });
9981
+ };
9982
+ var buildOwnershipAudit = async (targetPath, options, logger) => {
9983
+ const ref = options.ref ?? DEFAULT_OWNERS_REF;
9984
+ const windowDays = options.windowDays ?? DEFAULT_OWNERS_WINDOW_DAYS;
9985
+ const minCommits = options.minCommits ?? DEFAULT_MIN_COMMITS;
9986
+ const snapshot = readSnapshot(targetPath, ref);
9987
+ let parsedCodeowners;
9988
+ try {
9989
+ parsedCodeowners = readCodeowners({
9990
+ snapshot,
9991
+ explicitPath: options.codeownersPath
9992
+ });
9993
+ } catch (error) {
9994
+ if (error instanceof CodeownersError) {
9995
+ throw new OwnersConfigurationError(error.message);
9996
+ }
9997
+ throw error;
9998
+ }
9999
+ const aliasSource = await readOwnerAliases(
10000
+ snapshot,
10001
+ options.aliasesPath ?? DEFAULT_OWNERS_ALIASES_PATH
10002
+ );
10003
+ const collected = collectOwnershipEvidence(snapshot, windowDays);
10004
+ logger.debug(
10005
+ `ownership evidence: ${collected.files.length} files with history, window since ${collected.sinceUnix} of ${snapshot.trackedFiles.length} tracked`
10006
+ );
10007
+ const fanInByPath = collectFanInByPath(snapshot.repositoryPath, logger);
10008
+ const evidence = withFanIn(collected.files, fanInByPath);
10009
+ const audit = auditOwnership({
10010
+ codeowners: parsedCodeowners,
10011
+ trackedFiles: snapshot.trackedFiles,
10012
+ evidence,
10013
+ aliases: aliasSource.aliases,
10014
+ minCommits,
10015
+ warnings: [...options.warnings ?? [], ...aliasSource.warnings]
10016
+ });
10017
+ return {
10018
+ audit,
10019
+ trackedFileCount: snapshot.trackedFiles.length,
10020
+ repositoryPath: snapshot.repositoryPath
10021
+ };
10022
+ };
10023
+
10024
+ // src/application/run-ci-command.ts
8933
10025
  var isPathOutsideBase = (value) => {
8934
10026
  return value === ".." || value.startsWith("../") || value.startsWith("..\\");
8935
10027
  };
@@ -8942,7 +10034,7 @@ var runCiCommand = async (inputPath, authorIdentityMode, options, logger = creat
8942
10034
  if (options.baselineSha !== void 0 && options.baselineRef !== "auto") {
8943
10035
  throw new GovernanceConfigurationError("baseline-sha requires --baseline-ref auto");
8944
10036
  }
8945
- const resolvedTargetPath = resolve5(inputPath ?? process.cwd());
10037
+ const resolvedTargetPath = resolve6(inputPath ?? process.cwd());
8946
10038
  logger.info("building current snapshot");
8947
10039
  const current = await buildAnalysisSnapshot(
8948
10040
  inputPath,
@@ -9002,7 +10094,7 @@ var runCiCommand = async (inputPath, authorIdentityMode, options, logger = creat
9002
10094
  `target path is outside git repository root: ${resolvedTargetPath}`
9003
10095
  );
9004
10096
  }
9005
- const baselineTargetPath = relativeTargetPath.length === 0 || relativeTargetPath === "." ? worktreePath : resolve5(worktreePath, relativeTargetPath);
10097
+ const baselineTargetPath = relativeTargetPath.length === 0 || relativeTargetPath === "." ? worktreePath : resolve6(worktreePath, relativeTargetPath);
9006
10098
  return buildAnalysisSnapshot(
9007
10099
  baselineTargetPath,
9008
10100
  authorIdentityMode,
@@ -9028,7 +10120,7 @@ var runCiCommand = async (inputPath, authorIdentityMode, options, logger = creat
9028
10120
  diff = compareSnapshots(current, baseline);
9029
10121
  } else if (options.baselinePath !== void 0) {
9030
10122
  logger.info(`loading baseline snapshot: ${options.baselinePath}`);
9031
- const baselineRaw = await readFile4(options.baselinePath, "utf8");
10123
+ const baselineRaw = await readFile5(options.baselinePath, "utf8");
9032
10124
  try {
9033
10125
  baseline = parseSnapshot(baselineRaw);
9034
10126
  } catch (error) {
@@ -9037,11 +10129,63 @@ var runCiCommand = async (inputPath, authorIdentityMode, options, logger = creat
9037
10129
  }
9038
10130
  diff = compareSnapshots(current, baseline);
9039
10131
  }
10132
+ const ownershipConfigured = options.gateConfig.maxUnownedCritical !== void 0 || options.gateConfig.maxGhostOwners !== void 0 || options.gateConfig.maxDrift !== void 0;
10133
+ let ownershipInput;
10134
+ let ownershipSummary;
10135
+ if (ownershipConfigured) {
10136
+ logger.info("auditing declared ownership for ownership gates");
10137
+ let audit;
10138
+ try {
10139
+ ({ audit } = await buildOwnershipAudit(
10140
+ resolvedTargetPath,
10141
+ {
10142
+ ...options.ownership?.ref === void 0 ? {} : { ref: options.ownership.ref },
10143
+ ...options.ownership?.windowDays === void 0 ? {} : { windowDays: options.ownership.windowDays },
10144
+ ...options.ownership?.minCommits === void 0 ? {} : { minCommits: options.ownership.minCommits }
10145
+ },
10146
+ logger
10147
+ ));
10148
+ } catch (error) {
10149
+ if (error instanceof OwnersConfigurationError) {
10150
+ throw new GovernanceConfigurationError(error.message);
10151
+ }
10152
+ throw error;
10153
+ }
10154
+ if (audit.available) {
10155
+ const metrics = {
10156
+ declaredCoveragePercent: audit.metrics.declaredCoveragePercent,
10157
+ declaredCoverageCriticalPercent: audit.metrics.declaredCoverageCriticalPercent,
10158
+ driftPercent: audit.metrics.driftPercent,
10159
+ ghostOwnerCount: audit.metrics.ghostOwnerCount,
10160
+ unownedCriticalCount: audit.metrics.unownedCriticalCount
10161
+ };
10162
+ ownershipInput = {
10163
+ available: true,
10164
+ source: audit.codeowners.source,
10165
+ metrics
10166
+ };
10167
+ ownershipSummary = {
10168
+ available: true,
10169
+ codeownersSource: audit.codeowners.source,
10170
+ metrics,
10171
+ warnings: [...audit.warnings]
10172
+ };
10173
+ } else {
10174
+ ownershipInput = { available: false, warnings: [...audit.warnings] };
10175
+ ownershipSummary = {
10176
+ available: false,
10177
+ codeownersSource: null,
10178
+ metrics: null,
10179
+ warnings: [...audit.warnings]
10180
+ };
10181
+ }
10182
+ }
9040
10183
  const gateResult = evaluateGates({
9041
10184
  current,
9042
10185
  ...baseline === void 0 ? {} : { baseline },
9043
10186
  ...diff === void 0 ? {} : { diff },
9044
- gateConfig: options.gateConfig
10187
+ gateConfig: options.gateConfig,
10188
+ ...ownershipInput === void 0 ? {} : { ownership: ownershipInput }
9045
10189
  });
9046
10190
  const report = createReport(current, diff);
9047
10191
  const reportMarkdown = formatReport(report, "md");
@@ -9059,7 +10203,8 @@ ${ciMarkdown}`;
9059
10203
  ...diff === void 0 ? {} : { diff },
9060
10204
  violations: gateResult.violations,
9061
10205
  highestSeverity: gateResult.highestSeverity,
9062
- exitCode: gateResult.exitCode
10206
+ exitCode: gateResult.exitCode,
10207
+ ...ownershipSummary === void 0 ? {} : { ownership: ownershipSummary }
9063
10208
  };
9064
10209
  if (options.jsonOutputPath !== void 0) {
9065
10210
  await writeFile4(options.jsonOutputPath, JSON.stringify(machineReadable, null, 2), "utf8");
@@ -9071,20 +10216,21 @@ ${ciMarkdown}`;
9071
10216
  ...diff === void 0 ? {} : { diff },
9072
10217
  gateResult,
9073
10218
  markdownSummary,
10219
+ ...ownershipSummary === void 0 ? {} : { ownership: ownershipSummary },
9074
10220
  machineReadable
9075
10221
  };
9076
10222
  };
9077
10223
 
9078
10224
  // src/application/run-report-command.ts
9079
10225
  import { join as join10 } from "path";
9080
- import { readFile as readFile6, writeFile as writeFile6 } from "fs/promises";
10226
+ import { readFile as readFile7, writeFile as writeFile6 } from "fs/promises";
9081
10227
 
9082
10228
  // src/application/html-report.ts
9083
- import { mkdir as mkdir3, readFile as readFile5, rm, stat as stat2, writeFile as writeFile5 } from "fs/promises";
9084
- import { dirname as dirname2, join as join9, resolve as resolve6 } from "path";
10229
+ import { mkdir as mkdir3, readFile as readFile6, rm, stat as stat2, writeFile as writeFile5 } from "fs/promises";
10230
+ import { dirname as dirname2, join as join9, resolve as resolve7 } from "path";
9085
10231
  import { fileURLToPath } from "url";
9086
10232
  var HTML_REPORT_DIR = ".codesentinel/report";
9087
- var getBundledHtmlAppPath = () => resolve6(dirname2(fileURLToPath(import.meta.url)), "html-report-app");
10233
+ var getBundledHtmlAppPath = () => resolve7(dirname2(fileURLToPath(import.meta.url)), "html-report-app");
9088
10234
  var serializeReportBootstrap = (report) => `window.__CODESENTINEL_REPORT__ = ${JSON.stringify(report).replaceAll("</", "<\\/")};
9089
10235
  `;
9090
10236
  var escapeInlineScript = (script) => script.replaceAll("</script", "<\\/script").replaceAll("<script", "\\x3Cscript").replaceAll("<!--", "\\x3C!--").replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
@@ -9098,18 +10244,18 @@ var readReferencedAssets = async (appPath, indexHtml) => {
9098
10244
  (value) => value !== void 0 && !/^https?:\/\//.test(value) && !value.startsWith("//")
9099
10245
  );
9100
10246
  const styles = await Promise.all(
9101
- stylesheetPaths.map(async (href) => readFile5(resolve6(appPath, href), "utf8"))
10247
+ stylesheetPaths.map(async (href) => readFile6(resolve7(appPath, href), "utf8"))
9102
10248
  );
9103
10249
  const scriptPaths = [...indexHtml.matchAll(/<script[^>]+src=["']([^"']+)["'][^>]*><\/script>/g)].map((match) => match[1]).filter(
9104
10250
  (value) => value !== void 0 && !/^https?:\/\//.test(value) && !value.startsWith("//")
9105
10251
  );
9106
10252
  const scripts = await Promise.all(
9107
- scriptPaths.map(async (src) => readFile5(resolve6(appPath, src), "utf8"))
10253
+ scriptPaths.map(async (src) => readFile6(resolve7(appPath, src), "utf8"))
9108
10254
  );
9109
10255
  return { styles, scripts };
9110
10256
  };
9111
10257
  var inlineBuiltHtml = async (appPath, report) => {
9112
- const indexHtml = await readFile5(resolve6(appPath, "index.html"), "utf8");
10258
+ const indexHtml = await readFile6(resolve7(appPath, "index.html"), "utf8");
9113
10259
  const { styles, scripts } = await readReferencedAssets(appPath, indexHtml);
9114
10260
  const htmlWithoutExternalAssets = indexHtml.replace(
9115
10261
  /\s*<link[^>]+rel=["']stylesheet["'][^>]*>\s*/g,
@@ -9144,7 +10290,7 @@ var assertHtmlAppAssets = async (assetPath) => {
9144
10290
  };
9145
10291
  var resolveHtmlReportOutputPath = (repositoryPath, outputPath) => {
9146
10292
  const invocationCwd = process.env["INIT_CWD"] ?? process.cwd();
9147
- return resolve6(invocationCwd, outputPath ?? join9(repositoryPath, HTML_REPORT_DIR));
10293
+ return resolve7(invocationCwd, outputPath ?? join9(repositoryPath, HTML_REPORT_DIR));
9148
10294
  };
9149
10295
  var writeHtmlReportBundle = async (report, options) => {
9150
10296
  const bundledAppPath = options.bundledAppPath ?? getBundledHtmlAppPath();
@@ -9153,7 +10299,7 @@ var writeHtmlReportBundle = async (report, options) => {
9153
10299
  await rm(outputPath, { recursive: true, force: true });
9154
10300
  await ensureDirectory(outputPath);
9155
10301
  await writeFile5(
9156
- resolve6(outputPath, "index.html"),
10302
+ resolve7(outputPath, "index.html"),
9157
10303
  await inlineBuiltHtml(bundledAppPath, report),
9158
10304
  "utf8"
9159
10305
  );
@@ -9180,19 +10326,109 @@ var openPath = async (targetPath) => {
9180
10326
  if (command === void 0) {
9181
10327
  return false;
9182
10328
  }
9183
- return new Promise((resolve8) => {
10329
+ return new Promise((resolve10) => {
9184
10330
  const child = spawn3(command.command, command.args, {
9185
10331
  detached: true,
9186
10332
  stdio: "ignore"
9187
10333
  });
9188
- child.once("error", () => resolve8(false));
10334
+ child.once("error", () => resolve10(false));
9189
10335
  child.once("spawn", () => {
9190
10336
  child.unref();
9191
- resolve8(true);
10337
+ resolve10(true);
9192
10338
  });
9193
10339
  });
9194
10340
  };
9195
10341
 
10342
+ // src/application/report-ownership.ts
10343
+ import { execFileSync as execFileSync3 } from "child_process";
10344
+ var stripGitSuffix = (path) => path.replace(/\.git\/?$/i, "").replace(/\/+$/, "");
10345
+ var normalizeRepositoryWebUrl = (raw) => {
10346
+ const value = raw.trim();
10347
+ if (value.length === 0) {
10348
+ return null;
10349
+ }
10350
+ if (!value.includes("://")) {
10351
+ const scpMatch = value.match(/^(?:[^@\s]+@)?([^:/\s]+):(.+)$/);
10352
+ if (scpMatch === null) {
10353
+ return null;
10354
+ }
10355
+ const host = scpMatch[1];
10356
+ const path2 = stripGitSuffix(scpMatch[2] ?? "").replace(/^\/+/, "");
10357
+ if (host === void 0 || path2.length === 0) {
10358
+ return null;
10359
+ }
10360
+ return `https://${host}/${path2}`;
10361
+ }
10362
+ let url;
10363
+ try {
10364
+ url = new URL(value);
10365
+ } catch {
10366
+ return null;
10367
+ }
10368
+ if (url.protocol !== "https:" && url.protocol !== "http:" && url.protocol !== "ssh:") {
10369
+ return null;
10370
+ }
10371
+ const path = stripGitSuffix(url.pathname).replace(/^\/+/, "");
10372
+ if (url.hostname.length === 0 || path.length === 0) {
10373
+ return null;
10374
+ }
10375
+ return `https://${url.hostname}/${path}`;
10376
+ };
10377
+ var readRepositoryWebUrl = (repositoryPath) => {
10378
+ try {
10379
+ const raw = execFileSync3(
10380
+ "git",
10381
+ ["-C", repositoryPath, "config", "--get", "remote.origin.url"],
10382
+ {
10383
+ encoding: "utf8",
10384
+ stdio: ["ignore", "pipe", "ignore"]
10385
+ }
10386
+ );
10387
+ return normalizeRepositoryWebUrl(raw);
10388
+ } catch {
10389
+ return null;
10390
+ }
10391
+ };
10392
+ var toOwnershipAuditReport = (audit) => {
10393
+ if (!audit.available) {
10394
+ return {
10395
+ available: false,
10396
+ reason: audit.reason,
10397
+ warnings: audit.warnings
10398
+ };
10399
+ }
10400
+ return {
10401
+ available: true,
10402
+ codeowners: {
10403
+ source: audit.codeowners.source,
10404
+ ignoredSources: audit.codeowners.ignoredSources,
10405
+ errors: audit.codeowners.errors
10406
+ },
10407
+ metrics: audit.metrics,
10408
+ ghostOwners: audit.ghostOwners,
10409
+ files: audit.files,
10410
+ warnings: audit.warnings
10411
+ };
10412
+ };
10413
+ var buildReportOwnership = async (repositoryPath, logger) => {
10414
+ const webUrl = readRepositoryWebUrl(repositoryPath);
10415
+ try {
10416
+ const { audit } = await buildOwnershipAudit(repositoryPath, {}, logger);
10417
+ return { ownership: toOwnershipAuditReport(audit), webUrl };
10418
+ } catch (error) {
10419
+ const message = error instanceof Error ? error.message : "Unknown ownership audit error.";
10420
+ logger.warn(`ownership audit unavailable: ${message}`);
10421
+ return {
10422
+ ownership: {
10423
+ available: false,
10424
+ reason: "audit_unavailable",
10425
+ warnings: [message]
10426
+ },
10427
+ webUrl
10428
+ };
10429
+ }
10430
+ };
10431
+
9196
10432
  // src/application/run-report-command.ts
9197
10433
  var runReportCommand = async (inputPath, authorIdentityMode, options, logger = createSilentLogger()) => {
9198
10434
  logger.info("building analysis snapshot");
@@ -9210,15 +10446,20 @@ var runReportCommand = async (inputPath, authorIdentityMode, options, logger = c
9210
10446
  await writeFile6(options.snapshotPath, JSON.stringify(current, null, 2), "utf8");
9211
10447
  logger.info(`snapshot written: ${options.snapshotPath}`);
9212
10448
  }
10449
+ const { ownership, webUrl } = await buildReportOwnership(
10450
+ current.analysis.structural.targetPath,
10451
+ logger
10452
+ );
10453
+ const extras = { ownership, repositoryWebUrl: webUrl };
9213
10454
  let report;
9214
10455
  if (options.comparePath === void 0) {
9215
- report = createReport(current);
10456
+ report = createReport(current, void 0, extras);
9216
10457
  } else {
9217
10458
  logger.info(`loading baseline snapshot: ${options.comparePath}`);
9218
- const baselineRaw = await readFile6(options.comparePath, "utf8");
10459
+ const baselineRaw = await readFile7(options.comparePath, "utf8");
9219
10460
  const baseline = parseSnapshot(baselineRaw);
9220
10461
  const diff = compareSnapshots(current, baseline);
9221
- report = createReport(current, diff);
10462
+ report = createReport(current, diff, extras);
9222
10463
  }
9223
10464
  if (options.format === "html") {
9224
10465
  const bundlePath = await writeHtmlReportBundle(report, {
@@ -9315,9 +10556,429 @@ var runExplainCommand = async (inputPath, authorIdentityMode, options, logger =
9315
10556
  };
9316
10557
  };
9317
10558
 
10559
+ // src/application/run-owners-command.ts
10560
+ import { writeFile as writeFile7 } from "fs/promises";
10561
+ import { resolve as resolve8 } from "path";
10562
+
10563
+ // src/application/format-owners-output.ts
10564
+ var OWNERS_SCHEMA_VERSION = "codesentinel.owners.v1";
10565
+ var formatDeclaredOwner = (owner) => {
10566
+ if (owner.kind === "user") return `@${owner.handle}`;
10567
+ if (owner.kind === "team") return `@${owner.org}/${owner.slug}`;
10568
+ return owner.address;
10569
+ };
10570
+ var formatDeclaredOwners = (owners) => owners.map(formatDeclaredOwner).join(", ");
10571
+ var compareText3 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
10572
+ var countFileAudits = (files, trackedFiles) => {
10573
+ const declaredFiles = files.filter((file) => file.declared.length > 0);
10574
+ return {
10575
+ trackedFiles,
10576
+ declaredFiles: declaredFiles.length,
10577
+ criticalFiles: files.filter((file) => file.criticality.isCritical).length,
10578
+ declaredCriticalFiles: files.filter(
10579
+ (file) => file.declared.length > 0 && file.criticality.isCritical
10580
+ ).length,
10581
+ driftedFiles: declaredFiles.filter((file) => file.status === "drifted").length
10582
+ };
10583
+ };
10584
+ var evaluateOwnersThresholds = (metrics, config) => {
10585
+ if (metrics === null) {
10586
+ return [];
10587
+ }
10588
+ const violations = [];
10589
+ if (config.maxUnownedCritical !== null && metrics.unownedCriticalCount > config.maxUnownedCritical) {
10590
+ violations.push({
10591
+ threshold: "max-unowned-critical",
10592
+ limit: config.maxUnownedCritical,
10593
+ actual: metrics.unownedCriticalCount,
10594
+ message: `unowned critical files: ${metrics.unownedCriticalCount} (limit ${config.maxUnownedCritical})`
10595
+ });
10596
+ }
10597
+ if (config.maxGhostOwners !== null && metrics.ghostOwnerCount > config.maxGhostOwners) {
10598
+ violations.push({
10599
+ threshold: "max-ghost-owners",
10600
+ limit: config.maxGhostOwners,
10601
+ actual: metrics.ghostOwnerCount,
10602
+ message: `ghost owners: ${metrics.ghostOwnerCount} (limit ${config.maxGhostOwners})`
10603
+ });
10604
+ }
10605
+ if (config.maxDrift !== null) {
10606
+ const ratio = metrics.driftPercent / 100;
10607
+ if (ratio > config.maxDrift) {
10608
+ violations.push({
10609
+ threshold: "max-drift",
10610
+ limit: config.maxDrift,
10611
+ actual: ratio,
10612
+ message: `drift: ${metrics.driftPercent}% (limit ${formatRatio(config.maxDrift)})`
10613
+ });
10614
+ }
10615
+ }
10616
+ return violations;
10617
+ };
10618
+ var buildOwnersReport = (input) => {
10619
+ const { audit } = input;
10620
+ const files = audit.available ? audit.files : [];
10621
+ const report = {
10622
+ schemaVersion: OWNERS_SCHEMA_VERSION,
10623
+ available: audit.available,
10624
+ ref: input.ref,
10625
+ windowDays: input.windowDays,
10626
+ minCommits: input.minCommits,
10627
+ codeowners: audit.available ? {
10628
+ source: audit.codeowners.source,
10629
+ ignoredSources: [...audit.codeowners.ignoredSources].sort(compareText3),
10630
+ entryCount: audit.codeowners.entries.length,
10631
+ errorCount: audit.codeowners.errors.length,
10632
+ errors: [...audit.codeowners.errors].sort((a, b) => a.line - b.line)
10633
+ } : null,
10634
+ fileCounts: countFileAudits(files, input.trackedFileCount),
10635
+ metrics: audit.available ? audit.metrics : null,
10636
+ ghostOwners: audit.available ? audit.ghostOwners : [],
10637
+ files,
10638
+ warnings: [...audit.warnings],
10639
+ thresholds: {
10640
+ ...input.thresholds,
10641
+ violations: [...input.violations]
10642
+ }
10643
+ };
10644
+ return report;
10645
+ };
10646
+ var formatPercent = (value) => {
10647
+ const rounded = Number.isInteger(value) ? value.toString() : value.toFixed(2);
10648
+ return `${rounded}%`;
10649
+ };
10650
+ var formatRatio = (value) => {
10651
+ const percent = Math.round(value * 100);
10652
+ return `${percent}%`;
10653
+ };
10654
+ var formatShare = (share) => share === null ? "n/a" : `${Math.round(share * 100)}%`;
10655
+ var plural2 = (count, singular, pluralForm) => `${count} ${count === 1 ? singular : pluralForm}`;
10656
+ var padLabel = (label) => `${label}:`.padEnd(26, " ");
10657
+ var topLimit = (value) => Number.isFinite(value) && value > 0 ? value : 0;
10658
+ var renderConsoleSection = (title, lines, total, top) => {
10659
+ if (total === 0) {
10660
+ return [`${title}: none`];
10661
+ }
10662
+ const shown = lines.slice(0, topLimit(top));
10663
+ const remaining = total - shown.length;
10664
+ return [
10665
+ title,
10666
+ ...shown.map((line) => ` ${line}`),
10667
+ ...remaining > 0 ? [` ... ${plural2(remaining, "more file", "more files")}`] : []
10668
+ ];
10669
+ };
10670
+ var statusFiles = (files, status) => files.filter((file) => file.status === status);
10671
+ var renderConsole = (report, top) => {
10672
+ const lines = [];
10673
+ lines.push(
10674
+ `Ownership audit \u2014 ${plural2(report.fileCounts.trackedFiles, "tracked file", "tracked files")}, window ${report.windowDays}d, ref ${report.ref}`
10675
+ );
10676
+ if (!report.available || report.metrics === null) {
10677
+ lines.push("");
10678
+ lines.push(`No CODEOWNERS file was found at ${report.ref}.`);
10679
+ lines.push(
10680
+ "Looked for .github/CODEOWNERS, CODEOWNERS and docs/CODEOWNERS. The ownership audit is unavailable."
10681
+ );
10682
+ appendWarnings(lines, report.warnings);
10683
+ return lines.join("\n");
10684
+ }
10685
+ const { metrics, fileCounts, codeowners } = report;
10686
+ const source = codeowners === null ? "unknown" : codeowners.source;
10687
+ const errors = codeowners === null ? 0 : codeowners.errorCount;
10688
+ lines.push(
10689
+ `CODEOWNERS ${source} \xB7 ${plural2(codeowners?.entryCount ?? 0, "entry", "entries")} \xB7 ${plural2(errors, "invalid line", "invalid lines")}`
10690
+ );
10691
+ lines.push("");
10692
+ lines.push(
10693
+ `${padLabel("Declared coverage")}${formatPercent(metrics.declaredCoveragePercent)} (${fileCounts.declaredFiles}/${fileCounts.trackedFiles})`
10694
+ );
10695
+ lines.push(
10696
+ `${padLabel("Critical coverage")}${formatPercent(metrics.declaredCoverageCriticalPercent)} (${fileCounts.declaredCriticalFiles}/${fileCounts.criticalFiles})`
10697
+ );
10698
+ lines.push(
10699
+ `${padLabel("Drift")}${formatPercent(metrics.driftPercent)} (${fileCounts.driftedFiles}/${fileCounts.declaredFiles} declared files)`
10700
+ );
10701
+ lines.push(
10702
+ `${padLabel("Owners without activity")}${plural2(metrics.ghostOwnerCount, "owner", "owners")}`
10703
+ );
10704
+ lines.push(`${padLabel("Unowned critical")}${metrics.unownedCriticalCount}`);
10705
+ lines.push(`${padLabel("Single-owner modules")}${metrics.singleOwnerModuleCount}`);
10706
+ lines.push("");
10707
+ const unownedCritical = statusFiles(report.files, "unowned-critical");
10708
+ lines.push(
10709
+ ...renderConsoleSection(
10710
+ "Unowned critical",
10711
+ unownedCritical.map(
10712
+ (file) => `${file.filePath} fan-in ${file.criticality.fanIn ?? "n/a"} commits ${file.observed.commits} authors ${file.observed.authors}`
10713
+ ),
10714
+ unownedCritical.length,
10715
+ top
10716
+ )
10717
+ );
10718
+ lines.push("");
10719
+ const drifted = statusFiles(report.files, "drifted");
10720
+ lines.push(
10721
+ ...renderConsoleSection(
10722
+ "Drift \u2014 declared owner is not the top recent author",
10723
+ drifted.map(
10724
+ (file) => `${file.filePath} declared ${formatDeclaredOwners(file.declared)} observed ${file.observed.topAuthorId ?? "unknown"} (${formatShare(file.observed.topAuthorShare)})`
10725
+ ),
10726
+ drifted.length,
10727
+ top
10728
+ )
10729
+ );
10730
+ lines.push("");
10731
+ const ghosts = report.ghostOwners;
10732
+ lines.push(
10733
+ ...renderConsoleSection(
10734
+ "Ghost owners \u2014 declared, no commits in the window",
10735
+ ghosts.map(
10736
+ (entry) => `${formatDeclaredOwner(entry.owner)} ${entry.samplePaths.join(", ") || "no sample path"}`
10737
+ ),
10738
+ ghosts.length,
10739
+ top
10740
+ )
10741
+ );
10742
+ appendWarnings(lines, report.warnings);
10743
+ return lines.join("\n");
10744
+ };
10745
+ var appendWarnings = (lines, warnings) => {
10746
+ if (warnings.length === 0) return;
10747
+ lines.push("");
10748
+ lines.push("Warnings");
10749
+ for (const warning of warnings) {
10750
+ lines.push(` - ${warning}`);
10751
+ }
10752
+ };
10753
+ var escapeTableCell = (value) => value.replace(/\|/g, "\\|");
10754
+ var renderMarkdownTable = (header, rows) => {
10755
+ const lines = [`| ${header.join(" | ")} |`, `| ${header.map(() => "---").join(" | ")} |`];
10756
+ for (const row of rows) {
10757
+ lines.push(`| ${row.map(escapeTableCell).join(" | ")} |`);
10758
+ }
10759
+ return lines;
10760
+ };
10761
+ var renderMarkdown2 = (report, top) => {
10762
+ const lines = [];
10763
+ lines.push("# Ownership audit");
10764
+ lines.push("");
10765
+ lines.push(`- ref: \`${report.ref}\``);
10766
+ lines.push(`- window: ${report.windowDays} days`);
10767
+ lines.push(`- tracked files: ${report.fileCounts.trackedFiles}`);
10768
+ lines.push(`- minimum commits per file: ${report.minCommits}`);
10769
+ if (!report.available || report.metrics === null) {
10770
+ lines.push("- CODEOWNERS: not found");
10771
+ lines.push("");
10772
+ lines.push(
10773
+ `No CODEOWNERS file was found at \`${report.ref}\` (looked for \`.github/CODEOWNERS\`, \`CODEOWNERS\` and \`docs/CODEOWNERS\`). The ownership audit is unavailable.`
10774
+ );
10775
+ if (report.warnings.length > 0) {
10776
+ lines.push("");
10777
+ lines.push("## Warnings");
10778
+ lines.push("");
10779
+ for (const warning of report.warnings) {
10780
+ lines.push(`- ${warning}`);
10781
+ }
10782
+ }
10783
+ return lines.join("\n");
10784
+ }
10785
+ const { metrics, fileCounts, codeowners } = report;
10786
+ const source = codeowners === null ? "unknown" : codeowners.source;
10787
+ lines.push(`- CODEOWNERS: \`${source}\``);
10788
+ if (codeowners !== null && codeowners.ignoredSources.length > 0) {
10789
+ lines.push(
10790
+ `- ignored sources: ${codeowners.ignoredSources.map((item) => `\`${item}\``).join(", ")}`
10791
+ );
10792
+ }
10793
+ lines.push("");
10794
+ lines.push("## Metrics");
10795
+ lines.push("");
10796
+ lines.push(
10797
+ ...renderMarkdownTable(
10798
+ ["Metric", "Value"],
10799
+ [
10800
+ [
10801
+ "Declared coverage",
10802
+ `${formatPercent(metrics.declaredCoveragePercent)} (${fileCounts.declaredFiles}/${fileCounts.trackedFiles})`
10803
+ ],
10804
+ [
10805
+ "Critical coverage",
10806
+ `${formatPercent(metrics.declaredCoverageCriticalPercent)} (${fileCounts.declaredCriticalFiles}/${fileCounts.criticalFiles})`
10807
+ ],
10808
+ [
10809
+ "Drift",
10810
+ `${formatPercent(metrics.driftPercent)} (${fileCounts.driftedFiles}/${fileCounts.declaredFiles})`
10811
+ ],
10812
+ ["Owners without activity", `${metrics.ghostOwnerCount}`],
10813
+ ["Unowned critical", `${metrics.unownedCriticalCount}`],
10814
+ ["Single-owner modules", `${metrics.singleOwnerModuleCount}`]
10815
+ ]
10816
+ )
10817
+ );
10818
+ const unownedCritical = statusFiles(report.files, "unowned-critical").slice(0, topLimit(top));
10819
+ lines.push("");
10820
+ lines.push("## Unowned critical");
10821
+ lines.push("");
10822
+ lines.push(
10823
+ ...unownedCritical.length === 0 ? ["None."] : renderMarkdownTable(
10824
+ ["Path", "Fan-in", "Commits", "Authors"],
10825
+ unownedCritical.map((file) => [
10826
+ `\`${file.filePath}\``,
10827
+ `${file.criticality.fanIn ?? "n/a"}`,
10828
+ `${file.observed.commits}`,
10829
+ `${file.observed.authors}`
10830
+ ])
10831
+ )
10832
+ );
10833
+ const drifted = statusFiles(report.files, "drifted").slice(0, topLimit(top));
10834
+ lines.push("");
10835
+ lines.push("## Drift \u2014 declared owner is not the top recent author");
10836
+ lines.push("");
10837
+ lines.push(
10838
+ ...drifted.length === 0 ? ["None."] : renderMarkdownTable(
10839
+ ["Path", "Declared", "Observed", "Share"],
10840
+ drifted.map((file) => [
10841
+ `\`${file.filePath}\``,
10842
+ formatDeclaredOwners(file.declared),
10843
+ file.observed.topAuthorId ?? "unknown",
10844
+ formatShare(file.observed.topAuthorShare)
10845
+ ])
10846
+ )
10847
+ );
10848
+ const ghosts = report.ghostOwners.slice(0, topLimit(top));
10849
+ lines.push("");
10850
+ lines.push("## Ghost owners \u2014 declared, no commits in the window");
10851
+ lines.push("");
10852
+ lines.push(
10853
+ ...ghosts.length === 0 ? ["None."] : renderMarkdownTable(
10854
+ ["Owner", "Sample paths"],
10855
+ ghosts.map((entry) => [
10856
+ formatDeclaredOwner(entry.owner),
10857
+ entry.samplePaths.join(", ") || "no sample path"
10858
+ ])
10859
+ )
10860
+ );
10861
+ if (report.thresholds.violations.length > 0) {
10862
+ lines.push("");
10863
+ lines.push("## Threshold violations");
10864
+ lines.push("");
10865
+ for (const violation of report.thresholds.violations) {
10866
+ lines.push(`- \`${violation.threshold}\`: ${violation.message}`);
10867
+ }
10868
+ }
10869
+ if (report.warnings.length > 0) {
10870
+ lines.push("");
10871
+ lines.push("## Warnings");
10872
+ lines.push("");
10873
+ for (const warning of report.warnings) {
10874
+ lines.push(`- ${warning}`);
10875
+ }
10876
+ }
10877
+ return lines.join("\n");
10878
+ };
10879
+ var formatOwnersOutput = (report, format, top) => {
10880
+ if (format === "json") {
10881
+ return JSON.stringify(report, null, 2);
10882
+ }
10883
+ return format === "md" ? renderMarkdown2(report, top) : renderConsole(report, top);
10884
+ };
10885
+
10886
+ // src/application/run-owners-command.ts
10887
+ var OWNERS_EXIT_CODES = {
10888
+ ok: 0,
10889
+ thresholdExceeded: 1,
10890
+ invalidConfiguration: 2
10891
+ };
10892
+ var DEFAULT_OWNERS_TOP = 10;
10893
+ var DEFAULT_THRESHOLDS = {
10894
+ failOn: "none",
10895
+ maxUnownedCritical: null,
10896
+ maxGhostOwners: null,
10897
+ maxDrift: null
10898
+ };
10899
+ var resolveTargetPath2 = (inputPath) => {
10900
+ const invocationCwd = process.env["INIT_CWD"] ?? process.cwd();
10901
+ return resolve8(invocationCwd, inputPath ?? ".");
10902
+ };
10903
+ var normalizeThresholds = (input) => ({
10904
+ failOn: input?.failOn ?? DEFAULT_THRESHOLDS.failOn,
10905
+ maxUnownedCritical: input?.maxUnownedCritical ?? DEFAULT_THRESHOLDS.maxUnownedCritical,
10906
+ maxGhostOwners: input?.maxGhostOwners ?? DEFAULT_THRESHOLDS.maxGhostOwners,
10907
+ maxDrift: input?.maxDrift ?? DEFAULT_THRESHOLDS.maxDrift
10908
+ });
10909
+ var resolveExitCode = (failOn, violationCount) => {
10910
+ if (failOn === "none" || violationCount === 0) {
10911
+ return OWNERS_EXIT_CODES.ok;
10912
+ }
10913
+ return failOn === "error" ? OWNERS_EXIT_CODES.thresholdExceeded : OWNERS_EXIT_CODES.ok;
10914
+ };
10915
+ var runOwnersCommand = async (inputPath, options = {}, logger = createSilentLogger()) => {
10916
+ const targetPath = resolveTargetPath2(inputPath);
10917
+ const ref = options.ref ?? DEFAULT_OWNERS_REF;
10918
+ const windowDays = options.windowDays ?? DEFAULT_OWNERS_WINDOW_DAYS;
10919
+ const minCommits = options.minCommits ?? DEFAULT_MIN_COMMITS;
10920
+ const top = options.top ?? DEFAULT_OWNERS_TOP;
10921
+ const format = options.format ?? "console";
10922
+ const thresholds = normalizeThresholds(options.thresholds);
10923
+ logger.info(`auditing declared ownership at ${ref} in ${targetPath}`);
10924
+ const callerWarnings = [];
10925
+ if (options.resolveGithub === true) {
10926
+ callerWarnings.push(
10927
+ "--resolve-github is not implemented in this iteration; the audit stays offline and declared owners were resolved from local history only."
10928
+ );
10929
+ logger.warn(callerWarnings[callerWarnings.length - 1] ?? "");
10930
+ }
10931
+ const { audit, trackedFileCount } = await buildOwnershipAudit(
10932
+ targetPath,
10933
+ {
10934
+ ref,
10935
+ windowDays,
10936
+ minCommits,
10937
+ ...options.codeownersPath === void 0 ? {} : { codeownersPath: options.codeownersPath },
10938
+ ...options.aliasesPath === void 0 ? {} : { aliasesPath: options.aliasesPath },
10939
+ warnings: callerWarnings
10940
+ },
10941
+ logger
10942
+ );
10943
+ const metrics = audit.available ? audit.metrics : null;
10944
+ const violations = evaluateOwnersThresholds(metrics, thresholds);
10945
+ if (metrics === null && hasConfiguredThreshold(thresholds)) {
10946
+ logger.warn("no CODEOWNERS file was found; thresholds cannot be evaluated.");
10947
+ }
10948
+ if (violations.length > 0) {
10949
+ for (const violation of violations) {
10950
+ logger.warn(`threshold exceeded (${thresholds.failOn}): ${violation.message}`);
10951
+ }
10952
+ }
10953
+ const report = buildOwnersReport({
10954
+ audit,
10955
+ ref,
10956
+ windowDays,
10957
+ minCommits,
10958
+ trackedFileCount,
10959
+ thresholds,
10960
+ violations
10961
+ });
10962
+ const rendered = formatOwnersOutput(report, format, top);
10963
+ if (options.outputPath !== void 0) {
10964
+ await writeFile7(options.outputPath, `${rendered}
10965
+ `, "utf8");
10966
+ logger.info(`owners output written: ${options.outputPath}`);
10967
+ }
10968
+ return {
10969
+ audit,
10970
+ report,
10971
+ rendered,
10972
+ exitCode: resolveExitCode(thresholds.failOn, violations.length),
10973
+ trackedFileCount,
10974
+ ...options.outputPath === void 0 ? {} : { outputPath: options.outputPath }
10975
+ };
10976
+ };
10977
+ var hasConfiguredThreshold = (thresholds) => thresholds.maxUnownedCritical !== null || thresholds.maxGhostOwners !== null || thresholds.maxDrift !== null;
10978
+
9318
10979
  // src/index.ts
9319
10980
  var program = new Command();
9320
- var packageJsonPath = resolve7(dirname3(fileURLToPath2(import.meta.url)), "../package.json");
10981
+ var packageJsonPath = resolve9(dirname3(fileURLToPath2(import.meta.url)), "../package.json");
9321
10982
  var { version } = JSON.parse(readFileSync4(packageJsonPath, "utf8"));
9322
10983
  var parseRecentWindowDays = (value) => {
9323
10984
  const parsed = Number.parseInt(value, 10);
@@ -9641,12 +11302,12 @@ program.command("run").argument("[path]", "path to the project to analyze").addO
9641
11302
  ...options.trace === true ? { trace: explain.trace } : {}
9642
11303
  });
9643
11304
  if (options.snapshot !== void 0) {
9644
- await writeFile7(options.snapshot, JSON.stringify(snapshot, null, 2), "utf8");
11305
+ await writeFile8(options.snapshot, JSON.stringify(snapshot, null, 2), "utf8");
9645
11306
  logger.info(`snapshot written: ${options.snapshot}`);
9646
11307
  }
9647
11308
  const report = options.compare === void 0 ? createReport(snapshot) : createReport(
9648
11309
  snapshot,
9649
- compareSnapshots(snapshot, parseSnapshot(await readFile7(options.compare, "utf8")))
11310
+ compareSnapshots(snapshot, parseSnapshot(await readFile8(options.compare, "utf8")))
9650
11311
  );
9651
11312
  if (options.report === "html") {
9652
11313
  const htmlOutputPath = await writeHtmlReportBundle(report, {
@@ -9852,6 +11513,27 @@ var parseMainBranches = (options) => {
9852
11513
  const unique = Array.from(new Set(merged));
9853
11514
  return unique.length > 0 ? unique : void 0;
9854
11515
  };
11516
+ var parseCiCount = (value, optionName) => {
11517
+ if (value === void 0) {
11518
+ return void 0;
11519
+ }
11520
+ const trimmed = value.trim();
11521
+ const parsed = Number.parseInt(trimmed, 10);
11522
+ if (!/^\d+$/.test(trimmed) || !Number.isInteger(parsed) || parsed < 0) {
11523
+ throw new GovernanceConfigurationError(`${optionName} must be an integer >= 0`);
11524
+ }
11525
+ return parsed;
11526
+ };
11527
+ var parseCiRatio = (value, optionName) => {
11528
+ if (value === void 0) {
11529
+ return void 0;
11530
+ }
11531
+ const parsed = Number.parseFloat(value.trim());
11532
+ if (!Number.isFinite(parsed) || parsed < 0 || parsed > 1) {
11533
+ throw new GovernanceConfigurationError(`${optionName} must be a number between 0 and 1`);
11534
+ }
11535
+ return parsed;
11536
+ };
9855
11537
  var buildGateConfigFromOptions = (options) => {
9856
11538
  const maxRiskDelta = parseGateNumber(options.maxRiskDelta, "--max-risk-delta");
9857
11539
  const maxHealthDelta = parseGateNumber(options.maxHealthDelta, "--max-health-delta");
@@ -9862,6 +11544,9 @@ var buildGateConfigFromOptions = (options) => {
9862
11544
  options.newHotspotScoreThreshold,
9863
11545
  "--new-hotspot-score-threshold"
9864
11546
  );
11547
+ const maxUnownedCritical = parseCiCount(options.maxUnownedCritical, "--max-unowned-critical");
11548
+ const maxGhostOwners = parseCiCount(options.maxGhostOwners, "--max-ghost-owners");
11549
+ const maxDrift = parseCiRatio(options.maxDrift, "--max-drift");
9865
11550
  return {
9866
11551
  ...maxRiskDelta === void 0 ? {} : { maxRiskDelta },
9867
11552
  ...maxHealthDelta === void 0 ? {} : { maxHealthDelta },
@@ -9871,6 +11556,9 @@ var buildGateConfigFromOptions = (options) => {
9871
11556
  ...maxRiskScore === void 0 ? {} : { maxRiskScore },
9872
11557
  ...minHealthScore === void 0 ? {} : { minHealthScore },
9873
11558
  ...newHotspotScoreThreshold === void 0 ? {} : { newHotspotScoreThreshold },
11559
+ ...maxUnownedCritical === void 0 ? {} : { maxUnownedCritical },
11560
+ ...maxGhostOwners === void 0 ? {} : { maxGhostOwners },
11561
+ ...maxDrift === void 0 ? {} : { maxDrift },
9874
11562
  failOn: options.failOn
9875
11563
  };
9876
11564
  };
@@ -9958,7 +11646,16 @@ program.command("ci").argument("[path]", "path to the project to analyze").addOp
9958
11646
  ).option("--snapshot <path>", "write current snapshot JSON to path").option("--report <path>", "write markdown CI summary report").option("--json-output <path>", "write machine-readable CI JSON output").option("--max-risk-delta <value>", "maximum allowed normalized risk score increase").option(
9959
11647
  "--max-health-delta <value>",
9960
11648
  "maximum allowed normalized health score regression versus baseline"
9961
- ).option("--no-new-cycles", "fail if new structural cycles are introduced").option("--no-new-high-risk-deps", "fail if new high-risk direct dependencies are introduced").option("--max-new-hotspots <count>", "maximum allowed number of new hotspots").option("--new-hotspot-score-threshold <score>", "minimum hotspot score to count as new hotspot").option("--max-risk-score <score>", "absolute risk score limit (0..100)").option("--min-health-score <score>", "minimum health score threshold (0..100)").addOption(
11649
+ ).option("--no-new-cycles", "fail if new structural cycles are introduced").option("--no-new-high-risk-deps", "fail if new high-risk direct dependencies are introduced").option("--max-new-hotspots <count>", "maximum allowed number of new hotspots").option("--new-hotspot-score-threshold <score>", "minimum hotspot score to count as new hotspot").option("--max-risk-score <score>", "absolute risk score limit (0..100)").option("--min-health-score <score>", "minimum health score threshold (0..100)").option(
11650
+ "--max-unowned-critical <count>",
11651
+ "maximum allowed unowned critical files (requires CODEOWNERS)"
11652
+ ).option(
11653
+ "--max-ghost-owners <count>",
11654
+ "maximum allowed owners without activity (requires CODEOWNERS)"
11655
+ ).option(
11656
+ "--max-drift <ratio>",
11657
+ "maximum allowed ownership drift ratio between 0 and 1 (requires CODEOWNERS)"
11658
+ ).addOption(
9962
11659
  new Option("--fail-on <level>", "failing severity threshold").choices(["error", "warn"]).default("error")
9963
11660
  ).option("--no-trace", "disable trace embedding in generated snapshot").addOption(
9964
11661
  new Option(
@@ -10005,6 +11702,88 @@ program.command("ci").argument("[path]", "path to the project to analyze").addOp
10005
11702
  }
10006
11703
  }
10007
11704
  );
11705
+ var parseOwnersInteger = (value, optionName, minimum) => {
11706
+ if (value === void 0) {
11707
+ return void 0;
11708
+ }
11709
+ const trimmed = value.trim();
11710
+ const parsed = Number.parseInt(trimmed, 10);
11711
+ if (!/^\d+$/.test(trimmed) || !Number.isInteger(parsed) || parsed < minimum) {
11712
+ throw new OwnersConfigurationError(
11713
+ `${optionName} must be an integer greater than or equal to ${minimum}`
11714
+ );
11715
+ }
11716
+ return parsed;
11717
+ };
11718
+ var parseOwnersRatio = (value, optionName) => {
11719
+ if (value === void 0) {
11720
+ return void 0;
11721
+ }
11722
+ const parsed = Number.parseFloat(value.trim());
11723
+ if (!Number.isFinite(parsed) || parsed < 0 || parsed > 1) {
11724
+ throw new OwnersConfigurationError(`${optionName} must be a ratio between 0 and 1`);
11725
+ }
11726
+ return parsed;
11727
+ };
11728
+ program.command("owners").alias("ownership").exitOverride().argument("[path]", "path to the repository to audit").option(
11729
+ "--codeowners <file>",
11730
+ "explicit CODEOWNERS path, relative to the repository root (default: auto-discovery)"
11731
+ ).option("--ref <ref>", "git ref to read CODEOWNERS and the tracked tree from", "HEAD").option("--window-days <days>", "authorship observation window in days", "90").option("--min-commits <count>", "minimum per-file commits before a verdict is emitted", "2").option("--top <count>", "rows per console and markdown section", "10").addOption(
11732
+ new Option(
11733
+ "--format <mode>",
11734
+ "output format: console (default), json (stable, sorted payload) or md (pastes into a PR)"
11735
+ ).choices(["console", "json", "md"]).default("console")
11736
+ ).option("--output <file>", "write the rendered output to a file instead of stdout").option("--aliases <file>", "identity alias map", ".codesentinel/owners.json").option(
11737
+ "--resolve-github",
11738
+ "accepted for compatibility; not implemented in this iteration, the audit stays offline"
11739
+ ).addOption(
11740
+ new Option("--fail-on <level>", "failing severity threshold: none, warn or error").choices(["none", "warn", "error"]).default("none")
11741
+ ).option("--max-unowned-critical <count>", "maximum allowed unowned critical files").option("--max-ghost-owners <count>", "maximum allowed owners without activity").option("--max-drift <ratio>", "maximum allowed drift ratio between 0 and 1").addOption(
11742
+ new Option(
11743
+ "--log-level <level>",
11744
+ "log verbosity: silent, error, warn, info, debug (logs are written to stderr)"
11745
+ ).choices(["silent", "error", "warn", "info", "debug"]).default(parseLogLevel(process.env["CODESENTINEL_LOG_LEVEL"]))
11746
+ ).action(
11747
+ async (path, options) => {
11748
+ const logger = createStderrLogger(options.logLevel);
11749
+ try {
11750
+ const windowDays = parseOwnersInteger(options.windowDays, "--window-days", 1) ?? 90;
11751
+ const minCommits = parseOwnersInteger(options.minCommits, "--min-commits", 0) ?? 2;
11752
+ const top = parseOwnersInteger(options.top, "--top", 1) ?? 10;
11753
+ const commandOptions = {
11754
+ ...options.codeowners === void 0 ? {} : { codeownersPath: options.codeowners },
11755
+ ref: options.ref,
11756
+ windowDays,
11757
+ minCommits,
11758
+ top,
11759
+ format: options.format,
11760
+ ...options.output === void 0 ? {} : { outputPath: options.output },
11761
+ aliasesPath: options.aliases,
11762
+ ...options.resolveGithub === true ? { resolveGithub: true } : {},
11763
+ thresholds: {
11764
+ failOn: options.failOn,
11765
+ maxUnownedCritical: parseOwnersInteger(options.maxUnownedCritical, "--max-unowned-critical", 0) ?? null,
11766
+ maxGhostOwners: parseOwnersInteger(options.maxGhostOwners, "--max-ghost-owners", 0) ?? null,
11767
+ maxDrift: parseOwnersRatio(options.maxDrift, "--max-drift") ?? null
11768
+ }
11769
+ };
11770
+ const result = await runOwnersCommand(path, commandOptions, logger);
11771
+ if (result.outputPath === void 0) {
11772
+ process.stdout.write(`${result.rendered}
11773
+ `);
11774
+ }
11775
+ process.exitCode = result.exitCode;
11776
+ } catch (error) {
11777
+ if (error instanceof OwnersConfigurationError) {
11778
+ logger.error(error.message);
11779
+ process.exitCode = OWNERS_EXIT_CODES.invalidConfiguration;
11780
+ return;
11781
+ }
11782
+ logger.error(error instanceof Error ? error.message : "internal error");
11783
+ process.exitCode = OWNERS_EXIT_CODES.invalidConfiguration;
11784
+ }
11785
+ }
11786
+ );
10008
11787
  var executablePath = process.argv[0] ?? "";
10009
11788
  var scriptPath = process.argv[1] ?? "";
10010
11789
  var argv = process.argv[2] === "--" ? [executablePath, scriptPath, ...process.argv.slice(3)] : process.argv;
@@ -10027,5 +11806,14 @@ if (argv[2] !== "update") {
10027
11806
  env: process.env
10028
11807
  });
10029
11808
  }
10030
- await program.parseAsync(argv);
11809
+ try {
11810
+ await program.parseAsync(argv);
11811
+ } catch (error) {
11812
+ if (!(error instanceof CommanderError)) {
11813
+ throw error;
11814
+ }
11815
+ if (error.exitCode !== 0) {
11816
+ process.exitCode = OWNERS_EXIT_CODES.invalidConfiguration;
11817
+ }
11818
+ }
10031
11819
  //# sourceMappingURL=index.js.map