@opendesignai/harness 0.1.0-alpha.0 → 0.2.0-alpha.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/cli.mjs CHANGED
@@ -1,28 +1,100 @@
1
1
  #!/usr/bin/env node
2
2
  import { parseArgs } from "node:util";
3
- import { execFileSync, spawnSync } from "node:child_process";
4
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { closeSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, rmSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
5
4
  import path from "node:path";
5
+ import { execFileSync, spawnSync } from "node:child_process";
6
6
  import { t as compilePathPatterns } from "./paths-DBoYPrGy.mjs";
7
+ import { tmpdir } from "node:os";
8
+ import { runJscpd } from "jscpd";
9
+ import { parseSync } from "oxc-parser";
10
+ import { createRequire } from "node:module";
7
11
  // src/cli/git.ts
8
12
  var UsageError = class extends Error {
9
13
  name = "UsageError";
10
14
  };
11
- function git(cwd, args) {
15
+ /** A check could not run (a tool failed or printed no report): exit code 2, without usage text. */
16
+ var EnvironmentError = class extends Error {
17
+ name = "EnvironmentError";
18
+ };
19
+ function git$1(cwd, args) {
12
20
  return execFileSync("git", args, {
13
21
  cwd,
14
22
  encoding: "utf8",
15
23
  maxBuffer: 268435456
16
24
  });
17
25
  }
18
- /** Tracked files plus untracked files that are not ignored, repo-relative with forward slashes. */
19
- function listFiles(cwd) {
20
- return git(cwd, [
26
+ /**
27
+ * Tracked files plus untracked files that are not ignored, relative to `cwd` with forward
28
+ * slashes, limited to `pathspecs` when given.
29
+ */
30
+ function listFiles(cwd, pathspecs = []) {
31
+ return git$1(cwd, [
21
32
  "ls-files",
22
33
  "-z",
23
34
  "--cached",
24
35
  "--others",
36
+ "--exclude-standard",
37
+ "--",
38
+ ...pathspecs
39
+ ]).split("\0").filter(Boolean);
40
+ }
41
+ /**
42
+ * Paths, relative to the repository root, that the working tree adds, changes, deletes or moves
43
+ * relative to `commit` anywhere in the repository (a move counts under both paths), plus untracked
44
+ * files that are not ignored.
45
+ */
46
+ function changedPaths(cwd, commit) {
47
+ const top = git$1(cwd, ["rev-parse", "--show-toplevel"]).trim();
48
+ return `${git$1(top, [
49
+ "diff",
50
+ "--name-only",
51
+ "-z",
52
+ "--no-renames",
53
+ commit,
54
+ "--"
55
+ ])}\0${git$1(top, [
56
+ "ls-files",
57
+ "-z",
58
+ "--others",
25
59
  "--exclude-standard"
60
+ ])}`.split("\0").filter(Boolean);
61
+ }
62
+ /**
63
+ * Paths, relative to `cwd`, that the working tree adds, changes, deletes or moves relative to
64
+ * `commit` (a move counts under both paths), plus untracked files that are not ignored.
65
+ */
66
+ function changedFiles(cwd, commit) {
67
+ return `${git$1(cwd, [
68
+ "diff",
69
+ "--no-ext-diff",
70
+ "--no-textconv",
71
+ "--name-only",
72
+ "-z",
73
+ "--no-renames",
74
+ "--relative",
75
+ commit,
76
+ "--"
77
+ ])}\0${git$1(cwd, [
78
+ "ls-files",
79
+ "-z",
80
+ "--others",
81
+ "--exclude-standard"
82
+ ])}`.split("\0").filter(Boolean);
83
+ }
84
+ /**
85
+ * Tracked files that ignore rules exclude, relative to `cwd`, limited to `pathspecs`: the rules
86
+ * of .gitignore files, .git/info/exclude and core.excludesFile, or with `perDirectory` only those
87
+ * of the files with that name in each directory (for example `.ignore`).
88
+ */
89
+ function ignoredTrackedFiles(cwd, pathspecs, perDirectory) {
90
+ return git$1(cwd, [
91
+ "ls-files",
92
+ "-z",
93
+ "--cached",
94
+ "--ignored",
95
+ perDirectory === void 0 ? "--exclude-standard" : `--exclude-per-directory=${perDirectory}`,
96
+ "--",
97
+ ...pathspecs
26
98
  ]).split("\0").filter(Boolean);
27
99
  }
28
100
  function resolveRef(cwd, ref) {
@@ -55,7 +127,7 @@ function showFile(cwd, commit, file) {
55
127
  }
56
128
  /** Files under `cwd` at `commit`, relative to `cwd` with forward slashes (like `listFiles`). */
57
129
  function listFilesAt(cwd, commit) {
58
- return new Set(git(cwd, [
130
+ return new Set(git$1(cwd, [
59
131
  "ls-tree",
60
132
  "-r",
61
133
  "--name-only",
@@ -63,11 +135,220 @@ function listFilesAt(cwd, commit) {
63
135
  commit
64
136
  ]).split("\0").filter(Boolean));
65
137
  }
138
+ /** Renames git reports between `commit` and the working tree with `findRenames`, new → old path. */
139
+ function renamePairs(cwd, commit, findRenames) {
140
+ const fields = git$1(cwd, [
141
+ "diff",
142
+ "--no-ext-diff",
143
+ "--no-textconv",
144
+ "--name-status",
145
+ "-z",
146
+ ...findRenames,
147
+ "--relative",
148
+ commit,
149
+ "--"
150
+ ]).split("\0");
151
+ const renames = /* @__PURE__ */ new Map();
152
+ for (let i = 0; i < fields.length;) {
153
+ const status = fields[i++] ?? "";
154
+ if (status === "") break;
155
+ if (status.startsWith("R") || status.startsWith("C")) {
156
+ const from = fields[i++] ?? "";
157
+ const to = fields[i++] ?? "";
158
+ if (status.startsWith("R")) renames.set(to, from);
159
+ } else i++;
160
+ }
161
+ return renames;
162
+ }
163
+ /**
164
+ * Files git sees as renamed between `commit` and the working tree (tracked and staged files;
165
+ * untracked files are not compared), as new path → old path relative to `cwd`.
166
+ */
167
+ function renamesSince(cwd, commit) {
168
+ return renamePairs(cwd, commit, ["--find-renames"]);
169
+ }
170
+ /**
171
+ * The renames baseline entries may follow (`ratchet`, `baseline move`): files git sees as renamed
172
+ * between `commit` and the working tree at MOVE_SIMILARITY percent or more, over the whole change
173
+ * and without git's limit on the number of files it compares (`git diff -M30% -l0 <commit>`), as
174
+ * new path → old path relative to `cwd`. Only tracked files count: committed or staged (`git mv`,
175
+ * `git add`).
176
+ */
177
+ function movesSince(cwd, commit) {
178
+ return renamePairs(cwd, commit, [`--find-renames=30%`, "-l0"]);
179
+ }
180
+ const C_ESCAPES = {
181
+ a: 7,
182
+ b: 8,
183
+ t: 9,
184
+ n: 10,
185
+ v: 11,
186
+ f: 12,
187
+ r: 13,
188
+ "\"": 34,
189
+ "\\": 92
190
+ };
191
+ /**
192
+ * A C-quoted path from git ("a\"b", "a\tb", "\303\244"): git quotes paths with control
193
+ * characters, quotes or backslashes, and writes bytes as octal escapes (UTF-8).
194
+ */
195
+ function unquote(quoted) {
196
+ const bytes = [];
197
+ let i = 1;
198
+ while (i < quoted.length && quoted[i] !== "\"") {
199
+ if (quoted[i] === "\\") {
200
+ const octal = /^[0-7]{3}/.exec(quoted.slice(i + 1, i + 4));
201
+ if (octal) {
202
+ bytes.push(Number.parseInt(octal[0], 8));
203
+ i += 4;
204
+ } else {
205
+ const next = quoted[i + 1] ?? "";
206
+ bytes.push(C_ESCAPES[next] ?? next.charCodeAt(0));
207
+ i += 2;
208
+ }
209
+ continue;
210
+ }
211
+ const char = String.fromCodePoint(quoted.codePointAt(i) ?? 0);
212
+ bytes.push(...Buffer.from(char, "utf8"));
213
+ i += char.length;
214
+ }
215
+ return Buffer.from(bytes).toString("utf8");
216
+ }
217
+ /**
218
+ * The path of a `--- ` or `+++ ` diff header: C-quoted when it has special characters; otherwise
219
+ * as is, except for the TAB git appends to a path that contains a space.
220
+ */
221
+ function headerPath(text) {
222
+ if (text.startsWith("\"")) return unquote(text);
223
+ return text.endsWith(" ") ? text.slice(0, -1) : text;
224
+ }
225
+ /**
226
+ * Lines that the working tree adds or changes relative to `commit`, in the files `pathspecs`
227
+ * selects, per file relative to `cwd` (1-based, inclusive ranges). Renames are followed, so a
228
+ * moved file only counts its edited lines; untracked files count whole. Every file is compared as
229
+ * text (`--text`): otherwise a `-diff` or `binary` attribute in .gitattributes, or a NUL byte,
230
+ * makes git print "Binary files … differ" without lines, and the change would seem to touch none.
231
+ * `pathspecs` keeps binary files with other extensions out of that comparison (an empty list selects
232
+ * every file).
233
+ */
234
+ function changedLines(cwd, commit, pathspecs) {
235
+ const diff = git$1(cwd, [
236
+ "-c",
237
+ "core.quotePath=false",
238
+ "diff",
239
+ "--no-ext-diff",
240
+ "--no-textconv",
241
+ "--text",
242
+ "--no-color",
243
+ "--no-prefix",
244
+ "--unified=0",
245
+ "--find-renames",
246
+ "--relative",
247
+ commit,
248
+ "--",
249
+ ...pathspecs
250
+ ]);
251
+ const changed = /* @__PURE__ */ new Map();
252
+ let current = null;
253
+ let header = false;
254
+ for (const line of diff.split("\n")) if (line.startsWith("diff --git ")) {
255
+ header = true;
256
+ current = null;
257
+ } else if (header && line.startsWith("+++ ")) {
258
+ const file = headerPath(line.slice(4));
259
+ current = file === "/dev/null" ? null : [];
260
+ if (current) changed.set(file, current);
261
+ } else if (line.startsWith("@@ ")) {
262
+ header = false;
263
+ if (!current) continue;
264
+ const match = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/.exec(line);
265
+ const start = Number(match?.[1] ?? 0);
266
+ const count = match?.[2] === void 0 ? 1 : Number(match[2]);
267
+ if (count > 0) current.push([start, start + count - 1]);
268
+ }
269
+ const untracked = git$1(cwd, [
270
+ "ls-files",
271
+ "-z",
272
+ "--others",
273
+ "--exclude-standard",
274
+ "--",
275
+ ...pathspecs
276
+ ]);
277
+ for (const file of untracked.split("\0").filter(Boolean)) changed.set(file, [[1, Number.MAX_SAFE_INTEGER]]);
278
+ return changed;
279
+ }
280
+ // src/cli/moves.ts
281
+ /**
282
+ * Whether `file` (relative to `cwd`, forward slashes) exists spelled exactly so. Unlike
283
+ * existsSync it tells `old.ts` from `Old.ts` on file systems that ignore case (macOS, Windows),
284
+ * so a case-only rename does not look like a copy.
285
+ */
286
+ function existsExactly(cwd, file) {
287
+ let dir = cwd;
288
+ for (const part of file.split("/")) {
289
+ let names;
290
+ try {
291
+ names = readdirSync(dir);
292
+ } catch {
293
+ return false;
294
+ }
295
+ if (!names.includes(part)) return false;
296
+ dir = path.join(dir, part);
297
+ }
298
+ return true;
299
+ }
300
+ /**
301
+ * A path argument as a key of the baselines: relative to the directory od-harness runs in, with
302
+ * forward slashes, without `./` or a trailing slash. Rejects absolute paths and paths that leave
303
+ * that directory.
304
+ */
305
+ function normalizeRepoPath(input, what) {
306
+ if (input.trim() === "") throw new UsageError(`${what} is empty`);
307
+ if (path.posix.isAbsolute(input) || path.win32.isAbsolute(input)) throw new UsageError(`${what} "${input}" must be relative to the directory od-harness runs in (the repository root), like the keys of the baselines`);
308
+ const normal = path.posix.normalize(input).replace(/\/+$/, "");
309
+ if (normal === "." || normal === ".." || normal.startsWith("../")) throw new UsageError(`${what} "${input}" must name a path inside the directory od-harness runs in`);
310
+ return normal;
311
+ }
312
+ /** Where `file` lands when `move` is applied, or null when the move does not cover it. */
313
+ function movedPath(move, file) {
314
+ if (file === move.from) return move.to;
315
+ if (file.startsWith(`${move.from}/`)) return `${move.to}${file.slice(move.from.length)}`;
316
+ return null;
317
+ }
318
+ // src/cli/config.ts
319
+ const HARNESS_CONFIG = ".harness/config.json";
320
+ const EXAMPLE = `{"size": {"ignore": ["path/pattern/**"]}, "clones": {"ignore": ["**/generated/**"]}}`;
321
+ function patterns(config, section) {
322
+ const value = config[section];
323
+ if (value === void 0) return [];
324
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new UsageError(`${HARNESS_CONFIG}: "${section}" must be an object, as in ${EXAMPLE}`);
325
+ const ignore = value.ignore ?? [];
326
+ if (!Array.isArray(ignore) || !ignore.every((p) => typeof p === "string")) throw new UsageError(`${HARNESS_CONFIG}: ${section}.ignore must be an array of path patterns`);
327
+ return ignore;
328
+ }
329
+ function readHarnessConfig(cwd) {
330
+ const file = path.join(cwd, HARNESS_CONFIG);
331
+ if (!existsSync(file)) return {
332
+ sizeIgnore: [],
333
+ clonesIgnore: []
334
+ };
335
+ let config;
336
+ try {
337
+ config = JSON.parse(readFileSync(file, "utf8"));
338
+ } catch (error) {
339
+ throw new UsageError(`${HARNESS_CONFIG} is not valid JSON (${String(error)}). Expected ${EXAMPLE}.`);
340
+ }
341
+ if (typeof config !== "object" || config === null || Array.isArray(config)) throw new UsageError(`${HARNESS_CONFIG} must be a JSON object, for example ${EXAMPLE}.`);
342
+ const record = config;
343
+ return {
344
+ sizeIgnore: patterns(record, "size"),
345
+ clonesIgnore: patterns(record, "clones")
346
+ };
347
+ }
66
348
  // src/cli/size.ts
67
349
  const SOURCE_LIMIT = 800;
68
350
  const LARGE_LIMIT = 1500;
69
351
  const SIZE_BASELINE = ".harness/size-baseline.json";
70
- const HARNESS_CONFIG = ".harness/config.json";
71
352
  const SIZE_DOCS = "https://github.com/nexu-io/od-harness/blob/main/docs/size.md";
72
353
  const SOURCE_EXT = /\.(?:[cm]?[jt]sx?|css)$/;
73
354
  const LARGE_FILE = /(?:^|\/)__tests__\/|\.(?:test|spec)\.[^/]*$|\.css$/;
@@ -96,27 +377,13 @@ function formatSizeBaseline(baseline) {
96
377
  const files = Object.fromEntries(Object.entries(baseline.files).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
97
378
  return `${JSON.stringify({ files }, null, 2)}\n`;
98
379
  }
99
- function readIgnore(cwd) {
100
- const configPath = path.join(cwd, HARNESS_CONFIG);
101
- if (!existsSync(configPath)) return () => false;
102
- let config;
103
- try {
104
- config = JSON.parse(readFileSync(configPath, "utf8"));
105
- } catch (error) {
106
- throw new UsageError(`${HARNESS_CONFIG} is not valid JSON (${String(error)}). Expected {"size": {"ignore": ["path/pattern/**"]}}.`);
107
- }
108
- if (typeof config !== "object" || config === null || Array.isArray(config)) throw new UsageError(`${HARNESS_CONFIG} must be a JSON object, for example {"size": {"ignore": []}}.`);
109
- const ignore = config.size?.ignore ?? [];
110
- if (!Array.isArray(ignore) || !ignore.every((p) => typeof p === "string")) throw new UsageError(`${HARNESS_CONFIG}: size.ignore must be an array of path patterns`);
111
- return compilePathPatterns(ignore);
112
- }
113
380
  function runSize(options) {
114
381
  const { cwd } = options;
115
382
  const baselinePath = path.join(cwd, SIZE_BASELINE);
116
383
  const hasBaseline = existsSync(baselinePath);
117
384
  if (options.init && hasBaseline) throw new UsageError(`${SIZE_BASELINE} already exists. --init only creates the first baseline; use --update to tighten it.`);
118
385
  const baseline = hasBaseline ? readSizeBaseline(readFileSync(baselinePath, "utf8"), SIZE_BASELINE) : { files: {} };
119
- const ignored = readIgnore(cwd);
386
+ const ignored = compilePathPatterns(readHarnessConfig(cwd).sizeIgnore);
120
387
  const sizes = /* @__PURE__ */ new Map();
121
388
  for (const file of listFiles(cwd)) {
122
389
  if (!SOURCE_EXT.test(file) || ignored(file)) continue;
@@ -132,9 +399,11 @@ function runSize(options) {
132
399
  const lines = sizes.get(file);
133
400
  const limit = limitFor(file);
134
401
  if (lines === void 0) {
135
- const why = existsSync(path.join(cwd, file)) ? `is excluded by ${HARNESS_CONFIG} (size.ignore)` : "no longer exists";
402
+ const exists = existsSync(path.join(cwd, file));
403
+ const why = exists ? `is excluded by ${HARNESS_CONFIG} (size.ignore)` : "no longer exists";
404
+ const moved = exists ? "" : " If it was moved or renamed, run `od-harness baseline move <old path> <new path>` instead, so the frozen size moves with it.";
136
405
  if (options.update) notes.push(`${file}: removed from the baseline (the file ${why}).`);
137
- else errors.push(`${file}: listed in ${SIZE_BASELINE} but the file ${why}. ${tighten}`);
406
+ else errors.push(`${file}: listed in ${SIZE_BASELINE} but the file ${why}. ${tighten}${moved}`);
138
407
  } else if (lines <= limit) {
139
408
  if (options.update) notes.push(`${file}: back within budget (${lines}/${limit}); removed from the baseline.`);
140
409
  else errors.push(`${file}: now ${lines} lines, within the ${limit}-line budget, but still listed in the baseline. ${tighten}`);
@@ -171,10 +440,6 @@ function runSize(options) {
171
440
  notes
172
441
  };
173
442
  }
174
- // src/cli/ratchet.ts
175
- const SUPPRESSIONS = "oxlint-suppressions.json";
176
- const RATCHET_DOCS = "https://github.com/nexu-io/od-harness/blob/main/docs/ratchet.md";
177
- const HARNESS_PACKAGE = "@opendesignai/harness";
178
443
  function parseSuppressions(text, origin) {
179
444
  let parsed;
180
445
  try {
@@ -189,11 +454,716 @@ function parseSuppressions(text, origin) {
189
454
  }
190
455
  return parsed;
191
456
  }
457
+ /** Count per rule, summed over all files. */
192
458
  function totals(suppressions) {
193
459
  const out = /* @__PURE__ */ new Map();
194
460
  for (const rules of Object.values(suppressions)) for (const [rule, { count }] of Object.entries(rules)) out.set(rule, (out.get(rule) ?? 0) + count);
195
461
  return out;
196
462
  }
463
+ const byKey = ([a], [b]) => a < b ? -1 : a > b ? 1 : 0;
464
+ /**
465
+ * The file as Oxlint writes it (files and rules sorted, two-space indent, no final newline), so
466
+ * that `oxlint --prune-suppressions` leaves a rewritten file unchanged.
467
+ */
468
+ function formatSuppressions(suppressions) {
469
+ const sorted = Object.fromEntries(Object.entries(suppressions).sort(byKey).map(([file, rules]) => [file, Object.fromEntries(Object.entries(rules).sort(byKey))]));
470
+ return JSON.stringify(sorted, null, 2);
471
+ }
472
+ // src/cli/baseline-move.ts
473
+ const MOVE_DOCS = "https://github.com/nexu-io/od-harness/blob/main/docs/baseline-move.md";
474
+ function renameKeys(entries, renamed) {
475
+ return Object.fromEntries(Object.entries(entries).map(([key, v]) => [renamed.get(key) ?? key, v]));
476
+ }
477
+ function loadSuppressions(cwd, file) {
478
+ const abs = path.join(cwd, file);
479
+ if (!existsSync(abs)) return null;
480
+ const data = parseSuppressions(readFileSync(abs, "utf8"), file);
481
+ return {
482
+ file,
483
+ keys: Object.keys(data),
484
+ describe: (key) => Object.entries(data[key] ?? {}).map(([rule, { count }]) => `${rule} ${count}`).join(", "),
485
+ totals: () => totals(data),
486
+ rewrite(renamed) {
487
+ const next = renameKeys(data, renamed);
488
+ return {
489
+ text: formatSuppressions(next),
490
+ totals: totals(next)
491
+ };
492
+ }
493
+ };
494
+ }
495
+ function loadSizeBaseline(cwd) {
496
+ const abs = path.join(cwd, SIZE_BASELINE);
497
+ if (!existsSync(abs)) return null;
498
+ const data = readSizeBaseline(readFileSync(abs, "utf8"), SIZE_BASELINE);
499
+ const lineTotal = (files) => /* @__PURE__ */ new Map([["lines", Object.values(files).reduce((sum, n) => sum + n, 0)]]);
500
+ return {
501
+ file: SIZE_BASELINE,
502
+ keys: Object.keys(data.files),
503
+ describe: (key) => `${data.files[key] ?? 0} lines`,
504
+ totals: () => lineTotal(data.files),
505
+ rewrite(renamed) {
506
+ const files = renameKeys(data.files, renamed);
507
+ return {
508
+ text: formatSizeBaseline({ files }),
509
+ totals: lineTotal(files)
510
+ };
511
+ }
512
+ };
513
+ }
514
+ const BASELINES = [(cwd, suppressions) => loadSuppressions(cwd, suppressions), (cwd) => loadSizeBaseline(cwd)];
515
+ function sameTotals(a, b) {
516
+ return a.size === b.size && [...a].every(([key, value]) => b.get(key) === value);
517
+ }
518
+ function list(items) {
519
+ return `${items.slice(0, 10).join(", ")}${items.length > 10 ? `, … (${items.length} in all)` : ""}`;
520
+ }
521
+ function runBaselineMove(options) {
522
+ const { cwd } = options;
523
+ const move = {
524
+ from: normalizeRepoPath(options.from, "<from>"),
525
+ to: normalizeRepoPath(options.to, "<to>")
526
+ };
527
+ if (move.from === move.to) throw new UsageError("<from> and <to> are the same path");
528
+ if (move.to.startsWith(`${move.from}/`) || move.from.startsWith(`${move.to}/`)) throw new UsageError("<to> may not be inside <from>, nor <from> inside <to>");
529
+ const suppressions = options.suppressions ?? "oxlint-suppressions.json";
530
+ const baselines = BASELINES.map((load) => load(cwd, suppressions)).filter((b) => b !== null);
531
+ if (baselines.length === 0) throw new UsageError(`no baseline here: neither ${suppressions} nor ${SIZE_BASELINE} exists. Run od-harness from the directory that holds them (the repository root).`);
532
+ const exists = (file) => existsExactly(cwd, file);
533
+ const plans = baselines.map((baseline) => {
534
+ const renamed = /* @__PURE__ */ new Map();
535
+ for (const key of baseline.keys) {
536
+ const to = movedPath(move, key);
537
+ if (to !== null) renamed.set(key, to);
538
+ }
539
+ return {
540
+ baseline,
541
+ renamed
542
+ };
543
+ });
544
+ const files = baselines.map((b) => b.file).join(" and ");
545
+ if (plans.every((plan) => plan.renamed.size === 0)) return {
546
+ ok: false,
547
+ notes: [],
548
+ errors: [`${files} ${baselines.length > 1 ? "have" : "has"} no entry under ${move.from}, so there is nothing to move. Check <from>: it is the old path, relative to the repository root, exactly as the baseline keys spell it. See ${MOVE_DOCS}`]
549
+ };
550
+ const base = options.base ?? "HEAD";
551
+ const commit = resolveRef(cwd, base);
552
+ const stillThere = /* @__PURE__ */ new Set();
553
+ const missing = /* @__PURE__ */ new Set();
554
+ const taken = [];
555
+ const pairs = /* @__PURE__ */ new Map();
556
+ for (const { baseline, renamed } of plans) for (const [from, to] of renamed) {
557
+ if (exists(from)) stillThere.add(from);
558
+ if (!exists(to)) missing.add(to);
559
+ if (baseline.keys.includes(to) && !renamed.has(to)) taken.push(`${baseline.file}: ${to}`);
560
+ if (!exists(from) && exists(to)) pairs.set(from, to);
561
+ }
562
+ const renames = movesSince(cwd, commit);
563
+ const unrelated = [...pairs].filter(([from, to]) => renames.get(to) !== from).map(([from, to]) => {
564
+ const other = renames.get(to);
565
+ return `${from} → ${to}${other === void 0 ? "" : ` (git pairs it with ${other})`}`;
566
+ });
567
+ const errors = [];
568
+ if (stillThere.size > 0) errors.push(`${list([...stillThere])} still exist${stillThere.size === 1 ? "s" : ""}. A baseline move follows files that were moved; debt never moves to a file while the old one stays. Fix: move the files first (\`git mv ${move.from} ${move.to}\`), then run this command again.`);
569
+ if (missing.size > 0) errors.push(`${list([...missing])} ${missing.size === 1 ? "does" : "do"} not exist. <to> is the new path of <from> (not its new parent directory). Fix: move the files first (\`git mv ${move.from} ${move.to}\`), or correct <to>.`);
570
+ if (taken.length > 0) errors.push(`already in the baseline: ${list(taken)}. A move never merges debt into a file that has its own entries. Fix: move to a path without baseline entries, or fix the debt of one of the two files first.`);
571
+ if (unrelated.length > 0) errors.push(`git does not see ${unrelated.length === 1 ? "this new file as a rename of its old one" : "these new files as renames of their old ones"} (\`git diff -M30% -l0 ${base}\`, at least 30% similarity): ${list(unrelated)}. Entries only move with files that were moved, and \`ratchet\` accepts them only under the same condition. Fix: stage the move (\`git mv <old> <new>\`, or \`git add\` both paths) and run this command before committing it; for a move committed already, pass \`--base <the commit before it>\`. A new file whose content does not correspond to the old one is not a move: the old debt is gone with the old file, so prune its entries (\`oxlint --prune-suppressions\`, \`od-harness size --update\`) and fix the violations in the new file, or split it.`);
572
+ if (errors.length > 0) return {
573
+ ok: false,
574
+ errors: [...errors, `See ${MOVE_DOCS}`],
575
+ notes: []
576
+ };
577
+ const notes = [];
578
+ const writes = [];
579
+ for (const { baseline, renamed } of plans) {
580
+ if (renamed.size === 0) continue;
581
+ const { text, totals: after } = baseline.rewrite(renamed);
582
+ if (!sameTotals(baseline.totals(), after)) throw new Error(`${baseline.file}: totals changed while moving entries (bug in od-harness)`);
583
+ writes.push([baseline.file, text]);
584
+ const moved = [...renamed].map(([from, to]) => `${from} → ${to} (${baseline.describe(from)})`);
585
+ notes.push(`${baseline.file}: moved ${renamed.size} ${renamed.size === 1 ? "entry" : "entries"}, totals unchanged: ${list(moved)}`);
586
+ }
587
+ for (const [file, text] of writes) writeFileSync(path.join(cwd, file), text);
588
+ notes.push(`commit the baselines with the moved files, in one change; \`od-harness ratchet\` accepts the moved entries while git sees the renames against the PR base (\`git diff -M30% -l0 <base>\`).`);
589
+ return {
590
+ ok: true,
591
+ errors: [],
592
+ notes
593
+ };
594
+ }
595
+ // src/cli/hiding.ts
596
+ /** The extensions of the JavaScript and TypeScript files knip analyses (its DEFAULT_EXTENSIONS). */
597
+ const SCRIPT_EXTENSIONS = [
598
+ "js",
599
+ "jsx",
600
+ "mjs",
601
+ "cjs",
602
+ "ts",
603
+ "tsx",
604
+ "mts",
605
+ "cts"
606
+ ];
607
+ /**
608
+ * The extensions of the files jscpd 5.4.3 scans with the formats of `JSCPD_SETTINGS` (javascript,
609
+ * typescript, jsx, tsx): knip's, plus `.es` and `.es6`, which jscpd reads as JavaScript. Review it
610
+ * when upgrading jscpd; test/cli/clones.test.ts runs jscpd on candidate extensions to check it.
611
+ */
612
+ const JSCPD_EXTENSIONS = [
613
+ ...SCRIPT_EXTENSIONS,
614
+ "es",
615
+ "es6"
616
+ ];
617
+ /**
618
+ * First lines for which jscpd 5.4.3 scans a file without an extension in `JSCPD_EXTENSIONS` as
619
+ * JavaScript: a shebang that contains `node` anywhere, case-sensitively (`env node`,
620
+ * `/usr/bin/node16`, `env nodemon`, `/usr/bin/xnode`, `env sh -c node`, …), however long the line.
621
+ * jscpd ends the line at `\n` only, so `[^\n]` and not `.` (which stops at `\r` and U+2028). jscpd
622
+ * skips such a line that also names python; matching it anyway only fails closed. Review it when
623
+ * upgrading jscpd; test/cli/clones.test.ts runs jscpd on candidate first lines to check it.
624
+ */
625
+ const NODE_SHEBANG = /^#![^\n]*node/;
626
+ /** The first line of `file` up to `\n`, however long, when it starts with `#!`; otherwise "". */
627
+ function readFirstLine(cwd, file) {
628
+ let fd;
629
+ try {
630
+ fd = openSync(path.join(cwd, file), "r");
631
+ const chunks = [];
632
+ for (let position = 0;;) {
633
+ const chunk = Buffer.alloc(4096);
634
+ const bytes = readSync(fd, chunk, 0, chunk.length, position);
635
+ const read = chunk.subarray(0, bytes);
636
+ if (position === 0 && (read[0] !== 35 || read[1] !== 33)) return "";
637
+ const end = read.indexOf(10);
638
+ chunks.push(end === -1 ? read : read.subarray(0, end));
639
+ if (end !== -1 || bytes === 0) break;
640
+ position += bytes;
641
+ }
642
+ return Buffer.concat(chunks).toString("utf8");
643
+ } catch {
644
+ return "";
645
+ } finally {
646
+ if (fd !== void 0) closeSync(fd);
647
+ }
648
+ }
649
+ /**
650
+ * Subset of `files` (relative to `cwd`) that do not have an extension in `JSCPD_EXTENSIONS` and
651
+ * whose first line matches `NODE_SHEBANG`. Only the first line of each file is read, and only the
652
+ * first 4 KiB of a file that does not start with `#!`. Over-matching a file whose extension jscpd
653
+ * maps to another format (such as `.sh` or `.txt`) is deliberate: it can only fail closed on marker
654
+ * text or an ignore rule in that file.
655
+ */
656
+ function nodeShebangFiles(cwd, files) {
657
+ const found = [];
658
+ for (const file of new Set(files)) {
659
+ if (JSCPD_EXTENSIONS.some((ext) => file.endsWith(`.${ext}`))) continue;
660
+ if (NODE_SHEBANG.test(readFirstLine(cwd, file))) found.push(file);
661
+ }
662
+ return found;
663
+ }
664
+ /**
665
+ * Pathspecs for the files with these `extensions`, plus any `extra` literal files, minus `ignore`
666
+ * globs (relative to the working directory).
667
+ */
668
+ function scriptPathspecs(extensions, ignore = [], extra = []) {
669
+ return [
670
+ ...extensions.map((ext) => `:(glob)**/*.${ext}`),
671
+ ...extra.map((file) => `:(literal)${file}`),
672
+ ...ignore.map((glob) => `:(exclude,glob)${glob}`)
673
+ ];
674
+ }
675
+ const touches = (ranges, start, end) => (ranges ?? []).some(([from, to]) => from <= end && to >= start);
676
+ function read(cwd, file) {
677
+ try {
678
+ return readFileSync(path.join(cwd, file), "utf8");
679
+ } catch {
680
+ return null;
681
+ }
682
+ }
683
+ /**
684
+ * Added or edited lines that match `pattern`, in the files `pathspecs` selects, as
685
+ * "file (count)" per file. The whole text of a line counts: a comment, a string or code.
686
+ */
687
+ function addedLinesMatching(cwd, changed, pattern, pathspecs) {
688
+ const found = [];
689
+ for (const file of listFiles(cwd, pathspecs)) {
690
+ const ranges = changed.get(file);
691
+ if (!ranges || ranges.length === 0) continue;
692
+ const hits = (read(cwd, file)?.split("\n") ?? []).filter((text, i) => touches(ranges, i + 1, i + 1) && pattern.test(text));
693
+ if (hits.length > 0) found.push(`${file} (${hits.length})`);
694
+ }
695
+ return found;
696
+ }
697
+ /**
698
+ * The comments of a JavaScript or TypeScript file as oxc-parser reads them, the parser and version
699
+ * knip reads tags with (`sourceType: "unambiguous"` and the language from the file name, as
700
+ * knip parses): text in a string, a template literal, a regular expression or JSX text is not a
701
+ * comment. Like knip, this takes the comments the parser reports even after a syntax error.
702
+ */
703
+ function scriptComments(file, text) {
704
+ return parseSync(file, text, { sourceType: "unambiguous" }).comments;
705
+ }
706
+ /** The offset at which each line of `text` starts (lines split at "\n", 0-based). */
707
+ function lineStarts(text) {
708
+ const starts = [0];
709
+ for (let at = text.indexOf("\n"); at !== -1; at = text.indexOf("\n", at + 1)) starts.push(at + 1);
710
+ return starts;
711
+ }
712
+ /** The 0-based line that holds `offset`, given the `starts` of the lines. */
713
+ function lineAt(starts, offset) {
714
+ let low = 0;
715
+ let high = starts.length - 1;
716
+ while (low < high) {
717
+ const mid = low + high + 1 >> 1;
718
+ if ((starts[mid] ?? 0) <= offset) low = mid;
719
+ else high = mid - 1;
720
+ }
721
+ return low;
722
+ }
723
+ /**
724
+ * Tracked files that ignore rules exclude, among those `pathspecs` selects, when this change adds
725
+ * or edits them, or edits an ignore file (`ignoreFiles`, by name) anywhere: jscpd and knip skip
726
+ * such files, so a new file there, or an existing one newly ignored, would escape the gate.
727
+ * `.gitignore` stands for git's standard rules; other names are read per directory (jscpd also
728
+ * reads `.ignore`).
729
+ */
730
+ function changedIgnoredFiles(cwd, commit, changed, pathspecs, ignoreFiles = [".gitignore"]) {
731
+ const ignored = /* @__PURE__ */ new Set([...ignoredTrackedFiles(cwd, pathspecs), ...ignoreFiles.filter((name) => name !== ".gitignore").flatMap((name) => ignoredTrackedFiles(cwd, pathspecs, name))]);
732
+ if (ignored.size === 0) return [];
733
+ const rulesChanged = changedPaths(cwd, commit).some((file) => ignoreFiles.includes(path.posix.basename(file)));
734
+ return [...ignored].filter((file) => rulesChanged || (changed.get(file) ?? []).length > 0).sort();
735
+ }
736
+ /** The tags with which knip never reports an export (knip's `isAlwaysIgnored`). */
737
+ const HIDING_TAG = /@(public|beta|alias)\b/;
738
+ /** A space, a tab, "\n" or "\r": what knip skips after a comment. */
739
+ const isBlank = (code) => code === 32 || code === 9 || code === 10 || code === 13;
740
+ /**
741
+ * Whether knip reads tags from `comment` (knip's `buildJSDocTagLookup`): every block comment,
742
+ * `/* … *\/` as well as `/** … *\/`, and a line comment with only spaces and tabs before it on its
743
+ * line. A line comment after code on its line is not read.
744
+ */
745
+ function readsTags(text, comment) {
746
+ if (comment.type === "Block") return true;
747
+ let at = comment.start;
748
+ while (at > 0 && (text.charCodeAt(at - 1) === 32 || text.charCodeAt(at - 1) === 9)) at--;
749
+ return at === 0 || text.charCodeAt(at - 1) === 10 || text.charCodeAt(at - 1) === 13;
750
+ }
751
+ /**
752
+ * For each comment, the offset of the code it documents, as knip finds it: the first character
753
+ * after the comment that is not blank (`isBlank`). Comments with only blanks between them form a
754
+ * group, and every comment of the group documents the code after the group's last comment.
755
+ */
756
+ function documentedOffsets(text, comments) {
757
+ const offsets = [];
758
+ let reach = text.length;
759
+ for (let i = comments.length - 1; i >= 0; i--) {
760
+ let at = comments[i]?.end ?? text.length;
761
+ while (at < text.length && isBlank(text.charCodeAt(at))) at++;
762
+ if (at !== comments[i + 1]?.start) reach = at;
763
+ offsets[i] = reach;
764
+ }
765
+ return offsets;
766
+ }
767
+ /** The offset of the first "}" at or after `from` that is not in one of the `comments`. */
768
+ function closingBrace(text, comments, from) {
769
+ for (let at = text.indexOf("}", from); at !== -1; at = text.indexOf("}", at + 1)) if (!comments.some((comment) => comment.start <= at && at < comment.end)) return at;
770
+ return -1;
771
+ }
772
+ /**
773
+ * Comments with a tag that hides an export from knip, each with the declaration it documents:
774
+ * the line of the first character after the comment's group (`documentedOffsets`), up to the
775
+ * closing brace of an `export { … }` list (a brace in a comment inside the list does not close
776
+ * it). Comments count as knip reads them (`scriptComments`, with `file` naming the language;
777
+ * `readsTags`), whatever the parser reports.
778
+ */
779
+ function taggedDeclarations(text, file = "source.ts") {
780
+ const starts = lineStarts(text);
781
+ const comments = scriptComments(file, text);
782
+ const documented = documentedOffsets(text, comments);
783
+ const found = [];
784
+ comments.forEach((comment, i) => {
785
+ const tag = readsTags(text, comment) ? HIDING_TAG.exec(comment.value) : null;
786
+ if (!tag) return;
787
+ const at = documented[i] ?? text.length;
788
+ let end = at;
789
+ if (/^\s*export\s+(type\s+)?\{/.test(text.slice(at))) {
790
+ const close = closingBrace(text, comments, at);
791
+ end = close === -1 ? text.length : close;
792
+ }
793
+ found.push({
794
+ tag: tag[0],
795
+ start: lineAt(starts, comment.start) + 1,
796
+ end: lineAt(starts, end) + 1
797
+ });
798
+ });
799
+ return found;
800
+ }
801
+ /**
802
+ * Exports this change adds or edits under a tag that hides them from knip, or tags it adds or
803
+ * edits, as "file:line (@tag)".
804
+ */
805
+ function hidingTags(cwd, changed) {
806
+ const found = [];
807
+ for (const [file, ranges] of changed) {
808
+ if (ranges.length === 0 || !SCRIPT_EXTENSIONS.some((ext) => file.endsWith(`.${ext}`))) continue;
809
+ const text = read(cwd, file);
810
+ if (text === null) continue;
811
+ for (const { tag, start, end } of taggedDeclarations(text, file)) if (touches(ranges, start, end)) found.push(`${file}:${start} (${tag})`);
812
+ }
813
+ return found;
814
+ }
815
+ // src/cli/clones.ts
816
+ const CLONES_DOCS = "https://github.com/nexu-io/od-harness/blob/main/docs/clones.md";
817
+ const START_MARKER = ["jscpd", "ignore-start"].join(":");
818
+ const END_MARKER = ["jscpd", "ignore-end"].join(":");
819
+ /**
820
+ * jscpd settings: formats and thresholds of the maintainability report openmotion and opengame ran
821
+ * before. od-harness ignores no path or file name of its own: every glob jscpd leaves out comes
822
+ * from `clones.ignore` in .harness/config.json, which the owner reviews (docs/adopting.md has the
823
+ * recommended list). jscpd itself skips what .gitignore and .ignore files exclude.
824
+ */
825
+ const JSCPD_SETTINGS = {
826
+ format: [
827
+ "javascript",
828
+ "typescript",
829
+ "jsx",
830
+ "tsx"
831
+ ],
832
+ mode: "weak",
833
+ minLines: 12,
834
+ minTokens: 80
835
+ };
836
+ function where(fragment) {
837
+ return `${fragment.name}:${fragment.start}-${fragment.end}`;
838
+ }
839
+ function readReport(file, failure) {
840
+ if (!existsSync(file)) throw new EnvironmentError(`jscpd wrote no report. ${failure}`);
841
+ try {
842
+ const report = JSON.parse(readFileSync(file, "utf8"));
843
+ if (!Array.isArray(report.duplicates) || typeof report.statistics?.total !== "object") throw new TypeError("unexpected shape");
844
+ return report;
845
+ } catch (error) {
846
+ throw new EnvironmentError(`jscpd wrote an unreadable report (${String(error)}). ${failure}`);
847
+ }
848
+ }
849
+ /**
850
+ * A line that holds either marker. jscpd finds them in the raw text of a file, in a comment, a
851
+ * string, a template literal, a regular expression, JSX text or code alike, so every place counts.
852
+ */
853
+ const MARKER = new RegExp(`${START_MARKER}|${END_MARKER}`);
854
+ function runClones(options) {
855
+ const { cwd } = options;
856
+ if (!options.base) throw new UsageError("missing --base <ref>");
857
+ const commit = resolveRef(cwd, options.base);
858
+ const at = `${options.base} (${commit.slice(0, 10)})`;
859
+ const ignore = readHarnessConfig(cwd).clonesIgnore;
860
+ const temp = mkdtempSync(path.join(tmpdir(), "od-harness-clones-"));
861
+ let report;
862
+ try {
863
+ const config = path.join(temp, "jscpd.json");
864
+ writeFileSync(config, JSON.stringify({
865
+ ...JSCPD_SETTINGS,
866
+ ignore
867
+ }));
868
+ const output = path.join(temp, "report");
869
+ const result = runJscpd([
870
+ "--config",
871
+ config,
872
+ "--baseline-from-ref",
873
+ commit,
874
+ "--fail-on-new-clones",
875
+ "0",
876
+ "--reporters",
877
+ "json,silent",
878
+ "--output",
879
+ output,
880
+ "--no-colors",
881
+ "."
882
+ ], {
883
+ cwd,
884
+ encoding: "utf8",
885
+ maxBuffer: 268435456
886
+ });
887
+ if (result.error) throw result.error;
888
+ const failure = `jscpd exited with ${result.status ?? result.signal}: ${`${result.stderr}${result.stdout}`.trim().slice(-2e3)}`;
889
+ report = readReport(path.join(output, "jscpd-report.json"), failure);
890
+ if (result.status !== 0 && !report.duplicates.some((clone) => clone.isNew)) throw new EnvironmentError(failure);
891
+ } finally {
892
+ rmSync(temp, {
893
+ recursive: true,
894
+ force: true
895
+ });
896
+ }
897
+ const { total } = report.statistics;
898
+ if (total.sources === 0) throw new EnvironmentError(`jscpd scanned no file in ${cwd}: the globs in clones.ignore of ${HARNESS_CONFIG} (od-harness has no ignore list of its own) leave nothing, or no JavaScript or TypeScript file is large enough. Fix the globs, or turn the clones gate off for a repository without such code.`);
899
+ const reported = report.duplicates.filter((clone) => clone.isNew);
900
+ const shebang = nodeShebangFiles(cwd, [
901
+ ...changedFiles(cwd, commit),
902
+ ...ignoredTrackedFiles(cwd, []),
903
+ ...ignoredTrackedFiles(cwd, [], ".ignore")
904
+ ]);
905
+ const extra = /* @__PURE__ */ new Set([...shebang, ...reported.flatMap((clone) => [clone.firstFile.name, clone.secondFile.name])]);
906
+ const changed = changedLines(cwd, commit, scriptPathspecs(JSCPD_EXTENSIONS, [], [...extra]));
907
+ const touched = (fragment) => (changed.get(fragment.name) ?? []).some(([start, end]) => start <= fragment.end && end >= fragment.start);
908
+ const added = reported.filter((clone) => touched(clone.firstFile) || touched(clone.secondFile));
909
+ const repaired = reported.length - added.length;
910
+ const summary = `${total.sources} files, ${total.clones} clones, ${added.length} new against ${at}${repaired > 0 ? `; ${repaired} re-paired in unchanged code, not counted` : ""}`;
911
+ const errors = [];
912
+ if (added.length > 0) errors.push(`${added.length === 1 ? "A new duplicated fragment" : `${added.length} new duplicated fragments`} (at least ${JSCPD_SETTINGS.minLines} lines and ${JSCPD_SETTINGS.minTokens} tokens; the ${total.clones - added.length} clones ${at} already has are tolerated):`, ...added.slice(0, 50).map((clone) => ` ${where(clone.firstFile)} duplicates ${where(clone.secondFile)} (${clone.lines} lines)`), ...added.length > 50 ? [` … and ${added.length - 50} more`] : [], `This change copies code instead of reusing it. Fix: extract the shared code into one function or module and call it from both places (look for an existing implementation first), then run \`od-harness clones --base ${options.base}\` again. Editing code that was already duplicated also makes its clone new, because jscpd identifies a clone by its text: deduplicate it in this change. Exemption: code the gate does not check (tests, fixtures, generated or vendored code) is listed in "clones": {"ignore": [...]} in ${HARNESS_CONFIG}, which the owner reviews; od-harness ignores nothing else. Never use jscpd:ignore markers.`);
913
+ const scanned = scriptPathspecs(JSCPD_EXTENSIONS, ignore, shebang);
914
+ const markers = addedLinesMatching(cwd, changed, MARKER, scanned);
915
+ if (markers.length > 0) errors.push(`This change adds jscpd:ignore markers (${START_MARKER} or ${END_MARKER}): ${markers.slice(0, 10).join(", ")}. jscpd honours the marker text anywhere in a file, in a comment, a string or code, so it hides duplicated code from the gate without review. Fix: remove the marker text and deduplicate the code. Exemption: exclude generated or vendored files through "clones": {"ignore": [...]} in ${HARNESS_CONFIG} (owner review).`);
916
+ const hidden = changedIgnoredFiles(cwd, commit, changed, scanned, [".gitignore", ".ignore"]);
917
+ if (hidden.length > 0) errors.push(`jscpd does not scan these tracked files, because .gitignore or an .ignore file excludes them, and this change adds or edits them or the ignore rules: ${hidden.slice(0, 10).join(", ")}${hidden.length > 10 ? ", …" : ""}. The gate cannot see their clones. Fix: change the rule so it no longer matches them, or add a \`!path\` exception after it, so jscpd scans them; a rule that excludes a parent directory (\`dir/\`) cannot be undone with \`!path\`, because git does not look inside an excluded directory: exclude its contents instead (\`dir/*\`), then add \`!dir/file\`. Exemption: code the gate does not check (generated or vendored code) is listed in "clones": {"ignore": [...]} in ${HARNESS_CONFIG}, which the owner reviews; a file listed there is not reported.`);
918
+ if (errors.length > 0) errors.push(`See ${CLONES_DOCS}`);
919
+ return {
920
+ ok: errors.length === 0,
921
+ errors,
922
+ notes: [],
923
+ summary
924
+ };
925
+ }
926
+ // src/cli/child-env.ts
927
+ function childEnv(extra) {
928
+ return {
929
+ ...process.env,
930
+ ...extra
931
+ };
932
+ }
933
+ // src/cli/checkout.ts
934
+ function git(cwd, args, env) {
935
+ return execFileSync("git", args, {
936
+ cwd,
937
+ encoding: "utf8",
938
+ maxBuffer: 268435456,
939
+ stdio: "pipe",
940
+ ...env ? { env } : {}
941
+ });
942
+ }
943
+ /**
944
+ * Check `commit` out into a temporary directory without touching the repository: a temporary
945
+ * index file is filled from the commit and written out with `checkout-index`. No hooks run and
946
+ * Git LFS objects stay pointers.
947
+ */
948
+ function checkoutCommit(cwd, commit) {
949
+ const top = git(cwd, ["rev-parse", "--show-toplevel"]).trim();
950
+ const prefix = git(cwd, ["rev-parse", "--show-prefix"]).trim();
951
+ const temp = mkdtempSync(path.join(tmpdir(), "od-harness-base-"));
952
+ const root = path.join(temp, "tree");
953
+ const env = childEnv({
954
+ GIT_INDEX_FILE: path.join(temp, "index"),
955
+ GIT_LFS_SKIP_SMUDGE: "1"
956
+ });
957
+ const cleanup = () => rmSync(temp, {
958
+ recursive: true,
959
+ force: true
960
+ });
961
+ try {
962
+ git(top, ["read-tree", commit], env);
963
+ git(top, [
964
+ "checkout-index",
965
+ "--all",
966
+ "--force",
967
+ `--prefix=${root}/`
968
+ ], env);
969
+ } catch (error) {
970
+ cleanup();
971
+ throw error;
972
+ }
973
+ return {
974
+ dir: path.join(root, prefix),
975
+ root,
976
+ top,
977
+ cleanup
978
+ };
979
+ }
980
+ /** Directories (repository-relative, "" for the root) that hold a tracked package.json. */
981
+ function packageDirs(top) {
982
+ return git(top, [
983
+ "ls-files",
984
+ "-z",
985
+ "--",
986
+ ":(glob)**/package.json"
987
+ ]).split("\0").filter(Boolean).map((file) => path.posix.dirname(file)).map((dir) => dir === "." ? "" : dir);
988
+ }
989
+ /**
990
+ * Let the checkout resolve packages through the working tree's node_modules (CI installs only
991
+ * the head): every directory with a package.json gets a link to its installed node_modules.
992
+ * Returns the links.
993
+ */
994
+ function linkNodeModules(checkout) {
995
+ const links = [];
996
+ for (const dir of packageDirs(checkout.top)) {
997
+ const installed = path.join(checkout.top, dir, "node_modules");
998
+ const target = path.join(checkout.root, dir, "node_modules");
999
+ if (!existsSync(installed) || !statSync(installed).isDirectory()) continue;
1000
+ if (!existsSync(path.dirname(target)) || existsSync(target)) continue;
1001
+ symlinkSync(installed, target, "junction");
1002
+ links.push(target);
1003
+ }
1004
+ return links;
1005
+ }
1006
+ /** Remove links made by linkNodeModules (the links only, never what they point to). */
1007
+ function unlinkNodeModules(links) {
1008
+ for (const link of links) unlinkSync(link);
1009
+ }
1010
+ /**
1011
+ * Install a checkout's own dependencies from its lockfile, frozen and without lifecycle scripts:
1012
+ * the nearest package-lock.json (`npm ci`) or pnpm-lock.yaml (`pnpm install --frozen-lockfile`)
1013
+ * from `dir` up to `root`. Returns the command it ran.
1014
+ */
1015
+ function installFromLockfile(dir, root) {
1016
+ for (let at = dir;; at = path.dirname(at)) {
1017
+ const command = existsSync(path.join(at, "pnpm-lock.yaml")) ? ["pnpm", [
1018
+ "install",
1019
+ "--frozen-lockfile",
1020
+ "--ignore-scripts"
1021
+ ]] : existsSync(path.join(at, "package-lock.json")) ? ["npm", [
1022
+ "ci",
1023
+ "--ignore-scripts",
1024
+ "--no-audit",
1025
+ "--no-fund"
1026
+ ]] : null;
1027
+ if (command) {
1028
+ const [bin, args] = command;
1029
+ const result = spawnSync(bin, args, {
1030
+ cwd: at,
1031
+ encoding: "utf8",
1032
+ maxBuffer: 268435456
1033
+ });
1034
+ const ran = `${bin} ${args.join(" ")}`;
1035
+ if (result.error || result.status !== 0) {
1036
+ const output = `${result.stderr ?? ""}${result.stdout ?? ""}`.trim().slice(-1500);
1037
+ throw new EnvironmentError(`\`${ran}\` failed (${result.error ? String(result.error) : `exit ${result.status}`}): ${output}`);
1038
+ }
1039
+ return ran;
1040
+ }
1041
+ if (at === root || path.dirname(at) === at) break;
1042
+ }
1043
+ throw new EnvironmentError("it has no package-lock.json or pnpm-lock.yaml to install from");
1044
+ }
1045
+ // src/cli/lint-config.ts
1046
+ function toView(config) {
1047
+ const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : {};
1048
+ const { rules, overrides } = record(config);
1049
+ return {
1050
+ rules: record(rules),
1051
+ overrides: (Array.isArray(overrides) ? overrides : []).map((o) => ({
1052
+ files: record(o).files ?? null,
1053
+ rules: record(record(o).rules)
1054
+ }))
1055
+ };
1056
+ }
1057
+ const isOn = (setting) => {
1058
+ const severity = Array.isArray(setting) ? setting[0] : setting;
1059
+ return severity !== void 0 && ![
1060
+ "off",
1061
+ "allow",
1062
+ 0,
1063
+ "0"
1064
+ ].includes(severity);
1065
+ };
1066
+ /** The settings of `rule`: its top-level value and every override that sets it, with its files. */
1067
+ const settingsOf = (view, rule) => JSON.stringify([view.rules[rule] ?? null, view.overrides.filter((o) => Object.hasOwn(o.rules, rule)).map((o) => [o.files, o.rules[rule]])]);
1068
+ /** Oxlint's CLI script: the repository's own install first, else the peer of od-harness. */
1069
+ function oxlintBin(cwd) {
1070
+ for (const from of [path.join(cwd, "package.json"), import.meta.url]) try {
1071
+ const manifest = createRequire(from).resolve("oxlint/package.json");
1072
+ return path.join(path.dirname(manifest), "bin/oxlint");
1073
+ } catch {}
1074
+ return null;
1075
+ }
1076
+ /** The effective configuration of `file` (absolute), or why Oxlint could not print it. */
1077
+ function printConfig(bin, file) {
1078
+ const result = spawnSync(process.execPath, [
1079
+ bin,
1080
+ "-c",
1081
+ file,
1082
+ "--print-config"
1083
+ ], {
1084
+ cwd: path.dirname(file),
1085
+ encoding: "utf8",
1086
+ maxBuffer: 67108864
1087
+ });
1088
+ if (result.error || result.status !== 0) return `${result.stderr ?? ""}${result.stdout ?? ""}`.replace(/\s+/g, " ").trim().slice(0, 300) || String(result.error ?? `exit ${result.status}`);
1089
+ try {
1090
+ return toView(JSON.parse(result.stdout));
1091
+ } catch (error) {
1092
+ return `unreadable output (${String(error)})`;
1093
+ }
1094
+ }
1095
+ function parseRaw(text) {
1096
+ if (text === null) return toView({});
1097
+ try {
1098
+ return toView(JSON.parse(text));
1099
+ } catch {
1100
+ return toView({});
1101
+ }
1102
+ }
1103
+ /**
1104
+ * The rules that this change's version of `lintConfig` (relative to `cwd`) turns on compared
1105
+ * with the one at `commit`: on at the top level or in an override, and set differently at the
1106
+ * base (another value, or other override files). Falls back to the rules written in the two
1107
+ * files when Oxlint cannot print either effective configuration (for example when it cannot load
1108
+ * a plugin), which admits only rules the change sets itself.
1109
+ */
1110
+ function ruleChanges(cwd, commit, lintConfig) {
1111
+ const headFile = path.join(cwd, lintConfig);
1112
+ const baseText = showFile(cwd, commit, lintConfig);
1113
+ const bin = oxlintBin(cwd);
1114
+ let head = "Oxlint is not installed";
1115
+ let base = head;
1116
+ if (bin !== null) {
1117
+ const temp = mkdtempSync(path.join(tmpdir(), "od-harness-config-"));
1118
+ try {
1119
+ let file = headFile;
1120
+ if (!existsSync(file)) {
1121
+ file = path.join(temp, path.basename(lintConfig));
1122
+ writeFileSync(file, "{}\n");
1123
+ }
1124
+ head = printConfig(bin, file);
1125
+ } finally {
1126
+ rmSync(temp, {
1127
+ recursive: true,
1128
+ force: true
1129
+ });
1130
+ }
1131
+ if (typeof head !== "string") {
1132
+ const checkout = checkoutCommit(cwd, commit);
1133
+ try {
1134
+ linkNodeModules(checkout);
1135
+ const baseFile = path.join(checkout.dir, lintConfig);
1136
+ if (baseText === null) {
1137
+ mkdirSync(path.dirname(baseFile), { recursive: true });
1138
+ writeFileSync(baseFile, "{}\n");
1139
+ }
1140
+ base = printConfig(bin, baseFile);
1141
+ } finally {
1142
+ checkout.cleanup();
1143
+ }
1144
+ }
1145
+ }
1146
+ let how = "the effective configurations (oxlint --print-config)";
1147
+ if (typeof head === "string" || typeof base === "string") {
1148
+ how = `the rules written in ${lintConfig}, because Oxlint could not print the effective configuration of ${typeof head === "string" ? `this change: ${head}` : `the base: ${String(base)}`}`;
1149
+ head = parseRaw(existsSync(headFile) ? readFileSync(headFile, "utf8") : null);
1150
+ base = parseRaw(baseText);
1151
+ }
1152
+ const [after, before] = [head, base];
1153
+ return {
1154
+ turnsOn: (rule) => (isOn(after.rules[rule]) || after.overrides.some((o) => isOn(o.rules[rule]))) && settingsOf(after, rule) !== settingsOf(before, rule),
1155
+ how
1156
+ };
1157
+ }
1158
+ // src/cli/ratchet.ts
1159
+ const RATCHET_DOCS = "https://github.com/nexu-io/od-harness/blob/main/docs/ratchet.md";
1160
+ const HARNESS_PACKAGE = "@opendesignai/harness";
1161
+ /** How an accepted move was recognised, in notes and messages. */
1162
+ const RENAMED = "git sees the rename";
1163
+ /** The one condition under which baseline entries follow a file to a new path. */
1164
+ function seesRename(base) {
1165
+ return `git sees the rename at 30% similarity or more (\`git diff -M30% -l0 ${base}\`)`;
1166
+ }
197
1167
  function readWorking(cwd, file) {
198
1168
  const abs = path.join(cwd, file);
199
1169
  return existsSync(abs) ? readFileSync(abs, "utf8") : null;
@@ -207,28 +1177,60 @@ function harnessVersion(packageJson) {
207
1177
  return null;
208
1178
  }
209
1179
  }
1180
+ /** The nearest pnpm-workspace.yaml from `cwd` up to the repository root, relative to `cwd`. */
1181
+ function workspaceFile(cwd) {
1182
+ for (let dir = cwd;; dir = path.dirname(dir)) {
1183
+ const file = path.join(dir, "pnpm-workspace.yaml");
1184
+ if (existsSync(file)) return path.relative(cwd, file).split(path.sep).join("/");
1185
+ if (existsSync(path.join(dir, ".git")) || path.dirname(dir) === dir) return null;
1186
+ }
1187
+ }
1188
+ /** `text` as a literal inside a regular expression. */
1189
+ function escapeRegExp(text) {
1190
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1191
+ }
210
1192
  /**
211
- * Why this change may add new rule IDs to an existing baseline: it changed the lint config or the
212
- * harness version (both owner-reviewed). Null when it changed neither.
1193
+ * The harness release a version spec names: a pnpm catalog reference (`catalog:`) with the
1194
+ * harness entries of pnpm-workspace.yaml, where the version of a catalog lives.
213
1195
  */
214
- function ownerReviewedChange(cwd, commit, lintConfig, before, after) {
215
- const reasons = [];
216
- if (showFile(cwd, commit, lintConfig) !== readWorking(cwd, lintConfig)) reasons.push(`${lintConfig} changed`);
217
- if (before !== after) reasons.push(`${HARNESS_PACKAGE} ${before ?? "(none)"} → ${after ?? "(none)"}`);
218
- return reasons.length > 0 ? reasons.join(", ") : null;
1196
+ function release(spec, workspace) {
1197
+ if (spec === null || !spec.startsWith("catalog:") || workspace === null) return spec;
1198
+ const name = escapeRegExp(HARNESS_PACKAGE);
1199
+ const entry = new RegExp(`^\\s*["']?${name}["']?\\s*:\\s*["']?([^"'\\s#]+)`, "gm");
1200
+ return `${spec} (pnpm-workspace.yaml: ${[...workspace.matchAll(entry)].map((match) => match[1]).join(", ") || "no entry"})`;
219
1201
  }
220
1202
  function runRatchet(options) {
221
1203
  const { cwd } = options;
222
1204
  if (!options.base) throw new UsageError("missing --base <ref>");
223
1205
  const commit = resolveRef(cwd, options.base);
224
- const suppressionsPath = options.suppressions ?? SUPPRESSIONS;
1206
+ const suppressionsPath = options.suppressions ?? "oxlint-suppressions.json";
225
1207
  const lintConfig = options.lintConfig ?? ".oxlintrc.json";
226
1208
  const errors = [];
227
1209
  const notes = [];
228
1210
  const at = `${options.base} (${commit.slice(0, 10)})`;
229
1211
  const harnessBefore = harnessVersion(showFile(cwd, commit, "package.json"));
230
1212
  const harnessAfter = harnessVersion(readWorking(cwd, "package.json"));
231
- const ownerChange = ownerReviewedChange(cwd, commit, lintConfig, harnessBefore, harnessAfter);
1213
+ const workspace = workspaceFile(cwd);
1214
+ const releaseBefore = release(harnessBefore, workspace && showFile(cwd, commit, workspace));
1215
+ const releaseAfter = release(harnessAfter, workspace && readWorking(cwd, workspace));
1216
+ const upgrade = releaseBefore === releaseAfter ? null : `${HARNESS_PACKAGE} ${releaseBefore ?? "(none)"} → ${releaseAfter ?? "(none)"}`;
1217
+ const configChanged = showFile(cwd, commit, lintConfig) !== readWorking(cwd, lintConfig);
1218
+ let changes = null;
1219
+ const admits = (rule) => {
1220
+ if (upgrade !== null) return {
1221
+ ok: true,
1222
+ why: `${upgrade} in this change`
1223
+ };
1224
+ if (!configChanged) return null;
1225
+ changes ??= ruleChanges(cwd, commit, lintConfig);
1226
+ return changes.turnsOn(rule) ? {
1227
+ ok: true,
1228
+ why: `${lintConfig} turns it on in this change (compared ${changes.how})`
1229
+ } : {
1230
+ ok: false,
1231
+ why: `${lintConfig} changed in this change but does not turn it on (compared ${changes.how})`
1232
+ };
1233
+ };
232
1234
  const adoption = harnessBefore === null && harnessAfter !== null ? `${HARNESS_PACKAGE} (none) → ${harnessAfter}` : null;
233
1235
  const baseFiles = listFilesAt(cwd, commit);
234
1236
  const newBaseline = (file, fix, command) => {
@@ -240,20 +1242,49 @@ function runRatchet(options) {
240
1242
  errors.push(`${file} is new in this change, but ${at} has no such file. A baseline may only be introduced by the adoption change, which adds ${HARNESS_PACKAGE} to package.json. ${why} Fix: ${fix} Never run \`${command}\` to get a change through.`);
241
1243
  return false;
242
1244
  };
1245
+ let moves = null;
1246
+ const movedFrom = (file, inBase, claimed, grows) => {
1247
+ if (baseFiles.has(file)) return null;
1248
+ moves ??= movesSince(cwd, commit);
1249
+ const from = moves.get(file);
1250
+ if (from === void 0) return null;
1251
+ const growth = inBase(from) ? grows(from) : null;
1252
+ const problem = !inBase(from) ? `${from} has no entry at ${at}` : existsExactly(cwd, from) ? `${from} still exists, so its debt stays there` : claimed.has(from) ? `the entry of ${from} already moved to another file` : growth !== null ? `it holds more than ${from} did at ${at} (${growth})` : null;
1253
+ if (problem !== null) return { reason: `moved from ${from} (${RENAMED}), but ${problem}` };
1254
+ claimed.add(from);
1255
+ return { from };
1256
+ };
243
1257
  const headText = readWorking(cwd, suppressionsPath);
244
1258
  const baseText = showFile(cwd, commit, suppressionsPath);
245
1259
  if (headText === null) notes.push(`${suppressionsPath}: not present; nothing to compare.`);
246
1260
  else {
247
1261
  const head = parseSuppressions(headText, suppressionsPath);
248
- for (const file of Object.keys(head)) if (!existsSync(path.join(cwd, file))) errors.push(`${suppressionsPath}: still lists ${file}, which no longer exists. Fix: run \`oxlint --prune-suppressions\` (or delete the entry) and commit the result. If the file moved, its debt moves with it only through an owner-reviewed baseline move; do not re-suppress it under the new path.`);
1262
+ for (const file of Object.keys(head)) if (!existsSync(path.join(cwd, file))) errors.push(`${suppressionsPath}: still lists ${file}, which no longer exists. Fix: run \`oxlint --prune-suppressions\` (or delete the entry) and commit the result. If the file was moved or renamed, run \`od-harness baseline move <old path> <new path>\` instead, so its debt moves with it; never re-suppress it under the new path.`);
249
1263
  const rejected = baseText === null && !newBaseline(suppressionsPath, `delete ${suppressionsPath}, run oxlint and fix what it reports.`, "oxlint --suppress-all");
250
- const added = Object.entries(head).filter(([file]) => !baseFiles.has(file) && existsSync(path.join(cwd, file))).map(([file, rules]) => {
251
- const counts = Object.entries(rules).filter(([, { count }]) => count > 0).map(([rule, { count }]) => `${rule} ${count}`);
252
- return counts.length > 0 ? `${file} (${counts.join(", ")})` : null;
253
- }).filter((entry) => entry !== null);
254
- if (added.length > 0 && !rejected) errors.push(`${suppressionsPath}: suppresses violations in ${added.length === 1 ? "a file" : `${added.length} files`} that ${at} does not have: ${added.slice(0, 10).join("; ")}${added.length > 10 ? "; …" : ""}. New files do not get a baseline; it only freezes debt that existed when a rule was adopted. Fix: restore the entries from ${options.base}, fix the violations oxlint reports in these files, then run \`oxlint --prune-suppressions\`. If a file was moved or renamed, its debt does not move with it until the owner-reviewed \`od-harness baseline move\` exists; fix the violations in the moved file instead.`);
255
- if (baseText !== null) {
256
- const base = parseSuppressions(baseText, `${suppressionsPath}@${options.base}`);
1264
+ const base = baseText === null ? null : parseSuppressions(baseText, `${suppressionsPath}@${options.base}`);
1265
+ const claimed = /* @__PURE__ */ new Set();
1266
+ const added = [];
1267
+ for (const [file, rules] of Object.entries(head)) {
1268
+ if (baseFiles.has(file) || !existsSync(path.join(cwd, file))) continue;
1269
+ const counts = Object.entries(rules).filter(([, { count }]) => count > 0);
1270
+ if (counts.length === 0) continue;
1271
+ const held = counts.map(([rule, { count }]) => `${rule} ${count}`).join(", ");
1272
+ const moved = base === null ? null : movedFrom(file, (from) => Object.hasOwn(base, from), claimed, (from) => {
1273
+ const over = counts.map(([rule, { count }]) => [
1274
+ rule,
1275
+ count,
1276
+ base[from]?.[rule]?.count ?? 0
1277
+ ]).filter(([, count, before]) => count > before).map(([rule, count, before]) => `${rule} ${before} → ${count}`);
1278
+ return over.length > 0 ? over.join(", ") : null;
1279
+ });
1280
+ if (moved !== null && "from" in moved) {
1281
+ notes.push(`${file}: baseline entry moved from ${moved.from} (${RENAMED}): ${held}`);
1282
+ continue;
1283
+ }
1284
+ added.push(`${file} (${held})${moved === null ? "" : `: ${moved.reason}`}`);
1285
+ }
1286
+ if (added.length > 0 && !rejected) errors.push(`${suppressionsPath}: suppresses violations in ${added.length === 1 ? "a file" : `${added.length} files`} that ${at} does not have: ${added.slice(0, 10).join("; ")}${added.length > 10 ? "; …" : ""}. New files do not get a baseline; it only freezes debt that existed when a rule was adopted. Fix: restore the entries from ${options.base}, fix the violations oxlint reports in these files, then run \`oxlint --prune-suppressions\`. A moved or renamed file keeps its debt (\`od-harness baseline move <old path> <new path>\`) only when its old path is gone, its entry does not grow, and ${seesRename(options.base)}.`);
1287
+ if (base !== null) {
257
1288
  const baseTotals = totals(base);
258
1289
  const headTotals = totals(head);
259
1290
  for (const [rule, headTotal] of [...headTotals].sort(([a], [b]) => a.localeCompare(b))) {
@@ -262,13 +1293,15 @@ function runRatchet(options) {
262
1293
  if (headTotal < baseTotal) notes.push(`${rule}: ${baseTotal} → ${headTotal}`);
263
1294
  continue;
264
1295
  }
265
- if (baseTotal === 0 && ownerChange !== null) {
266
- notes.push(`${rule}: enters the baseline with ${headTotal} (allowed: ${ownerChange} in this change, which the owner reviews).`);
1296
+ const admitted = baseTotal === 0 ? admits(rule) : null;
1297
+ if (admitted?.ok) {
1298
+ notes.push(`${rule}: enters the baseline with ${headTotal} (allowed: ${admitted.why}, which the owner reviews).`);
267
1299
  continue;
268
1300
  }
269
1301
  const grown = Object.entries(head).map(([file, rules]) => [file, (rules[rule]?.count ?? 0) - (base[file]?.[rule]?.count ?? 0)]).filter(([, delta]) => delta > 0).map(([file, delta]) => `${file} +${delta}`);
270
1302
  const where = grown.length > 0 ? ` (${grown.slice(0, 10).join(", ")}${grown.length > 10 ? ", …" : ""})` : "";
271
- errors.push(`${suppressionsPath}: ${rule} grew from ${baseTotal} to ${headTotal}${where}. The baseline only freezes debt that existed when the rule was adopted; new violations must be fixed, not suppressed. Fix: restore ${suppressionsPath} from ${options.base}, fix the violations oxlint reports, then run \`oxlint --prune-suppressions\` (it can only shrink the file). Never run \`oxlint --suppress-all\` to get a change through.`);
1303
+ const newRule = admitted === null ? "" : ` A new rule ID enters the baseline only in the change that turns the rule on or upgrades ${HARNESS_PACKAGE}; ${admitted.why}.`;
1304
+ errors.push(`${suppressionsPath}: ${rule} grew from ${baseTotal} to ${headTotal}${where}. The baseline only freezes debt that existed when the rule was adopted; new violations must be fixed, not suppressed.${newRule} Fix: restore ${suppressionsPath} from ${options.base}, fix the violations oxlint reports, then run \`oxlint --prune-suppressions\` (it can only shrink the file). Never run \`oxlint --suppress-all\` to get a change through.`);
272
1305
  }
273
1306
  }
274
1307
  }
@@ -277,16 +1310,26 @@ function runRatchet(options) {
277
1310
  if (headSize === null) notes.push(`${SIZE_BASELINE}: not present; nothing to compare.`);
278
1311
  else {
279
1312
  const head = readSizeBaseline(headSize, SIZE_BASELINE);
280
- for (const file of Object.keys(head.files)) if (!existsSync(path.join(cwd, file))) errors.push(`${SIZE_BASELINE}: still lists ${file}, which no longer exists. Fix: run \`od-harness size --update\` and commit the result.`);
1313
+ for (const file of Object.keys(head.files)) if (!existsSync(path.join(cwd, file))) errors.push(`${SIZE_BASELINE}: still lists ${file}, which no longer exists. Fix: run \`od-harness size --update\` and commit the result. If the file was moved or renamed, run \`od-harness baseline move <old path> <new path>\` instead.`);
281
1314
  if (baseSize === null) {
282
1315
  const accepted = newBaseline(SIZE_BASELINE, `delete ${SIZE_BASELINE} and split every file \`od-harness size\` reports.`, "od-harness size --init");
283
1316
  for (const [file, lines] of Object.entries(head.files)) if (accepted && !baseFiles.has(file) && existsSync(path.join(cwd, file))) errors.push(`${SIZE_BASELINE}: freezes ${file} (${lines} lines), which ${at} does not have. Only files that were over budget before adoption are frozen; a new file must be split instead. Fix: remove the entry and split the file.`);
284
1317
  } else {
285
1318
  const base = readSizeBaseline(baseSize, `${SIZE_BASELINE}@${options.base}`);
1319
+ const claimed = /* @__PURE__ */ new Set();
286
1320
  for (const [file, lines] of Object.entries(head.files)) {
287
- const before = base.files[file];
288
- if (before === void 0) errors.push(`${SIZE_BASELINE}: adds ${file} (${lines} lines). Only files that were over budget at adoption are frozen; a new or newly oversized file must be split instead. Fix: remove the entry and split the file.`);
289
- else if (lines > before) errors.push(`${SIZE_BASELINE}: raises ${file} from ${before} to ${lines} lines. Frozen files may only shrink. Fix: restore the entry to ${before} and move code out of the file.`);
1321
+ const before = Object.hasOwn(base.files, file) ? base.files[file] : void 0;
1322
+ if (before === void 0) {
1323
+ const moved = movedFrom(file, (from) => Object.hasOwn(base.files, from), claimed, (from) => {
1324
+ const frozen = base.files[from] ?? 0;
1325
+ return lines > frozen ? `${frozen} → ${lines} lines` : null;
1326
+ });
1327
+ if (moved !== null && "from" in moved) {
1328
+ notes.push(`${file}: frozen size moved from ${moved.from} (${RENAMED}): ${lines} lines`);
1329
+ continue;
1330
+ }
1331
+ errors.push(`${SIZE_BASELINE}: adds ${file} (${lines} lines)${moved === null ? "" : `, ${moved.reason}`}. Only files that were over budget at adoption are frozen; a new or newly oversized file must be split instead. Fix: remove the entry and split the file. A moved file keeps its frozen size (\`od-harness baseline move\`) only when its old path is gone, the size does not grow, and ${seesRename(options.base)}.`);
1332
+ } else if (lines > before) errors.push(`${SIZE_BASELINE}: raises ${file} from ${before} to ${lines} lines. Frozen files may only shrink. Fix: restore the entry to ${before} and move code out of the file.`);
290
1333
  else if (lines < before) notes.push(`${file}: size baseline ${before} → ${lines}`);
291
1334
  }
292
1335
  }
@@ -298,6 +1341,244 @@ function runRatchet(options) {
298
1341
  notes
299
1342
  };
300
1343
  }
1344
+ // src/cli/unused.ts
1345
+ const UNUSED_DOCS = "https://github.com/nexu-io/od-harness/blob/main/docs/unused.md";
1346
+ const DEPENDENCY_KEYS = [
1347
+ "dependencies",
1348
+ "devDependencies",
1349
+ "optionalPeerDependencies"
1350
+ ];
1351
+ /** The configuration files knip looks for (besides package.json#knip): its KNIP_CONFIG_LOCATIONS. */
1352
+ const KNIP_CONFIGS = [
1353
+ "knip.json",
1354
+ "knip.jsonc",
1355
+ ".knip.json",
1356
+ ".knip.jsonc",
1357
+ "knip.ts",
1358
+ "knip.js",
1359
+ "knip.config.ts",
1360
+ "knip.config.js"
1361
+ ];
1362
+ /** knip's CLI entry, resolved from od-harness's own dependencies. */
1363
+ function knipBin() {
1364
+ const require = createRequire(import.meta.url);
1365
+ let dir = path.dirname(require.resolve("knip"));
1366
+ for (;;) {
1367
+ const manifest = path.join(dir, "package.json");
1368
+ if (existsSync(manifest) && JSON.parse(readFileSync(manifest, "utf8")).name === "knip") return path.join(dir, "bin/knip.js");
1369
+ const parent = path.dirname(dir);
1370
+ if (parent === dir) throw new EnvironmentError("cannot locate the knip package");
1371
+ dir = parent;
1372
+ }
1373
+ }
1374
+ /** knip exited with an error: it could not load the project (its configuration, a plugin's file). */
1375
+ var KnipFailed = class extends Error {
1376
+ name = "KnipFailed";
1377
+ exit;
1378
+ output;
1379
+ constructor(exit, output) {
1380
+ super(`knip exited with ${exit}: ${output}`);
1381
+ this.exit = exit;
1382
+ this.output = output;
1383
+ }
1384
+ };
1385
+ function runKnip(dir, label) {
1386
+ const result = spawnSync(process.execPath, [
1387
+ knipBin(),
1388
+ "--reporter",
1389
+ "json",
1390
+ "--no-exit-code",
1391
+ "--no-progress",
1392
+ "--no-config-hints",
1393
+ "--include",
1394
+ "files,exports,dependencies"
1395
+ ], {
1396
+ cwd: dir,
1397
+ encoding: "utf8",
1398
+ maxBuffer: 268435456
1399
+ });
1400
+ if (result.error) throw result.error;
1401
+ const output = (result.stderr.trim() || result.stdout.trim()).slice(-2e3);
1402
+ if (result.status !== 0) throw new KnipFailed(String(result.status ?? result.signal), output);
1403
+ let rows;
1404
+ try {
1405
+ rows = JSON.parse(result.stdout).issues;
1406
+ if (!Array.isArray(rows)) throw new TypeError("no issues array");
1407
+ } catch (error) {
1408
+ throw new EnvironmentError(`knip printed no JSON report on ${label} (${String(error)}): ${output}`);
1409
+ }
1410
+ const findings = [];
1411
+ for (const row of rows) {
1412
+ for (const item of row.files ?? []) findings.push({
1413
+ type: "files",
1414
+ file: item.name,
1415
+ name: item.name
1416
+ });
1417
+ for (const item of row.exports ?? []) findings.push({
1418
+ type: "exports",
1419
+ file: row.file,
1420
+ name: item.name,
1421
+ ...line(item)
1422
+ });
1423
+ for (const field of DEPENDENCY_KEYS) for (const item of row[field] ?? []) findings.push({
1424
+ type: "dependencies",
1425
+ file: row.file,
1426
+ name: item.name,
1427
+ field,
1428
+ ...line(item)
1429
+ });
1430
+ }
1431
+ return findings;
1432
+ }
1433
+ function line(item) {
1434
+ return item.line === void 0 ? {} : { line: item.line };
1435
+ }
1436
+ /**
1437
+ * Both sides are analysed with the working tree's knip configuration, so only code changes count:
1438
+ * a configuration change (owner-reviewed) neither creates nor hides findings by itself.
1439
+ */
1440
+ function applyWorkingConfig(cwd, baseDir) {
1441
+ for (const file of KNIP_CONFIGS) {
1442
+ rmSync(path.join(baseDir, file), { force: true });
1443
+ if (existsSync(path.join(cwd, file))) copyFileSync(path.join(cwd, file), path.join(baseDir, file));
1444
+ }
1445
+ const read = (dir) => JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8"));
1446
+ const head = read(cwd);
1447
+ const base = read(baseDir);
1448
+ if (JSON.stringify(head.knip) === JSON.stringify(base.knip)) return;
1449
+ if (head.knip === void 0) delete base.knip;
1450
+ else base.knip = head.knip;
1451
+ writeFileSync(path.join(baseDir, "package.json"), JSON.stringify(base, null, 2));
1452
+ }
1453
+ const key = (finding) => JSON.stringify([
1454
+ finding.type,
1455
+ finding.file,
1456
+ finding.name
1457
+ ]);
1458
+ /** Findings of `head` that `base` does not have, counting duplicates (a multiset difference). */
1459
+ function addedFindings(base, head) {
1460
+ const remaining = /* @__PURE__ */ new Map();
1461
+ for (const finding of base) remaining.set(key(finding), (remaining.get(key(finding)) ?? 0) + 1);
1462
+ return head.filter((finding) => {
1463
+ const left = remaining.get(key(finding)) ?? 0;
1464
+ if (left === 0) return true;
1465
+ remaining.set(key(finding), left - 1);
1466
+ return false;
1467
+ });
1468
+ }
1469
+ /** Base findings under the paths their files have now (old path → new path for renamed files). */
1470
+ function followRenames(findings, renames) {
1471
+ const moved = new Map([...renames].map(([to, from]) => [from, to]));
1472
+ return findings.map((finding) => {
1473
+ const file = moved.get(finding.file) ?? finding.file;
1474
+ return {
1475
+ ...finding,
1476
+ file,
1477
+ name: finding.type === "files" ? file : finding.name
1478
+ };
1479
+ });
1480
+ }
1481
+ const GUIDANCE = {
1482
+ files: {
1483
+ what: (n) => (n === 1 ? "A new unused file" : `${n} new unused files`) + " (no entry point imports it):",
1484
+ fix: "Fix: import the file where it is needed, or delete it. Exemption: a file that runs on its own (a script, a worker, a config) is an entry point; add it to \"entry\" in the knip configuration, which the owner reviews."
1485
+ },
1486
+ exports: {
1487
+ what: (n) => (n === 1 ? "A new unused export" : `${n} new unused exports`) + " (not imported anywhere):",
1488
+ fix: "Fix: delete the export, or the code, if nothing needs it, or import it where it is meant to be used; do not export code for later. Exemption: an export used where knip cannot see it goes into the knip configuration (\"entry\", \"ignore\", \"ignoreExportsUsedInFile\"), which the owner reviews."
1489
+ },
1490
+ dependencies: {
1491
+ what: (n) => (n === 1 ? "A new unused dependency" : `${n} new unused dependencies`) + " (no analysed file imports it):",
1492
+ fix: "Fix: remove it from package.json and the lockfile, or import it where it is used. Exemption: a dependency used where knip cannot see it goes into \"ignoreDependencies\" in the knip configuration, which the owner reviews."
1493
+ }
1494
+ };
1495
+ function describe(finding) {
1496
+ const at = finding.line === void 0 ? finding.file : `${finding.file}:${finding.line}`;
1497
+ if (finding.type === "files") return finding.file;
1498
+ if (finding.type === "exports") return `${at} ${finding.name}`;
1499
+ return `${at} ${finding.field ?? "dependencies"} ${finding.name}`;
1500
+ }
1501
+ /**
1502
+ * knip on the base checkout. It first runs with the working tree's node_modules (what CI
1503
+ * installed for this change). When that fails, typically because the change removed a package
1504
+ * that a tool configuration of the base imports, the base's own dependencies are installed from
1505
+ * its lockfile in the checkout, and knip runs once more.
1506
+ */
1507
+ function analyseBase(checkout, at, install, notes) {
1508
+ const links = linkNodeModules(checkout);
1509
+ let first;
1510
+ try {
1511
+ return runKnip(checkout.dir, at);
1512
+ } catch (error) {
1513
+ if (!(error instanceof KnipFailed)) throw error;
1514
+ first = error;
1515
+ }
1516
+ unlinkNodeModules(links);
1517
+ const cannot = `knip cannot load the tool configuration of ${at} with this change's dependencies`;
1518
+ let ran;
1519
+ try {
1520
+ ran = install(checkout.dir, checkout.root);
1521
+ } catch (error) {
1522
+ throw new EnvironmentError(`${cannot} (knip said: ${first.output}), and the dependencies of ${at} could not be installed in its checkout: ${error.message}. Fix: if the change removed a package that a configuration file of ${at} imports, check that ${at} has a committed lockfile and that its dependencies install; otherwise fix the configuration knip names. See ${UNUSED_DOCS}`);
1523
+ }
1524
+ notes.push(`${cannot}; installed its own dependencies (\`${ran}\`) and analysed it again.`);
1525
+ try {
1526
+ return runKnip(checkout.dir, at);
1527
+ } catch (error) {
1528
+ if (!(error instanceof KnipFailed)) throw error;
1529
+ throw new EnvironmentError(`${cannot} (knip said: ${first.output}), nor with its own dependencies (\`${ran}\` in its checkout): knip said: ${error.output}. This change's knip configuration is applied to ${at} too, so a configuration ${at} cannot satisfy fails there. Fix: make the configuration change in a change of its own and merge it first, or fix the file knip names. See ${UNUSED_DOCS}`);
1530
+ }
1531
+ }
1532
+ function runUnused(options) {
1533
+ const { cwd } = options;
1534
+ if (!options.base) throw new UsageError("missing --base <ref>");
1535
+ const commit = resolveRef(cwd, options.base);
1536
+ const at = `${options.base} (${commit.slice(0, 10)})`;
1537
+ if (!existsSync(path.join(cwd, "package.json"))) throw new EnvironmentError(`no package.json in ${cwd}: run od-harness unused from the package root.`);
1538
+ const notes = [];
1539
+ let head;
1540
+ try {
1541
+ head = runKnip(cwd, "the working tree");
1542
+ } catch (error) {
1543
+ if (!(error instanceof KnipFailed)) throw error;
1544
+ throw new EnvironmentError(`knip failed on the working tree (exit ${error.exit}). It loads the repository's tool configurations (vite.config.ts, …), so install the dependencies first. knip said: ${error.output}`);
1545
+ }
1546
+ let base = [];
1547
+ const checkout = checkoutCommit(cwd, commit);
1548
+ try {
1549
+ if (existsSync(path.join(checkout.dir, "package.json"))) {
1550
+ applyWorkingConfig(cwd, checkout.dir);
1551
+ base = analyseBase(checkout, at, options.installBaseDependencies ?? installFromLockfile, notes);
1552
+ } else notes.push(`${at} has no package.json here; every finding counts as new.`);
1553
+ } finally {
1554
+ checkout.cleanup();
1555
+ }
1556
+ const added = addedFindings(followRenames(base, renamesSince(cwd, commit)), head);
1557
+ const summary = `${head.length} findings, ${added.length} new against ${at}`;
1558
+ const errors = [];
1559
+ for (const type of [
1560
+ "files",
1561
+ "exports",
1562
+ "dependencies"
1563
+ ]) {
1564
+ const ofType = added.filter((finding) => finding.type === type);
1565
+ if (ofType.length === 0) continue;
1566
+ errors.push(GUIDANCE[type].what(ofType.length), ...ofType.slice(0, 50).map((finding) => ` ${describe(finding)}`), ...ofType.length > 50 ? [` … and ${ofType.length - 50} more`] : [], GUIDANCE[type].fix);
1567
+ }
1568
+ const scripts = scriptPathspecs(SCRIPT_EXTENSIONS);
1569
+ const changed = changedLines(cwd, commit, scripts);
1570
+ const tagged = hidingTags(cwd, changed);
1571
+ if (tagged.length > 0) errors.push(`This change adds tags (@public, @beta, @alias) in comments that hide exports from knip, or exports under such a tag: ${tagged.slice(0, 10).join(", ")}${tagged.length > 10 ? ", …" : ""}. knip never reports an export tagged @public, @beta or @alias, so the tag takes it out of this gate without review. Fix: remove the tag; delete the export if nothing imports it, or import it where it is used. Exemption: an export used where knip cannot see it goes into the knip configuration ("entry", "ignore", "ignoreExportsUsedInFile"), which the owner reviews.`);
1572
+ const ignored = changedIgnoredFiles(cwd, commit, changed, scripts);
1573
+ if (ignored.length > 0) errors.push(`knip does not analyse these tracked files, because .gitignore excludes them, and this change adds or edits them or the ignore rules: ${ignored.slice(0, 10).join(", ")}${ignored.length > 10 ? ", …" : ""}. The gate cannot see whether they or their exports are used. Fix: change the .gitignore rule so it no longer matches them, or add a \`!path\` exception after it, so knip analyses them; a rule that excludes a parent directory (\`dir/\`) cannot be undone with \`!path\`, because git does not look inside an excluded directory: exclude its contents instead (\`dir/*\`), then add \`!dir/file\`. A file knip must not analyse is then excluded in the knip configuration ("ignore", or "entry" if it runs on its own), which the owner reviews. The knip configuration alone does not exempt a file that .gitignore excludes: this check reads only the ignore rules.`);
1574
+ if (errors.length > 0) errors.push(`Only findings this change adds fail; the ${head.length - added.length} that ${at} already has are tolerated, and a file git sees as renamed keeps its findings. See ${UNUSED_DOCS}`);
1575
+ return {
1576
+ ok: errors.length === 0,
1577
+ errors,
1578
+ notes,
1579
+ summary
1580
+ };
1581
+ }
301
1582
  // src/cli/main.ts
302
1583
  const HELP = `Usage: od-harness <command> [options]
303
1584
 
@@ -307,10 +1588,20 @@ Commands:
307
1588
  --update tighten the baseline after files shrank (never loosens)
308
1589
  --init create the first baseline (adoption only)
309
1590
  ratchet --base <ref> Fail if oxlint-suppressions.json or the size baseline grew
310
- relative to <ref>, lists files <ref> does not have, still
311
- lists deleted files, or appears outside the adoption change.
1591
+ relative to <ref>, lists files <ref> does not have (unless they
1592
+ moved there), still lists deleted files, or appears outside the
1593
+ adoption change.
312
1594
  --suppressions <path> default: oxlint-suppressions.json
313
1595
  --lint-config <path> default: .oxlintrc.json
1596
+ clones --base <ref> Fail on duplicated code (jscpd) that <ref> does not have.
1597
+ unused --base <ref> Fail on unused files, exports and dependencies (knip) that <ref>
1598
+ does not have.
1599
+ baseline move <from> <to> After moving files (git mv, staged), move their entries in both
1600
+ baselines to the new paths. Each new file must be a rename git
1601
+ sees (git diff -M30% -l0), as ratchet requires.
1602
+ --suppressions <path> default: oxlint-suppressions.json
1603
+ --base <ref> check the move against <ref>; default HEAD
1604
+ (a pre-check: ratchet decides)
314
1605
 
315
1606
  Run from the repository root.`;
316
1607
  function print(command, outcome, summary) {
@@ -323,54 +1614,106 @@ function print(command, outcome, summary) {
323
1614
  for (const error of outcome.errors) console.error(` ${error}`);
324
1615
  return 1;
325
1616
  }
1617
+ function baseOption(rest) {
1618
+ const { values } = parseArgs({
1619
+ args: rest,
1620
+ options: { base: { type: "string" } },
1621
+ strict: true
1622
+ });
1623
+ return values.base ?? "";
1624
+ }
1625
+ function run(command, rest, cwd) {
1626
+ if (command === "size") {
1627
+ const { values } = parseArgs({
1628
+ args: rest,
1629
+ options: {
1630
+ update: { type: "boolean" },
1631
+ init: { type: "boolean" }
1632
+ },
1633
+ strict: true
1634
+ });
1635
+ if (values.update && values.init) throw new UsageError("use either --update or --init");
1636
+ const result = runSize({
1637
+ cwd,
1638
+ update: values.update ?? false,
1639
+ init: values.init ?? false
1640
+ });
1641
+ return print("size", result, `${result.checked} files checked`);
1642
+ }
1643
+ if (command === "ratchet") {
1644
+ const { values } = parseArgs({
1645
+ args: rest,
1646
+ options: {
1647
+ base: { type: "string" },
1648
+ suppressions: { type: "string" },
1649
+ "lint-config": { type: "string" }
1650
+ },
1651
+ strict: true
1652
+ });
1653
+ const options = {
1654
+ cwd,
1655
+ base: values.base ?? ""
1656
+ };
1657
+ if (values.suppressions) options.suppressions = values.suppressions;
1658
+ if (values["lint-config"]) options.lintConfig = values["lint-config"];
1659
+ return print("ratchet", runRatchet(options), "");
1660
+ }
1661
+ if (command === "clones") {
1662
+ const result = runClones({
1663
+ cwd,
1664
+ base: baseOption(rest)
1665
+ });
1666
+ return print("clones", result, result.summary);
1667
+ }
1668
+ if (command === "unused") {
1669
+ const result = runUnused({
1670
+ cwd,
1671
+ base: baseOption(rest)
1672
+ });
1673
+ return print("unused", result, result.summary);
1674
+ }
1675
+ if (command === "baseline") {
1676
+ const [sub, ...args] = rest;
1677
+ if (sub !== "move") throw new UsageError(`unknown baseline command "${sub ?? ""}"`);
1678
+ const { values, positionals } = parseArgs({
1679
+ args,
1680
+ options: {
1681
+ suppressions: { type: "string" },
1682
+ base: { type: "string" }
1683
+ },
1684
+ allowPositionals: true,
1685
+ strict: true
1686
+ });
1687
+ const [from, to, ...extra] = positionals;
1688
+ if (from === void 0 || to === void 0 || extra.length > 0) throw new UsageError("baseline move takes exactly two paths: <from> <to>");
1689
+ const options = {
1690
+ cwd,
1691
+ from,
1692
+ to
1693
+ };
1694
+ if (values.suppressions) options.suppressions = values.suppressions;
1695
+ if (values.base) options.base = values.base;
1696
+ return print("baseline move", runBaselineMove(options), "");
1697
+ }
1698
+ if (command === void 0 || command === "help" || command === "--help" || command === "-h") {
1699
+ console.log(HELP);
1700
+ return command === void 0 ? 2 : 0;
1701
+ }
1702
+ throw new UsageError(`unknown command "${command}"`);
1703
+ }
326
1704
  function main(argv, cwd = process.cwd()) {
327
1705
  const [command, ...rest] = argv;
328
1706
  try {
329
- if (command === "size") {
330
- const { values } = parseArgs({
331
- args: rest,
332
- options: {
333
- update: { type: "boolean" },
334
- init: { type: "boolean" }
335
- },
336
- strict: true
337
- });
338
- if (values.update && values.init) throw new UsageError("use either --update or --init");
339
- const result = runSize({
340
- cwd,
341
- update: values.update ?? false,
342
- init: values.init ?? false
343
- });
344
- return print("size", result, `${result.checked} files checked`);
345
- }
346
- if (command === "ratchet") {
347
- const { values } = parseArgs({
348
- args: rest,
349
- options: {
350
- base: { type: "string" },
351
- suppressions: { type: "string" },
352
- "lint-config": { type: "string" }
353
- },
354
- strict: true
355
- });
356
- const options = {
357
- cwd,
358
- base: values.base ?? ""
359
- };
360
- if (values.suppressions) options.suppressions = values.suppressions;
361
- if (values["lint-config"]) options.lintConfig = values["lint-config"];
362
- return print("ratchet", runRatchet(options), "");
363
- }
364
- if (command === void 0 || command === "help" || command === "--help" || command === "-h") {
365
- console.log(HELP);
366
- return command === void 0 ? 2 : 0;
367
- }
368
- throw new UsageError(`unknown command "${command}"`);
1707
+ return run(command, rest, cwd);
369
1708
  } catch (error) {
370
1709
  if (error instanceof UsageError || error.code?.startsWith("ERR_PARSE_ARGS")) {
371
1710
  console.error(`od-harness: ${error.message}\n\n${HELP}`);
372
1711
  return 2;
373
1712
  }
1713
+ if (error instanceof EnvironmentError) {
1714
+ console.error(`od-harness ${command}: ${error.message}`);
1715
+ return 2;
1716
+ }
374
1717
  console.error(`od-harness: ${error.stack ?? String(error)}`);
375
1718
  return 2;
376
1719
  }