@antelopejs/tooling-configs 0.2.17 → 0.2.18

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 (39) hide show
  1. package/README.md +27 -18
  2. package/dist/bin/api-diff.mjs +25 -14
  3. package/dist/bin/body-check.mjs +3 -3
  4. package/dist/bin/capture.d.mts +1 -0
  5. package/dist/bin/capture.mjs +559 -0
  6. package/dist/bin/check-size.mjs +3 -3
  7. package/dist/bin/checks.mjs +2 -2
  8. package/dist/bin/comment-proof.mjs +3 -3
  9. package/dist/bin/garden.mjs +1 -1
  10. package/dist/bin/ratchet.mjs +146 -100
  11. package/dist/bin/suppressions.mjs +5 -5
  12. package/dist/bin/sync.mjs +115 -169
  13. package/dist/bin/verify.mjs +238 -125
  14. package/dist/capture/index.d.mts +50 -0
  15. package/dist/capture/index.mjs +2 -0
  16. package/dist/{files-Bc036sJW.mjs → files-DJ0TeaTU.mjs} +10 -4
  17. package/dist/formal/index.d.mts +40 -0
  18. package/dist/formal/index.mjs +205 -0
  19. package/dist/oxc/anti-slop/index.mjs +717 -16
  20. package/dist/oxc/fmt.mjs +1 -1
  21. package/dist/oxc/guardrails/index.d.mts +1 -1
  22. package/dist/oxc/guardrails/index.mjs +93 -5
  23. package/dist/oxc/lint.d.mts +9 -0
  24. package/dist/oxc/lint.mjs +14 -3
  25. package/dist/{oxlint-Bltmk8-6.mjs → oxlint-DIV-lLSS.mjs} +7 -3
  26. package/dist/{package-DTxLPNDu.mjs → package-BRTjkzt5.mjs} +26 -1
  27. package/dist/{proof-stamp-w-3j47A-.mjs → proof-stamp-DDDC0J6l.mjs} +3 -3
  28. package/dist/{ratchet-DwRj9h4L.mjs → ratchet-BAcLRYuM.mjs} +194 -21
  29. package/dist/scenes-DZVXkcxS.mjs +104 -0
  30. package/dist/shared-igPpEDpS.mjs +622 -0
  31. package/dist/{size-DNtWruCO.mjs → size-DBatLT-F.mjs} +2 -2
  32. package/dist/{suppression-base-DAfCXwjL.mjs → suppression-base-9L8dlMQK.mjs} +36 -11
  33. package/dist/{suppression-budget-Bd2GqMYb.mjs → suppression-budget-C0SkPO5R.mjs} +56 -19
  34. package/dist/{suppressions-BD_f8f7L.mjs → suppressions-DM60NkvL.mjs} +1 -1
  35. package/dist/templates-CypDm-j9.mjs +121 -0
  36. package/dist/{typescript-BmS5BmrS.mjs → typescript-CM0LrVP7.mjs} +2 -2
  37. package/dist/verify/index.d.mts +6 -1
  38. package/package.json +28 -4
  39. package/dist/shared-CoUt4GUm.mjs +0 -73
package/dist/oxc/fmt.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { n as IGNORE_PATTERNS, t as AGENT_IGNORE_PATTERNS } from "../shared-CoUt4GUm.mjs";
1
+ import { n as IGNORE_PATTERNS, t as AGENT_IGNORE_PATTERNS } from "../shared-igPpEDpS.mjs";
2
2
  import { defineConfig } from "oxfmt";
3
3
  //#region src/oxc/fmt.ts
4
4
  /**
@@ -1,6 +1,6 @@
1
1
  import { n as TEST_FILE_GLOBS, t as ASSERTION_FUNCTION_NAMES } from "../../shared-BG0Nkzh0.mjs";
2
2
  //#region src/oxc/guardrails/index.d.ts
3
- /** AntelopeJS rules that reject comments, inherited-key lookups, presence-only type guards and low-evidence tests. */
3
+ /** AntelopeJS rules that reject comments, inherited-key lookups, presence-only type guards, low-evidence tests and files no tsconfig lists. */
4
4
  declare const guardrailsPlugin: import("@oxlint/plugins").Plugin;
5
5
  //#endregion
6
6
  export { ASSERTION_FUNCTION_NAMES, TEST_FILE_GLOBS, guardrailsPlugin as default };
@@ -1,7 +1,8 @@
1
1
  import { a as matcherChain, i as isAssertion, n as TEST_FILE_GLOBS, o as memberName, r as callName, s as testCallback, t as ASSERTION_FUNCTION_NAMES } from "../../shared-WC0z3y9F.mjs";
2
- import { lstatSync, readFileSync, realpathSync } from "node:fs";
3
- import { dirname, join } from "node:path";
2
+ import { existsSync, lstatSync, readFileSync, realpathSync } from "node:fs";
3
+ import { dirname, join, resolve } from "node:path";
4
4
  import { defineRule, eslintCompatPlugin } from "@oxlint/plugins";
5
+ import ts from "typescript";
5
6
  //#region src/oxc/guardrails/rules/no-comments.ts
