@getcodesentinel/codesentinel 1.36.0 → 1.38.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
@@ -1944,7 +1944,12 @@ var analyzeDependencyCandidateFromRegistry = async (input) => {
1944
1944
 
1945
1945
  // ../reporter/dist/index.js
1946
1946
  import { basename as basename2, posix } from "path";
1947
- var SNAPSHOT_SCHEMA_VERSION = "codesentinel.snapshot.v1";
1947
+ var SNAPSHOT_SCHEMA_VERSION = "codesentinel.snapshot.v2";
1948
+ var LEGACY_SNAPSHOT_SCHEMA_VERSIONS = ["codesentinel.snapshot.v1"];
1949
+ var SUPPORTED_SNAPSHOT_SCHEMA_VERSIONS = [
1950
+ SNAPSHOT_SCHEMA_VERSION,
1951
+ ...LEGACY_SNAPSHOT_SCHEMA_VERSIONS
1952
+ ];
1948
1953
  var REPORT_SCHEMA_VERSION = "codesentinel.report.v1";
1949
1954
  var RISK_MODEL_VERSION = "deterministic-v1";
1950
1955
  var round43 = (value) => Number(value.toFixed(4));
@@ -3071,15 +3076,19 @@ var createSnapshot = (input) => ({
3071
3076
  generatedAt: input.generatedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
3072
3077
  riskModelVersion: RISK_MODEL_VERSION,
3073
3078
  source: {
3074
- targetPath: input.analysis.structural.targetPath
3079
+ targetPath: input.analysis.structural.targetPath,
3080
+ ...input.source?.commit === void 0 ? {} : { commit: input.source.commit },
3081
+ ...input.source?.ref === void 0 ? {} : { ref: input.source.ref }
3075
3082
  },
3076
3083
  analysis: input.analysis,
3077
3084
  ...input.trace === void 0 ? {} : { trace: input.trace },
3078
- ...input.analysisConfig === void 0 ? {} : { analysisConfig: input.analysisConfig }
3085
+ ...input.analysisConfig === void 0 ? {} : { analysisConfig: input.analysisConfig },
3086
+ ...input.ownership === void 0 ? {} : { ownership: input.ownership }
3079
3087
  });
3088
+ var isSupportedSchemaVersion = (value) => typeof value === "string" && SUPPORTED_SNAPSHOT_SCHEMA_VERSIONS.includes(value);
3080
3089
  var parseSnapshot = (raw) => {
3081
3090
  const parsed = JSON.parse(raw);
3082
- if (parsed.schemaVersion !== SNAPSHOT_SCHEMA_VERSION) {
3091
+ if (!isSupportedSchemaVersion(parsed.schemaVersion)) {
3083
3092
  throw new Error("unsupported_snapshot_schema");
3084
3093
  }
3085
3094
  if (typeof parsed.generatedAt !== "string") {
@@ -3091,6 +3100,15 @@ var parseSnapshot = (raw) => {
3091
3100
  if (parsed.source === void 0 || typeof parsed.source.targetPath !== "string") {
3092
3101
  throw new Error("invalid_snapshot_source");
3093
3102
  }
3103
+ if (parsed.source.commit !== void 0 && (typeof parsed.source.commit !== "string" || parsed.source.commit.length === 0)) {
3104
+ throw new Error("invalid_snapshot_source_commit");
3105
+ }
3106
+ if (parsed.source.ref !== void 0 && (typeof parsed.source.ref !== "string" || parsed.source.ref.length === 0)) {
3107
+ throw new Error("invalid_snapshot_source_ref");
3108
+ }
3109
+ if (parsed.ownership !== void 0 && (typeof parsed.ownership !== "object" || parsed.ownership === null || Array.isArray(parsed.ownership))) {
3110
+ throw new Error("invalid_snapshot_ownership");
3111
+ }
3094
3112
  return parsed;
3095
3113
  };
3096
3114
  var formatReport = (report, format) => {
@@ -3838,7 +3856,7 @@ var resolveAutoBaselineRef = async (input) => {
3838
3856
 
3839
3857
  // src/index.ts
3840
3858
  import { readFileSync as readFileSync4 } from "fs";
3841
- import { readFile as readFile9, writeFile as writeFile10 } from "fs/promises";
3859
+ import { readFile as readFile10, writeFile as writeFile11 } from "fs/promises";
3842
3860
  import { dirname as dirname4, resolve as resolve11 } from "path";
3843
3861
  import { fileURLToPath as fileURLToPath2 } from "url";
3844
3862
 
@@ -8967,6 +8985,8 @@ var buildAnalysisSnapshot = async (inputPath, authorIdentityMode, options, logge
8967
8985
  return createSnapshot({
8968
8986
  analysis: summary,
8969
8987
  ...evaluation.trace === void 0 ? {} : { trace: evaluation.trace },
8988
+ ...options.source === void 0 ? {} : { source: options.source },
8989
+ ...options.ownership === void 0 ? {} : { ownership: options.ownership },
8970
8990
  analysisConfig: {
8971
8991
  authorIdentityMode,
8972
8992
  includeTrace: options.includeTrace,
@@ -9053,13 +9073,9 @@ var runCheckCommand = async (inputPath, authorIdentityMode, options, logger = cr
9053
9073
  };
9054
9074
 
9055
9075
  // src/application/run-ci-command.ts
9076
+ import { existsSync as existsSync5 } from "fs";
9056
9077
  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";
9078
+ import { join as join9, relative as relative3, resolve as resolve6 } from "path";
9063
9079
 
9064
9080
  // ../ownership/dist/index.js
9065
9081
  var CODEOWNERS_MAX_BYTES = 3 * 1024 * 1024;
@@ -9702,6 +9718,11 @@ var auditOwnership = (input) => {
9702
9718
  };
9703
9719
  };
9704
9720
 
9721
+ // src/application/build-ownership-audit.ts
9722
+ import { existsSync as existsSync4 } from "fs";
9723
+ import { readFile as readFile4 } from "fs/promises";
9724
+ import { resolve as resolve5 } from "path";
9725
+
9705
9726
  // src/application/owners-git.ts
9706
9727
  import { execFileSync as execFileSync2 } from "child_process";
9707
9728
  var RECORD_SEPARATOR = "";
@@ -9808,6 +9829,18 @@ var readRepositorySnapshot = (targetPath, ref) => {
9808
9829
  }
9809
9830
  return { repositoryPath, ref, commitUnix, trackedFiles };
9810
9831
  };
9832
+ var COMMIT_SHA_PATTERN = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i;
9833
+ var readRepositoryContext = (targetPath, ref = "HEAD") => {
9834
+ try {
9835
+ const repositoryPath = runGit2(targetPath, ["rev-parse", "--show-toplevel"]).trim();
9836
+ if (repositoryPath.length === 0) return null;
9837
+ const commit = runGit2(repositoryPath, ["rev-parse", "--verify", `${ref}^{commit}`]).trim();
9838
+ if (!COMMIT_SHA_PATTERN.test(commit)) return null;
9839
+ return { repositoryPath, commit, ref };
9840
+ } catch {
9841
+ return null;
9842
+ }
9843
+ };
9811
9844
  var readTextAtRef = (repositoryPath, ref, filePath) => runGit2(repositoryPath, ["show", `${ref}:${filePath}`]);
9812
9845
  var accumulateAuthor = (authors, authorId, authorName) => {
9813
9846
  const author = authors.get(authorId) ?? { authorName, commits: 0 };
@@ -10021,6 +10054,96 @@ var buildOwnershipAudit = async (targetPath, options, logger) => {
10021
10054
  };
10022
10055
  };
10023
10056
 
10057
+ // src/application/report-ownership.ts
10058
+ import { execFileSync as execFileSync3 } from "child_process";
10059
+ var stripGitSuffix = (path) => path.replace(/\.git\/?$/i, "").replace(/\/+$/, "");
10060
+ var normalizeRepositoryWebUrl = (raw) => {
10061
+ const value = raw.trim();
10062
+ if (value.length === 0) {
10063
+ return null;
10064
+ }
10065
+ if (!value.includes("://")) {
10066
+ const scpMatch = value.match(/^(?:[^@\s]+@)?([^:/\s]+):(.+)$/);
10067
+ if (scpMatch === null) {
10068
+ return null;
10069
+ }
10070
+ const host = scpMatch[1];
10071
+ const path2 = stripGitSuffix(scpMatch[2] ?? "").replace(/^\/+/, "");
10072
+ if (host === void 0 || path2.length === 0) {
10073
+ return null;
10074
+ }
10075
+ return `https://${host}/${path2}`;
10076
+ }
10077
+ let url;
10078
+ try {
10079
+ url = new URL(value);
10080
+ } catch {
10081
+ return null;
10082
+ }
10083
+ if (url.protocol !== "https:" && url.protocol !== "http:" && url.protocol !== "ssh:") {
10084
+ return null;
10085
+ }
10086
+ const path = stripGitSuffix(url.pathname).replace(/^\/+/, "");
10087
+ if (url.hostname.length === 0 || path.length === 0) {
10088
+ return null;
10089
+ }
10090
+ return `https://${url.hostname}/${path}`;
10091
+ };
10092
+ var readRepositoryWebUrl = (repositoryPath) => {
10093
+ try {
10094
+ const raw = execFileSync3(
10095
+ "git",
10096
+ ["-C", repositoryPath, "config", "--get", "remote.origin.url"],
10097
+ {
10098
+ encoding: "utf8",
10099
+ stdio: ["ignore", "pipe", "ignore"]
10100
+ }
10101
+ );
10102
+ return normalizeRepositoryWebUrl(raw);
10103
+ } catch {
10104
+ return null;
10105
+ }
10106
+ };
10107
+ var toOwnershipAuditReport = (audit) => {
10108
+ if (!audit.available) {
10109
+ return {
10110
+ available: false,
10111
+ reason: audit.reason,
10112
+ warnings: audit.warnings
10113
+ };
10114
+ }
10115
+ return {
10116
+ available: true,
10117
+ codeowners: {
10118
+ source: audit.codeowners.source,
10119
+ ignoredSources: audit.codeowners.ignoredSources,
10120
+ errors: audit.codeowners.errors
10121
+ },
10122
+ metrics: audit.metrics,
10123
+ ghostOwners: audit.ghostOwners,
10124
+ files: audit.files,
10125
+ warnings: audit.warnings
10126
+ };
10127
+ };
10128
+ var buildReportOwnership = async (repositoryPath, logger) => {
10129
+ const webUrl = readRepositoryWebUrl(repositoryPath);
10130
+ try {
10131
+ const { audit } = await buildOwnershipAudit(repositoryPath, {}, logger);
10132
+ return { ownership: toOwnershipAuditReport(audit), webUrl };
10133
+ } catch (error) {
10134
+ const message = error instanceof Error ? error.message : "Unknown ownership audit error.";
10135
+ logger.warn(`ownership audit unavailable: ${message}`);
10136
+ return {
10137
+ ownership: {
10138
+ available: false,
10139
+ reason: "audit_unavailable",
10140
+ warnings: [message]
10141
+ },
10142
+ webUrl
10143
+ };
10144
+ }
10145
+ };
10146
+
10024
10147
  // src/application/run-ci-command.ts
10025
10148
  var isPathOutsideBase = (value) => {
10026
10149
  return value === ".." || value.startsWith("../") || value.startsWith("..\\");
@@ -10035,6 +10158,38 @@ var runCiCommand = async (inputPath, authorIdentityMode, options, logger = creat
10035
10158
  throw new GovernanceConfigurationError("baseline-sha requires --baseline-ref auto");
10036
10159
  }
10037
10160
  const resolvedTargetPath = resolve6(inputPath ?? process.cwd());
10161
+ const repositoryContext = readRepositoryContext(resolvedTargetPath);
10162
+ const repositoryPath = repositoryContext?.repositoryPath ?? resolvedTargetPath;
10163
+ const ownershipConfigured = options.gateConfig.maxUnownedCritical !== void 0 || options.gateConfig.maxGhostOwners !== void 0 || options.gateConfig.maxDrift !== void 0;
10164
+ const needsOwnershipData = ownershipConfigured || CODEOWNERS_CANDIDATE_PATHS.some((candidate) => existsSync5(join9(repositoryPath, candidate)));
10165
+ let audit;
10166
+ if (needsOwnershipData) {
10167
+ logger.info(
10168
+ ownershipConfigured ? "auditing declared ownership for ownership gates" : "auditing declared ownership for the snapshot"
10169
+ );
10170
+ try {
10171
+ ({ audit } = await buildOwnershipAudit(
10172
+ resolvedTargetPath,
10173
+ {
10174
+ ...options.ownership?.ref === void 0 ? {} : { ref: options.ownership.ref },
10175
+ ...options.ownership?.windowDays === void 0 ? {} : { windowDays: options.ownership.windowDays },
10176
+ ...options.ownership?.minCommits === void 0 ? {} : { minCommits: options.ownership.minCommits }
10177
+ },
10178
+ logger
10179
+ ));
10180
+ } catch (error) {
10181
+ if (error instanceof OwnersConfigurationError) {
10182
+ if (ownershipConfigured) {
10183
+ throw new GovernanceConfigurationError(error.message);
10184
+ }
10185
+ logger.warn(`ownership data unavailable: ${error.message}`);
10186
+ } else {
10187
+ throw error;
10188
+ }
10189
+ }
10190
+ }
10191
+ const ownershipReport = audit !== void 0 && audit.available ? toOwnershipAuditReport(audit) : void 0;
10192
+ const source = repositoryContext === null ? void 0 : { commit: repositoryContext.commit, ref: repositoryContext.ref };
10038
10193
  logger.info("building current snapshot");
10039
10194
  const current = await buildAnalysisSnapshot(
10040
10195
  inputPath,
@@ -10042,7 +10197,9 @@ var runCiCommand = async (inputPath, authorIdentityMode, options, logger = creat
10042
10197
  {
10043
10198
  includeTrace: options.includeTrace,
10044
10199
  ...options.scoringProfile === void 0 ? {} : { scoringProfile: options.scoringProfile },
10045
- ...options.recentWindowDays === void 0 ? {} : { recentWindowDays: options.recentWindowDays }
10200
+ ...options.recentWindowDays === void 0 ? {} : { recentWindowDays: options.recentWindowDays },
10201
+ ...source === void 0 ? {} : { source },
10202
+ ...ownershipReport === void 0 ? {} : { ownership: ownershipReport }
10046
10203
  },
10047
10204
  logger
10048
10205
  );
@@ -10129,28 +10286,9 @@ var runCiCommand = async (inputPath, authorIdentityMode, options, logger = creat
10129
10286
  }
10130
10287
  diff = compareSnapshots(current, baseline);
10131
10288
  }
10132
- const ownershipConfigured = options.gateConfig.maxUnownedCritical !== void 0 || options.gateConfig.maxGhostOwners !== void 0 || options.gateConfig.maxDrift !== void 0;
10133
10289
  let ownershipInput;
10134
10290
  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
- }
10291
+ if (ownershipConfigured && audit !== void 0) {
10154
10292
  if (audit.available) {
10155
10293
  const metrics = {
10156
10294
  declaredCoveragePercent: audit.metrics.declaredCoveragePercent,
@@ -10222,12 +10360,12 @@ ${ciMarkdown}`;
10222
10360
  };
10223
10361
 
10224
10362
  // src/application/run-report-command.ts
10225
- import { join as join10 } from "path";
10363
+ import { join as join11 } from "path";
10226
10364
  import { readFile as readFile7, writeFile as writeFile6 } from "fs/promises";
10227
10365
 
10228
10366
  // src/application/html-report.ts
10229
10367
  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";
10368
+ import { dirname as dirname2, join as join10, resolve as resolve7 } from "path";
10231
10369
  import { fileURLToPath } from "url";
10232
10370
  var HTML_REPORT_DIR = ".codesentinel/report";
10233
10371
  var getBundledHtmlAppPath = () => resolve7(dirname2(fileURLToPath(import.meta.url)), "html-report-app");
@@ -10290,7 +10428,7 @@ var assertHtmlAppAssets = async (assetPath) => {
10290
10428
  };
10291
10429
  var resolveHtmlReportOutputPath = (repositoryPath, outputPath) => {
10292
10430
  const invocationCwd = process.env["INIT_CWD"] ?? process.cwd();
10293
- return resolve7(invocationCwd, outputPath ?? join9(repositoryPath, HTML_REPORT_DIR));
10431
+ return resolve7(invocationCwd, outputPath ?? join10(repositoryPath, HTML_REPORT_DIR));
10294
10432
  };
10295
10433
  var writeHtmlReportBundle = async (report, options) => {
10296
10434
  const bundledAppPath = options.bundledAppPath ?? getBundledHtmlAppPath();
@@ -10339,96 +10477,6 @@ var openPath = async (targetPath) => {
10339
10477
  });
10340
10478
  };
10341
10479
 
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
-
10432
10480
  // src/application/run-report-command.ts
10433
10481
  var runReportCommand = async (inputPath, authorIdentityMode, options, logger = createSilentLogger()) => {
10434
10482
  logger.info("building analysis snapshot");
@@ -10467,7 +10515,7 @@ var runReportCommand = async (inputPath, authorIdentityMode, options, logger = c
10467
10515
  ...options.outputPath === void 0 ? {} : { outputPath: options.outputPath }
10468
10516
  });
10469
10517
  if (options.open === true) {
10470
- const opened = await openPath(join10(bundlePath, "index.html"));
10518
+ const opened = await openPath(join11(bundlePath, "index.html"));
10471
10519
  if (!opened) {
10472
10520
  logger.warn("unable to open html report automatically on this platform");
10473
10521
  }
@@ -10560,8 +10608,150 @@ var runExplainCommand = async (inputPath, authorIdentityMode, options, logger =
10560
10608
  import { writeFile as writeFile7 } from "fs/promises";
10561
10609
  import { resolve as resolve8 } from "path";
10562
10610
 
10611
+ // src/application/format-owners-sarif.ts
10612
+ import { createHash as createHash2 } from "crypto";
10613
+ var SARIF_SCHEMA_URI = "https://json.schemastore.org/sarif-2.1.0.json";
10614
+ var SARIF_VERSION = "2.1.0";
10615
+ var CODESENTINEL_INFORMATION_URI = "https://github.com/getcodesentinel/codesentinel";
10616
+ var RULES = [
10617
+ {
10618
+ id: "ownership/unowned-critical",
10619
+ name: "UnownedCritical",
10620
+ level: "error",
10621
+ shortDescription: "Critical file without a declared owner"
10622
+ },
10623
+ {
10624
+ id: "ownership/ghost-owner",
10625
+ name: "GhostOwner",
10626
+ level: "error",
10627
+ shortDescription: "Declared owner with no commits in the window"
10628
+ },
10629
+ {
10630
+ id: "ownership/drift",
10631
+ name: "Drift",
10632
+ level: "warning",
10633
+ shortDescription: "Declared owner is not the recent top author"
10634
+ },
10635
+ {
10636
+ id: "ownership/unknown",
10637
+ name: "Unknown",
10638
+ level: "warning",
10639
+ shortDescription: "Ownership could not be verified offline"
10640
+ }
10641
+ ];
10642
+ var RULE_ID_BY_STATUS = {
10643
+ "unowned-critical": "ownership/unowned-critical",
10644
+ ghosted: "ownership/ghost-owner",
10645
+ drifted: "ownership/drift",
10646
+ unknown: "ownership/unknown"
10647
+ };
10648
+ var RULE_INDEX_BY_ID = new Map(RULES.map((rule, index) => [rule.id, index]));
10649
+ var buildRules = () => RULES.map((rule) => ({
10650
+ id: rule.id,
10651
+ name: rule.name,
10652
+ shortDescription: { text: rule.shortDescription },
10653
+ helpUri: `${CODESENTINEL_INFORMATION_URI}#ownership-audit`,
10654
+ defaultConfiguration: { level: rule.level }
10655
+ }));
10656
+ var normalizeSarifUri = (filePath) => {
10657
+ const withoutDrive = filePath.replace(/\\/g, "/").replace(/^[A-Za-z]:\//, "");
10658
+ const segments = [];
10659
+ for (const segment of withoutDrive.split("/")) {
10660
+ if (segment.length === 0 || segment === ".") {
10661
+ continue;
10662
+ }
10663
+ if (segment === "..") {
10664
+ segments.pop();
10665
+ continue;
10666
+ }
10667
+ segments.push(segment);
10668
+ }
10669
+ return segments.join("/");
10670
+ };
10671
+ var fingerprintFor = (ruleId, uri) => createHash2("sha256").update(`${ruleId}\0${uri}`).digest("hex");
10672
+ var formatShare = (share) => share === null ? "n/a" : `${Math.round(share * 100)}%`;
10673
+ var formatEvidence = (file) => {
10674
+ const criticality = file.criticality.isHotspot ? "hotspot, " : "";
10675
+ return `fan-in ${file.criticality.fanIn ?? "n/a"}, ${criticality}${file.observed.commits} commits, ${file.observed.authors} authors`;
10676
+ };
10677
+ var buildMessage = (file, windowDays) => {
10678
+ const owners = formatDeclaredOwners(file.declared);
10679
+ switch (file.status) {
10680
+ case "unowned-critical":
10681
+ return `\`${file.filePath}\` has no declared owner and is critical (${formatEvidence(file)}).`;
10682
+ case "ghosted":
10683
+ return `\`${file.filePath}\` is declared to ${owners}, but none of its owners committed in the last ${windowDays} days (${file.observed.commits} commits, top author ${file.observed.topAuthorId ?? "unknown"}).`;
10684
+ case "drifted":
10685
+ return `\`${file.filePath}\` is declared to ${owners}, but the top recent author is ${file.observed.topAuthorId ?? "unknown"} (${formatShare(file.observed.topAuthorShare)} of commits).`;
10686
+ case "unknown":
10687
+ return `\`${file.filePath}\` is declared to ${owners}, but its ownership cannot be verified offline.`;
10688
+ default:
10689
+ return `\`${file.filePath}\` has no ownership finding.`;
10690
+ }
10691
+ };
10692
+ var buildResult = (file, report) => {
10693
+ const ruleId = RULE_ID_BY_STATUS[file.status];
10694
+ const ruleIndex = ruleId === void 0 ? void 0 : RULE_INDEX_BY_ID.get(ruleId);
10695
+ if (ruleId === void 0 || ruleIndex === void 0) {
10696
+ return null;
10697
+ }
10698
+ const uri = normalizeSarifUri(file.filePath);
10699
+ const relatedLocations = [];
10700
+ if (file.matchLine !== null && report.codeowners !== null) {
10701
+ relatedLocations.push({
10702
+ id: 1,
10703
+ message: {
10704
+ text: `Ownership declared in ${report.codeowners.source} line ${file.matchLine}.`
10705
+ },
10706
+ physicalLocation: {
10707
+ artifactLocation: { uri: normalizeSarifUri(report.codeowners.source) },
10708
+ region: { startLine: file.matchLine }
10709
+ }
10710
+ });
10711
+ }
10712
+ return {
10713
+ ruleId,
10714
+ ruleIndex,
10715
+ level: RULES[ruleIndex]?.level ?? "warning",
10716
+ message: { text: buildMessage(file, report.windowDays) },
10717
+ locations: [{ physicalLocation: { artifactLocation: { uri }, region: { startLine: 1 } } }],
10718
+ ...relatedLocations.length > 0 ? { relatedLocations } : {},
10719
+ partialFingerprints: { "codesentinel/v1": fingerprintFor(ruleId, uri) }
10720
+ };
10721
+ };
10722
+ var buildOwnersSarif = (report, context) => {
10723
+ const results = [];
10724
+ if (report.available) {
10725
+ for (const file of report.files) {
10726
+ const result = buildResult(file, report);
10727
+ if (result !== null) {
10728
+ results.push(result);
10729
+ }
10730
+ }
10731
+ }
10732
+ return {
10733
+ $schema: SARIF_SCHEMA_URI,
10734
+ version: SARIF_VERSION,
10735
+ runs: [
10736
+ {
10737
+ tool: {
10738
+ driver: {
10739
+ name: "CodeSentinel",
10740
+ informationUri: CODESENTINEL_INFORMATION_URI,
10741
+ version: context.toolVersion,
10742
+ rules: buildRules()
10743
+ }
10744
+ },
10745
+ results
10746
+ }
10747
+ ]
10748
+ };
10749
+ };
10750
+ var formatOwnersSarif = (report, context) => JSON.stringify(buildOwnersSarif(report, context), null, 2);
10751
+
10563
10752
  // src/application/format-owners-output.ts
10564
10753
  var OWNERS_SCHEMA_VERSION = "codesentinel.owners.v1";
10754
+ var DEFAULT_SARIF_CONTEXT = { toolVersion: "0.0.0" };
10565
10755
  var formatDeclaredOwner = (owner) => {
10566
10756
  if (owner.kind === "user") return `@${owner.handle}`;
10567
10757
  if (owner.kind === "team") return `@${owner.org}/${owner.slug}`;
@@ -10651,7 +10841,7 @@ var formatRatio = (value) => {
10651
10841
  const percent = Math.round(value * 100);
10652
10842
  return `${percent}%`;
10653
10843
  };
10654
- var formatShare = (share) => share === null ? "n/a" : `${Math.round(share * 100)}%`;
10844
+ var formatShare2 = (share) => share === null ? "n/a" : `${Math.round(share * 100)}%`;
10655
10845
  var plural2 = (count, singular, pluralForm) => `${count} ${count === 1 ? singular : pluralForm}`;
10656
10846
  var padLabel = (label) => `${label}:`.padEnd(26, " ");
10657
10847
  var topLimit = (value) => Number.isFinite(value) && value > 0 ? value : 0;
@@ -10721,7 +10911,7 @@ var renderConsole = (report, top) => {
10721
10911
  ...renderConsoleSection(
10722
10912
  "Drift \u2014 declared owner is not the top recent author",
10723
10913
  drifted.map(
10724
- (file) => `${file.filePath} declared ${formatDeclaredOwners(file.declared)} observed ${file.observed.topAuthorId ?? "unknown"} (${formatShare(file.observed.topAuthorShare)})`
10914
+ (file) => `${file.filePath} declared ${formatDeclaredOwners(file.declared)} observed ${file.observed.topAuthorId ?? "unknown"} (${formatShare2(file.observed.topAuthorShare)})`
10725
10915
  ),
10726
10916
  drifted.length,
10727
10917
  top
@@ -10841,7 +11031,7 @@ var renderMarkdown2 = (report, top) => {
10841
11031
  `\`${file.filePath}\``,
10842
11032
  formatDeclaredOwners(file.declared),
10843
11033
  file.observed.topAuthorId ?? "unknown",
10844
- formatShare(file.observed.topAuthorShare)
11034
+ formatShare2(file.observed.topAuthorShare)
10845
11035
  ])
10846
11036
  )
10847
11037
  );
@@ -10876,10 +11066,13 @@ var renderMarkdown2 = (report, top) => {
10876
11066
  }
10877
11067
  return lines.join("\n");
10878
11068
  };
10879
- var formatOwnersOutput = (report, format, top) => {
11069
+ var formatOwnersOutput = (report, format, top, sarifContext) => {
10880
11070
  if (format === "json") {
10881
11071
  return JSON.stringify(report, null, 2);
10882
11072
  }
11073
+ if (format === "sarif") {
11074
+ return formatOwnersSarif(report, sarifContext ?? DEFAULT_SARIF_CONTEXT);
11075
+ }
10883
11076
  return format === "md" ? renderMarkdown2(report, top) : renderConsole(report, top);
10884
11077
  };
10885
11078
 
@@ -10959,7 +11152,9 @@ var runOwnersCommand = async (inputPath, options = {}, logger = createSilentLogg
10959
11152
  thresholds,
10960
11153
  violations
10961
11154
  });
10962
- const rendered = formatOwnersOutput(report, format, top);
11155
+ const rendered = formatOwnersOutput(report, format, top, {
11156
+ toolVersion: options.toolVersion ?? DEFAULT_SARIF_CONTEXT.toolVersion
11157
+ });
10963
11158
  if (options.outputPath !== void 0) {
10964
11159
  await writeFile7(options.outputPath, `${rendered}
10965
11160
  `, "utf8");
@@ -10976,8 +11171,463 @@ var runOwnersCommand = async (inputPath, options = {}, logger = createSilentLogg
10976
11171
  };
10977
11172
  var hasConfiguredThreshold = (thresholds) => thresholds.maxUnownedCritical !== null || thresholds.maxGhostOwners !== null || thresholds.maxDrift !== null;
10978
11173
 
11174
+ // src/application/format-pr-comment.ts
11175
+ var PR_COMMENT_MARKER = "<!-- codesentinel:summary -->";
11176
+ var PrCommentConfigurationError = class extends Error {
11177
+ constructor(message) {
11178
+ super(message);
11179
+ this.name = "PrCommentConfigurationError";
11180
+ }
11181
+ };
11182
+ var OFFENDER_STATUSES = /* @__PURE__ */ new Set([
11183
+ "unowned-critical",
11184
+ "ghosted",
11185
+ "drifted",
11186
+ "unknown"
11187
+ ]);
11188
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
11189
+ var readFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
11190
+ var readString = (value) => typeof value === "string" ? value : null;
11191
+ var round47 = (value) => Math.round(value * 1e4) / 1e4;
11192
+ var invalidInput = (field, expectation) => {
11193
+ throw new PrCommentConfigurationError(`invalid CI JSON input: ${field} must be ${expectation}`);
11194
+ };
11195
+ var readMetrics = (source) => {
11196
+ const metrics = source["metrics"];
11197
+ if (!isRecord2(metrics)) {
11198
+ return null;
11199
+ }
11200
+ return {
11201
+ unownedCritical: readFiniteNumber(metrics["unownedCriticalCount"]),
11202
+ ghostOwners: readFiniteNumber(metrics["ghostOwnerCount"]),
11203
+ driftPercent: readFiniteNumber(metrics["driftPercent"])
11204
+ };
11205
+ };
11206
+ var deltaWhenKnown = (current, baseline, enabled) => enabled && current !== null && baseline !== null ? round47(current - baseline) : null;
11207
+ var formatOffenderOwner = (owner) => {
11208
+ if (!isRecord2(owner)) {
11209
+ return null;
11210
+ }
11211
+ const kind = owner["kind"];
11212
+ if (kind === "user") {
11213
+ const handle = readString(owner["handle"]);
11214
+ return handle === null ? null : `@${handle}`;
11215
+ }
11216
+ if (kind === "team") {
11217
+ const org = readString(owner["org"]);
11218
+ const slug = readString(owner["slug"]);
11219
+ return org === null || slug === null ? null : `@${org}/${slug}`;
11220
+ }
11221
+ if (kind === "email") {
11222
+ return readString(owner["address"]);
11223
+ }
11224
+ return null;
11225
+ };
11226
+ var formatOffenderOwners = (declared) => {
11227
+ if (!Array.isArray(declared)) {
11228
+ return "\u2014";
11229
+ }
11230
+ const owners = declared.map(formatOffenderOwner).filter((owner) => owner !== null);
11231
+ return owners.length === 0 ? "\u2014" : owners.join(", ");
11232
+ };
11233
+ var readEvidence = (status, observed, criticality) => {
11234
+ const topAuthorId = observed === null ? null : readString(observed["topAuthorId"]);
11235
+ switch (status) {
11236
+ case "unowned-critical": {
11237
+ const fanIn = criticality === null ? null : readFiniteNumber(criticality["fanIn"]);
11238
+ const commits = observed === null ? null : readFiniteNumber(observed["commits"]);
11239
+ const authors = observed === null ? null : readFiniteNumber(observed["authors"]);
11240
+ return `fan-in ${fanIn ?? "n/a"}, ${commits ?? 0} commits, ${authors ?? 0} authors`;
11241
+ }
11242
+ case "ghosted":
11243
+ return `no commits in the window, top author ${topAuthorId ?? "unknown"}`;
11244
+ case "drifted": {
11245
+ const share = observed === null ? null : readFiniteNumber(observed["topAuthorShare"]);
11246
+ const renderedShare = share === null ? "n/a" : `${Math.round(share * 100)}%`;
11247
+ return `top author ${topAuthorId ?? "unknown"} (${renderedShare})`;
11248
+ }
11249
+ default:
11250
+ return "ownership cannot be verified offline";
11251
+ }
11252
+ };
11253
+ var parseOwnership = (summaryOwnership, current) => {
11254
+ const snapshotOwnership = current["ownership"];
11255
+ const source = isRecord2(snapshotOwnership) ? snapshotOwnership : isRecord2(summaryOwnership) ? summaryOwnership : null;
11256
+ if (source === null || source["available"] !== true) {
11257
+ return { available: false, metrics: null, offenders: [] };
11258
+ }
11259
+ const metrics = readMetrics(source);
11260
+ if (metrics === null) {
11261
+ return { available: false, metrics: null, offenders: [] };
11262
+ }
11263
+ const files = Array.isArray(source["files"]) ? source["files"] : [];
11264
+ const offenders = [];
11265
+ for (const entry of files) {
11266
+ if (offenders.length >= 5) {
11267
+ break;
11268
+ }
11269
+ if (!isRecord2(entry)) {
11270
+ continue;
11271
+ }
11272
+ const status = readString(entry["status"]);
11273
+ const filePath = readString(entry["filePath"]);
11274
+ if (status === null || filePath === null || !OFFENDER_STATUSES.has(status)) {
11275
+ continue;
11276
+ }
11277
+ const observed = isRecord2(entry["observed"]) ? entry["observed"] : null;
11278
+ const criticality = isRecord2(entry["criticality"]) ? entry["criticality"] : null;
11279
+ offenders.push({
11280
+ filePath,
11281
+ status,
11282
+ owners: formatOffenderOwners(entry["declared"]),
11283
+ evidence: readEvidence(status, observed, criticality)
11284
+ });
11285
+ }
11286
+ return { available: true, metrics, offenders };
11287
+ };
11288
+ var formatSigned = (value) => {
11289
+ if (value === null) {
11290
+ return "n/a";
11291
+ }
11292
+ if (value === 0) {
11293
+ return "0";
11294
+ }
11295
+ return value > 0 ? `+${String(value)}` : String(value);
11296
+ };
11297
+ var formatCount = (value) => value === null ? "n/a" : String(value);
11298
+ var formatPercent2 = (value) => value === null ? "n/a" : `${String(value)}%`;
11299
+ var formatPercentagePoints = (value) => value === null ? "n/a" : `${formatSigned(value)} pp`;
11300
+ var escapeTableCell2 = (value) => value.replace(/\|/g, "\\|");
11301
+ var renderTableRow = (cells) => `| ${cells.map(escapeTableCell2).join(" | ")} |`;
11302
+ var parsePrCommentInput = (raw) => {
11303
+ if (!isRecord2(raw)) {
11304
+ return invalidInput("root", "an object");
11305
+ }
11306
+ const current = raw["current"];
11307
+ if (!isRecord2(current)) {
11308
+ return invalidInput("current", "an object");
11309
+ }
11310
+ const analysis = current["analysis"];
11311
+ if (!isRecord2(analysis)) {
11312
+ return invalidInput("current.analysis", "an object");
11313
+ }
11314
+ const risk = analysis["risk"];
11315
+ if (!isRecord2(risk)) {
11316
+ return invalidInput("current.analysis.risk", "an object");
11317
+ }
11318
+ const riskScore = readFiniteNumber(risk["riskScore"]);
11319
+ if (riskScore === null) {
11320
+ return invalidInput("current.analysis.risk.riskScore", "a finite number");
11321
+ }
11322
+ const health = analysis["health"];
11323
+ if (!isRecord2(health)) {
11324
+ return invalidInput("current.analysis.health", "an object");
11325
+ }
11326
+ const healthScore = readFiniteNumber(health["healthScore"]);
11327
+ if (healthScore === null) {
11328
+ return invalidInput("current.analysis.health.healthScore", "a finite number");
11329
+ }
11330
+ const baselineRaw = raw["baseline"];
11331
+ const baseline = isRecord2(baselineRaw) ? baselineRaw : null;
11332
+ const diffRaw = raw["diff"];
11333
+ const diff = isRecord2(diffRaw) ? diffRaw : null;
11334
+ const riskDelta = diff === null ? null : readFiniteNumber(diff["riskScoreDelta"]);
11335
+ const baselineHealthScore = (() => {
11336
+ if (baseline === null) {
11337
+ return null;
11338
+ }
11339
+ const baselineAnalysis = baseline["analysis"];
11340
+ if (!isRecord2(baselineAnalysis)) {
11341
+ return null;
11342
+ }
11343
+ const baselineHealth = baselineAnalysis["health"];
11344
+ if (!isRecord2(baselineHealth)) {
11345
+ return null;
11346
+ }
11347
+ return readFiniteNumber(baselineHealth["healthScore"]);
11348
+ })();
11349
+ const healthDelta = baselineHealthScore === null ? null : round47(healthScore - baselineHealthScore);
11350
+ const ownershipRaw = raw["ownership"];
11351
+ const ownership = parseOwnership(ownershipRaw, current);
11352
+ const baselineOwnership = baseline === null ? void 0 : baseline["ownership"];
11353
+ const baselineMetrics = isRecord2(baselineOwnership) ? readMetrics(baselineOwnership) : null;
11354
+ const metrics = ownership.metrics;
11355
+ const baselineEnabled = ownership.available && baselineMetrics !== null;
11356
+ return {
11357
+ risk: { current: riskScore, delta: riskDelta },
11358
+ health: { current: healthScore, delta: healthDelta },
11359
+ ownership: {
11360
+ available: ownership.available,
11361
+ unownedCritical: metrics?.unownedCritical ?? null,
11362
+ unownedCriticalDelta: deltaWhenKnown(
11363
+ metrics?.unownedCritical ?? null,
11364
+ baselineMetrics?.unownedCritical ?? null,
11365
+ baselineEnabled
11366
+ ),
11367
+ ghostOwners: metrics?.ghostOwners ?? null,
11368
+ ghostOwnersDelta: deltaWhenKnown(
11369
+ metrics?.ghostOwners ?? null,
11370
+ baselineMetrics?.ghostOwners ?? null,
11371
+ baselineEnabled
11372
+ ),
11373
+ driftPercent: metrics?.driftPercent ?? null,
11374
+ driftPercentDelta: deltaWhenKnown(
11375
+ metrics?.driftPercent ?? null,
11376
+ baselineMetrics?.driftPercent ?? null,
11377
+ baselineEnabled
11378
+ )
11379
+ },
11380
+ offenders: ownership.offenders
11381
+ };
11382
+ };
11383
+ var renderPrCommentBody = (input) => {
11384
+ const lines = [
11385
+ PR_COMMENT_MARKER,
11386
+ "",
11387
+ "### CodeSentinel summary",
11388
+ "",
11389
+ "| Signal | Current | Delta |",
11390
+ "| --- | --- | --- |",
11391
+ renderTableRow(["Risk", String(input.risk.current), formatSigned(input.risk.delta)]),
11392
+ renderTableRow(["Health", String(input.health.current), formatSigned(input.health.delta)]),
11393
+ renderTableRow([
11394
+ "Unowned critical",
11395
+ formatCount(input.ownership.unownedCritical),
11396
+ formatSigned(input.ownership.unownedCriticalDelta)
11397
+ ]),
11398
+ renderTableRow([
11399
+ "Ghost owners",
11400
+ formatCount(input.ownership.ghostOwners),
11401
+ formatSigned(input.ownership.ghostOwnersDelta)
11402
+ ]),
11403
+ renderTableRow([
11404
+ "Drift",
11405
+ formatPercent2(input.ownership.driftPercent),
11406
+ formatPercentagePoints(input.ownership.driftPercentDelta)
11407
+ ])
11408
+ ];
11409
+ if (!input.ownership.available) {
11410
+ lines.push("");
11411
+ lines.push("_Ownership audit unavailable: no CODEOWNERS file was found._");
11412
+ }
11413
+ lines.push("");
11414
+ lines.push("**Top offenders**");
11415
+ lines.push("");
11416
+ if (input.offenders.length === 0) {
11417
+ lines.push("No ownership findings.");
11418
+ } else {
11419
+ lines.push("| File | Status | Owner | Evidence |");
11420
+ lines.push("| --- | --- | --- | --- |");
11421
+ for (const offender of input.offenders) {
11422
+ lines.push(
11423
+ renderTableRow([
11424
+ `\`${offender.filePath}\``,
11425
+ offender.status,
11426
+ offender.owners,
11427
+ offender.evidence
11428
+ ])
11429
+ );
11430
+ }
11431
+ }
11432
+ return lines.join("\n");
11433
+ };
11434
+
11435
+ // src/application/run-comment-command.ts
11436
+ import { readFile as readFile8, writeFile as writeFile8 } from "fs/promises";
11437
+
11438
+ // src/application/github-pr-comment-client.ts
11439
+ var DEFAULT_API_URL = "https://api.github.com";
11440
+ var REPOSITORY_PATTERN = /^([^/\s]+)\/([^/\s]+)$/;
11441
+ var isRecord3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
11442
+ var parseComment = (value) => {
11443
+ if (!isRecord3(value)) {
11444
+ return null;
11445
+ }
11446
+ const id = value["id"];
11447
+ const body = value["body"];
11448
+ if (typeof id !== "number" || !Number.isFinite(id) || typeof body !== "string") {
11449
+ return null;
11450
+ }
11451
+ return { id, body };
11452
+ };
11453
+ var buildHeaders = (token) => ({
11454
+ Accept: "application/vnd.github+json",
11455
+ Authorization: `Bearer ${token}`,
11456
+ "X-GitHub-Api-Version": "2022-11-28",
11457
+ "User-Agent": "codesentinel"
11458
+ });
11459
+ var createGitHubPrCommentClient = (options) => {
11460
+ const repositoryMatch = REPOSITORY_PATTERN.exec(options.repository);
11461
+ if (repositoryMatch === null) {
11462
+ throw new PrCommentConfigurationError(
11463
+ "repository must use the owner/repo format (for example: acme/widgets)"
11464
+ );
11465
+ }
11466
+ if (!Number.isInteger(options.pullRequest) || options.pullRequest <= 0) {
11467
+ throw new PrCommentConfigurationError("pull request number must be a positive integer");
11468
+ }
11469
+ const owner = repositoryMatch[1] ?? "";
11470
+ const repo = repositoryMatch[2] ?? "";
11471
+ const apiBase = (options.apiUrl ?? DEFAULT_API_URL).replace(/\/+$/, "");
11472
+ const repositoryPath = `${apiBase}/repos/${owner}/${repo}`;
11473
+ const commentsPath = `${repositoryPath}/issues/${options.pullRequest}/comments`;
11474
+ const headers = buildHeaders(options.token);
11475
+ const fetchImpl = options.fetchImpl ?? fetch;
11476
+ const request = async (url, init) => {
11477
+ const response = await fetchImpl(url, init);
11478
+ const text = await response.text();
11479
+ let payload = null;
11480
+ if (text.length > 0) {
11481
+ try {
11482
+ payload = JSON.parse(text);
11483
+ } catch {
11484
+ payload = null;
11485
+ }
11486
+ }
11487
+ if (!response.ok) {
11488
+ const message = isRecord3(payload) && typeof payload["message"] === "string" ? payload["message"] : response.statusText.length > 0 ? response.statusText : "request failed";
11489
+ throw new Error(`GitHub API request failed (${response.status}): ${message}`);
11490
+ }
11491
+ return payload;
11492
+ };
11493
+ return {
11494
+ listComments: async () => {
11495
+ const payload = await request(`${commentsPath}?per_page=100`, {
11496
+ method: "GET",
11497
+ headers
11498
+ });
11499
+ if (!Array.isArray(payload)) {
11500
+ return [];
11501
+ }
11502
+ return payload.map(parseComment).filter((comment) => comment !== null);
11503
+ },
11504
+ createComment: async (body) => {
11505
+ const payload = await request(commentsPath, {
11506
+ method: "POST",
11507
+ headers: { ...headers, "Content-Type": "application/json" },
11508
+ body: JSON.stringify({ body })
11509
+ });
11510
+ const comment = parseComment(payload);
11511
+ if (comment === null) {
11512
+ throw new Error("GitHub API returned an invalid comment payload");
11513
+ }
11514
+ return comment;
11515
+ },
11516
+ updateComment: async (commentId, body) => {
11517
+ const payload = await request(`${repositoryPath}/issues/comments/${commentId}`, {
11518
+ method: "PATCH",
11519
+ headers: { ...headers, "Content-Type": "application/json" },
11520
+ body: JSON.stringify({ body })
11521
+ });
11522
+ const comment = parseComment(payload);
11523
+ if (comment === null) {
11524
+ throw new Error("GitHub API returned an invalid comment payload");
11525
+ }
11526
+ return comment;
11527
+ }
11528
+ };
11529
+ };
11530
+
11531
+ // src/application/publish-pr-comment.ts
11532
+ var publishPrComment = async (client, body, mode) => {
11533
+ if (mode === "never") {
11534
+ return { action: "skipped", reason: "comment-on never" };
11535
+ }
11536
+ const comments = await client.listComments();
11537
+ const existing = comments.find((comment) => comment.body.includes(PR_COMMENT_MARKER));
11538
+ if (existing === void 0) {
11539
+ const created = await client.createComment(body);
11540
+ return { action: "created", commentId: created.id };
11541
+ }
11542
+ if (mode === "change" && existing.body.trim() === body.trim()) {
11543
+ return { action: "skipped", reason: "no change" };
11544
+ }
11545
+ const updated = await client.updateComment(existing.id, body);
11546
+ return { action: "updated", commentId: updated.id };
11547
+ };
11548
+
11549
+ // src/application/run-comment-command.ts
11550
+ var COMMENT_EXIT_CODES = {
11551
+ ok: 0,
11552
+ invalidConfiguration: 2
11553
+ };
11554
+ var readCiJson = async (inputPath) => {
11555
+ const raw = await readFile8(inputPath, "utf8");
11556
+ try {
11557
+ return JSON.parse(raw);
11558
+ } catch {
11559
+ throw new PrCommentConfigurationError(`invalid CI JSON input: ${inputPath} is not valid JSON`);
11560
+ }
11561
+ };
11562
+ var nonEmpty = (value) => {
11563
+ if (value === void 0) {
11564
+ return null;
11565
+ }
11566
+ return value.trim().length === 0 ? null : value;
11567
+ };
11568
+ var runCommentCommand = async (options, logger = createSilentLogger()) => {
11569
+ const input = parsePrCommentInput(await readCiJson(options.inputPath));
11570
+ const body = renderPrCommentBody(input);
11571
+ const mode = options.mode ?? "change";
11572
+ if (options.outputPath !== void 0) {
11573
+ await writeFile8(options.outputPath, `${body}
11574
+ `, "utf8");
11575
+ logger.info(`comment body written: ${options.outputPath}`);
11576
+ }
11577
+ const output = options.outputPath === void 0 ? {} : { outputPath: options.outputPath };
11578
+ if (options.pullRequest === void 0) {
11579
+ logger.info("no pull request provided; rendered the comment body without posting");
11580
+ return {
11581
+ body,
11582
+ mode,
11583
+ action: "not-requested",
11584
+ exitCode: COMMENT_EXIT_CODES.ok,
11585
+ ...output
11586
+ };
11587
+ }
11588
+ if (mode === "never") {
11589
+ return {
11590
+ body,
11591
+ mode,
11592
+ action: "skipped",
11593
+ reason: "comment-on never",
11594
+ exitCode: COMMENT_EXIT_CODES.ok,
11595
+ ...output
11596
+ };
11597
+ }
11598
+ const token = nonEmpty(options.token ?? process.env["GITHUB_TOKEN"]);
11599
+ if (token === null) {
11600
+ throw new PrCommentConfigurationError(
11601
+ "GITHUB_TOKEN is not set; set it in the environment to post a pull request comment."
11602
+ );
11603
+ }
11604
+ const repository = nonEmpty(options.repository ?? process.env["GITHUB_REPOSITORY"]);
11605
+ if (repository === null) {
11606
+ throw new PrCommentConfigurationError(
11607
+ "GITHUB_REPOSITORY is not set; pass --repository or set GITHUB_REPOSITORY."
11608
+ );
11609
+ }
11610
+ const client = createGitHubPrCommentClient({
11611
+ repository,
11612
+ pullRequest: options.pullRequest,
11613
+ token,
11614
+ ...options.fetchImpl === void 0 ? {} : { fetchImpl: options.fetchImpl }
11615
+ });
11616
+ const published = await publishPrComment(client, body, mode);
11617
+ logger.info(`pull request comment ${published.action}`);
11618
+ return {
11619
+ body,
11620
+ mode,
11621
+ action: published.action,
11622
+ ...published.reason === void 0 ? {} : { reason: published.reason },
11623
+ ...published.commentId === void 0 ? {} : { commentId: published.commentId },
11624
+ exitCode: COMMENT_EXIT_CODES.ok,
11625
+ ...output
11626
+ };
11627
+ };
11628
+
10979
11629
  // src/application/run-trend-command.ts
10980
- import { writeFile as writeFile8 } from "fs/promises";
11630
+ import { writeFile as writeFile9 } from "fs/promises";
10981
11631
 
10982
11632
  // src/application/format-trend-output.ts
10983
11633
  var TREND_SCHEMA_VERSION = "codesentinel.trend.v1";
@@ -11006,7 +11656,7 @@ var buildDeltas = (first, last) => ({
11006
11656
  var formatDate = (value) => new Date(value).toISOString().slice(0, 16).replace("T", " ");
11007
11657
  var formatCommit = (commit) => commit === null ? "\u2014" : commit.slice(0, 7);
11008
11658
  var formatNumber2 = (value) => String(roundToHundredths(value));
11009
- var formatPercent2 = (value) => `${formatNumber2(value)}%`;
11659
+ var formatPercent3 = (value) => `${formatNumber2(value)}%`;
11010
11660
  var formatDelta = (value) => {
11011
11661
  const rounded = roundToHundredths(value);
11012
11662
  return rounded === 0 ? "0" : rounded > 0 ? `+${formatNumber2(rounded)}` : formatNumber2(rounded);
@@ -11018,7 +11668,7 @@ var pointCells = (point) => [
11018
11668
  formatNumber2(point.healthScore),
11019
11669
  point.ownership === null ? "\u2014" : formatNumber2(point.ownership.unownedCritical),
11020
11670
  point.ownership === null ? "\u2014" : formatNumber2(point.ownership.ghostOwners),
11021
- point.ownership === null ? "\u2014" : formatPercent2(point.ownership.driftPercent)
11671
+ point.ownership === null ? "\u2014" : formatPercent3(point.ownership.driftPercent)
11022
11672
  ];
11023
11673
  var renderDeltas = (deltas) => [
11024
11674
  `\u0394 risk ${formatDelta(deltas.riskScore)}`,
@@ -11070,11 +11720,11 @@ var renderConsole2 = (report) => {
11070
11720
  appendWarnings2(lines, report.warnings);
11071
11721
  return lines.join("\n");
11072
11722
  };
11073
- var escapeTableCell2 = (value) => value.replace(/\|/g, "\\|");
11723
+ var escapeTableCell3 = (value) => value.replace(/\|/g, "\\|");
11074
11724
  var renderMarkdownTable2 = (header, rows) => {
11075
11725
  const lines = [`| ${header.join(" | ")} |`, `| ${header.map(() => "---").join(" | ")} |`];
11076
11726
  for (const row of rows) {
11077
- lines.push(`| ${row.map(escapeTableCell2).join(" | ")} |`);
11727
+ lines.push(`| ${row.map(escapeTableCell3).join(" | ")} |`);
11078
11728
  }
11079
11729
  return lines;
11080
11730
  };
@@ -11113,8 +11763,8 @@ var formatTrendOutput = (report, format) => {
11113
11763
  };
11114
11764
 
11115
11765
  // src/application/read-trend-snapshots.ts
11116
- import { glob, readFile as readFile8, readdir as readdir2, stat as stat3 } from "fs/promises";
11117
- import { basename as basename5, join as join11, resolve as resolve9 } from "path";
11766
+ import { glob, readFile as readFile9, readdir as readdir2, stat as stat3 } from "fs/promises";
11767
+ import { basename as basename5, join as join12, resolve as resolve9 } from "path";
11118
11768
  var TrendConfigurationError = class extends Error {
11119
11769
  constructor(message) {
11120
11770
  super(message);
@@ -11160,6 +11810,7 @@ var formatSchemaVersion = (value) => {
11160
11810
  }
11161
11811
  return JSON.stringify(value) ?? "invalid";
11162
11812
  };
11813
+ var isSupportedSchemaVersion2 = (value) => typeof value === "string" && SUPPORTED_SNAPSHOT_SCHEMA_VERSIONS.includes(value);
11163
11814
  var parseSnapshot2 = (fileName, content) => {
11164
11815
  let parsed;
11165
11816
  try {
@@ -11172,7 +11823,7 @@ var parseSnapshot2 = (fileName, content) => {
11172
11823
  return { point: null, warning: `skipped ${fileName}: unsupported schema version "missing"` };
11173
11824
  }
11174
11825
  const schemaVersion = snapshot["schemaVersion"];
11175
- if (schemaVersion !== SNAPSHOT_SCHEMA_VERSION) {
11826
+ if (!isSupportedSchemaVersion2(schemaVersion)) {
11176
11827
  const label = formatSchemaVersion(schemaVersion);
11177
11828
  return {
11178
11829
  point: null,
@@ -11219,7 +11870,7 @@ var discoverSnapshotFiles = async (from) => {
11219
11870
  const entries = await readdir2(resolved, { withFileTypes: true }).catch(() => {
11220
11871
  throw new TrendConfigurationError(`--from directory is not readable: ${from}`);
11221
11872
  });
11222
- const files2 = entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => ({ path: join11(resolved, entry.name), name: entry.name })).sort((a, b) => compareText4(a.name, b.name));
11873
+ const files2 = entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => ({ path: join12(resolved, entry.name), name: entry.name })).sort((a, b) => compareText4(a.name, b.name));
11223
11874
  if (files2.length === 0) {
11224
11875
  throw new TrendConfigurationError(`no snapshot JSON files found in ${from}`);
11225
11876
  }
@@ -11311,7 +11962,7 @@ var readTrendSnapshots = async (options) => {
11311
11962
  for (const file of files) {
11312
11963
  let content;
11313
11964
  try {
11314
- content = await readFile8(file.path, "utf8");
11965
+ content = await readFile9(file.path, "utf8");
11315
11966
  } catch {
11316
11967
  warnings.push(`skipped ${file.name}: invalid JSON`);
11317
11968
  continue;
@@ -11356,7 +12007,7 @@ var runTrendCommand = async (options, logger = createSilentLogger()) => {
11356
12007
  const rendered = formatTrendOutput(report, format);
11357
12008
  logger.debug(`trend series: ${report.series.length} snapshot(s)`);
11358
12009
  if (options.outputPath !== void 0) {
11359
- await writeFile8(options.outputPath, `${rendered}
12010
+ await writeFile9(options.outputPath, `${rendered}
11360
12011
  `, "utf8");
11361
12012
  logger.info(`trend output written: ${options.outputPath}`);
11362
12013
  }
@@ -11369,8 +12020,8 @@ var runTrendCommand = async (options, logger = createSilentLogger()) => {
11369
12020
  };
11370
12021
 
11371
12022
  // src/application/run-init-command.ts
11372
- import { access, mkdir as mkdir4, writeFile as writeFile9 } from "fs/promises";
11373
- import { dirname as dirname3, join as join12, resolve as resolve10 } from "path";
12023
+ import { access, mkdir as mkdir4, writeFile as writeFile10 } from "fs/promises";
12024
+ import { dirname as dirname3, join as join13, resolve as resolve10 } from "path";
11374
12025
  var CODESENTINEL_WORKFLOW_PATH = ".github/workflows/codesentinel.yml";
11375
12026
  var CODESENTINEL_OWNERS_PATH = ".codesentinel/owners.json";
11376
12027
  var CODESENTINEL_WORKFLOW_TEMPLATE = `name: CodeSentinel
@@ -11382,6 +12033,8 @@ on:
11382
12033
 
11383
12034
  permissions:
11384
12035
  contents: read
12036
+ security-events: write
12037
+ pull-requests: write
11385
12038
 
11386
12039
  jobs:
11387
12040
  codesentinel:
@@ -11398,12 +12051,29 @@ jobs:
11398
12051
  node-version: 24
11399
12052
 
11400
12053
  - name: Run CodeSentinel
11401
- run: npx --yes @getcodesentinel/codesentinel@latest ci --baseline-ref auto --fail-on error --snapshot codesentinel-snapshot.json
12054
+ run: npx --yes @getcodesentinel/codesentinel@latest ci --baseline-ref auto --fail-on error --snapshot codesentinel-snapshot.json --json-output codesentinel-ci.json
11402
12055
 
11403
12056
  - name: Build ownership report
11404
- if: hashFiles('CODEOWNERS', '.github/CODEOWNERS', 'docs/CODEOWNERS') != ''
12057
+ if: always() && hashFiles('CODEOWNERS', '.github/CODEOWNERS', 'docs/CODEOWNERS') != ''
11405
12058
  run: npx --yes @getcodesentinel/codesentinel@latest owners --format md --output ownership.md
11406
12059
 
12060
+ - name: Build ownership SARIF
12061
+ if: always() && hashFiles('CODEOWNERS', '.github/CODEOWNERS', 'docs/CODEOWNERS') != ''
12062
+ run: npx --yes @getcodesentinel/codesentinel@latest owners --format sarif --output codesentinel-ownership.sarif
12063
+
12064
+ - name: Upload ownership SARIF
12065
+ if: always() && hashFiles('codesentinel-ownership.sarif') != '' && (github.event_name == 'pull_request' || (github.event_name == 'push' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)))
12066
+ uses: github/codeql-action/upload-sarif@v3
12067
+ with:
12068
+ sarif_file: codesentinel-ownership.sarif
12069
+ category: codesentinel-ownership
12070
+
12071
+ - name: Post summary comment
12072
+ if: always() && github.event_name == 'pull_request'
12073
+ env:
12074
+ GITHUB_TOKEN: \${{ secrets.GITHUB_TOKEN }}
12075
+ run: npx --yes @getcodesentinel/codesentinel@latest comment --input codesentinel-ci.json --pr \${{ github.event.pull_request.number }} --comment-on change
12076
+
11407
12077
  - name: Upload CodeSentinel artifacts
11408
12078
  if: always()
11409
12079
  uses: actions/upload-artifact@v4
@@ -11512,7 +12182,7 @@ var fileExists = async (absolutePath) => {
11512
12182
  };
11513
12183
  var anyFileExists = async (targetPath, candidates) => {
11514
12184
  for (const candidate of candidates) {
11515
- if (await fileExists(join12(targetPath, candidate))) {
12185
+ if (await fileExists(join13(targetPath, candidate))) {
11516
12186
  return true;
11517
12187
  }
11518
12188
  }
@@ -11528,8 +12198,8 @@ var runInitCommand = async (inputPath, options = {}) => {
11528
12198
  const hasCodeownersFile = await anyFileExists(targetPath, CODEOWNERS_CANDIDATES);
11529
12199
  const plan = buildInitPlan({
11530
12200
  hasCodeownersFile,
11531
- workflowExists: ci === "github" && await fileExists(join12(targetPath, CODESENTINEL_WORKFLOW_PATH)),
11532
- ownersFileExists: hasCodeownersFile && await fileExists(join12(targetPath, CODESENTINEL_OWNERS_PATH)),
12201
+ workflowExists: ci === "github" && await fileExists(join13(targetPath, CODESENTINEL_WORKFLOW_PATH)),
12202
+ ownersFileExists: hasCodeownersFile && await fileExists(join13(targetPath, CODESENTINEL_OWNERS_PATH)),
11533
12203
  options: { ...options, ci }
11534
12204
  });
11535
12205
  if (options.dryRun !== true) {
@@ -11537,9 +12207,9 @@ var runInitCommand = async (inputPath, options = {}) => {
11537
12207
  if (entry.status !== "created" && entry.status !== "updated") {
11538
12208
  continue;
11539
12209
  }
11540
- const absolutePath = join12(targetPath, entry.path);
12210
+ const absolutePath = join13(targetPath, entry.path);
11541
12211
  await mkdir4(dirname3(absolutePath), { recursive: true });
11542
- await writeFile9(absolutePath, entry.content ?? "", "utf8");
12212
+ await writeFile10(absolutePath, entry.content ?? "", "utf8");
11543
12213
  }
11544
12214
  }
11545
12215
  return {
@@ -11876,12 +12546,12 @@ program.command("run").argument("[path]", "path to the project to analyze").addO
11876
12546
  ...options.trace === true ? { trace: explain.trace } : {}
11877
12547
  });
11878
12548
  if (options.snapshot !== void 0) {
11879
- await writeFile10(options.snapshot, JSON.stringify(snapshot, null, 2), "utf8");
12549
+ await writeFile11(options.snapshot, JSON.stringify(snapshot, null, 2), "utf8");
11880
12550
  logger.info(`snapshot written: ${options.snapshot}`);
11881
12551
  }
11882
12552
  const report = options.compare === void 0 ? createReport(snapshot) : createReport(
11883
12553
  snapshot,
11884
- compareSnapshots(snapshot, parseSnapshot(await readFile9(options.compare, "utf8")))
12554
+ compareSnapshots(snapshot, parseSnapshot(await readFile10(options.compare, "utf8")))
11885
12555
  );
11886
12556
  if (options.report === "html") {
11887
12557
  const htmlOutputPath = await writeHtmlReportBundle(report, {
@@ -12299,14 +12969,25 @@ var parseOwnersRatio = (value, optionName) => {
12299
12969
  }
12300
12970
  return parsed;
12301
12971
  };
12972
+ var parseCommentPullRequest = (value) => {
12973
+ if (value === void 0) {
12974
+ return void 0;
12975
+ }
12976
+ const trimmed = value.trim();
12977
+ const parsed = Number.parseInt(trimmed, 10);
12978
+ if (!/^\d+$/.test(trimmed) || !Number.isInteger(parsed) || parsed <= 0) {
12979
+ throw new PrCommentConfigurationError("--pr must be a positive integer");
12980
+ }
12981
+ return parsed;
12982
+ };
12302
12983
  program.command("owners").alias("ownership").exitOverride().argument("[path]", "path to the repository to audit").option(
12303
12984
  "--codeowners <file>",
12304
12985
  "explicit CODEOWNERS path, relative to the repository root (default: auto-discovery)"
12305
12986
  ).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(
12306
12987
  new Option(
12307
12988
  "--format <mode>",
12308
- "output format: console (default), json (stable, sorted payload) or md (pastes into a PR)"
12309
- ).choices(["console", "json", "md"]).default("console")
12989
+ "output format: console (default), json (stable, sorted payload), md (pastes into a PR) or sarif (code scanning)"
12990
+ ).choices(["console", "json", "md", "sarif"]).default("console")
12310
12991
  ).option("--output <file>", "write the rendered output to a file instead of stdout").option("--aliases <file>", "identity alias map", ".codesentinel/owners.json").option(
12311
12992
  "--resolve-github",
12312
12993
  "accepted for compatibility; not implemented in this iteration, the audit stays offline"
@@ -12333,6 +13014,7 @@ program.command("owners").alias("ownership").exitOverride().argument("[path]", "
12333
13014
  format: options.format,
12334
13015
  ...options.output === void 0 ? {} : { outputPath: options.output },
12335
13016
  aliasesPath: options.aliases,
13017
+ toolVersion: version,
12336
13018
  ...options.resolveGithub === true ? { resolveGithub: true } : {},
12337
13019
  thresholds: {
12338
13020
  failOn: options.failOn,
@@ -12358,6 +13040,47 @@ program.command("owners").alias("ownership").exitOverride().argument("[path]", "
12358
13040
  }
12359
13041
  }
12360
13042
  );
13043
+ program.command("comment").exitOverride().description("render or upsert the sticky CodeSentinel pull request summary comment").requiredOption("--input <file>", "CI JSON input written by `codesentinel ci --json-output`").option("--pr <number>", "pull request number to comment on").addOption(
13044
+ new Option(
13045
+ "--comment-on <mode>",
13046
+ "comment behavior: change (only when the body moved), always or never"
13047
+ ).choices(["change", "always", "never"]).default("change")
13048
+ ).option("--repository <owner/repo>", "repository slug (default: GITHUB_REPOSITORY)").option("--output <file>", "write the rendered comment body to a file instead of stdout").addOption(
13049
+ new Option(
13050
+ "--log-level <level>",
13051
+ "log verbosity: silent, error, warn, info, debug (logs are written to stderr)"
13052
+ ).choices(["silent", "error", "warn", "info", "debug"]).default(parseLogLevel(process.env["CODESENTINEL_LOG_LEVEL"]))
13053
+ ).action(
13054
+ async (options) => {
13055
+ const logger = createStderrLogger(options.logLevel);
13056
+ try {
13057
+ const pullRequest = parseCommentPullRequest(options.pr);
13058
+ const result = await runCommentCommand(
13059
+ {
13060
+ inputPath: options.input,
13061
+ ...pullRequest === void 0 ? {} : { pullRequest },
13062
+ mode: options.commentOn,
13063
+ ...options.repository === void 0 ? {} : { repository: options.repository },
13064
+ ...options.output === void 0 ? {} : { outputPath: options.output }
13065
+ },
13066
+ logger
13067
+ );
13068
+ if (result.outputPath === void 0) {
13069
+ process.stdout.write(`${result.body}
13070
+ `);
13071
+ }
13072
+ process.exitCode = result.exitCode;
13073
+ } catch (error) {
13074
+ if (error instanceof PrCommentConfigurationError) {
13075
+ logger.error(error.message);
13076
+ process.exitCode = COMMENT_EXIT_CODES.invalidConfiguration;
13077
+ return;
13078
+ }
13079
+ logger.error(error instanceof Error ? error.message : "internal error");
13080
+ process.exitCode = COMMENT_EXIT_CODES.invalidConfiguration;
13081
+ }
13082
+ }
13083
+ );
12361
13084
  program.command("trend").exitOverride().option(
12362
13085
  "--from <dir-or-glob>",
12363
13086
  "directory of snapshot JSON files (non-recursive) or a glob pattern (required)"