@getcodesentinel/codesentinel 1.34.0 → 1.36.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
@@ -3838,8 +3838,8 @@ var resolveAutoBaselineRef = async (input) => {
3838
3838
 
3839
3839
  // src/index.ts
3840
3840
  import { readFileSync as readFileSync4 } from "fs";
3841
- import { readFile as readFile8, writeFile as writeFile8 } from "fs/promises";
3842
- import { dirname as dirname3, resolve as resolve9 } from "path";
3841
+ import { readFile as readFile9, writeFile as writeFile10 } from "fs/promises";
3842
+ import { dirname as dirname4, resolve as resolve11 } from "path";
3843
3843
  import { fileURLToPath as fileURLToPath2 } from "url";
3844
3844
 
3845
3845
  // src/application/format-analyze-output.ts
@@ -4520,7 +4520,7 @@ var promptInstall = async (packageName, latestVersion, currentVersion) => {
4520
4520
  );
4521
4521
  return "skip";
4522
4522
  }
4523
- return await new Promise((resolve10) => {
4523
+ return await new Promise((resolve12) => {
4524
4524
  emitKeypressEvents(stdin);
4525
4525
  let selectedIndex = 0;
4526
4526
  const previousRawMode = stdin.isRaw;
@@ -4545,7 +4545,7 @@ var promptInstall = async (packageName, latestVersion, currentVersion) => {
4545
4545
  } else {
4546
4546
  stderr.write("\n");
4547
4547
  }
4548
- resolve10(choice);
4548
+ resolve12(choice);
4549
4549
  };
4550
4550
  const onKeypress = (_str, key) => {
4551
4551
  if (key.ctrl === true && key.name === "c") {
@@ -4666,19 +4666,19 @@ var ANSI2 = {
4666
4666
  };
4667
4667
  var PROMPT_PADDING = " ";
4668
4668
  var renderMenu = (currentVersion, actions, selectedIndex) => {
4669
- const optionLabels = actions.map((action, index) => `${index + 1}. ${action.label}`);
4669
+ const optionLabels = actions.map((action2, index) => `${index + 1}. ${action2.label}`);
4670
4670
  const labelWidth = optionLabels.reduce((max, label) => Math.max(max, label.length), 0);
4671
4671
  const lines = [
4672
4672
  ` ${ANSI2.bold}${ANSI2.cyan}CodeSentinel${ANSI2.reset} ${ANSI2.dim}v${currentVersion}${ANSI2.reset}`,
4673
4673
  "",
4674
4674
  " Choose an action:",
4675
4675
  "",
4676
- ...actions.map((action, index) => {
4676
+ ...actions.map((action2, index) => {
4677
4677
  const selected = index === selectedIndex;
4678
4678
  const prefix = selected ? `${ANSI2.green}>${ANSI2.reset}` : " ";
4679
4679
  const label = optionLabels[index]?.padEnd(labelWidth, " ") ?? "";
4680
4680
  const renderedLabel = selected ? `${ANSI2.bold}${label}${ANSI2.reset}` : label;
4681
- return `${prefix} ${renderedLabel} ${ANSI2.dim}${action.description}${ANSI2.reset}`;
4681
+ return `${prefix} ${renderedLabel} ${ANSI2.dim}${action2.description}${ANSI2.reset}`;
4682
4682
  }),
4683
4683
  "",
4684
4684
  ` ${ANSI2.dim}Use \u2191/\u2193 to choose. Press enter to continue. Press q or Ctrl+C to exit.${ANSI2.reset}`
@@ -4739,7 +4739,7 @@ var promptSelection = async (currentVersion, actions) => {
4739
4739
  if (!stdin2.isTTY || !stderr2.isTTY || typeof stdin2.setRawMode !== "function") {
4740
4740
  return "exit";
4741
4741
  }
4742
- return await new Promise((resolve10) => {
4742
+ return await new Promise((resolve12) => {
4743
4743
  emitKeypressEvents2(stdin2);
4744
4744
  let selectedIndex = 0;
4745
4745
  const previousRawMode = stdin2.isRaw;
@@ -4754,7 +4754,7 @@ var promptSelection = async (currentVersion, actions) => {
4754
4754
  stdin2.setRawMode(previousRawMode);
4755
4755
  clearTerminal();
4756
4756
  showCursor2();
4757
- resolve10(selection);
4757
+ resolve12(selection);
4758
4758
  };
4759
4759
  const onKeypress = (_str, key) => {
4760
4760
  if (key.ctrl === true && key.name === "c") {
@@ -4847,7 +4847,7 @@ var waitForReturnToMenu = async () => {
4847
4847
  }
4848
4848
  stderr2.write(`
4849
4849
  ${PROMPT_PADDING}Press enter to return to the menu...`);
4850
- await new Promise((resolve10) => {
4850
+ await new Promise((resolve12) => {
4851
4851
  emitKeypressEvents2(stdin2);
4852
4852
  const previousRawMode = stdin2.isRaw;
4853
4853
  const cleanup = () => {
@@ -4856,7 +4856,7 @@ ${PROMPT_PADDING}Press enter to return to the menu...`);
4856
4856
  stdin2.setRawMode(previousRawMode);
4857
4857
  showCursor2();
4858
4858
  stderr2.write("\n");
4859
- resolve10();
4859
+ resolve12();
4860
4860
  };
4861
4861
  const onKeypress = (_str, key) => {
4862
4862
  if (key.ctrl === true && key.name === "c") {
@@ -4874,7 +4874,7 @@ ${PROMPT_PADDING}Press enter to return to the menu...`);
4874
4874
  });
4875
4875
  };
4876
4876
  var runCliCommand = async (scriptPath2, args) => {
4877
- return await new Promise((resolve10, reject) => {
4877
+ return await new Promise((resolve12, reject) => {
4878
4878
  const child = spawn2(process.execPath, [...process.execArgv, scriptPath2, ...args], {
4879
4879
  stdio: ["inherit", "pipe", "pipe"],
4880
4880
  env: {
@@ -4888,7 +4888,7 @@ var runCliCommand = async (scriptPath2, args) => {
4888
4888
  reject(error);
4889
4889
  });
4890
4890
  child.on("close", (code) => {
4891
- resolve10(code ?? 1);
4891
+ resolve12(code ?? 1);
4892
4892
  });
4893
4893
  });
4894
4894
  };
@@ -10326,15 +10326,15 @@ var openPath = async (targetPath) => {
10326
10326
  if (command === void 0) {
10327
10327
  return false;
10328
10328
  }
10329
- return new Promise((resolve10) => {
10329
+ return new Promise((resolve12) => {
10330
10330
  const child = spawn3(command.command, command.args, {
10331
10331
  detached: true,
10332
10332
  stdio: "ignore"
10333
10333
  });
10334
- child.once("error", () => resolve10(false));
10334
+ child.once("error", () => resolve12(false));
10335
10335
  child.once("spawn", () => {
10336
10336
  child.unref();
10337
- resolve10(true);
10337
+ resolve12(true);
10338
10338
  });
10339
10339
  });
10340
10340
  };
@@ -10976,9 +10976,583 @@ var runOwnersCommand = async (inputPath, options = {}, logger = createSilentLogg
10976
10976
  };
10977
10977
  var hasConfiguredThreshold = (thresholds) => thresholds.maxUnownedCritical !== null || thresholds.maxGhostOwners !== null || thresholds.maxDrift !== null;
10978
10978
 
10979
+ // src/application/run-trend-command.ts
10980
+ import { writeFile as writeFile8 } from "fs/promises";
10981
+
10982
+ // src/application/format-trend-output.ts
10983
+ var TREND_SCHEMA_VERSION = "codesentinel.trend.v1";
10984
+ var buildTrendReport = (series, warnings) => {
10985
+ const first = series[0];
10986
+ const last = series[series.length - 1];
10987
+ const deltas = series.length < 2 || first === void 0 || last === void 0 ? null : buildDeltas(first, last);
10988
+ return {
10989
+ schemaVersion: TREND_SCHEMA_VERSION,
10990
+ series: [...series],
10991
+ deltas,
10992
+ warnings: [...warnings]
10993
+ };
10994
+ };
10995
+ var roundToHundredths = (value) => {
10996
+ const rounded = Math.round(value * 100) / 100;
10997
+ return rounded === 0 ? 0 : rounded;
10998
+ };
10999
+ var buildDeltas = (first, last) => ({
11000
+ riskScore: roundToHundredths(last.riskScore - first.riskScore),
11001
+ healthScore: roundToHundredths(last.healthScore - first.healthScore),
11002
+ unownedCritical: first.ownership === null || last.ownership === null ? null : roundToHundredths(last.ownership.unownedCritical - first.ownership.unownedCritical),
11003
+ ghostOwners: first.ownership === null || last.ownership === null ? null : roundToHundredths(last.ownership.ghostOwners - first.ownership.ghostOwners),
11004
+ driftPercent: first.ownership === null || last.ownership === null ? null : roundToHundredths(last.ownership.driftPercent - first.ownership.driftPercent)
11005
+ });
11006
+ var formatDate = (value) => new Date(value).toISOString().slice(0, 16).replace("T", " ");
11007
+ var formatCommit = (commit) => commit === null ? "\u2014" : commit.slice(0, 7);
11008
+ var formatNumber2 = (value) => String(roundToHundredths(value));
11009
+ var formatPercent2 = (value) => `${formatNumber2(value)}%`;
11010
+ var formatDelta = (value) => {
11011
+ const rounded = roundToHundredths(value);
11012
+ return rounded === 0 ? "0" : rounded > 0 ? `+${formatNumber2(rounded)}` : formatNumber2(rounded);
11013
+ };
11014
+ var pointCells = (point) => [
11015
+ formatDate(point.generatedAt),
11016
+ formatCommit(point.commit),
11017
+ formatNumber2(point.riskScore),
11018
+ formatNumber2(point.healthScore),
11019
+ point.ownership === null ? "\u2014" : formatNumber2(point.ownership.unownedCritical),
11020
+ point.ownership === null ? "\u2014" : formatNumber2(point.ownership.ghostOwners),
11021
+ point.ownership === null ? "\u2014" : formatPercent2(point.ownership.driftPercent)
11022
+ ];
11023
+ var renderDeltas = (deltas) => [
11024
+ `\u0394 risk ${formatDelta(deltas.riskScore)}`,
11025
+ `\u0394 health ${formatDelta(deltas.healthScore)}`,
11026
+ `\u0394 unowned ${deltas.unownedCritical === null ? "\u2014" : formatDelta(deltas.unownedCritical)}`,
11027
+ `\u0394 ghosts ${deltas.ghostOwners === null ? "\u2014" : formatDelta(deltas.ghostOwners)}`,
11028
+ `\u0394 drift ${deltas.driftPercent === null ? "\u2014" : `${formatDelta(deltas.driftPercent)}pp`}`
11029
+ ].join(" ");
11030
+ var renderHeader = (report) => {
11031
+ const count = report.series.length;
11032
+ const label = `${count} ${count === 1 ? "snapshot" : "snapshots"}`;
11033
+ const first = report.series[0];
11034
+ const last = report.series[count - 1];
11035
+ if (first === void 0 || last === void 0) {
11036
+ return `Snapshot trend \u2014 ${label}`;
11037
+ }
11038
+ return `Snapshot trend \u2014 ${label} (${formatDate(first.generatedAt)} \u2192 ${formatDate(last.generatedAt)})`;
11039
+ };
11040
+ var appendWarnings2 = (lines, warnings) => {
11041
+ if (warnings.length === 0) return;
11042
+ lines.push("");
11043
+ lines.push("Warnings");
11044
+ for (const warning of warnings) {
11045
+ lines.push(` - ${warning}`);
11046
+ }
11047
+ };
11048
+ var TREND_HEADERS = ["Date", "Commit", "Risk", "Health", "Unowned", "Ghosts", "Drift"];
11049
+ var renderAlignedRow = (cells, widths) => cells.map((cell, index) => {
11050
+ const width = widths[index] ?? cell.length;
11051
+ return index < 2 ? cell.padEnd(width) : cell.padStart(width);
11052
+ }).join(" ");
11053
+ var renderConsole2 = (report) => {
11054
+ const rows = report.series.map(pointCells);
11055
+ const widths = TREND_HEADERS.map(
11056
+ (header, index) => Math.max(header.length, ...rows.map((row) => (row[index] ?? "").length))
11057
+ );
11058
+ const lines = [renderHeader(report), ""];
11059
+ lines.push(renderAlignedRow(TREND_HEADERS, widths).trimEnd());
11060
+ for (const row of rows) {
11061
+ lines.push(renderAlignedRow(row, widths).trimEnd());
11062
+ }
11063
+ if (report.deltas === null) {
11064
+ lines.push("");
11065
+ lines.push("not enough history for a trend");
11066
+ } else {
11067
+ lines.push("");
11068
+ lines.push(renderDeltas(report.deltas));
11069
+ }
11070
+ appendWarnings2(lines, report.warnings);
11071
+ return lines.join("\n");
11072
+ };
11073
+ var escapeTableCell2 = (value) => value.replace(/\|/g, "\\|");
11074
+ var renderMarkdownTable2 = (header, rows) => {
11075
+ const lines = [`| ${header.join(" | ")} |`, `| ${header.map(() => "---").join(" | ")} |`];
11076
+ for (const row of rows) {
11077
+ lines.push(`| ${row.map(escapeTableCell2).join(" | ")} |`);
11078
+ }
11079
+ return lines;
11080
+ };
11081
+ var renderMarkdown3 = (report) => {
11082
+ const lines = ["# Snapshot trend", ""];
11083
+ lines.push(`- snapshots: ${report.series.length}`);
11084
+ const first = report.series[0];
11085
+ const last = report.series[report.series.length - 1];
11086
+ if (first !== void 0 && last !== void 0) {
11087
+ lines.push(`- window: ${formatDate(first.generatedAt)} \u2192 ${formatDate(last.generatedAt)}`);
11088
+ }
11089
+ lines.push("");
11090
+ lines.push(...renderMarkdownTable2(TREND_HEADERS, report.series.map(pointCells)));
11091
+ if (report.deltas === null) {
11092
+ lines.push("");
11093
+ lines.push("not enough history for a trend");
11094
+ } else {
11095
+ lines.push("");
11096
+ lines.push(renderDeltas(report.deltas));
11097
+ }
11098
+ if (report.warnings.length > 0) {
11099
+ lines.push("");
11100
+ lines.push("## Warnings");
11101
+ lines.push("");
11102
+ for (const warning of report.warnings) {
11103
+ lines.push(`- ${warning}`);
11104
+ }
11105
+ }
11106
+ return lines.join("\n");
11107
+ };
11108
+ var formatTrendOutput = (report, format) => {
11109
+ if (format === "json") {
11110
+ return JSON.stringify(report, null, 2);
11111
+ }
11112
+ return format === "md" ? renderMarkdown3(report) : renderConsole2(report);
11113
+ };
11114
+
11115
+ // 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";
11118
+ var TrendConfigurationError = class extends Error {
11119
+ constructor(message) {
11120
+ super(message);
11121
+ this.name = "TrendConfigurationError";
11122
+ }
11123
+ };
11124
+ var compareText4 = (a, b) => a < b ? -1 : a > b ? 1 : 0;
11125
+ var asRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
11126
+ var isFiniteNumber = (value) => typeof value === "number" && Number.isFinite(value);
11127
+ var readCommit = (snapshot) => {
11128
+ const candidates = [
11129
+ snapshot["commit"],
11130
+ asRecord(snapshot["git"])?.["commit"],
11131
+ asRecord(snapshot["source"])?.["commit"],
11132
+ asRecord(snapshot["analysisConfig"])?.["commit"]
11133
+ ];
11134
+ for (const candidate of candidates) {
11135
+ if (typeof candidate === "string" && candidate.trim().length > 0) {
11136
+ return candidate;
11137
+ }
11138
+ }
11139
+ return null;
11140
+ };
11141
+ var readOwnership = (snapshot) => {
11142
+ const ownership = asRecord(snapshot["ownership"]);
11143
+ if (ownership === null || ownership["available"] === false) {
11144
+ return null;
11145
+ }
11146
+ const source = asRecord(ownership["metrics"]) ?? ownership;
11147
+ const unownedCritical = source["unownedCriticalCount"];
11148
+ const ghostOwners = source["ghostOwnerCount"];
11149
+ const driftPercent = source["driftPercent"];
11150
+ if (!isFiniteNumber(unownedCritical) || !isFiniteNumber(ghostOwners) || !isFiniteNumber(driftPercent)) {
11151
+ return null;
11152
+ }
11153
+ return { unownedCritical, ghostOwners, driftPercent };
11154
+ };
11155
+ var formatSchemaVersion = (value) => {
11156
+ if (value === void 0) return "missing";
11157
+ if (typeof value === "string") return value;
11158
+ if (typeof value === "number" || typeof value === "boolean" || value === null) {
11159
+ return String(value);
11160
+ }
11161
+ return JSON.stringify(value) ?? "invalid";
11162
+ };
11163
+ var parseSnapshot2 = (fileName, content) => {
11164
+ let parsed;
11165
+ try {
11166
+ parsed = JSON.parse(content);
11167
+ } catch {
11168
+ return { point: null, warning: `skipped ${fileName}: invalid JSON` };
11169
+ }
11170
+ const snapshot = asRecord(parsed);
11171
+ if (snapshot === null) {
11172
+ return { point: null, warning: `skipped ${fileName}: unsupported schema version "missing"` };
11173
+ }
11174
+ const schemaVersion = snapshot["schemaVersion"];
11175
+ if (schemaVersion !== SNAPSHOT_SCHEMA_VERSION) {
11176
+ const label = formatSchemaVersion(schemaVersion);
11177
+ return {
11178
+ point: null,
11179
+ warning: `skipped ${fileName}: unsupported schema version "${label}"`
11180
+ };
11181
+ }
11182
+ const generatedAt = snapshot["generatedAt"];
11183
+ if (typeof generatedAt !== "string" || Number.isNaN(Date.parse(generatedAt))) {
11184
+ return { point: null, warning: `skipped ${fileName}: missing or invalid generatedAt` };
11185
+ }
11186
+ const analysis = asRecord(snapshot["analysis"]);
11187
+ const riskScore = asRecord(analysis?.["risk"])?.["riskScore"];
11188
+ const healthScore = asRecord(analysis?.["health"])?.["healthScore"];
11189
+ if (!isFiniteNumber(riskScore) || !isFiniteNumber(healthScore)) {
11190
+ return { point: null, warning: `skipped ${fileName}: missing risk or health score` };
11191
+ }
11192
+ return {
11193
+ point: {
11194
+ file: fileName,
11195
+ generatedAt,
11196
+ commit: readCommit(snapshot),
11197
+ riskScore,
11198
+ healthScore,
11199
+ ownership: readOwnership(snapshot)
11200
+ },
11201
+ warning: null
11202
+ };
11203
+ };
11204
+ var pathExists = async (absolutePath) => {
11205
+ try {
11206
+ await stat3(absolutePath);
11207
+ return true;
11208
+ } catch {
11209
+ return false;
11210
+ }
11211
+ };
11212
+ var discoverSnapshotFiles = async (from) => {
11213
+ const cwd = process.env["INIT_CWD"] ?? process.cwd();
11214
+ const resolved = resolve9(cwd, from);
11215
+ const exists = await pathExists(resolved);
11216
+ if (exists) {
11217
+ const info = await stat3(resolved);
11218
+ if (info.isDirectory()) {
11219
+ const entries = await readdir2(resolved, { withFileTypes: true }).catch(() => {
11220
+ throw new TrendConfigurationError(`--from directory is not readable: ${from}`);
11221
+ });
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));
11223
+ if (files2.length === 0) {
11224
+ throw new TrendConfigurationError(`no snapshot JSON files found in ${from}`);
11225
+ }
11226
+ return files2;
11227
+ }
11228
+ }
11229
+ const hasGlobMetacharacters = /[*?[\]{}()!]/.test(from);
11230
+ if (!exists && !hasGlobMetacharacters) {
11231
+ throw new TrendConfigurationError(`--from path not found: ${from}`);
11232
+ }
11233
+ const matches = [];
11234
+ try {
11235
+ for await (const match of glob(from, { cwd })) {
11236
+ matches.push(match);
11237
+ }
11238
+ } catch {
11239
+ throw new TrendConfigurationError(`--from pattern could not be read: ${from}`);
11240
+ }
11241
+ const files = [];
11242
+ for (const match of matches.sort(compareText4)) {
11243
+ const absolutePath = resolve9(cwd, match);
11244
+ try {
11245
+ const info = await stat3(absolutePath);
11246
+ if (!info.isFile() || !absolutePath.endsWith(".json")) {
11247
+ continue;
11248
+ }
11249
+ } catch {
11250
+ continue;
11251
+ }
11252
+ files.push({ path: absolutePath, name: basename5(absolutePath) });
11253
+ }
11254
+ if (files.length === 0) {
11255
+ throw new TrendConfigurationError(`--from matched no snapshot JSON files: ${from}`);
11256
+ }
11257
+ return files;
11258
+ };
11259
+ var parseSinceDays = (since) => {
11260
+ if (since === void 0) {
11261
+ return null;
11262
+ }
11263
+ if (!/^\d+d$/.test(since)) {
11264
+ throw new TrendConfigurationError("--since must be a day window like 90d");
11265
+ }
11266
+ const days = Number.parseInt(since.slice(0, -1), 10);
11267
+ if (!Number.isInteger(days) || days <= 0) {
11268
+ throw new TrendConfigurationError("--since must be a day window like 90d");
11269
+ }
11270
+ return days;
11271
+ };
11272
+ var parseLast = (last) => {
11273
+ if (last === void 0) {
11274
+ return null;
11275
+ }
11276
+ if (!Number.isInteger(last) || last <= 0) {
11277
+ throw new TrendConfigurationError("--last must be a positive integer");
11278
+ }
11279
+ return last;
11280
+ };
11281
+ var comparePoints = (a, b) => {
11282
+ const timeDifference = Date.parse(a.generatedAt) - Date.parse(b.generatedAt);
11283
+ if (timeDifference !== 0) {
11284
+ return timeDifference;
11285
+ }
11286
+ return compareText4(a.file, b.file);
11287
+ };
11288
+ var deduplicatePoints = (points) => {
11289
+ const seen = /* @__PURE__ */ new Set();
11290
+ const unique = [];
11291
+ for (const point of points) {
11292
+ const key = point.generatedAt + "\0" + (point.commit ?? "");
11293
+ if (seen.has(key)) {
11294
+ continue;
11295
+ }
11296
+ seen.add(key);
11297
+ unique.push(point);
11298
+ }
11299
+ return unique;
11300
+ };
11301
+ var readTrendSnapshots = async (options) => {
11302
+ const from = options.from;
11303
+ if (from === void 0 || from.trim().length === 0) {
11304
+ throw new TrendConfigurationError("--from is required");
11305
+ }
11306
+ const sinceDays = parseSinceDays(options.since);
11307
+ const last = parseLast(options.last);
11308
+ const files = await discoverSnapshotFiles(from);
11309
+ const warnings = [];
11310
+ const points = [];
11311
+ for (const file of files) {
11312
+ let content;
11313
+ try {
11314
+ content = await readFile8(file.path, "utf8");
11315
+ } catch {
11316
+ warnings.push(`skipped ${file.name}: invalid JSON`);
11317
+ continue;
11318
+ }
11319
+ const parsed = parseSnapshot2(file.name, content);
11320
+ if (parsed.point === null) {
11321
+ warnings.push(parsed.warning);
11322
+ continue;
11323
+ }
11324
+ points.push(parsed.point);
11325
+ }
11326
+ if (points.length === 0) {
11327
+ throw new TrendConfigurationError("no readable snapshots were found");
11328
+ }
11329
+ const ordered = deduplicatePoints([...points].sort(comparePoints));
11330
+ let filtered = ordered;
11331
+ if (sinceDays !== null) {
11332
+ const now = (options.now ?? (() => /* @__PURE__ */ new Date()))();
11333
+ const cutoff = now.getTime() - sinceDays * 24 * 60 * 60 * 1e3;
11334
+ filtered = filtered.filter((point) => Date.parse(point.generatedAt) >= cutoff);
11335
+ }
11336
+ if (last !== null) {
11337
+ filtered = filtered.slice(-last);
11338
+ }
11339
+ return { series: filtered, warnings };
11340
+ };
11341
+
11342
+ // src/application/run-trend-command.ts
11343
+ var TREND_EXIT_CODES = {
11344
+ ok: 0,
11345
+ invalidConfiguration: 2
11346
+ };
11347
+ var runTrendCommand = async (options, logger = createSilentLogger()) => {
11348
+ const format = options.format ?? "console";
11349
+ const { series, warnings } = await readTrendSnapshots({
11350
+ ...options.from === void 0 ? {} : { from: options.from },
11351
+ ...options.since === void 0 ? {} : { since: options.since },
11352
+ ...options.last === void 0 ? {} : { last: options.last },
11353
+ ...options.now === void 0 ? {} : { now: options.now }
11354
+ });
11355
+ const report = buildTrendReport(series, warnings);
11356
+ const rendered = formatTrendOutput(report, format);
11357
+ logger.debug(`trend series: ${report.series.length} snapshot(s)`);
11358
+ if (options.outputPath !== void 0) {
11359
+ await writeFile8(options.outputPath, `${rendered}
11360
+ `, "utf8");
11361
+ logger.info(`trend output written: ${options.outputPath}`);
11362
+ }
11363
+ return {
11364
+ report,
11365
+ rendered,
11366
+ exitCode: TREND_EXIT_CODES.ok,
11367
+ ...options.outputPath === void 0 ? {} : { outputPath: options.outputPath }
11368
+ };
11369
+ };
11370
+
11371
+ // 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";
11374
+ var CODESENTINEL_WORKFLOW_PATH = ".github/workflows/codesentinel.yml";
11375
+ var CODESENTINEL_OWNERS_PATH = ".codesentinel/owners.json";
11376
+ var CODESENTINEL_WORKFLOW_TEMPLATE = `name: CodeSentinel
11377
+
11378
+ on:
11379
+ push:
11380
+ branches: [main]
11381
+ pull_request:
11382
+
11383
+ permissions:
11384
+ contents: read
11385
+
11386
+ jobs:
11387
+ codesentinel:
11388
+ runs-on: ubuntu-latest
11389
+ steps:
11390
+ - name: Checkout
11391
+ uses: actions/checkout@v4
11392
+ with:
11393
+ fetch-depth: 0
11394
+
11395
+ - name: Setup Node.js
11396
+ uses: actions/setup-node@v4
11397
+ with:
11398
+ node-version: 24
11399
+
11400
+ - name: Run CodeSentinel
11401
+ run: npx --yes @getcodesentinel/codesentinel@latest ci --baseline-ref auto --fail-on error --snapshot codesentinel-snapshot.json
11402
+
11403
+ - name: Build ownership report
11404
+ if: hashFiles('CODEOWNERS', '.github/CODEOWNERS', 'docs/CODEOWNERS') != ''
11405
+ run: npx --yes @getcodesentinel/codesentinel@latest owners --format md --output ownership.md
11406
+
11407
+ - name: Upload CodeSentinel artifacts
11408
+ if: always()
11409
+ uses: actions/upload-artifact@v4
11410
+ with:
11411
+ name: codesentinel
11412
+ path: |
11413
+ codesentinel-snapshot.json
11414
+ ownership.md
11415
+ retention-days: 90
11416
+ if-no-files-found: warn
11417
+ `;
11418
+ var CODESENTINEL_OWNERS_FILE_CONTENT = `{"aliases": {}}
11419
+ `;
11420
+ var CODEOWNERS_CANDIDATES = ["CODEOWNERS", ".github/CODEOWNERS", "docs/CODEOWNERS"];
11421
+ var SKIPPED_REASON = "already exists (use --force to overwrite)";
11422
+ var action = (status, path, extra = {}) => ({
11423
+ status,
11424
+ path,
11425
+ ...extra.content === void 0 ? {} : { content: extra.content },
11426
+ ...extra.reason === void 0 ? {} : { reason: extra.reason }
11427
+ });
11428
+ var buildInitPlan = (input) => {
11429
+ const ci = input.options?.ci ?? "github";
11430
+ const force = input.options?.force === true;
11431
+ const actions = [];
11432
+ if (ci === "none") {
11433
+ actions.push(
11434
+ action("disabled", CODESENTINEL_WORKFLOW_PATH, { reason: "disabled by --ci none" })
11435
+ );
11436
+ } else if (!input.workflowExists) {
11437
+ actions.push(
11438
+ action("created", CODESENTINEL_WORKFLOW_PATH, { content: CODESENTINEL_WORKFLOW_TEMPLATE })
11439
+ );
11440
+ } else if (force) {
11441
+ actions.push(
11442
+ action("updated", CODESENTINEL_WORKFLOW_PATH, { content: CODESENTINEL_WORKFLOW_TEMPLATE })
11443
+ );
11444
+ } else {
11445
+ actions.push(action("skipped", CODESENTINEL_WORKFLOW_PATH, { reason: SKIPPED_REASON }));
11446
+ }
11447
+ if (input.hasCodeownersFile) {
11448
+ if (!input.ownersFileExists) {
11449
+ actions.push(
11450
+ action("created", CODESENTINEL_OWNERS_PATH, {
11451
+ content: CODESENTINEL_OWNERS_FILE_CONTENT
11452
+ })
11453
+ );
11454
+ } else if (force) {
11455
+ actions.push(
11456
+ action("updated", CODESENTINEL_OWNERS_PATH, {
11457
+ content: CODESENTINEL_OWNERS_FILE_CONTENT
11458
+ })
11459
+ );
11460
+ } else {
11461
+ actions.push(action("skipped", CODESENTINEL_OWNERS_PATH, { reason: SKIPPED_REASON }));
11462
+ }
11463
+ }
11464
+ return { actions };
11465
+ };
11466
+ var SECTION_ORDER = ["created", "updated", "skipped", "disabled"];
11467
+ var SECTION_LABELS = {
11468
+ created: "Created",
11469
+ updated: "Updated",
11470
+ skipped: "Skipped",
11471
+ disabled: "Disabled"
11472
+ };
11473
+ var indentContent = (content) => content.replace(/\n$/, "").split("\n").map((line) => ` ${line}`);
11474
+ var renderInitOutput = (plan, options = {}) => {
11475
+ const dryRun = options.dryRun === true;
11476
+ const ci = options.ci ?? "github";
11477
+ const lines = [];
11478
+ lines.push(dryRun ? "CodeSentinel init (dry run)" : "CodeSentinel init");
11479
+ lines.push("");
11480
+ for (const status of SECTION_ORDER) {
11481
+ const actions = plan.actions.filter((entry) => entry.status === status);
11482
+ if (actions.length === 0) {
11483
+ continue;
11484
+ }
11485
+ lines.push(SECTION_LABELS[status]);
11486
+ for (const entry of actions) {
11487
+ const suffix = entry.reason === void 0 ? "" : ` \u2014 ${entry.reason}`;
11488
+ lines.push(` ${entry.path}${suffix}`);
11489
+ if (dryRun && (status === "created" || status === "updated") && entry.content !== void 0) {
11490
+ lines.push(...indentContent(entry.content));
11491
+ }
11492
+ }
11493
+ lines.push("");
11494
+ }
11495
+ lines.push("Next steps");
11496
+ lines.push(" 1. Review and commit the generated files.");
11497
+ lines.push(
11498
+ ci === "none" ? " 2. Add `codesentinel ci` to your existing CI pipeline." : " 2. Push or open a pull request so the workflow runs."
11499
+ );
11500
+ lines.push(
11501
+ " 3. Download the codesentinel artifact with `gh run download` to keep history for `codesentinel trend`."
11502
+ );
11503
+ return lines.join("\n");
11504
+ };
11505
+ var fileExists = async (absolutePath) => {
11506
+ try {
11507
+ await access(absolutePath);
11508
+ return true;
11509
+ } catch {
11510
+ return false;
11511
+ }
11512
+ };
11513
+ var anyFileExists = async (targetPath, candidates) => {
11514
+ for (const candidate of candidates) {
11515
+ if (await fileExists(join12(targetPath, candidate))) {
11516
+ return true;
11517
+ }
11518
+ }
11519
+ return false;
11520
+ };
11521
+ var resolveTargetPath3 = (inputPath) => {
11522
+ const invocationCwd = process.env["INIT_CWD"] ?? process.cwd();
11523
+ return resolve10(invocationCwd, inputPath ?? ".");
11524
+ };
11525
+ var runInitCommand = async (inputPath, options = {}) => {
11526
+ const targetPath = resolveTargetPath3(inputPath);
11527
+ const ci = options.ci ?? "github";
11528
+ const hasCodeownersFile = await anyFileExists(targetPath, CODEOWNERS_CANDIDATES);
11529
+ const plan = buildInitPlan({
11530
+ hasCodeownersFile,
11531
+ workflowExists: ci === "github" && await fileExists(join12(targetPath, CODESENTINEL_WORKFLOW_PATH)),
11532
+ ownersFileExists: hasCodeownersFile && await fileExists(join12(targetPath, CODESENTINEL_OWNERS_PATH)),
11533
+ options: { ...options, ci }
11534
+ });
11535
+ if (options.dryRun !== true) {
11536
+ for (const entry of plan.actions) {
11537
+ if (entry.status !== "created" && entry.status !== "updated") {
11538
+ continue;
11539
+ }
11540
+ const absolutePath = join12(targetPath, entry.path);
11541
+ await mkdir4(dirname3(absolutePath), { recursive: true });
11542
+ await writeFile9(absolutePath, entry.content ?? "", "utf8");
11543
+ }
11544
+ }
11545
+ return {
11546
+ targetPath,
11547
+ plan,
11548
+ rendered: renderInitOutput(plan, { dryRun: options.dryRun === true, ci }),
11549
+ exitCode: 0
11550
+ };
11551
+ };
11552
+
10979
11553
  // src/index.ts
10980
11554
  var program = new Command();
10981
- var packageJsonPath = resolve9(dirname3(fileURLToPath2(import.meta.url)), "../package.json");
11555
+ var packageJsonPath = resolve11(dirname4(fileURLToPath2(import.meta.url)), "../package.json");
10982
11556
  var { version } = JSON.parse(readFileSync4(packageJsonPath, "utf8"));
10983
11557
  var parseRecentWindowDays = (value) => {
10984
11558
  const parsed = Number.parseInt(value, 10);
@@ -11302,12 +11876,12 @@ program.command("run").argument("[path]", "path to the project to analyze").addO
11302
11876
  ...options.trace === true ? { trace: explain.trace } : {}
11303
11877
  });
11304
11878
  if (options.snapshot !== void 0) {
11305
- await writeFile8(options.snapshot, JSON.stringify(snapshot, null, 2), "utf8");
11879
+ await writeFile10(options.snapshot, JSON.stringify(snapshot, null, 2), "utf8");
11306
11880
  logger.info(`snapshot written: ${options.snapshot}`);
11307
11881
  }
11308
11882
  const report = options.compare === void 0 ? createReport(snapshot) : createReport(
11309
11883
  snapshot,
11310
- compareSnapshots(snapshot, parseSnapshot(await readFile8(options.compare, "utf8")))
11884
+ compareSnapshots(snapshot, parseSnapshot(await readFile9(options.compare, "utf8")))
11311
11885
  );
11312
11886
  if (options.report === "html") {
11313
11887
  const htmlOutputPath = await writeHtmlReportBundle(report, {
@@ -11784,6 +12358,63 @@ program.command("owners").alias("ownership").exitOverride().argument("[path]", "
11784
12358
  }
11785
12359
  }
11786
12360
  );
12361
+ program.command("trend").exitOverride().option(
12362
+ "--from <dir-or-glob>",
12363
+ "directory of snapshot JSON files (non-recursive) or a glob pattern (required)"
12364
+ ).option("--since <window>", "only include snapshots newer than this window, for example 90d").option("--last <count>", "only include the N most recent snapshots").addOption(
12365
+ new Option(
12366
+ "--format <mode>",
12367
+ "output format: console (default), json (stable payload) or md (pastes into a PR)"
12368
+ ).choices(["console", "json", "md"]).default("console")
12369
+ ).option("--output <file>", "write the rendered output to a file instead of stdout").addOption(
12370
+ new Option(
12371
+ "--log-level <level>",
12372
+ "log verbosity: silent, error, warn, info, debug (logs are written to stderr)"
12373
+ ).choices(["silent", "error", "warn", "info", "debug"]).default(parseLogLevel(process.env["CODESENTINEL_LOG_LEVEL"]))
12374
+ ).action(
12375
+ async (options) => {
12376
+ const logger = createStderrLogger(options.logLevel);
12377
+ try {
12378
+ const result = await runTrendCommand(
12379
+ {
12380
+ ...options.from === void 0 ? {} : { from: options.from },
12381
+ ...options.since === void 0 ? {} : { since: options.since },
12382
+ ...options.last === void 0 ? {} : { last: Number(options.last) },
12383
+ format: options.format,
12384
+ ...options.output === void 0 ? {} : { outputPath: options.output }
12385
+ },
12386
+ logger
12387
+ );
12388
+ if (result.outputPath === void 0) {
12389
+ process.stdout.write(`${result.rendered}
12390
+ `);
12391
+ }
12392
+ process.exitCode = result.exitCode;
12393
+ } catch (error) {
12394
+ if (error instanceof TrendConfigurationError) {
12395
+ logger.error(error.message);
12396
+ process.exitCode = TREND_EXIT_CODES.invalidConfiguration;
12397
+ return;
12398
+ }
12399
+ logger.error(error instanceof Error ? error.message : "internal error");
12400
+ process.exitCode = TREND_EXIT_CODES.invalidConfiguration;
12401
+ }
12402
+ }
12403
+ );
12404
+ program.command("init").argument("[path]", "path to the repository to scaffold").option("--force", "overwrite generated files that already exist").addOption(
12405
+ new Option("--ci <mode>", "CI provider: github (default) or none").choices(["github", "none"]).default("github")
12406
+ ).option("--dry-run", "print what would be written without writing anything").action(
12407
+ async (path, options) => {
12408
+ const result = await runInitCommand(path, {
12409
+ ...options.force === true ? { force: true } : {},
12410
+ ci: options.ci,
12411
+ ...options.dryRun === true ? { dryRun: true } : {}
12412
+ });
12413
+ process.stdout.write(`${result.rendered}
12414
+ `);
12415
+ process.exitCode = result.exitCode;
12416
+ }
12417
+ );
11787
12418
  var executablePath = process.argv[0] ?? "";
11788
12419
  var scriptPath = process.argv[1] ?? "";
11789
12420
  var argv = process.argv[2] === "--" ? [executablePath, scriptPath, ...process.argv.slice(3)] : process.argv;