@getcodesentinel/codesentinel 1.34.0 → 1.35.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
@@ -81,7 +81,7 @@ CI example:
81
81
 
82
82
  `--baseline-ref auto` requires enough git history to resolve a baseline deterministically. In GitHub Actions, use `fetch-depth: 0` and ensure the CI base branch ref is fetched.
83
83
 
84
- A full workflow template is available at `examples/github-actions/codesentinel-ci.yml`.
84
+ A full workflow template is available at `examples/github-actions/codesentinel-ci.yml`. For a faster setup, run `codesentinel init` in the repository root instead of copying the example: it writes the workflow and, when a `CODEOWNERS` file exists, the ownership configuration.
85
85
 
86
86
  ## Vision
87
87
 
@@ -150,6 +150,7 @@ codesentinel report [path]
150
150
  codesentinel check [path]
151
151
  codesentinel ci [path]
152
152
  codesentinel owners [path]
153
+ codesentinel init [path]
153
154
  codesentinel dependency-risk <dependency[@version]>
154
155
  codesentinel update
155
156
  ```
@@ -177,6 +178,9 @@ codesentinel ci --baseline-ref auto --fail-on error
177
178
  codesentinel owners
178
179
  codesentinel owners . --format md --output ownership.md
179
180
  codesentinel owners . --fail-on error --max-unowned-critical 0 --max-ghost-owners 2 --max-drift 0.25
181
+ codesentinel init
182
+ codesentinel init . --force
183
+ codesentinel init . --ci none --dry-run
180
184
  codesentinel dependency-risk react
181
185
  codesentinel dependency-risk react@19.0.0
182
186
  codesentinel update
@@ -186,6 +190,8 @@ Use `codesentinel update` to manually check for a newer CLI release and install
186
190
 
187
191
  `codesentinel owners` cross-checks the owners declared in `CODEOWNERS` with the authors that history proves. It is offline, reads the `CODEOWNERS` file and the tracked tree from `--ref` so CI and a local run measure the same revision, and exits with `0` when the audit ran, `1` when a configured threshold is exceeded under `--fail-on error`, and `2` on a configuration or parse error (an untracked `CODEOWNERS`, an invalid flag value, or a file above GitHub's 3 MB limit). A repository without a `CODEOWNERS` file reports `available: false` and still exits `0`.
188
192
 
193
+ `codesentinel init [path]` scaffolds a working CI setup in the target repository. It writes `.github/workflows/codesentinel.yml` and, when a `CODEOWNERS` file exists, `.codesentinel/owners.json`. The workflow runs `codesentinel ci --baseline-ref auto --fail-on error --snapshot codesentinel-snapshot.json`, builds an ownership report when a `CODEOWNERS` file is present, and uploads both artifacts with 90-day retention. Use `--force` to overwrite existing generated files, `--ci none` to skip the workflow (for example when CI lives elsewhere), or `--dry-run` to print what would be written without changing anything. Existing files are never overwritten without `--force`, and the command never edits `package.json`.
194
+
189
195
  Author identity mode:
190
196
 
191
197
  ```bash
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 readFile8, writeFile as writeFile9 } from "fs/promises";
3842
+ import { dirname as dirname4, resolve as resolve10 } 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((resolve11) => {
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
+ resolve11(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((resolve11) => {
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
+ resolve11(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((resolve11) => {
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
+ resolve11();
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((resolve11, 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
+ resolve11(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((resolve11) => {
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", () => resolve11(false));
10335
10335
  child.once("spawn", () => {
10336
10336
  child.unref();
10337
- resolve10(true);
10337
+ resolve11(true);
10338
10338
  });
10339
10339
  });
10340
10340
  };
@@ -10976,9 +10976,191 @@ 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-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";
10982
+ var CODESENTINEL_WORKFLOW_PATH = ".github/workflows/codesentinel.yml";
10983
+ var CODESENTINEL_OWNERS_PATH = ".codesentinel/owners.json";
10984
+ var CODESENTINEL_WORKFLOW_TEMPLATE = `name: CodeSentinel
10985
+
10986
+ on:
10987
+ push:
10988
+ branches: [main]
10989
+ pull_request:
10990
+
10991
+ permissions:
10992
+ contents: read
10993
+
10994
+ jobs:
10995
+ codesentinel:
10996
+ runs-on: ubuntu-latest
10997
+ steps:
10998
+ - name: Checkout
10999
+ uses: actions/checkout@v4
11000
+ with:
11001
+ fetch-depth: 0
11002
+
11003
+ - name: Setup Node.js
11004
+ uses: actions/setup-node@v4
11005
+ with:
11006
+ node-version: 24
11007
+
11008
+ - name: Run CodeSentinel
11009
+ run: npx --yes @getcodesentinel/codesentinel@latest ci --baseline-ref auto --fail-on error --snapshot codesentinel-snapshot.json
11010
+
11011
+ - name: Build ownership report
11012
+ if: hashFiles('CODEOWNERS', '.github/CODEOWNERS', 'docs/CODEOWNERS') != ''
11013
+ run: npx --yes @getcodesentinel/codesentinel@latest owners --format md --output ownership.md
11014
+
11015
+ - name: Upload CodeSentinel artifacts
11016
+ if: always()
11017
+ uses: actions/upload-artifact@v4
11018
+ with:
11019
+ name: codesentinel
11020
+ path: |
11021
+ codesentinel-snapshot.json
11022
+ ownership.md
11023
+ retention-days: 90
11024
+ if-no-files-found: warn
11025
+ `;
11026
+ var CODESENTINEL_OWNERS_FILE_CONTENT = `{"aliases": {}}
11027
+ `;
11028
+ var CODEOWNERS_CANDIDATES = ["CODEOWNERS", ".github/CODEOWNERS", "docs/CODEOWNERS"];
11029
+ var SKIPPED_REASON = "already exists (use --force to overwrite)";
11030
+ var action = (status, path, extra = {}) => ({
11031
+ status,
11032
+ path,
11033
+ ...extra.content === void 0 ? {} : { content: extra.content },
11034
+ ...extra.reason === void 0 ? {} : { reason: extra.reason }
11035
+ });
11036
+ var buildInitPlan = (input) => {
11037
+ const ci = input.options?.ci ?? "github";
11038
+ const force = input.options?.force === true;
11039
+ const actions = [];
11040
+ if (ci === "none") {
11041
+ actions.push(
11042
+ action("disabled", CODESENTINEL_WORKFLOW_PATH, { reason: "disabled by --ci none" })
11043
+ );
11044
+ } else if (!input.workflowExists) {
11045
+ actions.push(
11046
+ action("created", CODESENTINEL_WORKFLOW_PATH, { content: CODESENTINEL_WORKFLOW_TEMPLATE })
11047
+ );
11048
+ } else if (force) {
11049
+ actions.push(
11050
+ action("updated", CODESENTINEL_WORKFLOW_PATH, { content: CODESENTINEL_WORKFLOW_TEMPLATE })
11051
+ );
11052
+ } else {
11053
+ actions.push(action("skipped", CODESENTINEL_WORKFLOW_PATH, { reason: SKIPPED_REASON }));
11054
+ }
11055
+ if (input.hasCodeownersFile) {
11056
+ if (!input.ownersFileExists) {
11057
+ actions.push(
11058
+ action("created", CODESENTINEL_OWNERS_PATH, {
11059
+ content: CODESENTINEL_OWNERS_FILE_CONTENT
11060
+ })
11061
+ );
11062
+ } else if (force) {
11063
+ actions.push(
11064
+ action("updated", CODESENTINEL_OWNERS_PATH, {
11065
+ content: CODESENTINEL_OWNERS_FILE_CONTENT
11066
+ })
11067
+ );
11068
+ } else {
11069
+ actions.push(action("skipped", CODESENTINEL_OWNERS_PATH, { reason: SKIPPED_REASON }));
11070
+ }
11071
+ }
11072
+ return { actions };
11073
+ };
11074
+ var SECTION_ORDER = ["created", "updated", "skipped", "disabled"];
11075
+ var SECTION_LABELS = {
11076
+ created: "Created",
11077
+ updated: "Updated",
11078
+ skipped: "Skipped",
11079
+ disabled: "Disabled"
11080
+ };
11081
+ var indentContent = (content) => content.replace(/\n$/, "").split("\n").map((line) => ` ${line}`);
11082
+ var renderInitOutput = (plan, options = {}) => {
11083
+ const dryRun = options.dryRun === true;
11084
+ const ci = options.ci ?? "github";
11085
+ const lines = [];
11086
+ lines.push(dryRun ? "CodeSentinel init (dry run)" : "CodeSentinel init");
11087
+ lines.push("");
11088
+ for (const status of SECTION_ORDER) {
11089
+ const actions = plan.actions.filter((entry) => entry.status === status);
11090
+ if (actions.length === 0) {
11091
+ continue;
11092
+ }
11093
+ lines.push(SECTION_LABELS[status]);
11094
+ for (const entry of actions) {
11095
+ const suffix = entry.reason === void 0 ? "" : ` \u2014 ${entry.reason}`;
11096
+ lines.push(` ${entry.path}${suffix}`);
11097
+ if (dryRun && (status === "created" || status === "updated") && entry.content !== void 0) {
11098
+ lines.push(...indentContent(entry.content));
11099
+ }
11100
+ }
11101
+ lines.push("");
11102
+ }
11103
+ lines.push("Next steps");
11104
+ lines.push(" 1. Review and commit the generated files.");
11105
+ lines.push(
11106
+ ci === "none" ? " 2. Add `codesentinel ci` to your existing CI pipeline." : " 2. Push or open a pull request so the workflow runs."
11107
+ );
11108
+ lines.push(
11109
+ " 3. Download the codesentinel artifact with `gh run download` to keep history for `codesentinel trend`."
11110
+ );
11111
+ return lines.join("\n");
11112
+ };
11113
+ var fileExists = async (absolutePath) => {
11114
+ try {
11115
+ await access(absolutePath);
11116
+ return true;
11117
+ } catch {
11118
+ return false;
11119
+ }
11120
+ };
11121
+ var anyFileExists = async (targetPath, candidates) => {
11122
+ for (const candidate of candidates) {
11123
+ if (await fileExists(join11(targetPath, candidate))) {
11124
+ return true;
11125
+ }
11126
+ }
11127
+ return false;
11128
+ };
11129
+ var resolveTargetPath3 = (inputPath) => {
11130
+ const invocationCwd = process.env["INIT_CWD"] ?? process.cwd();
11131
+ return resolve9(invocationCwd, inputPath ?? ".");
11132
+ };
11133
+ var runInitCommand = async (inputPath, options = {}) => {
11134
+ const targetPath = resolveTargetPath3(inputPath);
11135
+ const ci = options.ci ?? "github";
11136
+ const hasCodeownersFile = await anyFileExists(targetPath, CODEOWNERS_CANDIDATES);
11137
+ const plan = buildInitPlan({
11138
+ hasCodeownersFile,
11139
+ workflowExists: ci === "github" && await fileExists(join11(targetPath, CODESENTINEL_WORKFLOW_PATH)),
11140
+ ownersFileExists: hasCodeownersFile && await fileExists(join11(targetPath, CODESENTINEL_OWNERS_PATH)),
11141
+ options: { ...options, ci }
11142
+ });
11143
+ if (options.dryRun !== true) {
11144
+ for (const entry of plan.actions) {
11145
+ if (entry.status !== "created" && entry.status !== "updated") {
11146
+ continue;
11147
+ }
11148
+ const absolutePath = join11(targetPath, entry.path);
11149
+ await mkdir4(dirname3(absolutePath), { recursive: true });
11150
+ await writeFile8(absolutePath, entry.content ?? "", "utf8");
11151
+ }
11152
+ }
11153
+ return {
11154
+ targetPath,
11155
+ plan,
11156
+ rendered: renderInitOutput(plan, { dryRun: options.dryRun === true, ci }),
11157
+ exitCode: 0
11158
+ };
11159
+ };
11160
+
10979
11161
  // src/index.ts
10980
11162
  var program = new Command();
10981
- var packageJsonPath = resolve9(dirname3(fileURLToPath2(import.meta.url)), "../package.json");
11163
+ var packageJsonPath = resolve10(dirname4(fileURLToPath2(import.meta.url)), "../package.json");
10982
11164
  var { version } = JSON.parse(readFileSync4(packageJsonPath, "utf8"));
10983
11165
  var parseRecentWindowDays = (value) => {
10984
11166
  const parsed = Number.parseInt(value, 10);
@@ -11302,7 +11484,7 @@ program.command("run").argument("[path]", "path to the project to analyze").addO
11302
11484
  ...options.trace === true ? { trace: explain.trace } : {}
11303
11485
  });
11304
11486
  if (options.snapshot !== void 0) {
11305
- await writeFile8(options.snapshot, JSON.stringify(snapshot, null, 2), "utf8");
11487
+ await writeFile9(options.snapshot, JSON.stringify(snapshot, null, 2), "utf8");
11306
11488
  logger.info(`snapshot written: ${options.snapshot}`);
11307
11489
  }
11308
11490
  const report = options.compare === void 0 ? createReport(snapshot) : createReport(
@@ -11784,6 +11966,20 @@ program.command("owners").alias("ownership").exitOverride().argument("[path]", "
11784
11966
  }
11785
11967
  }
11786
11968
  );
11969
+ program.command("init").argument("[path]", "path to the repository to scaffold").option("--force", "overwrite generated files that already exist").addOption(
11970
+ new Option("--ci <mode>", "CI provider: github (default) or none").choices(["github", "none"]).default("github")
11971
+ ).option("--dry-run", "print what would be written without writing anything").action(
11972
+ async (path, options) => {
11973
+ const result = await runInitCommand(path, {
11974
+ ...options.force === true ? { force: true } : {},
11975
+ ci: options.ci,
11976
+ ...options.dryRun === true ? { dryRun: true } : {}
11977
+ });
11978
+ process.stdout.write(`${result.rendered}
11979
+ `);
11980
+ process.exitCode = result.exitCode;
11981
+ }
11982
+ );
11787
11983
  var executablePath = process.argv[0] ?? "";
11788
11984
  var scriptPath = process.argv[1] ?? "";
11789
11985
  var argv = process.argv[2] === "--" ? [executablePath, scriptPath, ...process.argv.slice(3)] : process.argv;