@getcodesentinel/codesentinel 1.37.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
@@ -3856,7 +3856,7 @@ var resolveAutoBaselineRef = async (input) => {
3856
3856
 
3857
3857
  // src/index.ts
3858
3858
  import { readFileSync as readFileSync4 } from "fs";
3859
- import { readFile as readFile9, writeFile as writeFile10 } from "fs/promises";
3859
+ import { readFile as readFile10, writeFile as writeFile11 } from "fs/promises";
3860
3860
  import { dirname as dirname4, resolve as resolve11 } from "path";
3861
3861
  import { fileURLToPath as fileURLToPath2 } from "url";
3862
3862
 
@@ -10608,8 +10608,150 @@ var runExplainCommand = async (inputPath, authorIdentityMode, options, logger =
10608
10608
  import { writeFile as writeFile7 } from "fs/promises";
10609
10609
  import { resolve as resolve8 } from "path";
10610
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
+
10611
10752
  // src/application/format-owners-output.ts
10612
10753
  var OWNERS_SCHEMA_VERSION = "codesentinel.owners.v1";
10754
+ var DEFAULT_SARIF_CONTEXT = { toolVersion: "0.0.0" };
10613
10755
  var formatDeclaredOwner = (owner) => {
10614
10756
  if (owner.kind === "user") return `@${owner.handle}`;
10615
10757
  if (owner.kind === "team") return `@${owner.org}/${owner.slug}`;
@@ -10699,7 +10841,7 @@ var formatRatio = (value) => {
10699
10841
  const percent = Math.round(value * 100);
10700
10842
  return `${percent}%`;
10701
10843
  };
10702
- var formatShare = (share) => share === null ? "n/a" : `${Math.round(share * 100)}%`;
10844
+ var formatShare2 = (share) => share === null ? "n/a" : `${Math.round(share * 100)}%`;
10703
10845
  var plural2 = (count, singular, pluralForm) => `${count} ${count === 1 ? singular : pluralForm}`;
10704
10846
  var padLabel = (label) => `${label}:`.padEnd(26, " ");
10705
10847
  var topLimit = (value) => Number.isFinite(value) && value > 0 ? value : 0;
@@ -10769,7 +10911,7 @@ var renderConsole = (report, top) => {
10769
10911
  ...renderConsoleSection(
10770
10912
  "Drift \u2014 declared owner is not the top recent author",
10771
10913
  drifted.map(
10772
- (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)})`
10773
10915
  ),
10774
10916
  drifted.length,
10775
10917
  top
@@ -10889,7 +11031,7 @@ var renderMarkdown2 = (report, top) => {
10889
11031
  `\`${file.filePath}\``,
10890
11032
  formatDeclaredOwners(file.declared),
10891
11033
  file.observed.topAuthorId ?? "unknown",
10892
- formatShare(file.observed.topAuthorShare)
11034
+ formatShare2(file.observed.topAuthorShare)
10893
11035
  ])
10894
11036
  )
10895
11037
  );
@@ -10924,10 +11066,13 @@ var renderMarkdown2 = (report, top) => {
10924
11066
  }
10925
11067
  return lines.join("\n");
10926
11068
  };
10927
- var formatOwnersOutput = (report, format, top) => {
11069
+ var formatOwnersOutput = (report, format, top, sarifContext) => {
10928
11070
  if (format === "json") {
10929
11071
  return JSON.stringify(report, null, 2);
10930
11072
  }
11073
+ if (format === "sarif") {
11074
+ return formatOwnersSarif(report, sarifContext ?? DEFAULT_SARIF_CONTEXT);
11075
+ }
10931
11076
  return format === "md" ? renderMarkdown2(report, top) : renderConsole(report, top);
10932
11077
  };
10933
11078
 
@@ -11007,7 +11152,9 @@ var runOwnersCommand = async (inputPath, options = {}, logger = createSilentLogg
11007
11152
  thresholds,
11008
11153
  violations
11009
11154
  });
