@crown3/repo-doctor 0.0.0 → 0.2.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.
Files changed (86) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +40 -1
  3. package/UPSTREAM.md +20 -0
  4. package/bin/repo-doctor.mjs +9 -0
  5. package/dist/check-comments.d.ts +3 -0
  6. package/dist/check-docs.d.ts +16 -0
  7. package/dist/check-runs.d.ts +23 -0
  8. package/dist/cli.d.ts +16 -0
  9. package/dist/cli.js +1743 -0
  10. package/dist/comments.d.ts +17 -0
  11. package/dist/config.d.ts +152 -0
  12. package/dist/file-kinds.d.ts +8 -0
  13. package/dist/files.d.ts +8 -0
  14. package/dist/format-sh.d.ts +6 -0
  15. package/dist/g.js +360 -0
  16. package/dist/git.d.ts +17 -0
  17. package/dist/go-comments.d.ts +7 -0
  18. package/dist/index.d.ts +4 -0
  19. package/dist/index.js +16 -0
  20. package/dist/python.d.ts +18 -0
  21. package/dist/quality.d.ts +39 -0
  22. package/dist/review-comments.d.ts +14 -0
  23. package/dist/rules.d.ts +8 -0
  24. package/dist/run-if-main.d.ts +2 -0
  25. package/dist/scrub-git-hook-env.d.ts +1 -0
  26. package/dist/scrub-git-hook-env.js +2 -0
  27. package/dist/settings.d.ts +19 -0
  28. package/dist/shard.d.ts +10 -0
  29. package/dist/sites.d.ts +9 -0
  30. package/dist/units.d.ts +30 -0
  31. package/package.json +61 -3
  32. package/python/crapper/LICENSE +7 -0
  33. package/python/crapper/README.md +93 -0
  34. package/python/crapper/pyproject.toml +28 -0
  35. package/python/crapper/src/crapper/__init__.py +3 -0
  36. package/python/crapper/src/crapper/__main__.py +4 -0
  37. package/python/crapper/src/crapper/analyze.py +56 -0
  38. package/python/crapper/src/crapper/cli.py +334 -0
  39. package/python/crapper/src/crapper/coverage.py +596 -0
  40. package/python/crapper/src/crapper/crap.py +47 -0
  41. package/python/crapper/src/crapper/discover.py +116 -0
  42. package/python/crapper/src/crapper/languages/__init__.py +27 -0
  43. package/python/crapper/src/crapper/languages/clojure.py +451 -0
  44. package/python/crapper/src/crapper/languages/golang.py +143 -0
  45. package/python/crapper/src/crapper/languages/java.py +117 -0
  46. package/python/crapper/src/crapper/languages/python.py +133 -0
  47. package/python/crapper/src/crapper/languages/rust.py +190 -0
  48. package/python/crapper/src/crapper/languages/treesitter.py +82 -0
  49. package/python/crapper/src/crapper/languages/typescript.py +399 -0
  50. package/python/crapper/src/crapper/metrics.py +59 -0
  51. package/python/crapper/src/crapper/model.py +32 -0
  52. package/python/crapper/src/crapper/report.py +42 -0
  53. package/python/crapper/src/crapper/runners.py +596 -0
  54. package/python/dryer/LICENSE +7 -0
  55. package/python/dryer/README.md +115 -0
  56. package/python/dryer/pyproject.toml +29 -0
  57. package/python/dryer/src/dryer/__init__.py +3 -0
  58. package/python/dryer/src/dryer/__main__.py +4 -0
  59. package/python/dryer/src/dryer/astnorm.py +391 -0
  60. package/python/dryer/src/dryer/cli.py +324 -0
  61. package/python/dryer/src/dryer/clojure_read.py +519 -0
  62. package/python/dryer/src/dryer/discover.py +121 -0
  63. package/python/dryer/src/dryer/extract.py +204 -0
  64. package/python/dryer/src/dryer/model.py +34 -0
  65. package/python/dryer/src/dryer/report.py +74 -0
  66. package/python/dryer/src/dryer/scan.py +91 -0
  67. package/python/dryer/src/dryer/shape.py +108 -0
  68. package/python/dryer/src/dryer/treesitter.py +47 -0
  69. package/python/mutator/LICENSE +7 -0
  70. package/python/mutator/README.md +123 -0
  71. package/python/mutator/pyproject.toml +28 -0
  72. package/python/mutator/src/mutator/__init__.py +3 -0
  73. package/python/mutator/src/mutator/__main__.py +4 -0
  74. package/python/mutator/src/mutator/cli.py +591 -0
  75. package/python/mutator/src/mutator/coverage.py +233 -0
  76. package/python/mutator/src/mutator/crapper_link.py +36 -0
  77. package/python/mutator/src/mutator/edn.py +239 -0
  78. package/python/mutator/src/mutator/engine.py +356 -0
  79. package/python/mutator/src/mutator/functions.py +214 -0
  80. package/python/mutator/src/mutator/metrics.py +344 -0
  81. package/python/mutator/src/mutator/model.py +83 -0
  82. package/python/mutator/src/mutator/report.py +74 -0
  83. package/python/mutator/src/mutator/runner.py +248 -0
  84. package/python/mutator/src/mutator/sites.py +376 -0
  85. package/python/mutator/src/mutator/workers.py +446 -0
  86. package/python/requirements.lock +12 -0
