@getcodesentinel/codesentinel 1.35.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/README.md CHANGED
@@ -150,6 +150,7 @@ codesentinel report [path]
150
150
  codesentinel check [path]
151
151
  codesentinel ci [path]
152
152
  codesentinel owners [path]
153
+ codesentinel trend --from <dir-or-glob>
153
154
  codesentinel init [path]
154
155
  codesentinel dependency-risk <dependency[@version]>
155
156
  codesentinel update
@@ -178,6 +179,8 @@ codesentinel ci --baseline-ref auto --fail-on error
178
179
  codesentinel owners
179
180
  codesentinel owners . --format md --output ownership.md
180
181
  codesentinel owners . --fail-on error --max-unowned-critical 0 --max-ghost-owners 2 --max-drift 0.25
182
+ codesentinel trend --from ./snapshots
183
+ codesentinel trend --from './snapshots/*.json' --since 90d --format md --output trend.md
181
184
  codesentinel init
182
185
  codesentinel init . --force
183
186
  codesentinel init . --ci none --dry-run
@@ -435,6 +438,17 @@ This measures system risk, not individual performance. No owner or author rankin
435
438
  - The universe is tracked files only: untracked, ignored and binary-only files are out of scope.
436
439
  - Identity matching is heuristic (noreply address, email local part, display name, alias map in `.codesentinel/owners.json`).
437
440
 
441
+ ## Trend
442
+
443
+ `codesentinel trend` reads snapshot JSON artifacts written by `codesentinel ci --snapshot` and prints the series over time. Snapshots are CI artifacts, not repository files: `trend` never writes history into the repository and never changes the snapshot schema.
444
+
445
+ ```bash
446
+ codesentinel trend --from ./snapshots
447
+ codesentinel trend --from './snapshots/*.json' --since 90d --last 12 --format md --output trend.md
448
+ ```
449
+
450
+ `--from` accepts a directory (non-recursive `*.json` files) or a glob pattern. Each snapshot is parsed independently: a corrupt file, an unsupported schema version or a missing score is skipped with a warning so the remaining history still renders. Series are ordered by `generatedAt`, duplicate timestamp and commit pairs are collapsed, and `--since <N>d`/`--last <N>` narrow the window. Output is available as `console` (default), `json` (stable payload) and `md`. Deltas are last minus first; ownership deltas stay `null` when either endpoint has no ownership block. Fewer than two snapshots still exits `0` and prints `not enough history for a trend`. Configuration errors exit `2`.
451
+
438
452
  ## Explain Output
439
453
 