11010
- const rendered = formatOwnersOutput(report, format, top);
11155
+ const rendered = formatOwnersOutput(report, format, top, {
11156
+ toolVersion: options.toolVersion ?? DEFAULT_SARIF_CONTEXT.toolVersion
11157
+ });
11011
11158
  if (options.outputPath !== void 0) {
11012
11159
  await writeFile7(options.outputPath, `${rendered}
11013
11160
  `, "utf8");
@@ -11024,8 +11171,463 @@ var runOwnersCommand = async (inputPath, options = {}, logger = createSilentLogg
11024
11171
  };
11025
11172
  var hasConfiguredThreshold = (thresholds) => thresholds.maxUnownedCritical !== null || thresholds.maxGhostOwners !== null || thresholds.maxDrift !== null;
11026
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
+
11027
11629
  // src/application/run-trend-command.ts
11028
- import { writeFile as writeFile8 } from "fs/promises";
11630
+ import { writeFile as writeFile9 } from "fs/promises";
11029
11631
 
11030
11632
  // src/application/format-trend-output.ts
11031
11633
  var TREND_SCHEMA_VERSION = "codesentinel.trend.v1";
@@ -11054,7 +11656,7 @@ var buildDeltas = (first, last) => ({
11054
11656
  var formatDate = (value) => new Date(value).toISOString().slice(0, 16).replace("T", " ");
11055
11657
  var formatCommit = (commit) => commit === null ? "\u2014" : commit.slice(0, 7);
11056
11658
  var formatNumber2 = (value) => String(roundToHundredths(value));
11057
- var formatPercent2 = (value) => `${formatNumber2(value)}%`;
11659
+ var formatPercent3 = (value) => `${formatNumber2(value)}%`;
11058
11660
  var formatDelta = (value) => {
11059
11661
  const rounded = roundToHundredths(value);
11060
11662
  return rounded === 0 ? "0" : rounded > 0 ? `+${formatNumber2(rounded)}` : formatNumber2(rounded);
@@ -11066,7 +11668,7 @@ var pointCells = (point) => [
11066
11668
  formatNumber2(point.healthScore),
11067
11669
  point.ownership === null ? "\u2014" : formatNumber2(point.ownership.unownedCritical),
11068
11670
  point.ownership === null ? "\u2014" : formatNumber2(point.ownership.ghostOwners),
11069
- point.ownership === null ? "\u2014" : formatPercent2(point.ownership.driftPercent)
11671
+ point.ownership === null ? "\u2014" : formatPercent3(point.ownership.driftPercent)
11070
11672
  ];
11071
11673
  var renderDeltas = (deltas) => [
11072
11674
  `\u0394 risk ${formatDelta(deltas.riskScore)}`,
@@ -11118,11 +11720,11 @@ var renderConsole2 = (report) => {
11118
11720
  appendWarnings2(lines, report.warnings);
11119
11721
  return lines.join("\n");
11120
11722
  };
11121
- var escapeTableCell2 = (value) => value.replace(/\|/g, "\\|");
11723
+ var escapeTableCell3 = (value) => value.replace(/\|/g, "\\|");
11122
11724
  var renderMarkdownTable2 = (header, rows) => {
11123
11725
  const lines = [`| ${header.join(" | ")} |`, `| ${header.map(() => "---").join(" | ")} |`];
11124
11726
  for (const row of rows) {
11125
- lines.push(`| ${row.map(escapeTableCell2).join(" | ")} |`);
11727
+ lines.push(`| ${row.map(escapeTableCell3).join(" | ")} |`);
11126
11728
  }
11127
11729
  return lines;
11128
11730
  };
@@ -11161,7 +11763,7 @@ var formatTrendOutput = (report, format) => {
11161
11763
  };
11162
11764
 
11163
11765
  // src/application/read-trend-snapshots.ts
11164
- import { glob, readFile as readFile8, readdir as readdir2, stat as stat3 } from "fs/promises";
11766
+ import { glob, readFile as readFile9, readdir as readdir2, stat as stat3 } from "fs/promises";
11165
11767
  import { basename as basename5, join as join12, resolve as resolve9 } from "path";
11166
11768
  var TrendConfigurationError = class extends Error {
11167
11769
  constructor(message) {
@@ -11360,7 +11962,7 @@ var readTrendSnapshots = async (options) => {
11360
11962
  for (const file of files) {
11361
11963
  let content;
11362
11964
  try {
11363
- content = await readFile8(file.path, "utf8");
11965
+ content = await readFile9(file.path, "utf8");
11364
11966
  } catch {
11365
11967
  warnings.push(`skipped ${file.name}: invalid JSON`);
11366
11968
  continue;
@@ -11405,7 +12007,7 @@ var runTrendCommand = async (options, logger = createSilentLogger()) => {
11405
12007
  const rendered = formatTrendOutput(report, format);
11406
12008
  logger.debug(`trend series: ${report.series.length} snapshot(s)`);
11407
12009
  if (options.outputPath !== void 0) {
11408
- await writeFile8(options.outputPath, `${rendered}
12010
+ await writeFile9(options.outputPath, `${rendered}
11409
12011
  `, "utf8");
11410
12012
  logger.info(`trend output written: ${options.outputPath}`);
11411
12013
  }
@@ -11418,7 +12020,7 @@ var runTrendCommand = async (options, logger = createSilentLogger()) => {
11418
12020
  };
11419
12021
 
11420
12022
  // src/application/run-init-command.ts
11421
- import { access, mkdir as mkdir4, writeFile as writeFile9 } from "fs/promises";
12023
+ import { access, mkdir as mkdir4, writeFile as writeFile10 } from "fs/promises";
11422
12024
  import { dirname as dirname3, join as join13, resolve as resolve10 } from "path";
11423
12025
  var CODESENTINEL_WORKFLOW_PATH = ".github/workflows/codesentinel.yml";
11424
12026
  var CODESENTINEL_OWNERS_PATH = ".codesentinel/owners.json";
@@ -11431,6 +12033,8 @@ on:
11431
12033
 
11432
12034
  permissions:
11433
12035
  contents: read
12036
+ security-events: write
12037
+ pull-requests: write
11434
12038
 
11435
12039
  jobs:
11436
12040
  codesentinel:
@@ -11447,12 +12051,29 @@ jobs:
11447
12051
  node-version: 24
11448
12052
 
11449
12053
  - name: Run CodeSentinel
11450
- 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
11451
12055
 
11452
12056
  - name: Build ownership report
11453
- if: hashFiles('CODEOWNERS', '.github/CODEOWNERS', 'docs/CODEOWNERS') != ''
12057
+ if: always() && hashFiles('CODEOWNERS', '.github/CODEOWNERS', 'docs/CODEOWNERS') != ''
11454
12058
  run: npx --yes @getcodesentinel/codesentinel@latest owners --format md --output ownership.md
11455
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
+
11456
12077
  - name: Upload CodeSentinel artifacts
11457
12078
  if: always()
11458
12079
  uses: actions/upload-artifact@v4
@@ -11588,7 +12209,7 @@ var runInitCommand = async (inputPath, options = {}) => {
11588
12209
  }
11589
12210
  const absolutePath = join13(targetPath, entry.path);
11590
12211
  await mkdir4(dirname3(absolutePath), { recursive: true });
11591
- await writeFile9(absolutePath, entry.content ?? "", "utf8");
12212
+ await writeFile10(absolutePath, entry.content ?? "", "utf8");
11592
12213
  }
11593
12214
  }
11594
12215
  return {
@@ -11925,12 +12546,12 @@ program.command("run").argument("[path]", "path to the project to analyze").addO
11925
12546
  ...options.trace === true ? { trace: explain.trace } : {}
11926
12547
  });
11927
12548
  if (options.snapshot !== void 0) {
11928
- await writeFile10(options.snapshot, JSON.stringify(snapshot, null, 2), "utf8");
12549
+ await writeFile11(options.snapshot, JSON.stringify(snapshot, null, 2), "utf8");
11929
12550
  logger.info(`snapshot written: ${options.snapshot}`);
11930
12551
  }
11931
12552
  const report = options.compare === void 0 ? createReport(snapshot) : createReport(
11932
12553
  snapshot,
11933
- compareSnapshots(snapshot, parseSnapshot(await readFile9(options.compare, "utf8")))
12554
+ compareSnapshots(snapshot, parseSnapshot(await readFile10(options.compare, "utf8")))
11934
12555
  );
11935
12556
  if (options.report === "html") {
11936
12557
  const htmlOutputPath = await writeHtmlReportBundle(report, {
@@ -12348,14 +12969,25 @@ var parseOwnersRatio = (value, optionName) => {
12348
12969
  }
12349
12970
  return parsed;
12350
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
+ };
12351
12983
  program.command("owners").alias("ownership").exitOverride().argument("[path]", "path to the repository to audit").option(
12352
12984
  "--codeowners <file>",
12353
12985
  "explicit CODEOWNERS path, relative to the repository root (default: auto-discovery)"
12354
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(
12355
12987
  new Option(
12356
12988
  "--format <mode>",
12357
- "output format: console (default), json (stable, sorted payload) or md (pastes into a PR)"
12358
- ).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")
12359
12991
  ).option("--output <file>", "write the rendered output to a file instead of stdout").option("--aliases <file>", "identity alias map", ".codesentinel/owners.json").option(
12360
12992
  "--resolve-github",
12361
12993
  "accepted for compatibility; not implemented in this iteration, the audit stays offline"
@@ -12382,6 +13014,7 @@ program.command("owners").alias("ownership").exitOverride().argument("[path]", "
12382
13014
  format: options.format,
12383
13015
  ...options.output === void 0 ? {} : { outputPath: options.output },
12384
13016
  aliasesPath: options.aliases,
13017
+ toolVersion: version,
12385
13018
  ...options.resolveGithub === true ? { resolveGithub: true } : {},
12386
13019
  thresholds: {
12387
13020
  failOn: options.failOn,
@@ -12407,6 +13040,47 @@ program.command("owners").alias("ownership").exitOverride().argument("[path]", "
12407
13040
  }
12408
13041
  }
12409
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
+ );
12410
13084
  program.command("trend").exitOverride().option(
12411
13085
  "--from <dir-or-glob>",
12412
13086
  "directory of snapshot JSON files (non-recursive) or a glob pattern (required)"