6
7
  const allowedCommentForms = [
7
8
  {
@@ -583,6 +584,7 @@ const noInheritedKeyLookupRule = defineRule({
583
584
  //#endregion
584
585
  //#region src/oxc/guardrails/rules/no-presence-only-type-guard.ts
585
586
  const MAX_ALIAS_DEPTH = 8;
587
+ const OBJECT_PROTOTYPE_KEYS = Object.getOwnPropertyNames(Object.prototype);
586
588
  const OPEN_TYPES = /* @__PURE__ */ new Set(["TSUnknownKeyword", "TSAnyKeyword"]);
587
589
  const WIDE_TYPES = /* @__PURE__ */ new Set([...OPEN_TYPES, "TSObjectKeyword"]);
588
590
  function signatureName(member) {
@@ -632,6 +634,15 @@ function parameterType(fn, name) {
632
634
  if (binding.type === "Identifier" && binding.name === name) return binding.typeAnnotation?.typeAnnotation ?? void 0;
633
635
  }
634
636
  }
637
+ /**
638
+ * A key typed `prefix${string}` cannot name an inherited member when no `Object.prototype` member starts with that prefix.
639
+ * The prefix is the cooked text TypeScript reads, so `\x63onstructor` is `constructor`. A prefix with no cooked text is open.
640
+ */
641
+ function excludesPrototypeKeys(type) {
642
+ if (type?.type !== "TSTemplateLiteralType") return false;
643
+ const prefix = type.quasis[0]?.value.cooked;
644
+ return prefix !== void 0 && prefix !== null && !OBJECT_PROTOTYPE_KEYS.some((key) => key.startsWith(prefix));
645
+ }
635
646
  function isOpenRecord(type) {
636
647
  const value = type.typeArguments?.params[1];
637
648
  return referenceName(type) === "Record" && value !== void 0 && OPEN_TYPES.has(value.type);
@@ -818,7 +829,7 @@ const noPresenceOnlyTypeGuardRule = defineRule({
818
829
  const frame = active().at(-1);
819
830
  if (node.operator !== "in" || frame === void 0) return;
820
831
  if (node.left.type === "Identifier" && node.left.name === frame.name) {
821
- context.report({
832
+ if (!excludesPrototypeKeys(frame.parameter)) context.report({
822
833
  node,
823
834
  messageId: "inheritedKey",
824
835
  data: { key: frame.name }
@@ -1062,8 +1073,84 @@ const requireAssertionRule = defineRule({
1062
1073
  }
1063
1074
  });
1064
1075
  //#endregion
1076
+ //#region src/oxc/guardrails/tsconfig-program.ts
1077
+ const CONFIG_NAMES = ["tsconfig.json", "jsconfig.json"];
1078
+ const HOST = {
1079
+ ...ts.sys,
1080
+ onUnRecoverableConfigFileDiagnostic: () => void 0
1081
+ };
1082
+ const projects = /* @__PURE__ */ new Map();
1083
+ function configAbove(directory) {
1084
+ for (let current = directory;; current = dirname(current)) {
1085
+ const config = CONFIG_NAMES.map((name) => join(current, name)).find((path) => existsSync(path));
1086
+ if (config !== void 0) return config;
1087
+ if (dirname(current) === current) return void 0;
1088
+ }
1089
+ }
1090
+ /** The files `config` lists and the configs it references, parsed once per lint run. */
1091
+ function project(config) {
1092
+ if (projects.has(config)) return projects.get(config);
1093
+ const parsed = ts.getParsedCommandLineOfConfigFile(config, void 0, HOST);
1094
+ const result = parsed && {
1095
+ files: new Set(parsed.fileNames),
1096
+ references: (parsed.projectReferences ?? []).map((reference) => ts.resolveProjectReferencePath(reference))
1097
+ };
1098
+ projects.set(config, result);
1099
+ return result;
1100
+ }
1101
+ /** The first config the nearest one or its references reach that lists `file`, skipping configs already visited. */
1102
+ function listing(nearest, file, visited) {
1103
+ const queue = [nearest];
1104
+ for (let config = queue.shift(); config; config = queue.shift()) {
1105
+ if (visited.has(config)) continue;
1106
+ visited.add(config);
1107
+ const parsed = project(config);
1108
+ if (parsed?.files.has(file)) return config;
1109
+ queue.push(...parsed?.references ?? []);
1110
+ }
1111
+ }
1112
+ /**
1113
+ * The tsconfig.json or jsconfig.json whose program type-aware lint gives `file`,
1114
+ * found as oxlint-tsgolint finds it: the nearest config, the configs it references,
1115
+ * then the same search from each config above. Undefined when none lists the file,
1116
+ * where tsgolint reads it in its inferred program.
1117
+ */
1118
+ function programConfig(file) {
1119
+ const path = resolve(file).replaceAll("\\", "/");
1120
+ const visited = /* @__PURE__ */ new Set();
1121
+ let directory = dirname(path);
1122
+ for (;;) {
1123
+ const nearest = configAbove(directory);
1124
+ if (nearest === void 0) return void 0;
1125
+ const config = listing(nearest, path, visited);
1126
+ if (config !== void 0) return config;
1127
+ const parent = dirname(dirname(nearest));
1128
+ if (parent === dirname(nearest)) return void 0;
1129
+ directory = parent;
1130
+ }
1131
+ }
1132
+ //#endregion
1133
+ //#region src/oxc/guardrails/rules/require-tsconfig-include.ts
1134
+ const TYPE_LINTED = /\.[cm]?[jt]sx?$/u;
1135
+ /** A file type-aware lint reads must be listed by a tsconfig, or tsgolint types it without the repository's compiler options and `types`. */
1136
+ const requireTsconfigIncludeRule = defineRule({
1137
+ meta: {
1138
+ type: "problem",
1139
+ docs: { description: "Every file type-aware lint reads is listed by a tsconfig.json, so its findings use the repository's compiler options and types." },
1140
+ messages: { outside: "No tsconfig.json lists this file, so type-aware lint reads it in tsgolint's inferred program, without this repository's compiler options or `types`: Node and test-runner globals are error types, so `typescript/no-unsafe-*` reports here are false and findings that need those types go missing. List the file in a tsconfig.json that names the `types` it uses: one beside it that extends the root tsconfig, or, for a file at the root, a composite tsconfig that the root tsconfig references." }
1141
+ },
1142
+ createOnce(context) {
1143
+ return { Program(node) {
1144
+ if (TYPE_LINTED.test(context.filename) && programConfig(context.filename) === void 0) context.report({
1145
+ node,
1146
+ messageId: "outside"
1147
+ });
1148
+ } };
1149
+ }
1150
+ });
1151
+ //#endregion
1065
1152
  //#region src/oxc/guardrails/index.ts
1066
- /** AntelopeJS rules that reject comments, inherited-key lookups, presence-only type guards and low-evidence tests. */
1153
+ /** AntelopeJS rules that reject comments, inherited-key lookups, presence-only type guards, low-evidence tests and files no tsconfig lists. */
1067
1154
  const guardrailsPlugin = eslintCompatPlugin({
1068
1155
  meta: { name: "antelopejs" },
1069
1156
  rules: {
@@ -1074,7 +1161,8 @@ const guardrailsPlugin = eslintCompatPlugin({
1074
1161
  "no-constant-value-assertion": noConstantValueAssertionRule,
1075
1162
  "no-self-import-in-tests": noSelfImportInTestsRule,
1076
1163
  "no-typeof-function-only-test": noTypeofFunctionOnlyTestRule,
1077
- "require-assertion": requireAssertionRule
1164
+ "require-assertion": requireAssertionRule,
1165
+ "require-tsconfig-include": requireTsconfigIncludeRule
1078
1166
  }
1079
1167
  });
1080
1168
  //#endregion
@@ -194,6 +194,15 @@ declare function antelopePreset(options?: AntelopePresetOptions): {
194
194
  name: string;
195
195
  specifier: string;
196
196
  }[];
197
+ rules: {
198
+ "antelopejs/require-tsconfig-include": "off" | "error";
199
+ };
200
+ overrides: {
201
+ files: ("oxlint.config.ts" | "oxfmt.config.ts" | "knip.config.ts")[];
202
+ rules: {
203
+ "antelopejs/require-tsconfig-include": "off";
204
+ };
205
+ }[];
197
206
  } | {
198
207
  rules: {
199
208
  "eslint/max-params": ["error", {
package/dist/oxc/lint.mjs CHANGED
@@ -1,7 +1,8 @@
1
1
  import { i as findGitRoot } from "../ceilings-B7KayYIG.mjs";
2
2
  import { t as readCarriedCeilings } from "../renames-L2owF5GD.mjs";
3
+ import { t as PRESET_CONFIGS } from "../templates-CypDm-j9.mjs";
3
4
  import { n as TEST_FILE_GLOBS, t as ASSERTION_FUNCTION_NAMES } from "../shared-WC0z3y9F.mjs";
4
- import { n as IGNORE_PATTERNS, r as SYNCED_AGENT_PATTERNS } from "../shared-CoUt4GUm.mjs";
5
+ import { n as IGNORE_PATTERNS, r as SYNCED_AGENT_PATTERNS } from "../shared-igPpEDpS.mjs";
5
6
  import { defineConfig } from "oxlint";
6
7
  //#region src/oxc/lint.ts
7
8
  /**
@@ -129,12 +130,22 @@ function guardrailsRules() {
129
130
  }]
130
131
  });
131
132
  }
132
- function guardrailsPreset() {
133
+ /**
134
+ * With type-aware lint, a file no tsconfig lists is reported. The root configs
135
+ * `antelopejs-sync` writes are exempt: a tsconfig that builds `src` reaches them
136
+ * only through a referenced composite tsconfig, which every repository would need.
137
+ */
138
+ function guardrailsPreset(typeAware) {
133
139
  return defineConfig({
134
140
  extends: [guardrailsRules()],
135
141
  jsPlugins: [{
136
142
  name: "antelopejs",
137
143
  specifier: "@antelopejs/tooling-configs/oxc/guardrails"
144
+ }],
145
+ rules: { "antelopejs/require-tsconfig-include": typeAware ? "error" : "off" },
146
+ overrides: [{
147
+ files: PRESET_CONFIGS.map(({ path }) => path),
148
+ rules: { "antelopejs/require-tsconfig-include": "off" }
138
149
  }]
139
150
  });
140
151
  }
@@ -226,7 +237,7 @@ function antelopePreset(options = {}) {
226
237
  basePreset(options.importCycles !== false),
227
238
  options.typeAware === false ? null : typeAwarePreset(),
228
239
  options.antiSlop === false ? null : antiSlopPreset(),
229
- options.guardrails === false ? null : guardrailsPreset(),
240
+ options.guardrails === false ? null : guardrailsPreset(options.typeAware !== false),
230
241
  options.complexity === false ? null : complexityPreset(thresholds),
231
242
  options.importSorting === true ? importSortingPreset() : null
232
243
  ].filter((config) => config !== null),
@@ -1,10 +1,11 @@
1
1
  import { r as MEASURE_ENV } from "./ceilings-B7KayYIG.mjs";
2
- import { a as repositoryPath } from "./files-Bc036sJW.mjs";
2
+ import { s as repositoryPath } from "./files-DJ0TeaTU.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
5
5
  import { basename, dirname, join } from "node:path";
6
6
  import { spawnSync } from "node:child_process";
7
7
  //#region src/guardrails/oxlint.ts
8
+ const TSCONFIG_ERROR = "typescript/tsconfig-error";
8
9
  function resolveOxlint(root) {
9
10
  try {
10
11
  const require = createRequire(join(root, "package.json"));
@@ -73,8 +74,11 @@ function runOxlint(root, config, files, flags) {
73
74
  });
74
75
  }
75
76
  }
76
- function lintDiagnostics(root, config, files) {
77
- return runOxlint(root, config, files, []).map((item) => toDiagnostic(item, root));
77
+ function lintDiagnostics(root, config, files, { rejectBrokenProject = false } = {}) {
78
+ const diagnostics = runOxlint(root, config, files, []).map((item) => toDiagnostic(item, root));
79
+ const broken = rejectBrokenProject ? diagnostics.find(({ rule }) => rule === TSCONFIG_ERROR) : void 0;
80
+ if (broken) throw new Error(`${broken.location}: ${broken.message}${broken.help ? ` ${broken.help}` : ""}. The type-aware rules cannot be measured until the TypeScript project loads.`);
81
+ return diagnostics;
78
82
  }
79
83
  const UNUSED_RULES = /\(no problems were reported from (.+)\)/u;
80
84
  /**
@@ -115,9 +115,34 @@ function managedPackage(current, versions, options = {}) {
115
115
  dependencies.knip ??= versions.knip;
116
116
  if (options.typeAware) dependencies["oxlint-tsgolint"] ??= versions.tsgolint;
117
117
  manifest.devDependencies = Object.fromEntries(Object.entries(dependencies).sort(([a], [b]) => a.localeCompare(b)));
118
+ return serializeManifest(manifest, current);
119
+ }
120
+ /**
121
+ * The template profile owns only the scripts `antelopejs-checks` requires and
122
+ * the profile's `sync` scripts do not provide. An already complete manifest is
123
+ * returned unchanged, so a template is never reformatted for nothing.
124
+ */
125
+ function templatePackage(current, options) {
126
+ if (current === void 0) throw new Error("package.json is missing.");
127
+ const manifest = parseManifest(current);
128
+ const commands = repositoryTools(manifest).commands;
129
+ const wanted = {
130
+ suppressions: commands.suppressions,
131
+ "suppressions:update": `${commands.suppressions} --update`,
132
+ ...options.ratchet && {
133
+ ratchet: commands.ratchet,
134
+ "ratchet:update": `${commands.ratchet} --update`
135
+ }
136
+ };
137
+ const scripts = manifest.scripts ??= {};
138
+ if (Object.entries(wanted).every(([name, command]) => scripts[name] === command)) return current;
139
+ Object.assign(scripts, wanted);
140
+ return serializeManifest(manifest, current);
141
+ }
142
+ function serializeManifest(manifest, current) {
118
143
  const indent = /^([\t ]+)"/m.exec(current)?.[1] ?? " ";
119
144
  const newline = current.includes("\r\n") ? "\r\n" : "\n";
120
145
  return `${JSON.stringify(manifest, null, indent).replaceAll("\n", newline)}${newline}`;
121
146
  }
122
147
  //#endregion
123
- export { repositoryTools as a, parseManifest as i, managedPackage as n, toolingVersions as o, packageManager as r, execCommand as t };
148
+ export { repositoryTools as a, parseManifest as i, managedPackage as n, templatePackage as o, packageManager as r, toolingVersions as s, execCommand as t };
@@ -1,10 +1,10 @@
1
- import { c as trackedManifests, s as resolveRevision } from "./files-Bc036sJW.mjs";
2
- import { o as revisionSuppressions, r as countSuppressions } from "./suppressions-BD_f8f7L.mjs";
1
+ import { l as resolveRevision, u as trackedManifests } from "./files-DJ0TeaTU.mjs";
2
+ import { o as revisionSuppressions, r as countSuppressions } from "./suppressions-DM60NkvL.mjs";
3
3
  import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from "node:fs";
4
4
  import { dirname, join, matchesGlob } from "node:path";
5
5
  import { execFileSync, spawnSync } from "node:child_process";
6
- import { tmpdir } from "node:os";
7
6
  import { createHash } from "node:crypto";
7
+ import { tmpdir } from "node:os";
8
8
  //#region src/guardrails/added-entries.ts
9
9
  function createAddedPolicy(globs) {
10
10
  return {
@@ -1,13 +1,14 @@
1
1
  import { a as formatCeilings, c as parseCeilings, n as MAX_FILE_BYTES, o as isPackRelease, s as isRetired, t as CEILINGS_FILE } from "./ceilings-B7KayYIG.mjs";
2
2
  import { n as renamedPaths, t as readCarriedCeilings } from "./renames-L2owF5GD.mjs";
3
- import { n as changedFiles, t as authoredSizes } from "./files-Bc036sJW.mjs";
4
- import { o as toolingVersions } from "./package-DTxLPNDu.mjs";
5
- import { t as lintDiagnostics } from "./oxlint-Bltmk8-6.mjs";
6
- import "./suppression-budget-Bd2GqMYb.mjs";
7
- import { n as sizeFailure } from "./size-DNtWruCO.mjs";
8
- import { existsSync, unlinkSync, writeFileSync } from "node:fs";
9
- import { join } from "node:path";
10
- import { spawnSync } from "node:child_process";
3
+ import { s as toolingVersions } from "./package-BRTjkzt5.mjs";
4
+ import { n as authoredSizes, o as isAgentFile, r as changedFiles, t as LINT_CONFIG } from "./files-DJ0TeaTU.mjs";
5
+ import { t as lintDiagnostics } from "./oxlint-DIV-lLSS.mjs";
6
+ import "./suppression-budget-C0SkPO5R.mjs";
7
+ import { n as sizeFailure } from "./size-DBatLT-F.mjs";
8
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
9
+ import { dirname, join } from "node:path";
10
+ import { execFileSync, spawnSync } from "node:child_process";
11
+ import { tmpdir } from "node:os";
11
12
  //#region src/guardrails/adoption.ts
12
13
  /**
13
14
  * Each rule the preset turned on after repositories recorded their ratchet,
@@ -19,12 +20,15 @@ import { spawnSync } from "node:child_process";
19
20
  const PACK_NEW_RULES = /* @__PURE__ */ new Map([
20
21
  ["antelopejs/no-inherited-key-lookup", "0.2.17"],
21
22
  ["antelopejs/no-presence-only-type-guard", "0.2.17"],
23
+ ["antelopejs/require-tsconfig-include", "0.2.18"],
22
24
  ["typescript/no-unnecessary-type-parameters", "0.2.17"],
23
25
  ["typescript/no-unsafe-argument", "0.2.17"],
24
26
  ["typescript/no-unsafe-assignment", "0.2.17"],
25
27
  ["typescript/no-unsafe-return", "0.2.17"],
26
28
  ["typescript/use-unknown-in-catch-callback-variable", "0.2.17"]
27
29
  ]);
30
+ /** The first pack release whose size guard counts a repository's own files under the agent directories; `ratchet:update` records the oversize ones once, in a repository recorded before it. */
31
+ const AGENT_FILES_RELEASE = "0.2.18";
28
32
  function parts(release) {
29
33
  return release.split(".").map(Number);
30
34
  }
@@ -79,15 +83,122 @@ function newlyEnabled(rule, adopted) {
79
83
  if (since === void 0) return void 0;
80
84
  return adopted === void 0 || compareReleases(since, adopted) > 0 ? since : void 0;
81
85
  }
82
- /** The release an update records: the latest of `adopted`, the installed pack and every listed rule's release, so no listed rule is adopted twice. */
86
+ /** Whether `adopted` predates the release that began counting the repository's own agent files in the size guard. */
87
+ function agentFilesPending(adopted) {
88
+ return adopted === void 0 || compareReleases("0.2.18", adopted) > 0;
89
+ }
90
+ /** The release an update records: the latest of `adopted`, the installed pack and every listed rule's release and the agent files' release, so none is adopted twice. */
83
91
  function recordedRelease(adopted) {
84
92
  return latest([
85
93
  adopted,
86
94
  toolingVersions().pack,
95
+ "0.2.18",
87
96
  ...PACK_NEW_RULES.values()
88
97
  ]) ?? "0.0.0";
89
98
  }
90
99
  //#endregion
100
+ //#region src/guardrails/previous-tree.ts
101
+ function git(root, args, env, input = "") {
102
+ return execFileSync("git", args, {
103
+ cwd: root,
104
+ encoding: "utf8",
105
+ env: {
106
+ ...process.env,
107
+ ...env
108
+ },
109
+ input,
110
+ maxBuffer: 268435456
111
+ });
112
+ }
113
+ function revisionEntries(root, revision) {
114
+ const entries = /* @__PURE__ */ new Map();
115
+ for (const entry of git(root, [
116
+ "ls-tree",
117
+ "-r",
118
+ "-z",
119
+ revision
120
+ ], {}).split("\0")) {
121
+ const tab = entry.indexOf(" ");
122
+ if (tab > 0) entries.set(entry.slice(tab + 1), entry.slice(0, tab));
123
+ }
124
+ return entries;
125
+ }
126
+ /** Links the `node_modules` of the repository root and of each tracked package into `tree`, so the checkout resolves dependencies as the real one does. */
127
+ function linkModules(root, tree, env) {
128
+ const manifests = git(root, [
129
+ "ls-files",
130
+ "-z",
131
+ "--",
132
+ "package.json",
133
+ ":(glob)**/package.json"
134
+ ], env).split("\0").filter(Boolean);
135
+ for (const manifest of manifests) {
136
+ const directory = dirname(manifest);
137
+ const modules = join(root, directory, "node_modules");
138
+ const target = join(tree, directory, "node_modules");
139
+ if (existsSync(modules) && !existsSync(target)) symlinkSync(modules, target, "dir");
140
+ }
141
+ }
142
+ /**
143
+ * Runs `use` on a checkout of the index in which each of `paths` holds its
144
+ * content at `revision`, or is absent when `revision` does not have it or does
145
+ * not exist, so the files are linted under the staged configuration. The
146
+ * checkout is deleted afterwards. With `wholeIndex`, files the index marks
147
+ * skip-worktree (a sparse checkout) are written too, so the tree is the commit,
148
+ * and an empty `.git` stops ignore-file lookups at the tree, not above `TMPDIR`.
149
+ */
150
+ function withPreviousTree(root, revision, paths, use, { wholeIndex = false } = {}) {
151
+ const scratch = mkdtempSync(join(tmpdir(), "antelopejs-previous."));
152
+ try {
153
+ const exists = spawnSync("git", [
154
+ "rev-parse",
155
+ "--verify",
156
+ `${revision}^{commit}`
157
+ ], {
158
+ cwd: root,
159
+ stdio: "ignore"
160
+ }).status === 0;
161
+ const index = join(scratch, "index");
162
+ copyFileSync(git(root, [
163
+ "rev-parse",
164
+ "--path-format=absolute",
165
+ "--git-path",
166
+ "index"
167
+ ], {}).trim(), index);
168
+ const env = { GIT_INDEX_FILE: index };
169
+ const head = exists ? revisionEntries(root, revision) : /* @__PURE__ */ new Map();
170
+ const restored = paths.filter((path) => head.has(path));
171
+ const removed = paths.filter((path) => !head.has(path));
172
+ if (restored.length) git(root, [
173
+ "update-index",
174
+ "-z",
175
+ "--index-info"
176
+ ], env, restored.map((path) => `${head.get(path)}\t${path}\0`).join(""));
177
+ if (removed.length) git(root, [
178
+ "update-index",
179
+ "-z",
180
+ "--force-remove",
181
+ "--stdin"
182
+ ], env, removed.map((path) => `${path}\0`).join(""));
183
+ const tree = join(scratch, "tree");
184
+ git(root, [
185
+ "checkout-index",
186
+ "-a",
187
+ "-f",
188
+ ...wholeIndex ? ["--ignore-skip-worktree-bits"] : [],
189
+ `--prefix=${tree}/`
190
+ ], env);
191
+ if (wholeIndex) mkdirSync(join(tree, ".git"), { recursive: true });
192
+ linkModules(root, tree, env);
193
+ return use(tree);
194
+ } finally {
195
+ rmSync(scratch, {
196
+ recursive: true,
197
+ force: true
198
+ });
199
+ }
200
+ }
201
+ //#endregion
91
202
  //#region src/guardrails/ratchet-raises.ts
92
203
  function committed(root, revision, path) {
93
204
  const result = spawnSync("git", ["show", `${revision}:${path}`], {
@@ -96,6 +207,17 @@ function committed(root, revision, path) {
96
207
  });
97
208
  return result.status === 0 ? result.stdout : void 0;
98
209
  }
210
+ function committedSize(root, revision, path) {
211
+ const result = spawnSync("git", [
212
+ "cat-file",
213
+ "-s",
214
+ `${revision}:${path}`
215
+ ], {
216
+ cwd: root,
217
+ encoding: "utf8"
218
+ });
219
+ return result.status === 0 ? Number(result.stdout) : void 0;
220
+ }
99
221
  function packFailure(base, ceilings) {
100
222
  if (base.pack === void 0) return [];
101
223
  if (ceilings.pack === void 0) return [`${CEILINGS_FILE}: drops the recorded pack release ${base.pack} the base has.`];
@@ -105,7 +227,33 @@ function notNewlyEnabled(rule, adopted) {
105
227
  const since = PACK_NEW_RULES.get(rule);
106
228
  return since === void 0 ? `${CEILINGS_FILE}: adds ${rule}, which the pack did not newly enable.` : `${CEILINGS_FILE}: adds ${rule}, which the pack enabled in ${since}, not after this repository's ${adopted ?? since}.`;
107
229
  }
108
- function ruleFailures$1(base, ceilings, measured, adopted) {
230
+ /** The rules' finding counts over the tree at `revision`, linted under the current configuration; the repository's files that differ from `revision` are restored to it. */
231
+ function countsAtRevision(root, revision) {
232
+ return withPreviousTree(root, revision, execFileSync("git", [
233
+ "diff",
234
+ "--cached",
235
+ "--name-only",
236
+ "--no-renames",
237
+ "-z",
238
+ revision
239
+ ], {
240
+ cwd: root,
241
+ encoding: "utf8"
242
+ }).split("\0").filter((file) => file && !LINT_CONFIG.test(file)), (tree) => {
243
+ const counts = /* @__PURE__ */ new Map();
244
+ for (const { rule } of lintDiagnostics(tree)) counts.set(rule, (counts.get(rule) ?? 0) + 1);
245
+ return counts;
246
+ });
247
+ }
248
+ /** Counts a rule's findings at the base revision, linting it once and only when an adoption asks. */
249
+ function baseCounter(root, revision) {
250
+ let counts;
251
+ return (rule) => {
252
+ counts ??= countsAtRevision(root, revision);
253
+ return counts.get(rule) ?? 0;
254
+ };
255
+ }
256
+ function ruleFailures$1(base, ceilings, measured, adopted, countAtBase) {
109
257
  const failures = [];
110
258
  for (const [rule, limit] of Object.entries(ceilings.rules)) {
111
259
  const before = base.rules[rule];
@@ -114,22 +262,32 @@ function ruleFailures$1(base, ceilings, measured, adopted) {
114
262
  if (limit > before) failures.push(`${CEILINGS_FILE}: raises ${rule} from ${before} on the base to ${limit}.`);
115
263
  } else if (newlyEnabled(rule, adopted) === void 0) failures.push(notNewlyEnabled(rule, adopted));
116
264
  else if (limit > count) failures.push(`${CEILINGS_FILE}: adds ${rule} at ${limit}, above its ${count} findings.`);
265
+ else {
266
+ const atBase = countAtBase(rule);
267
+ if (limit > atBase) failures.push(`${CEILINGS_FILE}: adds ${rule} at ${limit}, above its ${atBase} findings on the base.`);
268
+ }
117
269
  }
118
270
  return failures;
119
271
  }
120
- function oversizeFailures(base, ceilings, renames) {
272
+ function oversizeFailures({ root, revision, renames, adopted }, base, ceilings, measured) {
121
273
  const failures = [];
122
274
  for (const [file, limit] of Object.entries(ceilings.oversizeFiles)) {
123
275
  const before = base.oversizeFiles[file] ?? base.oversizeFiles[renames.get(file) ?? file];
124
- if (before === void 0) failures.push(`${CEILINGS_FILE}: adds an oversize allowance for ${file}.`);
125
- else if (limit > before) failures.push(`${CEILINGS_FILE}: raises the oversize allowance of ${file} from ${before} bytes on the base to ${limit}.`);
276
+ if (before === void 0) {
277
+ const existing = isAgentFile(file) && agentFilesPending(adopted) ? committedSize(root, revision, renames.get(file) ?? file) : void 0;
278
+ if (existing === void 0) failures.push(`${CEILINGS_FILE}: adds an oversize allowance for ${file}.`);
279
+ else if (limit > Math.min(existing, measured.oversizeFiles[file] ?? 0)) failures.push(`${CEILINGS_FILE}: raises the oversize allowance of ${file} from ${existing} bytes on the base to ${limit}.`);
280
+ } else if (limit > before) failures.push(`${CEILINGS_FILE}: raises the oversize allowance of ${file} from ${before} bytes on the base to ${limit}.`);
126
281
  }
127
282
  return failures;
128
283
  }
129
284
  /**
130
285
  * Fails each ceiling of `ceilings` added or raised against the ratchet file
131
286
  * at `revision`, except a rule the pack enabled after the base's adopted
132
- * release, recorded at no more than its `measured` count; and a recorded pack
287
+ * release, recorded at no more than its `measured` count and its count in the
288
+ * tree at `revision`, and an oversize
289
+ * agent file that exists at the base, allowed at no more than its size there
290
+ * and its measured size, while the base predates counting those files; and a recorded pack
133
291
  * release dropped or lowered. Renamed files keep their allowance. A base with
134
292
  * neither a ratchet file nor a suppression budget, a first adoption, passes.
135
293
  */
@@ -140,10 +298,16 @@ function raisedRatchet(root, revision, ceilings, measured) {
140
298
  rules: {},
141
299
  oversizeFiles: {}
142
300
  } : parseCeilings(text, `${revision.slice(0, 12)}:${CEILINGS_FILE}`);
301
+ const adopted = adoptedRelease(root, base.pack, revision);
143
302
  const failures = [
144
303
  ...packFailure(base, ceilings),
145
- ...ruleFailures$1(base, ceilings, measured, adoptedRelease(root, base.pack, revision)),
146
- ...oversizeFailures(base, ceilings, renamedPaths(root, false, [revision]))
304
+ ...ruleFailures$1(base, ceilings, measured, adopted, baseCounter(root, revision)),
305
+ ...oversizeFailures({
306
+ root,
307
+ revision,
308
+ renames: renamedPaths(root, false, [revision]),
309
+ adopted
310
+ }, base, ceilings, measured)
147
311
  ];
148
312
  return failures.length ? [...failures, "Ceilings only go down: ratchet:update lowers them and records only the rules the pack newly enabled. Fix the code; raising a ceiling needs the operator's approval through the ruleset bypass."] : [];
149
313
  }
@@ -183,7 +347,7 @@ function lowerCeilings(ceilings, current) {
183
347
  }
184
348
  return lowered;
185
349
  }
186
- /** Records today's count of each rule without a ceiling that the pack enabled after `adopted`. */
350
+ /** Records today's count of each rule without a ceiling that the pack enabled after `adopted`, and the size of each oversize agent file without an allowance when the repository predates counting them. */
187
351
  function adopt(ceilings, current, adopted) {
188
352
  const adoptions = [];
189
353
  for (const [rule, count] of Object.entries(current.rules)) {
@@ -193,6 +357,11 @@ function adopt(ceilings, current, adopted) {
193
357
  ceilings.rules[rule] = count;
194
358
  adoptions.push(`${rule}: ${count}, enabled by the pack in ${since}.`);
195
359
  }
360
+ if (agentFilesPending(adopted)) for (const [file, size] of Object.entries(current.oversizeFiles)) {
361
+ if (!isAgentFile(file) || Object.hasOwn(ceilings.oversizeFiles, file)) continue;
362
+ ceilings.oversizeFiles[file] = size;
363
+ adoptions.push(`${file}: ${size} bytes, counted by the size guard from ${AGENT_FILES_RELEASE}.`);
364
+ }
196
365
  return adoptions;
197
366
  }
198
367
  function adoptionHint(rule, ceilings, adopted) {
@@ -214,9 +383,13 @@ function ruleFailures(ceilings, current, diagnostics, changed, adopted) {
214
383
  }
215
384
  return failures;
216
385
  }
217
- function sizeFailures(root, ceilings, current) {
386
+ function sizeFailures(root, ceilings, current, adopted) {
218
387
  const failures = [];
219
- for (const [file, size] of Object.entries(current.oversizeFiles)) if (ceilings.oversizeFiles[file] === void 0) failures.push(size > 2e4 ? sizeFailure(file, size, MAX_FILE_BYTES) : `${file}: ${size} bytes and an eslint/max-lines diagnostic; this file has no oversize allowance. Split by responsibility into sibling modules, or split tests by behaviour under test, one file per describe.`);
388
+ for (const [file, size] of Object.entries(current.oversizeFiles)) {
389
+ if (ceilings.oversizeFiles[file] !== void 0) continue;
390
+ const hint = isAgentFile(file) && agentFilesPending(adopted) ? ` The size guard counts the repository's own agent files from ${AGENT_FILES_RELEASE}; run ratchet:update to record today's size.` : "";
391
+ failures.push(`${size > 2e4 ? sizeFailure(file, size, MAX_FILE_BYTES) : `${file}: ${size} bytes and an eslint/max-lines diagnostic; this file has no oversize allowance. Split by responsibility into sibling modules, or split tests by behaviour under test, one file per describe.`}${hint}`);
392
+ }
220
393
  const sizes = authoredSizes(root, Object.keys(ceilings.oversizeFiles));
221
394
  for (const [file, limit] of Object.entries(ceilings.oversizeFiles)) {
222
395
  const size = sizes.get(file);
@@ -255,7 +428,7 @@ function ratchet(root, update = false, base = "HEAD", pullBase) {
255
428
  const diagnostics = lintDiagnostics(root);
256
429
  const current = baseline(root, diagnostics);
257
430
  const adoptions = update ? adopt(ceilings, current, adopted) : [];
258
- const failures = [...ruleFailures(ceilings, current, diagnostics, changedFiles(root), adopted), ...sizeFailures(root, ceilings, current)];
431
+ const failures = [...ruleFailures(ceilings, current, diagnostics, changedFiles(root), adopted), ...sizeFailures(root, ceilings, current, adopted)];
259
432
  const lowered = update ? lowerCeilings(ceilings, current) : [];
260
433
  if (update) ceilings.pack = recordedRelease(adopted);
261
434
  if (pullBase !== void 0) failures.push(...raisedRatchet(root, pullBase, ceilings, current));
@@ -272,4 +445,4 @@ function ratchet(root, update = false, base = "HEAD", pullBase) {
272
445
  };
273
446
  }
274
447
  //#endregion
275
- export { ratchet as n, recordedRelease as r, measureBaseline as t };
448
+ export { recordedRelease as i, ratchet as n, withPreviousTree as r, measureBaseline as t };