package/dist/cli.js ADDED
@@ -0,0 +1,1743 @@
1
+ import node_path from "node:path";
2
+ import { createHash } from "node:crypto";
3
+ import { spawn, spawnSync } from "node:child_process";
4
+ import node_os from "node:os";
5
+ import { fileURLToPath, pathToFileURL } from "node:url";
6
+ import { parseSync } from "oxc-parser";
7
+ import { parse as external_yaml_parse } from "yaml";
8
+ import { format as shfmt_format } from "@wasm-fmt/shfmt";
9
+ import { ownChanges, repoRoot, repoFiles, matchesAny, listFiles, changedLines, withoutGitHookEnv, isShell, git, check as config_check, ConfigError } from "./g.js";
10
+ import * as __rspack_external_node_fs_1b05aee1 from "node:fs";
11
+ const SCRIPT_EXTENSIONS = [
12
+ '.ts',
13
+ '.tsx',
14
+ '.mts',
15
+ '.cts',
16
+ '.js',
17
+ '.jsx',
18
+ '.mjs',
19
+ '.cjs'
20
+ ];
21
+ const LANGUAGES = [
22
+ {
23
+ extensions: SCRIPT_EXTENSIONS,
24
+ tests: /\.(test|spec)\.[cm]?[jt]sx?$/,
25
+ skip: /\.d\.[cm]?ts$/
26
+ },
27
+ {
28
+ extensions: [
29
+ '.py'
30
+ ],
31
+ tests: /(^|\/)(test_[^/]*|[^/]*_test|conftest)\.py$/
32
+ },
33
+ {
34
+ extensions: [
35
+ '.go'
36
+ ],
37
+ tests: /_test\.go$/
38
+ },
39
+ {
40
+ extensions: [
41
+ '.rs'
42
+ ]
43
+ },
44
+ {
45
+ extensions: [
46
+ '.java'
47
+ ]
48
+ },
49
+ {
50
+ extensions: [
51
+ '.clj',
52
+ '.cljc',
53
+ '.cljs',
54
+ '.cljd',
55
+ '.bb'
56
+ ]
57
+ }
58
+ ];
59
+ const TEST_DIRS = /(^|\/)(tests?|__tests__|benches|e2e)\//;
60
+ const FIXTURE_DIRS = /(^|\/)(fixtures|testdata)\//;
61
+ const OUTPUT_DIRS = /(^|\/)(node_modules|dist|build|target|coverage|vendor|\.venv|venv)\//;
62
+ const RUNNER_FILES = /(^|\/)(rstest|vitest|jest|playwright)[.-][^/]*$/;
63
+ const CONFIG_FILES = /(^|\/)[^/]+\.config\.[cm]?[jt]s$/;
64
+ const isTest = (file, lang)=>TEST_DIRS.test(file) || RUNNER_FILES.test(file) || !!lang.tests?.test(file);
65
+ const ignored = (file, lang)=>!!lang.skip?.test(file) || OUTPUT_DIRS.test(file) || FIXTURE_DIRS.test(file);
66
+ function file_kinds_kind(file) {
67
+ const lang = LANGUAGES.find((l)=>l.extensions.includes(node_path.extname(file)));
68
+ if (!lang || ignored(file, lang)) return;
69
+ if (isTest(file, lang)) return 'test';
70
+ return CONFIG_FILES.test(file) ? void 0 : 'source';
71
+ }
72
+ const inside = (dir, file)=>'.' === dir || file.startsWith(`${dir}/`);
73
+ function file_kinds_owner(units, file) {
74
+ let best;
75
+ for (const unit of units)if (inside(unit.dir, file) && (!best || unit.dir.length > best.dir.length)) best = unit;
76
+ return best;
77
+ }
78
+ const excluded = (unit, file)=>matchesAny(file, unit.exclude);
79
+ const file_kinds_local = (unit, file)=>'.' === unit.dir ? file : file.slice(unit.dir.length + 1);
80
+ function selects(units, unit, file) {
81
+ if (file_kinds_owner(units, file) !== unit || excluded(unit, file)) return false;
82
+ return unit.paths.some((p)=>inside(p, file_kinds_local(unit, file)));
83
+ }
84
+ const isScript = (file)=>SCRIPT_EXTENSIONS.includes(node_path.extname(file));
85
+ const PYTHON = node_path.join(node_path.dirname(fileURLToPath(import.meta.url)), '..', 'python');
86
+ const LOCK = node_path.join(PYTHON, 'requirements.lock');
87
+ const TOOLS = [
88
+ 'crapper',
89
+ 'dryer',
90
+ 'mutator'
91
+ ];
92
+ const PARSERS = [
93
+ "typescript",
94
+ 'tsx',
95
+ "javascript",
96
+ 'python',
97
+ 'go',
98
+ 'rust'
99
+ ];
100
+ function home(env) {
101
+ if (env.REPO_DOCTOR_HOME) return env.REPO_DOCTOR_HOME;
102
+ return node_path.join(env.XDG_CACHE_HOME || node_path.join(node_os.homedir(), '.cache'), 'repo-doctor');
103
+ }
104
+ function envDir(base) {
105
+ const hash = createHash('sha256').update(__rspack_external_node_fs_1b05aee1.readFileSync(LOCK)).digest('hex').slice(0, 12);
106
+ return node_path.join(base, `env-${hash}`);
107
+ }
108
+ const onPath = (name, env)=>0 === spawnSync('sh', [
109
+ '-c',
110
+ `command -v ${name}`
111
+ ], {
112
+ env
113
+ }).status;
114
+ function python_run(command, args, env) {
115
+ const { status } = spawnSync(command, args, {
116
+ env,
117
+ stdio: 'inherit'
118
+ });
119
+ if (0 !== status) throw new Error(`${command} ${args.join(' ')} failed (exit ${status})`);
120
+ }
121
+ const PYTHON_OK = 'import sys; sys.exit(sys.version_info < (3, 11))';
122
+ const pythonIn = (dir)=>node_path.join(dir, 'bin', 'python');
123
+ function recipe(dir, env) {
124
+ const python = pythonIn(dir);
125
+ if (onPath('uv', env)) return [
126
+ [
127
+ 'uv',
128
+ [
129
+ 'venv',
130
+ '--quiet',
131
+ '--python',
132
+ '>=3.11',
133
+ dir
134
+ ]
135
+ ],
136
+ [
137
+ 'uv',
138
+ [
139
+ 'pip',
140
+ 'install',
141
+ '--quiet',
142
+ '--python',
143
+ python,
144
+ '-r',
145
+ LOCK
146
+ ]
147
+ ]
148
+ ];
149
+ if (0 !== spawnSync('python3', [
150
+ '-c',
151
+ PYTHON_OK
152
+ ], {
153
+ env
154
+ }).status) throw new Error('repo-doctor needs uv, or python3 >= 3.11 on PATH');
155
+ const pip = [
156
+ '-m',
157
+ 'pip',
158
+ 'install',
159
+ '-q',
160
+ '--disable-pip-version-check'
161
+ ];
162
+ return [
163
+ [
164
+ 'python3',
165
+ [
166
+ '-m',
167
+ 'venv',
168
+ dir
169
+ ]
170
+ ],
171
+ [
172
+ python,
173
+ [
174
+ ...pip,
175
+ '-r',
176
+ LOCK
177
+ ]
178
+ ]
179
+ ];
180
+ }
181
+ const isReady = (dir)=>__rspack_external_node_fs_1b05aee1.existsSync(pythonIn(dir));
182
+ const remove = (dir)=>__rspack_external_node_fs_1b05aee1.rmSync(dir, {
183
+ recursive: true,
184
+ force: true
185
+ });
186
+ function buildBeside(dir, env) {
187
+ const built = `${dir}.tmp-${process.pid}`;
188
+ remove(built);
189
+ __rspack_external_node_fs_1b05aee1.mkdirSync(node_path.dirname(dir), {
190
+ recursive: true
191
+ });
192
+ for (const [command, args] of recipe(built, env))python_run(command, args, env);
193
+ return built;
194
+ }
195
+ function replaceBroken(dir, built) {
196
+ remove(dir);
197
+ __rspack_external_node_fs_1b05aee1.renameSync(built, dir);
198
+ }
199
+ function moveIntoPlace(built, dir) {
200
+ if (isReady(dir)) remove(built);
201
+ else replaceBroken(dir, built);
202
+ }
203
+ function ensureEnv(env) {
204
+ const dir = envDir(home(env));
205
+ if (!isReady(dir)) moveIntoPlace(buildBeside(dir, env), dir);
206
+ return pythonIn(dir);
207
+ }
208
+ function toolEnv(env) {
209
+ return {
210
+ ...withoutGitHookEnv(env),
211
+ PYTHONPATH: TOOLS.map((t)=>node_path.join(PYTHON, t, 'src')).join(node_path.delimiter),
212
+ TREE_SITTER_LANGUAGE_PACK_CACHE_DIR: env.TREE_SITTER_LANGUAGE_PACK_CACHE_DIR || node_path.join(home(env), 'parsers')
213
+ };
214
+ }
215
+ function runTool(tool, args, { cwd, env, log }) {
216
+ const python = ensureEnv(env);
217
+ return new Promise((resolve, reject)=>{
218
+ const child = spawn(python, [
219
+ '-m',
220
+ tool,
221
+ ...args
222
+ ], {
223
+ cwd,
224
+ env: toolEnv(env),
225
+ stdio: [
226
+ 'inherit',
227
+ 'pipe',
228
+ 'pipe'
229
+ ]
230
+ });
231
+ const chunks = [];
232
+ const sink = log ? __rspack_external_node_fs_1b05aee1.createWriteStream(log) : void 0;
233
+ const tee = (out)=>(chunk)=>{
234
+ chunks.push(chunk);
235
+ sink?.write(chunk);
236
+ out.write(chunk);
237
+ };
238
+ child.stdout.on('data', tee(process.stdout));
239
+ child.stderr.on('data', tee(process.stderr));
240
+ child.on('error', reject);
241
+ child.on('close', (code)=>{
242
+ const done = ()=>resolve({
243
+ code: code ?? 1,
244
+ output: Buffer.concat(chunks).toString()
245
+ });
246
+ if (sink) sink.end(done);
247
+ else done();
248
+ });
249
+ });
250
+ }
251
+ async function setup(env) {
252
+ const python = ensureEnv(env);
253
+ const code = `from tree_sitter_language_pack import download; download(${JSON.stringify(PARSERS)})`;
254
+ const { status } = spawnSync(python, [
255
+ '-c',
256
+ code
257
+ ], {
258
+ env: toolEnv(env),
259
+ stdio: 'inherit'
260
+ });
261
+ if (0 !== status) throw new Error('parser download failed');
262
+ return python;
263
+ }
264
+ function parseShard(text) {
265
+ const m = /^([1-9]\d*)\/([1-9]\d*)$/.exec(text);
266
+ const index = Number(m?.[1]);
267
+ const count = Number(m?.[2]);
268
+ if (!m || index > count) throw new Error(`--shard must be i/n with 1 <= i <= n, got ${text}`);
269
+ return {
270
+ index,
271
+ count
272
+ };
273
+ }
274
+ function deal(entries, { index, count }) {
275
+ const load = Array.from({
276
+ length: count
277
+ }, ()=>0);
278
+ const mine = [];
279
+ const ranked = [
280
+ ...entries
281
+ ].sort((a, b)=>b.cost - a.cost || (a.file < b.file ? -1 : 1));
282
+ for (const { file, cost } of ranked){
283
+ const lightest = load.indexOf(Math.min(...load));
284
+ load[lightest] += cost;
285
+ if (lightest === index - 1) mine.push(file);
286
+ }
287
+ return mine;
288
+ }
289
+ const SITE = /^(KILLED|SURVIVED|UNCOVERED) +(.+):(\d+) (.*)$/gm;
290
+ const sitesIn = (output)=>[
291
+ ...output.matchAll(SITE)
292
+ ].map((m)=>({
293
+ status: m[1] ?? '',
294
+ file: m[2] ?? '',
295
+ line: Number(m[3]),
296
+ text: m[4] ?? ''
297
+ }));
298
+ const sites_count = (sites, status)=>sites.filter((s)=>s.status === status).length;
299
+ function sites_summary(name, sites) {
300
+ const killed = sites_count(sites, 'KILLED');
301
+ const survived = sites_count(sites, 'SURVIVED');
302
+ const tested = killed + survived;
303
+ const score = tested ? ` (${(100 * killed / tested).toFixed(1)}%)` : '';
304
+ return `${name}: ${killed} killed, ${survived} survived, ${sites_count(sites, 'UNCOVERED')} uncovered${score}`;
305
+ }
306
+ const sites_open = (sites)=>sites.filter((s)=>'KILLED' !== s.status).map((s)=>` ${s.status.padEnd(9)} ${s.file}:${s.line} ${s.text}`);
307
+ function splitByChange(dir, sites, touched) {
308
+ const changed = (s)=>touched(node_path.posix.join(dir, s.file), s.line);
309
+ const groups = [
310
+ [
311
+ 'changed lines',
312
+ sites.filter(changed)
313
+ ],
314
+ [
315
+ 'older lines',
316
+ sites.filter((s)=>!changed(s))
317
+ ]
318
+ ];
319
+ return groups.flatMap(([name, group])=>[
320
+ `mutator: ${dir} ${sites_summary(name, group)}`,
321
+ ...sites_open(group)
322
+ ]);
323
+ }
324
+ const quality_checked = (ctx)=>ctx.units.filter((u)=>!u.dropped);
325
+ const sourcesOf = (ctx, unit, files)=>files.filter((f)=>'source' === file_kinds_kind(f) && selects(ctx.units, unit, f));
326
+ const testsOf = (ctx, unit, files)=>files.filter((f)=>'test' === file_kinds_kind(f) && !unit.dropped && file_kinds_owner(ctx.units, f) === unit && !excluded(unit, f));
327
+ function noSources(ctx, tool, what) {
328
+ console.error(`${tool}: ${what} has no ${ctx.changed ? 'changed ' : ''}sources`);
329
+ return ctx.changed ? 0 : 1;
330
+ }
331
+ const TOOL_DEFAULT = {
332
+ kind: 'tool default'
333
+ };
334
+ const commandOrDefault = (command)=>command ? {
335
+ kind: 'run',
336
+ command
337
+ } : TOOL_DEFAULT;
338
+ function commandFor(choice, files) {
339
+ if ('command' === choice.kind) return commandOrDefault(choice.command);
340
+ if ('tool default' === choice.kind || !files.some(isScript)) return TOOL_DEFAULT;
341
+ if (void 0 === choice.command) return {
342
+ kind: "missing npm script"
343
+ };
344
+ return commandOrDefault(choice.command);
345
+ }
346
+ const flag = (name, command)=>'run' === command.kind ? [
347
+ name,
348
+ command.command
349
+ ] : [];
350
+ const coverageArgs = (unit, files)=>flag('--coverage-command', commandFor(unit.coverage, files));
351
+ async function crap(ctx) {
352
+ const files = ctx.list(ctx.changed);
353
+ let status = 0;
354
+ for (const unit of quality_checked(ctx)){
355
+ const mine = sourcesOf(ctx, unit, files);
356
+ if (!mine.length) {
357
+ status ||= noSources(ctx, 'crapper', unit.dir);
358
+ continue;
359
+ }
360
+ const threshold = String(unit.crap.threshold);
361
+ const args = [
362
+ '--root',
363
+ unit.dir,
364
+ '--threshold',
365
+ threshold,
366
+ ...coverageArgs(unit, mine),
367
+ ...ctx.extra
368
+ ];
369
+ const { code } = await runTool('crapper', [
370
+ ...args,
371
+ ...mine.map((f)=>file_kinds_local(unit, f))
372
+ ], {
373
+ cwd: ctx.root,
374
+ env: ctx.env
375
+ });
376
+ if (0 !== code) status = 1;
377
+ }
378
+ return status;
379
+ }
380
+ function dryFiles(ctx, files) {
381
+ const withTests = ctx.dry.includeTests;
382
+ return quality_checked(ctx).flatMap((unit)=>[
383
+ ...sourcesOf(ctx, unit, files),
384
+ ...withTests ? testsOf(ctx, unit, files) : []
385
+ ]);
386
+ }
387
+ function filesNamedIn(candidate) {
388
+ const files = [
389
+ ...candidate.matchAll(/:file "((?:[^"\\]|\\.)*)"/g)
390
+ ].map((m)=>m[1] ?? '');
391
+ return files.length ? files : 'unknown';
392
+ }
393
+ const dryCandidates = (edn)=>edn.split(/^ \{:score /m).slice(1).map(filesNamedIn);
394
+ function duplicates(metrics, output) {
395
+ if (!__rspack_external_node_fs_1b05aee1.existsSync(metrics)) return output.includes('DUPLICATE') ? [
396
+ 'unknown'
397
+ ] : [];
398
+ return dryCandidates(__rspack_external_node_fs_1b05aee1.readFileSync(metrics, 'utf8'));
399
+ }
400
+ function involving(found, focus) {
401
+ if (!focus) return found;
402
+ const hits = found.filter((files)=>'unknown' === files || files.some((f)=>focus.has(f)));
403
+ if (hits.length) console.error(`dryer: ${hits.length} duplicate(s) involve changed files`);
404
+ return hits;
405
+ }
406
+ async function quality_dry(ctx) {
407
+ const focus = ctx.changed ? new Set(dryFiles(ctx, ctx.list(true))) : void 0;
408
+ const picked = dryFiles(ctx, ctx.list(false));
409
+ if (!picked.length || focus?.size === 0) return noSources(ctx, 'dryer', 'the repo');
410
+ const threshold = String(ctx.dry.threshold);
411
+ const metrics = node_path.join(ctx.root, '.metrics', 'dry.edn');
412
+ __rspack_external_node_fs_1b05aee1.rmSync(metrics, {
413
+ force: true
414
+ });
415
+ const { code, output } = await runTool('dryer', [
416
+ '--root',
417
+ '.',
418
+ '--threshold',
419
+ threshold,
420
+ ...ctx.extra,
421
+ ...picked
422
+ ], {
423
+ cwd: ctx.root,
424
+ env: ctx.env
425
+ });
426
+ if (0 !== code) return 1;
427
+ return involving(duplicates(metrics, output), focus).length ? 1 : 0;
428
+ }
429
+ function mutationScore(output) {
430
+ const last = [
431
+ ...output.matchAll(/^Total .* (\d+)\.\d+%$/gm)
432
+ ].at(-1);
433
+ return last ? Number(last[1]) : void 0;
434
+ }
435
+ const MUTATOR_PASSED = 0;
436
+ const MUTANTS_SURVIVED = 3;
437
+ function judge(code, output, minScore) {
438
+ if (code !== MUTANTS_SURVIVED) return {
439
+ ok: code === MUTATOR_PASSED
440
+ };
441
+ const score = mutationScore(output);
442
+ if (void 0 === minScore || 0 === score) return {
443
+ ok: false,
444
+ score
445
+ };
446
+ return {
447
+ ok: void 0 !== score && score >= minScore,
448
+ score
449
+ };
450
+ }
451
+ const lineCount = (file)=>__rspack_external_node_fs_1b05aee1.readFileSync(file, 'utf8').split('\n').length - 1;
452
+ const totalLines = (ctx, files)=>files.reduce((n, f)=>n + lineCount(node_path.join(ctx.root, f)), 0);
453
+ function inShard(ctx, shard, selected) {
454
+ const listed = ctx.list(false);
455
+ const sized = ctx.units.flatMap((unit)=>{
456
+ const weight = Math.max(1, totalLines(ctx, testsOf(ctx, unit, listed)));
457
+ return sourcesOf(ctx, unit, listed).map((file)=>({
458
+ file,
459
+ cost: lineCount(node_path.join(ctx.root, file)) * weight
460
+ }));
461
+ });
462
+ const keep = new Set(selected);
463
+ return deal(sized, shard).filter((f)=>keep.has(f));
464
+ }
465
+ function testsDigest(ctx, unit) {
466
+ const hash = createHash('sha256');
467
+ for (const file of testsOf(ctx, unit, ctx.list(false)).sort())hash.update(`${file}\0`).update(__rspack_external_node_fs_1b05aee1.readFileSync(node_path.join(ctx.root, file))).update('\0');
468
+ return `${hash.digest('hex')}\n`;
469
+ }
470
+ function freshSnapshot(ctx, unit) {
471
+ const dir = node_path.join(ctx.root, unit.dir, '.metrics', 'mutate');
472
+ const digest = testsDigest(ctx, unit);
473
+ const snapshots = ()=>__rspack_external_node_fs_1b05aee1.existsSync(dir) ? __rspack_external_node_fs_1b05aee1.readdirSync(dir).filter((f)=>f.endsWith('.edn')) : [];
474
+ const stamp = (edn)=>node_path.join(dir, `${edn}.tests`);
475
+ const stale = snapshots().filter((edn)=>!__rspack_external_node_fs_1b05aee1.existsSync(stamp(edn)) || __rspack_external_node_fs_1b05aee1.readFileSync(stamp(edn), 'utf8') !== digest);
476
+ for (const edn of stale){
477
+ __rspack_external_node_fs_1b05aee1.rmSync(node_path.join(dir, edn));
478
+ __rspack_external_node_fs_1b05aee1.rmSync(stamp(edn), {
479
+ force: true
480
+ });
481
+ }
482
+ if (stale.length) console.log(`mutator: ${unit.dir} tests changed, dropped ${stale.join(' ')}`);
483
+ return ()=>{
484
+ for (const edn of snapshots())if (!__rspack_external_node_fs_1b05aee1.existsSync(stamp(edn))) __rspack_external_node_fs_1b05aee1.writeFileSync(stamp(edn), digest);
485
+ };
486
+ }
487
+ function scoreLine(dir, verdict, minScore) {
488
+ if (0 === verdict.score) return `mutator: ${dir} killed no mutant; check that its test command fails when a source breaks`;
489
+ if (void 0 === verdict.score || void 0 === minScore) return;
490
+ return `mutator: ${dir} scores ${verdict.score}% (${verdict.ok ? '>=' : 'below'} ${minScore}%)`;
491
+ }
492
+ async function mutateUnit(ctx, unit, files) {
493
+ const test = commandFor(unit.test, files);
494
+ if ("missing npm script" === test.kind) {
495
+ const skipped = files.filter(isScript);
496
+ console.error(`mutator: ${unit.dir} has no test script, skipped ${skipped.join(' ')}`);
497
+ files = files.filter((f)=>!isScript(f));
498
+ if (!files.length) return 0;
499
+ }
500
+ const target = node_path.join(ctx.root, unit.dir, 'target');
501
+ __rspack_external_node_fs_1b05aee1.mkdirSync(target, {
502
+ recursive: true
503
+ });
504
+ const args = [
505
+ '--root',
506
+ unit.dir,
507
+ ...flag('--test-command', test),
508
+ ...coverageArgs(unit, files),
509
+ ...ctx.extra
510
+ ];
511
+ const stamp = freshSnapshot(ctx, unit);
512
+ const { code, output } = await runTool('mutator', [
513
+ ...args,
514
+ ...files.map((f)=>file_kinds_local(unit, f))
515
+ ], {
516
+ cwd: ctx.root,
517
+ env: ctx.env,
518
+ log: node_path.join(target, 'mutator.log')
519
+ });
520
+ stamp();
521
+ const minScore = ctx.minScore ?? unit.mutate.minScore;
522
+ const verdict = judge(code, output, minScore);
523
+ const say = console[verdict.ok ? 'log' : 'error'];
524
+ const summary = scoreLine(unit.dir, verdict, minScore);
525
+ if (summary) say(summary);
526
+ const sites = ctx.changed ? sitesIn(output) : [];
527
+ if (sites.length) say(splitByChange(unit.dir, sites, ctx.touched()).join('\n'));
528
+ return verdict.ok ? 0 : 1;
529
+ }
530
+ async function mutate(ctx) {
531
+ const files = ctx.list(ctx.changed);
532
+ const selected = ctx.units.flatMap((u)=>sourcesOf(ctx, u, files));
533
+ const shard = ctx.shard;
534
+ let status = 0;
535
+ if (shard && !selected.length) status = noSources(ctx, 'mutator', 'every unit');
536
+ const picked = shard ? inShard(ctx, shard, selected) : selected;
537
+ for (const unit of quality_checked(ctx)){
538
+ const mine = picked.filter((f)=>file_kinds_owner(ctx.units, f) === unit);
539
+ if (!mine.length) {
540
+ if (!shard) status ||= noSources(ctx, 'mutator', unit.dir);
541
+ continue;
542
+ }
543
+ if (shard) console.log(`mutator: shard ${shard.index}/${shard.count} takes ${unit.dir}: ${mine.join(' ')}`);
544
+ if (await mutateUnit(ctx, unit, mine) !== 0) status = 1;
545
+ }
546
+ return status;
547
+ }
548
+ function ratio(ctx) {
549
+ const files = ctx.list(false);
550
+ const total = (list)=>totalLines(ctx, list);
551
+ const rows = quality_checked(ctx).map((unit)=>{
552
+ const code = total(sourcesOf(ctx, unit, files));
553
+ const tests = total(testsOf(ctx, unit, files));
554
+ return `| ${unit.dir} | ${code} | ${tests} | ${code > 0 ? (tests / code).toFixed(1) : '-'} |`;
555
+ });
556
+ const report = [
557
+ '| Unit | Code lines | Test lines | Tests per code line |',
558
+ '| --- | --- | --- | --- |',
559
+ ...rows
560
+ ].join('\n');
561
+ console.log(report);
562
+ if (ctx.env.GITHUB_STEP_SUMMARY) __rspack_external_node_fs_1b05aee1.appendFileSync(ctx.env.GITHUB_STEP_SUMMARY, `### Test size\n\n${report}\n`);
563
+ return 0;
564
+ }
565
+ async function prepare(env) {
566
+ const python = await setup(env);
567
+ console.log(`repo-doctor: environment ready at ${node_path.dirname(node_path.dirname(python))}`);
568
+ return 0;
569
+ }
570
+ const QUALITY = {
571
+ crap,
572
+ dry: quality_dry,
573
+ mutate,
574
+ ratio
575
+ };
576
+ const GO_QUOTES = new Set([
577
+ '"',
578
+ "'",
579
+ '`'
580
+ ]);
581
+ const GO_BLANK = new Set([
582
+ ' ',
583
+ '\t',
584
+ '\r'
585
+ ]);
586
+ function skipQuoted(scan, quote) {
587
+ const { source } = scan;
588
+ for(scan.i += 1; scan.i < source.length && source[scan.i] !== quote; scan.i += 1)if ('\\' === source[scan.i] && '`' !== quote) scan.i += 1;
589
+ else if ('\n' === source[scan.i]) scan.line += 1;
590
+ scan.i += 1;
591
+ scan.lineHasCode = true;
592
+ }
593
+ function lineComment(scan) {
594
+ const end = scan.source.indexOf('\n', scan.i);
595
+ const stop = -1 === end ? scan.source.length : end;
596
+ scan.found.push({
597
+ line: scan.line,
598
+ text: scan.source.slice(scan.i + 2, stop),
599
+ chains: !scan.lineHasCode
600
+ });
601
+ scan.i = stop;
602
+ }
603
+ function blockComment(scan) {
604
+ const end = scan.source.indexOf('*/', scan.i + 2);
605
+ const stop = -1 === end ? scan.source.length : end;
606
+ scan.found.push({
607
+ line: scan.line,
608
+ text: scan.source.slice(scan.i + 2, stop).trim(),
609
+ chains: false
610
+ });
611
+ scan.line += scan.source.slice(scan.i, stop).split('\n').length - 1;
612
+ scan.i = stop + 2;
613
+ scan.lineHasCode = true;
614
+ }
615
+ function goStep(scan) {
616
+ const ch = scan.source[scan.i] ?? '';
617
+ const pair = scan.source.slice(scan.i, scan.i + 2);
618
+ if ('\n' === ch) {
619
+ scan.line += 1;
620
+ scan.lineHasCode = false;
621
+ scan.i += 1;
622
+ } else if ('//' === pair) lineComment(scan);
623
+ else if ('/*' === pair) blockComment(scan);
624
+ else if (GO_QUOTES.has(ch)) skipQuoted(scan, ch);
625
+ else {
626
+ if (!GO_BLANK.has(ch)) scan.lineHasCode = true;
627
+ scan.i += 1;
628
+ }
629
+ }
630
+ function goComments(source) {
631
+ const scan = {
632
+ source,
633
+ i: 0,
634
+ line: 1,
635
+ lineHasCode: false,
636
+ found: []
637
+ };
638
+ while(scan.i < source.length)goStep(scan);
639
+ return scan.found;
640
+ }
641
+ const EXTERNAL = /^external\([^)\s][^)]*\): \S/;
642
+ const DIRECTIVE = /^(biome-ignore|shellcheck |\/ <reference )/;
643
+ const GO_DIRECTIVE = /^(go:|nolint:)/;
644
+ const SCRIPT = /\.(ts|mts|cts|tsx|js|mjs|cjs|jsx)$/;
645
+ const GENERATED = /^\/\/ Code generated .* DO NOT EDIT\.$/m;
646
+ function externalLines(comments) {
647
+ const lines = new Set();
648
+ let next;
649
+ for (const c of comments){
650
+ const external = EXTERNAL.test(c.text) || c.chains && c.line === next;
651
+ next = external && c.chains ? c.line + 1 : void 0;
652
+ if (external) lines.add(c.line);
653
+ }
654
+ return lines;
655
+ }
656
+ function disallowed(comments) {
657
+ const external = externalLines(comments);
658
+ return comments.filter((c)=>!external.has(c.line) && !c.directive && !c.publicDoc).map((c)=>c.line);
659
+ }
660
+ const lineAt = (source, offset)=>source.slice(0, offset).split('\n').length;
661
+ const ownLine = (source, offset)=>!/[^ \t]/.test(source.slice(source.lastIndexOf('\n', offset) + 1, offset));
662
+ function members(declaration) {
663
+ if (declaration?.type === 'TSInterfaceDeclaration') return declaration.body.body;
664
+ if (declaration?.type === 'TSTypeAliasDeclaration' && 'TSTypeLiteral' === declaration.typeAnnotation.type) return declaration.typeAnnotation.members;
665
+ return [];
666
+ }
667
+ function publicStarts(program) {
668
+ const starts = new Set();
669
+ for (const node of program.body)if ('ExportNamedDeclaration' === node.type || 'ExportDefaultDeclaration' === node.type) {
670
+ starts.add(node.start);
671
+ for (const member of members('ExportNamedDeclaration' === node.type ? node.declaration : null))starts.add(member.start);
672
+ }
673
+ return starts;
674
+ }
675
+ const afterHashbang = (program, comments)=>comments.filter((c)=>c.start >= (program.hashbang?.end || 0));
676
+ function scriptComments(file, source, publicApi) {
677
+ const { program, comments, errors } = parseSync(file, source);
678
+ const [error] = errors;
679
+ if (error) throw new Error(error.message);
680
+ const documented = publicApi ? publicStarts(program) : new Set();
681
+ const documents = (end)=>{
682
+ const rest = source.slice(end);
683
+ return documented.has(end + rest.length - rest.trimStart().length);
684
+ };
685
+ return afterHashbang(program, comments).map((c)=>({
686
+ line: lineAt(source, c.start),
687
+ text: c.value.trim(),
688
+ chains: 'Line' === c.type && ownLine(source, c.start),
689
+ directive: DIRECTIVE.test(c.value.trim()),
690
+ publicDoc: 'Block' === c.type && c.value.startsWith('*') && documents(c.end)
691
+ }));
692
+ }
693
+ const SHELL_TOKEN = /'[^']*'|"(?:\\.|[^"\\])*"|\\.|(?<=^|\s)#/g;
694
+ function commentStart(line) {
695
+ for (const m of line.matchAll(SHELL_TOKEN))if ('#' === m[0]) return m.index;
696
+ return -1;
697
+ }
698
+ function shellComments(source) {
699
+ const found = [];
700
+ let heredoc = '';
701
+ source.split('\n').forEach((line, index)=>{
702
+ if (heredoc) {
703
+ if (line.trim() === heredoc) heredoc = '';
704
+ return;
705
+ }
706
+ if (0 === index && line.startsWith('#!')) return;
707
+ const start = commentStart(line);
708
+ if (start >= 0) {
709
+ const text = line.slice(start + 1).trim();
710
+ found.push({
711
+ line: index + 1,
712
+ text,
713
+ chains: !line.slice(0, start).trim(),
714
+ directive: DIRECTIVE.test(text),
715
+ publicDoc: false
716
+ });
717
+ }
718
+ const code = start >= 0 ? line.slice(0, start) : line;
719
+ heredoc = code.match(/<<-?\s*['"]?(\w+)['"]?/)?.[1] || '';
720
+ });
721
+ return found;
722
+ }
723
+ const goFile = (source)=>goComments(source).map((c)=>({
724
+ line: c.line,
725
+ text: c.text.trim(),
726
+ chains: c.chains,
727
+ directive: GO_DIRECTIVE.test(c.text),
728
+ publicDoc: false
729
+ }));
730
+ function commentsOf(file, source, publicApi) {
731
+ if (file.endsWith('.go')) return goFile(source);
732
+ if (SCRIPT.test(file)) return scriptComments(file, source, publicApi);
733
+ if (isShell(file, source.split('\n', 1)[0] || '')) return shellComments(source);
734
+ }
735
+ function disallowedLines(file, source, publicApi = false) {
736
+ if (GENERATED.test(source)) return [];
737
+ const comments = commentsOf(file, source, publicApi);
738
+ return comments ? disallowed(comments) : [];
739
+ }
740
+ const EXCLUDED = /(^|\/)(node_modules|fixtures)\//;
741
+ const PACKAGE_SRC = /^packages\/([^/]+)\/src\//;
742
+ const MESSAGE = 'comment not allowed: rename or extract so the code says it, move the constraint to docs/, or mark external(<dependency>): why';
743
+ function isPublicPackage(root, file) {
744
+ const name = file.match(PACKAGE_SRC)?.[1];
745
+ if (!name) return false;
746
+ const manifest = node_path.join(root, 'packages', name, 'package.json');
747
+ if (!__rspack_external_node_fs_1b05aee1.existsSync(manifest)) return false;
748
+ return true !== JSON.parse(__rspack_external_node_fs_1b05aee1.readFileSync(manifest, 'utf8')).private;
749
+ }
750
+ const isFile = (full)=>__rspack_external_node_fs_1b05aee1.statSync(full, {
751
+ throwIfNoEntry: false
752
+ })?.isFile() === true;
753
+ function checkComments(root, files, { exclude, publicApi }) {
754
+ const errors = [];
755
+ const skipped = (file)=>EXCLUDED.test(file) || matchesAny(file, exclude);
756
+ const isPublicApi = (file)=>publicApi.some((dir)=>file.startsWith(dir)) || isPublicPackage(root, file);
757
+ for (const file of files){
758
+ const full = node_path.join(root, file);
759
+ if (skipped(file) || !isFile(full)) continue;
760
+ const source = __rspack_external_node_fs_1b05aee1.readFileSync(full, 'utf8');
761
+ try {
762
+ for (const line of disallowedLines(file, source, isPublicApi(file)))errors.push(`${file}:${line}: ${MESSAGE}`);
763
+ } catch (error) {
764
+ errors.push(`${file}: cannot parse: ${error.message}`);
765
+ }
766
+ }
767
+ return errors;
768
+ }
769
+ const HEADING = '## Where checks run';
770
+ const HOOK_ENTRY = /^pnpm (\S+)[^\n]*$/;
771
+ const HOOK_HINT = "call a package.json script as `pnpm <script>` instead";
772
+ const check_runs_text = (file)=>__rspack_external_node_fs_1b05aee1.existsSync(file) ? __rspack_external_node_fs_1b05aee1.readFileSync(file, 'utf8') : '';
773
+ const isObject = (value)=>'object' == typeof value && null !== value;
774
+ const field = (value, key)=>isObject(value) && key in value ? value[key] : void 0;
775
+ const check_runs_list = (value)=>Array.isArray(value) ? value : [];
776
+ function collect(value, keys, found) {
777
+ if (Array.isArray(value)) {
778
+ for (const item of value)collect(item, keys, found);
779
+ return;
780
+ }
781
+ if (!isObject(value)) return;
782
+ for (const [key, child] of Object.entries(value))if ('run' === key && 'string' == typeof child) found.push({
783
+ path: keys,
784
+ command: child
785
+ });
786
+ else collect(child, [
787
+ ...keys,
788
+ key
789
+ ], found);
790
+ }
791
+ function runs(yaml) {
792
+ const found = [];
793
+ collect(external_yaml_parse(yaml), [], found);
794
+ return found;
795
+ }
796
+ function commands(yaml) {
797
+ const jobs = field(external_yaml_parse(yaml), 'jobs');
798
+ return Object.entries(isObject(jobs) ? jobs : {}).flatMap(([job, body])=>check_runs_list(field(body, 'steps')).flatMap((step)=>check_runs_list(field(step, 'commands')).filter((c)=>'string' == typeof c).map((command)=>({
799
+ path: [
800
+ 'jobs',
801
+ job
802
+ ],
803
+ command
804
+ }))));
805
+ }
806
+ const COMMAND = /^(check|fix|check_diff|check_list_files)\s*=\s*(.*)$/;
807
+ const STRING = /^"((?:[^"\\]|\\.)*)"$/;
808
+ const OPEN = /^(?:\["([^"]+)"\]|(\w+))\s*\{$/;
809
+ const inStep = (stack)=>4 === stack.length && 'hooks' === stack[0] && 'steps' === stack[2];
810
+ function commandOf(line, stack) {
811
+ const [, key, value = ''] = line.match(COMMAND) ?? [];
812
+ if (void 0 === key || /^(true|false)$/.test(value)) return;
813
+ if (!inStep(stack)) throw new Error(`${key} must sit in a step under hooks { ["<hook>"] { steps { ["<step>"] { … } } } }`);
814
+ const body = value.match(STRING)?.[1];
815
+ if (void 0 === body) throw new Error(`write ${key} as a one-line "…" string`);
816
+ return JSON.parse(`"${body}"`);
817
+ }
818
+ function readLine(line, stack) {
819
+ const open = line.match(OPEN);
820
+ if (open) stack.push(open[1] ?? open[2] ?? '');
821
+ else if ('}' === line) stack.pop();
822
+ else if (line.startsWith('[') || line.endsWith('{')) throw new Error('put each block on its own lines: name {, then }');
823
+ else {
824
+ const command = commandOf(line, stack);
825
+ if (void 0 !== command) return {
826
+ path: stack.slice(1),
827
+ command
828
+ };
829
+ }
830
+ }
831
+ function hookRuns(pkl) {
832
+ const found = [];
833
+ const stack = [];
834
+ for (const [i, raw] of pkl.split('\n').entries()){
835
+ const line = raw.trim();
836
+ if (!('' === line || line.startsWith('//'))) try {
837
+ const run = readLine(line, stack);
838
+ if (run) found.push(run);
839
+ } catch (error) {
840
+ throw new Error(`line ${i + 1}: ${error.message}`);
841
+ }
842
+ }
843
+ return found;
844
+ }
845
+ function check_runs_table(markdown) {
846
+ const section = markdown.split(HEADING)[1]?.split(/^## /m)[0] ?? '';
847
+ const names = (cell = '')=>[
848
+ ...cell.matchAll(/`([^`]+)`/g)
849
+ ].map((m)=>m[1] ?? '').sort();
850
+ const rows = new Map();
851
+ for (const line of section.split('\n')){
852
+ const cells = line.split('|').slice(1, -1);
853
+ const script = cells[0]?.trim().match(/^`([^`]+)`$/)?.[1];
854
+ if (script) rows.set(script, {
855
+ hooks: names(cells[1]),
856
+ jobs: names(cells[2])
857
+ });
858
+ }
859
+ return rows;
860
+ }
861
+ function parsedOr(errors, file, format, parse, fallback) {
862
+ try {
863
+ return parse();
864
+ } catch (error) {
865
+ const [first = ''] = String(error.message).split('\n');
866
+ errors.push(`${file}: not valid ${format}: ${first.replace(/:$/, '')}`);
867
+ return fallback;
868
+ }
869
+ }
870
+ function pipelineFiles(root, patterns) {
871
+ return [
872
+ ...new Set(patterns.flatMap((p)=>__rspack_external_node_fs_1b05aee1.globSync(p, {
873
+ cwd: root
874
+ }).sort()))
875
+ ];
876
+ }
877
+ function describeFiles(patterns) {
878
+ if (1 === patterns.length) return patterns[0] ?? '';
879
+ const dirs = new Set(patterns.map((p)=>node_path.posix.dirname(p)));
880
+ const exts = new Set(patterns.map((p)=>node_path.posix.extname(p)));
881
+ const [dir] = dirs;
882
+ const [ext = ''] = exts;
883
+ if (1 !== dirs.size || 1 !== exts.size) return patterns.join(', ');
884
+ const names = patterns.map((p)=>node_path.posix.basename(p, ext));
885
+ return `${dir}/{${names.join(',')}}${ext}`;
886
+ }
887
+ function check_runs_sites(root, config, errors) {
888
+ const read = (file, format, find)=>parsedOr(errors, file, format, ()=>find(check_runs_text(node_path.join(root, file))), []);
889
+ const hooks = read(config.hooks, 'hk config', hookRuns).map((r)=>({
890
+ file: config.hooks,
891
+ label: r.path.join('.'),
892
+ kind: 'hooks',
893
+ where: r.path[0] ?? '',
894
+ command: r.command,
895
+ script: r.command.trimEnd().match(HOOK_ENTRY)?.[1],
896
+ hint: HOOK_HINT
897
+ }));
898
+ const { ci } = config;
899
+ if (!ci) return hooks;
900
+ const find = 'github' === ci.platform ? runs : commands;
901
+ const allowed = (command)=>ci.allow.some((pattern)=>pattern.test(command.trim()));
902
+ const jobs = pipelineFiles(root, ci.files).flatMap((file)=>read(file, 'YAML', find).map((r)=>({
903
+ file,
904
+ r
905
+ }))).filter(({ r })=>'jobs' === r.path[0] && !allowed(r.command)).map(({ file, r })=>({
906
+ file,
907
+ label: r.path.slice(0, 2).join('.'),
908
+ kind: 'jobs',
909
+ where: r.path[1] ?? '',
910
+ command: r.command,
911
+ script: r.command.trim().match(ci.entry)?.[1],
912
+ hint: ci.hint
913
+ }));
914
+ return [
915
+ ...hooks,
916
+ ...jobs
917
+ ];
918
+ }
919
+ const check_runs_short = (command)=>{
920
+ const words = command.trim().split(/\s+/);
921
+ return words.length > 3 ? `${words.slice(0, 3).join(' ')} …` : command;
922
+ };
923
+ const check_runs_names = (items)=>items.map((n)=>`\`${n}\``).join(', ') || 'nothing';
924
+ const where = (entry)=>[
925
+ entry.hooks.length && `hk ${check_runs_names(entry.hooks)}`,
926
+ entry.jobs.length && `CI job ${check_runs_names(entry.jobs)}`
927
+ ].filter(Boolean).join(' and ');
928
+ const NONE = {
929
+ hooks: [],
930
+ jobs: []
931
+ };
932
+ function invoked(root, config, scripts, errors) {
933
+ const actual = new Map();
934
+ for (const site of check_runs_sites(root, config, errors)){
935
+ const { script } = site;
936
+ if (void 0 === script || !Object.hasOwn(scripts, script)) {
937
+ errors.push(`${site.file}: ${site.label} runs \`${check_runs_short(site.command)}\`; ${site.hint}`);
938
+ continue;
939
+ }
940
+ const entry = actual.get(script) ?? {
941
+ hooks: [],
942
+ jobs: []
943
+ };
944
+ entry[site.kind].push(site.where);
945
+ actual.set(script, entry);
946
+ }
947
+ return actual;
948
+ }
949
+ function checkRow(errors, config, table, script, row, entry) {
950
+ for (const [kind, file, column] of [
951
+ [
952
+ 'hooks',
953
+ config.hooks,
954
+ 'hk'
955
+ ],
956
+ [
957
+ 'jobs',
958
+ config.ci ? describeFiles(config.ci.files) : 'pipelines.ci (unset)',
959
+ 'CI job'
960
+ ]
961
+ ]){
962
+ const want = [
963
+ ...new Set(entry[kind])
964
+ ].sort();
965
+ if (want.join() !== row[kind].join()) errors.push(`${table}: Where checks run table row \`${script}\` lists ${column} ${check_runs_names(row[kind])}; ${file} runs it in ${check_runs_names(want)}`);
966
+ }
967
+ }
968
+ function packageScripts(pkg, errors) {
969
+ const parsed = parsedOr(errors, 'package.json', 'JSON', ()=>pkg ? JSON.parse(pkg) : {}, {});
970
+ const scripts = field(parsed, "scripts");
971
+ return isObject(scripts) ? scripts : {};
972
+ }
973
+ function checkRuns(root, config) {
974
+ const errors = [];
975
+ const scripts = packageScripts(check_runs_text(node_path.join(root, 'package.json')), errors);
976
+ const actual = invoked(root, config, scripts, errors);
977
+ const { table: page } = config;
978
+ if (void 0 === page) return errors;
979
+ const rows = check_runs_table(check_runs_text(node_path.join(root, page)));
980
+ for (const [script, entry] of actual)if (!rows.has(script)) errors.push(`${page}: script \`${script}\` is run by ${where(entry)} but is missing from the Where checks run table`);
981
+ for (const [script, row] of rows)if (Object.hasOwn(scripts, script)) checkRow(errors, config, page, script, row, actual.get(script) ?? NONE);
982
+ else errors.push(`${page}: Where checks run table row \`${script}\` names a script package.json does not define`);
983
+ return errors;
984
+ }
985
+ const TOP = [
986
+ 'AGENTS.md',
987
+ 'GLOSSARY-MAP.md',
988
+ 'GLOSSARY.md',
989
+ 'LESSONS.md',
990
+ 'README.md'
991
+ ];
992
+ const PER_WORKSPACE = [
993
+ 'AGENTS.md',
994
+ 'GLOSSARY.md',
995
+ 'README.md'
996
+ ];
997
+ const ENGLISH = new Set([
998
+ 'AGENTS.md',
999
+ 'GLOSSARY-MAP.md',
1000
+ 'GLOSSARY.md',
1001
+ 'LESSONS.md'
1002
+ ]);
1003
+ const CJK = /[\u{3000}-\u{30ff}\u{3400}-\u{9fff}\u{ac00}-\u{d7af}\u{ff00}-\u{ffef}]/u;
1004
+ const SKIP = [
1005
+ 'node_modules',
1006
+ 'coverage',
1007
+ '.metrics',
1008
+ 'target',
1009
+ 'dist',
1010
+ 'log',
1011
+ 'output',
1012
+ '.ci-cache',
1013
+ '.eden-mono'
1014
+ ];
1015
+ const AGENT_FILES = new Set([
1016
+ 'AGENTS.md',
1017
+ 'CLAUDE.md'
1018
+ ]);
1019
+ const SKILL_TREES = new Set([
1020
+ 'skills',
1021
+ '.agents/skills',
1022
+ '.claude/skills'
1023
+ ]);
1024
+ const SHARED_WORDS = 10;
1025
+ const WORD = /`[^`\n]*`|[a-z0-9]+(?:['.-][a-z0-9]+)*/g;
1026
+ const check_docs_HEADING = /^#{1,6}[ \t]+(.*?)(?:[ \t]+#+)?[ \t]*$/gm;
1027
+ const HTML_ANCHOR = /<a\s[^>]*?\b(?:id|name)="([^"]+)"/g;
1028
+ const LINK = /\[[^\]\n]*\]\([^)\s]*(?:\s+"[^"]*")?\)/;
1029
+ const UNREACHED = 'no link chain from AGENTS.md reaches it; link it from AGENTS.md or a page it links to';
1030
+ const check_docs_text = (file)=>__rspack_external_node_fs_1b05aee1.existsSync(file) ? __rspack_external_node_fs_1b05aee1.readFileSync(file, 'utf8') : '';
1031
+ const byName = (a, b)=>a.name.localeCompare(b.name);
1032
+ function walk(ctx, dir) {
1033
+ const full = node_path.join(ctx.root, dir);
1034
+ if (!__rspack_external_node_fs_1b05aee1.existsSync(full)) return [];
1035
+ return __rspack_external_node_fs_1b05aee1.readdirSync(full, {
1036
+ withFileTypes: true
1037
+ }).filter((d)=>!ctx.skip.has(d.name)).sort(byName).flatMap((d)=>{
1038
+ const rel = node_path.join(dir, d.name);
1039
+ if (d.isDirectory()) return walk(ctx, rel);
1040
+ return d.name.endsWith('.md') ? [
1041
+ rel
1042
+ ] : [];
1043
+ });
1044
+ }
1045
+ function workspaceDirs(ctx) {
1046
+ return ctx.workspaces.filter((dir)=>!ctx.skip.has(node_path.basename(dir))).sort((a, b)=>a.localeCompare(b));
1047
+ }
1048
+ const check_docs_read = (ctx, file)=>!matchesAny(file, ctx.exclude);
1049
+ const present = (root, files)=>files.filter((f)=>__rspack_external_node_fs_1b05aee1.existsSync(node_path.join(root, f)));
1050
+ function agentDocs(ctx) {
1051
+ const workspaces = ctx.docs.workspaceDocs ? workspaceDirs(ctx) : [];
1052
+ return [
1053
+ ...present(ctx.root, TOP),
1054
+ ...walk(ctx, 'docs'),
1055
+ ...workspaces.flatMap((dir)=>[
1056
+ ...present(ctx.root, PER_WORKSPACE.map((f)=>node_path.join(dir, f))),
1057
+ ...walk(ctx, node_path.join(dir, 'docs'))
1058
+ ])
1059
+ ];
1060
+ }
1061
+ function unfenced(markdown) {
1062
+ return markdown.replace(/^(```|~~~)[^\n]*\n[\s\S]*?^\1[^\n]*$/gm, (block)=>block.replace(/[^\n]/g, ''));
1063
+ }
1064
+ function prose(markdown) {
1065
+ return unfenced(markdown).replace(/`[^`\n]*`/g, '');
1066
+ }
1067
+ function links(markdown) {
1068
+ return [
1069
+ ...prose(markdown).matchAll(/\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g)
1070
+ ].map((m)=>m[1] ?? '');
1071
+ }
1072
+ const check_docs_external = (target)=>/^([a-z][a-z0-9+.-]*:|#)/i.test(target);
1073
+ function slug(heading) {
1074
+ return heading.replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1').replace(/<[^>]+>/g, '').toLowerCase().replace(/[^\p{L}\p{M}\p{N}\p{Pc} -]/gu, '').replace(/ /g, '-');
1075
+ }
1076
+ function check_docs_anchors(markdown) {
1077
+ const out = new Set();
1078
+ const seen = new Map();
1079
+ for (const [, heading = ''] of unfenced(markdown).matchAll(check_docs_HEADING)){
1080
+ const base = slug(heading);
1081
+ const n = seen.get(base) ?? 0;
1082
+ seen.set(base, n + 1);
1083
+ out.add(n ? `${base}-${n}` : base);
1084
+ }
1085
+ for (const [, id = ''] of markdown.matchAll(HTML_ANCHOR))out.add(id);
1086
+ return out;
1087
+ }
1088
+ function decoded(fragment) {
1089
+ try {
1090
+ return decodeURIComponent(fragment);
1091
+ } catch {
1092
+ return fragment;
1093
+ }
1094
+ }
1095
+ const withoutQuery = (target)=>target.replace(/[?#].*$/, '');
1096
+ function linkProblem(root, file, target) {
1097
+ const hash = target.indexOf('#');
1098
+ const local = withoutQuery(target);
1099
+ const resolved = 0 === hash ? node_path.join(root, file) : node_path.resolve(node_path.dirname(node_path.join(root, file)), local);
1100
+ if (!__rspack_external_node_fs_1b05aee1.existsSync(resolved)) return `link to ${target} does not resolve`;
1101
+ if (hash < 0 || !resolved.endsWith('.md')) return '';
1102
+ const anchor = decoded(target.slice(hash + 1));
1103
+ return check_docs_anchors(check_docs_text(resolved)).has(anchor) ? '' : `link to ${target}: no heading ${anchor} in ${local || file}`;
1104
+ }
1105
+ function unlinkedDir(ctx, file, target) {
1106
+ const rel = node_path.relative(ctx.root, node_path.resolve(node_path.dirname(node_path.join(ctx.root, file)), withoutQuery(target)));
1107
+ return ctx.docs.noLinksInto.find((dir)=>rel === dir || rel.startsWith(`${dir}${node_path.sep}`));
1108
+ }
1109
+ function checkLinks(ctx, file) {
1110
+ for (const target of links(check_docs_text(node_path.join(ctx.root, file)))){
1111
+ if (check_docs_external(target) && !target.startsWith('#')) continue;
1112
+ const dir = unlinkedDir(ctx, file, target);
1113
+ const problem = dir ? `link to ${target} points into ${dir}/, which check:docs does not read; write the fact into its owning doc instead (docs/subsystems/README.md#archives-and-scratch)` : linkProblem(ctx.root, file, target);
1114
+ if (problem) ctx.fail(file, problem);
1115
+ }
1116
+ }
1117
+ function linked(root, file) {
1118
+ return links(check_docs_text(node_path.join(root, file))).filter((target)=>!check_docs_external(target)).map((target)=>node_path.normalize(node_path.join(node_path.dirname(file), withoutQuery(target)))).filter((rel)=>rel.endsWith('.md'));
1119
+ }
1120
+ function checkReachable(ctx, files) {
1121
+ const seen = new Set();
1122
+ const queue = __rspack_external_node_fs_1b05aee1.existsSync(node_path.join(ctx.root, 'AGENTS.md')) ? [
1123
+ 'AGENTS.md'
1124
+ ] : [];
1125
+ for(let file = queue.shift(); void 0 !== file; file = queue.shift())if (!seen.has(file)) {
1126
+ seen.add(file);
1127
+ queue.push(...linked(ctx.root, file));
1128
+ }
1129
+ for (const file of files)if ('README.md' !== node_path.basename(file) && !seen.has(file)) ctx.fail(file, UNREACHED);
1130
+ }
1131
+ const workspaceRoot = (ctx, dir)=>ctx.workspaces.includes(dir);
1132
+ function strayAgentFiles(ctx, dir = '') {
1133
+ const allowed = (at)=>!at || 'workspaces' === ctx.docs.agentFiles && workspaceRoot(ctx, at);
1134
+ return __rspack_external_node_fs_1b05aee1.readdirSync(node_path.join(ctx.root, dir), {
1135
+ withFileTypes: true
1136
+ }).filter((d)=>!ctx.skip.has(d.name) && '.git' !== d.name).sort(byName).flatMap((d)=>{
1137
+ const rel = dir ? `${dir}/${d.name}` : d.name;
1138
+ if (d.isDirectory()) return SKILL_TREES.has(rel) ? [] : strayAgentFiles(ctx, rel);
1139
+ return AGENT_FILES.has(d.name) && !allowed(dir) ? [
1140
+ rel
1141
+ ] : [];
1142
+ });
1143
+ }
1144
+ const STRAY = {
1145
+ root: 'agent knowledge lives in the root AGENTS.md, LESSONS.md and docs/ (docs/subsystems/README.md#one-fact-one-place); move its content to the owning page and delete it',
1146
+ workspaces: 'agent knowledge lives in the root AGENTS.md, LESSONS.md and docs/, or in an app or package AGENTS.md (docs/subsystems/README.md#one-fact-one-place); move its content to the owning page and delete it'
1147
+ };
1148
+ function checkStrayAgentFiles(ctx) {
1149
+ const { agentFiles } = ctx.docs;
1150
+ if ('anywhere' === agentFiles) return;
1151
+ for (const file of strayAgentFiles(ctx).filter((f)=>check_docs_read(ctx, f)))ctx.fail(file, STRAY[agentFiles]);
1152
+ }
1153
+ const english = (file)=>ENGLISH.has(node_path.basename(file)) || file.split(node_path.sep).includes('docs');
1154
+ function checkEnglish(ctx, file) {
1155
+ const line = prose(check_docs_text(node_path.join(ctx.root, file))).split('\n').findIndex((l)=>CJK.test(l));
1156
+ if (line >= 0) ctx.fail(file, `line ${line + 1} has CJK text outside code; write it in English, or quote it in backticks as data`);
1157
+ }
1158
+ function phrases(markdown) {
1159
+ const out = new Set();
1160
+ for (const run of unfenced(markdown).toLowerCase().split(LINK)){
1161
+ const words = [
1162
+ ...run.matchAll(WORD)
1163
+ ].map((m)=>m[0]);
1164
+ for(let i = 0; i + SHARED_WORDS <= words.length; i++)out.add(words.slice(i, i + SHARED_WORDS).join(' '));
1165
+ }
1166
+ return out;
1167
+ }
1168
+ function checkRepeats(ctx, files) {
1169
+ const first = new Map();
1170
+ for (const file of files){
1171
+ const reported = new Set();
1172
+ for (const phrase of phrases(check_docs_text(node_path.join(ctx.root, file)))){
1173
+ const owner = first.get(phrase);
1174
+ if (void 0 === owner) first.set(phrase, file);
1175
+ else if (!reported.has(owner)) {
1176
+ reported.add(owner);
1177
+ ctx.fail(file, `shares "${phrase}" with ${owner}; keep the copy in the document that owns this fact (owner table: docs/subsystems/README.md#one-fact-one-place) and link to it from the other`);
1178
+ }
1179
+ }
1180
+ }
1181
+ }
1182
+ function checkDocs(root, settings) {
1183
+ const errors = [];
1184
+ const ctx = {
1185
+ root,
1186
+ docs: settings.docs,
1187
+ workspaces: settings.workspaces,
1188
+ exclude: settings.exclude,
1189
+ skip: new Set([
1190
+ ...SKIP,
1191
+ ...settings.docs.skip
1192
+ ]),
1193
+ fail: (file, message)=>errors.push(`${file}: ${message}`)
1194
+ };
1195
+ const agent = agentDocs(ctx).filter((f)=>check_docs_read(ctx, f));
1196
+ const files = [
1197
+ ...agent,
1198
+ ...settings.docs.dirs.flatMap((dir)=>walk(ctx, dir)).filter((f)=>check_docs_read(ctx, f))
1199
+ ];
1200
+ for (const file of files)checkLinks(ctx, file);
1201
+ checkReachable(ctx, agent);
1202
+ checkStrayAgentFiles(ctx);
1203
+ for (const file of files.filter(english))checkEnglish(ctx, file);
1204
+ checkRepeats(ctx, files);
1205
+ if (settings.pipelines) errors.push(...checkRuns(root, settings.pipelines));
1206
+ return {
1207
+ errors,
1208
+ count: files.length
1209
+ };
1210
+ }
1211
+ const OPTIONS = {
1212
+ indent: 2,
1213
+ switchCaseIndent: true
1214
+ };
1215
+ function formatFiles(root, files, write) {
1216
+ const result = {
1217
+ changed: [],
1218
+ errors: []
1219
+ };
1220
+ for (const file of files){
1221
+ const full = node_path.join(root, file);
1222
+ if (!__rspack_external_node_fs_1b05aee1.existsSync(full) || !__rspack_external_node_fs_1b05aee1.statSync(full).isFile()) continue;
1223
+ const source = __rspack_external_node_fs_1b05aee1.readFileSync(full, 'utf8');
1224
+ if (!isShell(file, source.split('\n', 1)[0] ?? '')) continue;
1225
+ let formatted;
1226
+ try {
1227
+ formatted = shfmt_format(source, file, OPTIONS);
1228
+ } catch (error) {
1229
+ result.errors.push(`${file}: ${error.message}`);
1230
+ continue;
1231
+ }
1232
+ if (formatted !== source) {
1233
+ result.changed.push(file);
1234
+ if (write) __rspack_external_node_fs_1b05aee1.writeFileSync(full, formatted);
1235
+ }
1236
+ }
1237
+ return result;
1238
+ }
1239
+ function reviewLines(file, source, added) {
1240
+ const comments = commentsOf(file, source, false);
1241
+ if (!comments) return [];
1242
+ const external = externalLines(comments);
1243
+ return added.filter((l)=>external.has(l));
1244
+ }
1245
+ function hunkLines(hunk) {
1246
+ const [header = '', ...body] = hunk.split('\n');
1247
+ const start = Number.parseInt(header, 10);
1248
+ return body.filter((l)=>l.startsWith('+')).map((l, i)=>({
1249
+ line: start + i,
1250
+ text: l.slice(1)
1251
+ }));
1252
+ }
1253
+ function parseDiff(diff) {
1254
+ return diff.split(/^\+\+\+ /m).flatMap((chunk)=>{
1255
+ const [target = '', ...rest] = chunk.split('\n');
1256
+ const added = rest.join('\n').split(/^@@ -\S+ \+/m).flatMap(hunkLines);
1257
+ return added.length ? [
1258
+ {
1259
+ file: target.slice(2),
1260
+ added
1261
+ }
1262
+ ] : [];
1263
+ });
1264
+ }
1265
+ const isRegular = (root, file)=>__rspack_external_node_fs_1b05aee1.lstatSync(node_path.join(root, file)).isFile();
1266
+ const readText = (root, file)=>__rspack_external_node_fs_1b05aee1.readFileSync(node_path.join(root, file), 'utf8');
1267
+ function untracked(root) {
1268
+ return git(root, [
1269
+ 'ls-files',
1270
+ '--others',
1271
+ '--exclude-standard'
1272
+ ]).split('\n').filter((file)=>file && isRegular(root, file)).map((file)=>({
1273
+ file,
1274
+ added: readText(root, file).split('\n').map((text, i)=>({
1275
+ line: i + 1,
1276
+ text
1277
+ }))
1278
+ }));
1279
+ }
1280
+ function reviewComments(root, against, exclude = []) {
1281
+ const base = git(root, [
1282
+ 'merge-base',
1283
+ against,
1284
+ 'HEAD'
1285
+ ]).trim();
1286
+ const diff = git(root, [
1287
+ 'diff',
1288
+ '--unified=0',
1289
+ '--no-color',
1290
+ base
1291
+ ]);
1292
+ const changed = parseDiff(diff).filter(({ file })=>isRegular(root, file));
1293
+ const read = ({ file })=>!matchesAny(file, exclude);
1294
+ return [
1295
+ ...changed,
1296
+ ...untracked(root)
1297
+ ].filter(read).flatMap(({ file, added })=>reviewLines(file, readText(root, file), added.map((a)=>a.line)).map((line)=>`${file}:${line}: an external(...) comment`));
1298
+ }
1299
+ const units_read = (file)=>__rspack_external_node_fs_1b05aee1.existsSync(file) ? __rspack_external_node_fs_1b05aee1.readFileSync(file, 'utf8') : '';
1300
+ function packageJson(dir) {
1301
+ const text = units_read(node_path.join(dir, 'package.json'));
1302
+ return text ? JSON.parse(text) : void 0;
1303
+ }
1304
+ function pnpmMembers(root) {
1305
+ const list = units_read(node_path.join(root, 'pnpm-workspace.yaml')).split(/^packages:\s*$/m)[1]?.split(/^\S/m)[0] ?? '';
1306
+ return [
1307
+ ...list.matchAll(/^\s*-\s*["']?([^"'#\s]+)/gm)
1308
+ ].map((m)=>m[1] ?? '');
1309
+ }
1310
+ function npmMembers(root) {
1311
+ const workspaces = packageJson(root)?.workspaces;
1312
+ return (Array.isArray(workspaces) ? workspaces : workspaces?.packages) ?? [];
1313
+ }
1314
+ function goMembers(root) {
1315
+ const text = units_read(node_path.join(root, 'go.work')).replace(/\/\/.*$/gm, '');
1316
+ return [
1317
+ ...text.matchAll(/^use\s*(?:\(([^)]*)\)|(\S+))/gm)
1318
+ ].flatMap((m)=>(m[1] ?? m[2] ?? '').split(/\s+/).filter(Boolean));
1319
+ }
1320
+ function cargoMembers(root) {
1321
+ const table = units_read(node_path.join(root, 'Cargo.toml')).split(/^\[workspace\]\s*$/m)[1] ?? '';
1322
+ const list = table.split(/^\[/m)[0]?.match(/^members\s*=\s*\[([^\]]*)\]/m)?.[1] ?? '';
1323
+ return [
1324
+ ...list.matchAll(/["']([^"']+)["']/g)
1325
+ ].map((m)=>m[1] ?? '');
1326
+ }
1327
+ const MANIFESTS = [
1328
+ 'package.json',
1329
+ 'go.mod',
1330
+ 'Cargo.toml',
1331
+ 'pyproject.toml'
1332
+ ];
1333
+ const hasManifest = (dir)=>MANIFESTS.some((m)=>__rspack_external_node_fs_1b05aee1.existsSync(node_path.join(dir, m)));
1334
+ const isDirectory = (dir)=>__rspack_external_node_fs_1b05aee1.statSync(dir, {
1335
+ throwIfNoEntry: false
1336
+ })?.isDirectory() === true;
1337
+ function expand(root, all, keep) {
1338
+ const clean = (g)=>node_path.posix.normalize(g).replace(/\/$/, '');
1339
+ const globs = all.filter((g)=>!g.startsWith('!')).map(clean);
1340
+ const negated = all.filter((g)=>g.startsWith('!')).map((g)=>clean(g.slice(1)));
1341
+ const dirs = __rspack_external_node_fs_1b05aee1.globSync(globs, {
1342
+ cwd: root
1343
+ }).map((d)=>d.split(node_path.sep).join('/')).filter((d)=>!d.split('/').includes('node_modules') && !negated.some((g)=>node_path.matchesGlob(d, g)) && keep(node_path.join(root, d)));
1344
+ return [
1345
+ ...new Set(dirs)
1346
+ ].filter((d)=>'.' !== d).sort();
1347
+ }
1348
+ const discovered = (root)=>expand(root, [
1349
+ ...pnpmMembers(root),
1350
+ ...npmMembers(root),
1351
+ ...goMembers(root),
1352
+ ...cargoMembers(root)
1353
+ ], hasManifest);
1354
+ const units_workspaces = (root, globs)=>globs ? expand(root, globs, isDirectory) : discovered(root);
1355
+ function given(option, dir, scripts) {
1356
+ return 'function' == typeof option ? option({
1357
+ dir,
1358
+ scripts
1359
+ }) : option;
1360
+ }
1361
+ function units_choice(command, pkg, script) {
1362
+ if (void 0 !== command) return {
1363
+ kind: 'command',
1364
+ command
1365
+ };
1366
+ if (!pkg) return {
1367
+ kind: 'tool default'
1368
+ };
1369
+ return {
1370
+ kind: "npm script",
1371
+ command: pkg.scripts?.[script] ? NPM[script] : void 0
1372
+ };
1373
+ }
1374
+ const NPM = {
1375
+ coverage: 'npm run --silent coverage',
1376
+ test: 'npm test --silent'
1377
+ };
1378
+ const inherited = (own, quality, key)=>own && Object.hasOwn(own, key) ? own[key] : quality[key];
1379
+ function thresholds(own, quality) {
1380
+ const pick = (get)=>[
1381
+ own ?? {},
1382
+ quality
1383
+ ].map(get).find((value)=>void 0 !== value);
1384
+ const minScore = pick((config)=>config.mutate?.minScore);
1385
+ return {
1386
+ crap: {
1387
+ threshold: pick((config)=>config.crap?.threshold) ?? 10
1388
+ },
1389
+ mutate: void 0 === minScore ? {} : {
1390
+ minScore
1391
+ }
1392
+ };
1393
+ }
1394
+ function units_unit(dir, own, quality, exclude, root) {
1395
+ const pkg = packageJson(node_path.join(root, dir));
1396
+ const command = (key)=>units_choice(given(inherited(own, quality, key), dir, pkg?.scripts), pkg, key);
1397
+ return {
1398
+ dir,
1399
+ paths: inherited(own, quality, 'paths') ?? [
1400
+ '.'
1401
+ ],
1402
+ exclude: [
1403
+ exclude,
1404
+ quality.exclude,
1405
+ own?.exclude
1406
+ ].flatMap((e)=>e ?? []),
1407
+ coverage: command('coverage'),
1408
+ test: command('test'),
1409
+ ...thresholds(own, quality)
1410
+ };
1411
+ }
1412
+ function units_resolve(root, quality, dirs, exclude = []) {
1413
+ const named = quality.units ?? {};
1414
+ return [
1415
+ ...new Set([
1416
+ '.',
1417
+ ...dirs,
1418
+ ...Object.keys(named)
1419
+ ])
1420
+ ].sort().map((dir)=>{
1421
+ const own = named[dir];
1422
+ if (false !== own) return units_unit(dir, own, quality, exclude, root);
1423
+ return {
1424
+ ...units_unit(dir, void 0, quality, exclude, root),
1425
+ paths: [],
1426
+ dropped: true
1427
+ };
1428
+ });
1429
+ }
1430
+ const CONFIG_FILE = 'repo-doctor.config.mjs';
1431
+ const REPLACED = [
1432
+ 'repo-rules.config.mjs',
1433
+ 'ub-mode-tools.config.mjs'
1434
+ ];
1435
+ class UsageError extends Error {
1436
+ }
1437
+ function resolveSettings(root, config = {}) {
1438
+ const checked = config_check(config);
1439
+ const dirs = units_workspaces(root, checked.workspaces);
1440
+ const { quality } = checked;
1441
+ return {
1442
+ ...checked,
1443
+ workspaces: dirs,
1444
+ quality: quality && {
1445
+ units: units_resolve(root, quality, dirs, checked.exclude),
1446
+ dry: {
1447
+ threshold: quality.dry?.threshold ?? 0.8,
1448
+ includeTests: quality.dry?.includeTests ?? true
1449
+ }
1450
+ }
1451
+ };
1452
+ }
1453
+ async function importConfig(target) {
1454
+ try {
1455
+ return await import(pathToFileURL(target).href);
1456
+ } catch (error) {
1457
+ const [line] = String(error?.message ?? error).split('\n');
1458
+ throw new ConfigError(`${node_path.basename(target)} failed to load: ${line}`);
1459
+ }
1460
+ }
1461
+ async function loadSettings(root, file, cwd = root) {
1462
+ const replaced = REPLACED.filter((f)=>__rspack_external_node_fs_1b05aee1.existsSync(node_path.join(root, f)));
1463
+ if (replaced.length) throw new ConfigError(`${replaced.join(' and ')} is no longer read: move its settings into ${CONFIG_FILE} and delete it`);
1464
+ const target = file ? node_path.resolve(cwd, file) : node_path.join(root, CONFIG_FILE);
1465
+ if (!__rspack_external_node_fs_1b05aee1.existsSync(target)) {
1466
+ if (file) throw new UsageError(`config not found: ${file}`);
1467
+ return resolveSettings(root);
1468
+ }
1469
+ const module = await importConfig(target);
1470
+ return resolveSettings(root, module.default);
1471
+ }
1472
+ const settingsJson = (settings)=>JSON.stringify(settings, (_key, value)=>value instanceof RegExp || 'function' == typeof value ? String(value) : value, 2);
1473
+ function rules_report(errors, footer, ok) {
1474
+ if (errors.length) {
1475
+ console.error(`${errors.join('\n')}\n\n${footer}`);
1476
+ return 1;
1477
+ }
1478
+ console.log(ok);
1479
+ return 0;
1480
+ }
1481
+ function positional(args, max, flags = []) {
1482
+ const unknown = args.find((a)=>a.startsWith('-') && !flags.includes(a));
1483
+ if (void 0 !== unknown) throw new UsageError(`unknown option: ${unknown}`);
1484
+ const rest = args.filter((a)=>!flags.includes(a));
1485
+ if (rest.length > max) throw new UsageError(`unexpected argument: ${rest[max]}`);
1486
+ return rest;
1487
+ }
1488
+ function filesFrom(cwd, named) {
1489
+ const root = repoRoot(cwd);
1490
+ const here = __rspack_external_node_fs_1b05aee1.realpathSync(cwd);
1491
+ return {
1492
+ root,
1493
+ named: named.map((f)=>node_path.relative(root, node_path.resolve(here, f)))
1494
+ };
1495
+ }
1496
+ const rootOf = (cwd, args)=>repoRoot(node_path.resolve(cwd, positional(args, 1)[0] ?? '.'));
1497
+ const off = (command, section)=>{
1498
+ console.log(`${command}: off (${section}: false in the config)`);
1499
+ return 0;
1500
+ };
1501
+ const RULES = {
1502
+ 'check-comments': async ({ cwd, args, load })=>{
1503
+ const { root, named } = filesFrom(cwd, positional(args, 1 / 0));
1504
+ const { comments, exclude } = await load(root);
1505
+ if (!comments) return off('check-comments', 'comments');
1506
+ const files = named.length ? ownChanges(root, named) : repoFiles(root);
1507
+ const errors = checkComments(root, files, {
1508
+ ...comments,
1509
+ exclude: [
1510
+ ...exclude,
1511
+ ...comments.exclude
1512
+ ]
1513
+ });
1514
+ return rules_report(errors, `${errors.length} comment(s) not allowed; see docs/code-standards.md#comments`, 'comments ok');
1515
+ },
1516
+ 'format-sh': async ({ cwd, args, load })=>{
1517
+ const { root, named } = filesFrom(cwd, positional(args, 1 / 0, [
1518
+ '--check'
1519
+ ]));
1520
+ const { exclude } = await load(root);
1521
+ const check = args.includes('--check');
1522
+ const files = named.length ? ownChanges(root, named) : repoFiles(root);
1523
+ const { changed, errors } = formatFiles(root, files.filter((file)=>!matchesAny(file, exclude)), !check);
1524
+ if (errors.length) console.error(errors.join('\n'));
1525
+ if (check && changed.length) {
1526
+ console.error(`${changed.join('\n')}\n\n${changed.length} shell file(s) need formatting: run pnpm format:sh`);
1527
+ return 1;
1528
+ }
1529
+ for (const file of changed)console.log(`formatted ${file}`);
1530
+ return errors.length ? 1 : 0;
1531
+ },
1532
+ 'check-docs': async ({ cwd, args, load })=>{
1533
+ const root = rootOf(cwd, args);
1534
+ const settings = await load(root);
1535
+ const { docs, pipelines } = settings;
1536
+ if (!docs) {
1537
+ if (!pipelines) return off('check-docs', 'docs');
1538
+ return rules_report(checkRuns(root, pipelines), 'Fix the files named above.', 'docs off; runs ok');
1539
+ }
1540
+ const { errors, count } = checkDocs(root, {
1541
+ ...settings,
1542
+ docs
1543
+ });
1544
+ if (errors.length) {
1545
+ console.error(errors.join('\n'));
1546
+ console.error(`\n${errors.length} problem(s). Fix the files named above.`);
1547
+ return 1;
1548
+ }
1549
+ console.log(`docs ok: ${count} checked`);
1550
+ return 0;
1551
+ },
1552
+ 'check-runs': async ({ cwd, args, load })=>{
1553
+ const root = rootOf(cwd, args);
1554
+ const { pipelines } = await load(root);
1555
+ if (!pipelines) return off('check-runs', 'pipelines');
1556
+ return rules_report(checkRuns(root, pipelines), 'Fix the files named above.', 'runs ok');
1557
+ },
1558
+ 'review-comments': async ({ cwd, args, load })=>{
1559
+ const [ref] = positional(args, 1);
1560
+ const root = repoRoot(cwd);
1561
+ const { comments, exclude, baseRef } = await load(root);
1562
+ if (!comments) return off('review-comments', 'comments');
1563
+ const found = reviewComments(root, ref ?? baseRef, exclude);
1564
+ if (!found.length) {
1565
+ console.log('no comment needs /pstack:no-comments');
1566
+ return 0;
1567
+ }
1568
+ console.log(`${found.join('\n')}\n\nrun /pstack:no-comments on this diff`);
1569
+ return 1;
1570
+ }
1571
+ };
1572
+ const USAGE = `usage: repo-doctor <command> [--config <file>] [options] [args...]
1573
+
1574
+ commands:
1575
+ check-comments [files...] comments the policy allows; no files: every file git does not ignore
1576
+ format-sh [--check] [files...] shfmt on shell files; --check only lists them
1577
+ check-docs [root] links, reachability, agent files, English, shared phrases, and check-runs
1578
+ check-runs [root] hooks and CI call package.json scripts (and the docs table lists them, with pipelines.table)
1579
+ review-comments [ref] external(...) comments added since the merge base with ref
1580
+ setup build the Python environment and fetch the parsers
1581
+ crap crapper on each unit: every function under the CRAP threshold
1582
+ dry dryer over every unit at once: no duplicates at the similarity threshold
1583
+ mutate mutator on each unit: every mutant killed, or the unit's minimum score
1584
+ ratio each unit's code and test lines, a report only
1585
+ config print the resolved config as JSON
1586
+
1587
+ options:
1588
+ --config <file> config module, from the working directory (default: repo-doctor.config.mjs in the root)
1589
+ --changed only files changed in the working tree, or since --base
1590
+ --base <ref> with --changed, files changed since the merge base with <ref>, committed or not
1591
+ --min-score <n> mutate passes when each unit scores at least n%, whatever the config says
1592
+ --shard <i/n> mutate only shard i of n
1593
+
1594
+ [root] is any directory in the repo; every command works on its git top level.
1595
+ Other arguments of crap, dry, mutate and ratio go to the tool; any other unknown argument is a usage error.
1596
+
1597
+ exit codes: 0 pass, 1 a finding or a failed gate, 2 an internal error, 64 a usage or config error`;
1598
+ const EXIT_INTERNAL = 2;
1599
+ const EXIT_USAGE = 64;
1600
+ const isPercent = (n)=>'number' == typeof n && Number.isInteger(n) && n >= 0 && n <= 100;
1601
+ function minScoreArg(text) {
1602
+ const n = Number(text);
1603
+ if (!isPercent(n)) throw new UsageError(`--min-score must be an integer 0-100, got ${JSON.stringify(text)}`);
1604
+ return n;
1605
+ }
1606
+ function cli_shard(text) {
1607
+ try {
1608
+ return parseShard(text);
1609
+ } catch (error) {
1610
+ throw new UsageError(error.message);
1611
+ }
1612
+ }
1613
+ const VALUED = {
1614
+ '--base': (o, v)=>{
1615
+ o.base = v;
1616
+ },
1617
+ '--min-score': (o, v)=>{
1618
+ o.minScore = minScoreArg(v);
1619
+ },
1620
+ '--shard': (o, v)=>{
1621
+ o.shard = cli_shard(v);
1622
+ }
1623
+ };
1624
+ function parseArgs(argv) {
1625
+ const options = {
1626
+ changed: false,
1627
+ extra: []
1628
+ };
1629
+ for(let i = 0; i < argv.length; i++){
1630
+ const arg = argv[i] ?? '';
1631
+ const parse = VALUED[arg];
1632
+ if ('--changed' === arg) options.changed = true;
1633
+ else if (parse) {
1634
+ const value = argv[++i];
1635
+ if (void 0 === value) throw new UsageError(`${arg} needs a value`);
1636
+ parse(options, value);
1637
+ } else options.extra.push(arg);
1638
+ }
1639
+ return options;
1640
+ }
1641
+ function splitConfig(args) {
1642
+ const at = args.indexOf('--config');
1643
+ if (at < 0) return {
1644
+ rest: args
1645
+ };
1646
+ const config = args[at + 1];
1647
+ if (void 0 === config) throw new UsageError('--config needs a value');
1648
+ return {
1649
+ config,
1650
+ rest: [
1651
+ ...args.slice(0, at),
1652
+ ...args.slice(at + 2)
1653
+ ]
1654
+ };
1655
+ }
1656
+ function ignoreMetrics(root, dirs) {
1657
+ for (const dir of new Set([
1658
+ '.',
1659
+ ...dirs
1660
+ ])){
1661
+ const metrics = node_path.join(root, dir, '.metrics');
1662
+ const ignore = node_path.join(metrics, '.gitignore');
1663
+ if (!__rspack_external_node_fs_1b05aee1.existsSync(ignore)) {
1664
+ __rspack_external_node_fs_1b05aee1.mkdirSync(metrics, {
1665
+ recursive: true
1666
+ });
1667
+ __rspack_external_node_fs_1b05aee1.writeFileSync(ignore, '*\n');
1668
+ }
1669
+ }
1670
+ }
1671
+ async function cli_quality(name, args, cwd, env, load) {
1672
+ const command = QUALITY[name];
1673
+ if (!command && 'setup' !== name) throw new UsageError(`unknown command: ${name}`);
1674
+ if (!command && args.length) throw new UsageError('setup takes no arguments');
1675
+ const options = parseArgs(args);
1676
+ const root = repoRoot(cwd);
1677
+ const settings = await load(root);
1678
+ if (!command) return await prepare(env);
1679
+ if (!settings.quality) {
1680
+ console.log(`${name}: off (quality: false in the config)`);
1681
+ return 0;
1682
+ }
1683
+ const { units, dry } = settings.quality;
1684
+ ignoreMetrics(root, units.map((u)=>u.dir));
1685
+ return await command({
1686
+ root,
1687
+ env,
1688
+ units,
1689
+ dry,
1690
+ changed: options.changed,
1691
+ minScore: options.minScore,
1692
+ shard: options.shard,
1693
+ extra: options.extra,
1694
+ list: (changed)=>listFiles(root, {
1695
+ changed,
1696
+ base: options.base
1697
+ }),
1698
+ touched: ()=>changedLines(root, {
1699
+ changed: true,
1700
+ base: options.base
1701
+ })
1702
+ });
1703
+ }
1704
+ async function cli_run(name, args, cwd, env) {
1705
+ if (!name) throw new UsageError('no command');
1706
+ const { config, rest } = splitConfig(args);
1707
+ const load = (root)=>loadSettings(root, config, cwd);
1708
+ const rule = RULES[name];
1709
+ if (rule) return await rule({
1710
+ cwd,
1711
+ args: rest,
1712
+ load
1713
+ });
1714
+ if ('config' === name) {
1715
+ if (rest.length) throw new UsageError('config takes no arguments');
1716
+ console.log(settingsJson(await load(repoRoot(cwd))));
1717
+ return 0;
1718
+ }
1719
+ return await cli_quality(name, rest, cwd, env, load);
1720
+ }
1721
+ async function main(argv, { cwd = process.cwd(), env = process.env } = {}) {
1722
+ const [name, ...rest] = argv;
1723
+ if ('-h' === name || '--help' === name) {
1724
+ console.log(USAGE);
1725
+ return 0;
1726
+ }
1727
+ try {
1728
+ return await cli_run(name, rest, cwd, env);
1729
+ } catch (error) {
1730
+ if (error instanceof ConfigError) {
1731
+ console.error(`repo-doctor: config: ${error.message}`);
1732
+ return EXIT_USAGE;
1733
+ }
1734
+ if (error instanceof UsageError) {
1735
+ console.error(`repo-doctor: ${error.message}\n\n${USAGE}`);
1736
+ return EXIT_USAGE;
1737
+ }
1738
+ const [line] = String(error?.message ?? error).split('\n');
1739
+ console.error(`repo-doctor: ${line}`);
1740
+ return EXIT_INTERNAL;
1741
+ }
1742
+ }
1743
+ export { USAGE, main, parseArgs };