440
454
  `codesentinel explain` uses the same risk-engine scoring model as `analyze` and adds structured explanation traces.
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 writeFile9 } from "fs/promises";
3842
- import { dirname as dirname4, resolve as resolve10 } 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((resolve11) => {
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
- resolve11(choice);
4548
+ resolve12(choice);
4549
4549
  };
4550
4550
  const onKeypress = (_str, key) => {
4551
4551
  if (key.ctrl === true && key.name === "c") {
@@ -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((resolve11) => {
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
- resolve11(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((resolve11) => {
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
- resolve11();
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((resolve11, 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
- resolve11(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((resolve11) => {
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", () => resolve11(false));
10334
+ child.once("error", () => resolve12(false));
10335
10335
  child.once("spawn", () => {
10336
10336
  child.unref();
10337
- resolve11(true);
10337
+ resolve12(true);
10338
10338
  });
10339
10339
  });
10340
10340
  };
@@ -10976,9 +10976,401 @@ 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
+
10979
11371
  // src/application/run-init-command.ts
10980
- import { access, mkdir as mkdir4, writeFile as writeFile8 } from "fs/promises";
10981
- import { dirname as dirname3, join as join11, resolve as resolve9 } from "path";
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";
10982
11374
  var CODESENTINEL_WORKFLOW_PATH = ".github/workflows/codesentinel.yml";
10983
11375
  var CODESENTINEL_OWNERS_PATH = ".codesentinel/owners.json";
10984
11376
  var CODESENTINEL_WORKFLOW_TEMPLATE = `name: CodeSentinel
@@ -11120,7 +11512,7 @@ var fileExists = async (absolutePath) => {
11120
11512
  };
11121
11513
  var anyFileExists = async (targetPath, candidates) => {
11122
11514
  for (const candidate of candidates) {
11123
- if (await fileExists(join11(targetPath, candidate))) {
11515
+ if (await fileExists(join12(targetPath, candidate))) {
11124
11516
  return true;
11125
11517
  }
11126
11518
  }
@@ -11128,7 +11520,7 @@ var anyFileExists = async (targetPath, candidates) => {
11128
11520
  };
11129
11521
  var resolveTargetPath3 = (inputPath) => {
11130
11522
  const invocationCwd = process.env["INIT_CWD"] ?? process.cwd();
11131
- return resolve9(invocationCwd, inputPath ?? ".");
11523
+ return resolve10(invocationCwd, inputPath ?? ".");
11132
11524
  };
11133
11525
  var runInitCommand = async (inputPath, options = {}) => {
11134
11526
  const targetPath = resolveTargetPath3(inputPath);
@@ -11136,8 +11528,8 @@ var runInitCommand = async (inputPath, options = {}) => {
11136
11528
  const hasCodeownersFile = await anyFileExists(targetPath, CODEOWNERS_CANDIDATES);
11137
11529
  const plan = buildInitPlan({
11138
11530
  hasCodeownersFile,
11139
- workflowExists: ci === "github" && await fileExists(join11(targetPath, CODESENTINEL_WORKFLOW_PATH)),
11140
- ownersFileExists: hasCodeownersFile && await fileExists(join11(targetPath, CODESENTINEL_OWNERS_PATH)),
11531
+ workflowExists: ci === "github" && await fileExists(join12(targetPath, CODESENTINEL_WORKFLOW_PATH)),
11532
+ ownersFileExists: hasCodeownersFile && await fileExists(join12(targetPath, CODESENTINEL_OWNERS_PATH)),
11141
11533
  options: { ...options, ci }
11142
11534
  });
11143
11535
  if (options.dryRun !== true) {
@@ -11145,9 +11537,9 @@ var runInitCommand = async (inputPath, options = {}) => {
11145
11537
  if (entry.status !== "created" && entry.status !== "updated") {
11146
11538
  continue;
11147
11539
  }
11148
- const absolutePath = join11(targetPath, entry.path);
11540
+ const absolutePath = join12(targetPath, entry.path);
11149
11541
  await mkdir4(dirname3(absolutePath), { recursive: true });
11150
- await writeFile8(absolutePath, entry.content ?? "", "utf8");
11542
+ await writeFile9(absolutePath, entry.content ?? "", "utf8");
11151
11543
  }
11152
11544
  }
11153
11545
  return {
@@ -11160,7 +11552,7 @@ var runInitCommand = async (inputPath, options = {}) => {
11160
11552
 
11161
11553
  // src/index.ts
11162
11554
  var program = new Command();
11163
- var packageJsonPath = resolve10(dirname4(fileURLToPath2(import.meta.url)), "../package.json");
11555
+ var packageJsonPath = resolve11(dirname4(fileURLToPath2(import.meta.url)), "../package.json");
11164
11556
  var { version } = JSON.parse(readFileSync4(packageJsonPath, "utf8"));
11165
11557
  var parseRecentWindowDays = (value) => {
11166
11558
  const parsed = Number.parseInt(value, 10);
@@ -11484,12 +11876,12 @@ program.command("run").argument("[path]", "path to the project to analyze").addO
11484
11876
  ...options.trace === true ? { trace: explain.trace } : {}
11485
11877
  });
11486
11878
  if (options.snapshot !== void 0) {
11487
- await writeFile9(options.snapshot, JSON.stringify(snapshot, null, 2), "utf8");
11879
+ await writeFile10(options.snapshot, JSON.stringify(snapshot, null, 2), "utf8");
11488
11880
  logger.info(`snapshot written: ${options.snapshot}`);
11489
11881
  }
11490
11882
  const report = options.compare === void 0 ? createReport(snapshot) : createReport(
11491
11883
  snapshot,
11492
- compareSnapshots(snapshot, parseSnapshot(await readFile8(options.compare, "utf8")))
11884
+ compareSnapshots(snapshot, parseSnapshot(await readFile9(options.compare, "utf8")))
11493
11885
  );
11494
11886
  if (options.report === "html") {
11495
11887
  const htmlOutputPath = await writeHtmlReportBundle(report, {
@@ -11966,6 +12358,49 @@ program.command("owners").alias("ownership").exitOverride().argument("[path]", "
11966
12358
  }
11967
12359
  }
11968
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
+ );
11969
12404
  program.command("init").argument("[path]", "path to the repository to scaffold").option("--force", "overwrite generated files that already exist").addOption(
11970
12405
  new Option("--ci <mode>", "CI provider: github (default) or none").choices(["github", "none"]).default("github")
11971
12406
  ).option("--dry-run", "print what would be written without writing anything").action(