@tayomi/deterministic-gates 0.0.0-stage → 0.4.1

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 (49) hide show
  1. package/.claude-plugin/marketplace.json +15 -0
  2. package/.claude-plugin/plugin.json +14 -0
  3. package/.codex-plugin/plugin.json +20 -0
  4. package/LICENSE +21 -0
  5. package/README.md +111 -2
  6. package/catalog/go.json +92 -0
  7. package/catalog/index.html +398 -0
  8. package/catalog/python.json +46 -0
  9. package/catalog/typescript.json +125 -0
  10. package/dist/src/cli.js +65 -0
  11. package/dist/src/core/check.js +157 -0
  12. package/dist/src/core/config.js +180 -0
  13. package/dist/src/core/json.js +32 -0
  14. package/dist/src/core/report-cache.js +35 -0
  15. package/dist/src/core/report.js +127 -0
  16. package/dist/src/core/run.js +172 -0
  17. package/dist/src/core/send-back.js +53 -0
  18. package/dist/src/core/snapshot.js +94 -0
  19. package/dist/src/core/turn-state.js +93 -0
  20. package/dist/src/core/waive-line.js +15 -0
  21. package/dist/src/helpers/new-clones.js +57 -0
  22. package/dist/src/helpers/new-suppressions.js +31 -0
  23. package/dist/src/helpers/related-tests.js +109 -0
  24. package/dist/src/helpers/test-reporter.js +57 -0
  25. package/dist/src/hook/display.js +22 -0
  26. package/dist/src/hook/hook.js +119 -0
  27. package/hooks/claude.json +17 -0
  28. package/hooks/hooks.json +38 -0
  29. package/hooks/register.ts +12 -0
  30. package/package.json +51 -4
  31. package/src/catalog/catalog.ts +168 -0
  32. package/src/cli.ts +61 -0
  33. package/src/core/check.ts +209 -0
  34. package/src/core/config.ts +225 -0
  35. package/src/core/json.ts +36 -0
  36. package/src/core/report-cache.ts +51 -0
  37. package/src/core/report.ts +159 -0
  38. package/src/core/run.ts +217 -0
  39. package/src/core/send-back.ts +87 -0
  40. package/src/core/snapshot.ts +105 -0
  41. package/src/core/turn-state.ts +153 -0
  42. package/src/core/waive-line.ts +19 -0
  43. package/src/helpers/new-clones.ts +58 -0
  44. package/src/helpers/new-suppressions.ts +44 -0
  45. package/src/helpers/related-tests.ts +119 -0
  46. package/src/helpers/test-reporter.ts +71 -0
  47. package/src/hook/display.ts +21 -0
  48. package/src/hook/hook.ts +144 -0
  49. package/src/testing.ts +39 -0
@@ -0,0 +1,172 @@
1
+ import { execFile } from "node:child_process";
2
+ import { accessSync, constants, existsSync } from "node:fs";
3
+ import { delimiter, isAbsolute, join, resolve, sep } from "node:path";
4
+ import { stripVTControlCharacters } from "node:util";
5
+ import { FILES, isCompared, TURN } from "./config.js";
6
+ import { isRecord, messageOf, readJsonFile } from "./json.js";
7
+ /** A gate that judged the turn and found a problem: the only kind that sends the agent back. */
8
+ export function failed(outcome) {
9
+ return !outcome.ok && !outcome.timedOut;
10
+ }
11
+ const ENGINE = resolve(import.meta.dirname, "..", "..");
12
+ const MAX_OUTPUT_MB = 16;
13
+ const ENGINE_PREFIX = "{engine}/";
14
+ /** A script of this engine: its .ts source, or the .js it is built to when the engine runs from its npm package. */
15
+ function engineScript(name) {
16
+ const file = resolve(ENGINE, name);
17
+ return file.endsWith(".ts") && !existsSync(file) ? `${file.slice(0, -".ts".length)}.js` : file;
18
+ }
19
+ // A script of the repo runs on the interpreter of its extension.
20
+ const INTERPRETERS = [
21
+ [/\.(ts|js|mjs)$/, process.execPath],
22
+ [/\.py$/, "python3"],
23
+ ];
24
+ /** The script of a package of the repo's node_modules, or nothing when the repo does not have the package. */
25
+ export function packageScript(root, name) {
26
+ const dir = resolve(root, "node_modules", name);
27
+ const manifest = readJsonFile(resolve(dir, "package.json"));
28
+ if (manifest === undefined)
29
+ return undefined;
30
+ const bin = isRecord(manifest) ? manifest.bin : undefined;
31
+ const commands = isRecord(bin) ? bin : {};
32
+ const script = typeof bin === "string" ? bin : (commands[name] ?? Object.values(commands)[0]);
33
+ if (typeof script !== "string")
34
+ throw new Error(`${name} has no command.`);
35
+ return resolve(dir, script);
36
+ }
37
+ /**
38
+ * Resolves the first word of a gate's command, in this order: a script of this engine under {engine}/, a script of the
39
+ * repo by its extension, a package of the repo's node_modules, then a program: by its path in the repo, or by its name
40
+ * on the PATH.
41
+ */
42
+ export function commandOf(root, name) {
43
+ if (name.startsWith(ENGINE_PREFIX)) {
44
+ return { file: process.execPath, args: [engineScript(name.slice(ENGINE_PREFIX.length))], missing: "" };
45
+ }
46
+ const interpreter = INTERPRETERS.find(([extension]) => extension.test(name))?.[1];
47
+ if (interpreter !== undefined) {
48
+ return {
49
+ file: interpreter,
50
+ args: [resolve(root, name)],
51
+ missing: `${interpreter} is not installed, and ${name} needs it.`,
52
+ };
53
+ }
54
+ const script = packageScript(root, name);
55
+ if (script !== undefined)
56
+ return { file: process.execPath, args: [script], missing: "" };
57
+ if (name.includes("/"))
58
+ return { file: resolve(root, name), args: [], missing: `${name} does not exist.` };
59
+ return {
60
+ file: name,
61
+ args: [],
62
+ missing: `${name} is not installed: it is neither a package of node_modules nor a program on the PATH.`,
63
+ };
64
+ }
65
+ // A program by its path, or by its name on the PATH, that the system would execute.
66
+ function executable(file) {
67
+ const candidates = isAbsolute(file)
68
+ ? [file]
69
+ : (process.env.PATH ?? "").split(delimiter).map((dir) => join(dir, file));
70
+ return candidates.some((candidate) => {
71
+ try {
72
+ accessSync(candidate, constants.X_OK);
73
+ return true;
74
+ }
75
+ catch {
76
+ return false;
77
+ }
78
+ });
79
+ }
80
+ /**
81
+ * Why the program of a gate cannot run on this machine, or nothing when it can: looked up as the gate would start it,
82
+ * without starting it. A command the engine cannot resolve is left to the run, which reports it.
83
+ */
84
+ export function missingTool(root, gate) {
85
+ let command;
86
+ try {
87
+ command = commandOf(root, gate.run[0] ?? "");
88
+ }
89
+ catch {
90
+ return undefined;
91
+ }
92
+ return command.missing && !executable(command.file) ? command.missing : undefined;
93
+ }
94
+ export function argumentsOf(gate, files, turn) {
95
+ return gate.run.slice(1).flatMap((argument) => (argument === FILES ? files : [argument.replaceAll(TURN, turn)]));
96
+ }
97
+ /** Whether the gate is given the changed files, where another reads the whole project. */
98
+ export function givenFiles(gate) {
99
+ return gate.run.includes(FILES);
100
+ }
101
+ export function filesOf(gate, changed) {
102
+ const pattern = new RegExp(gate.files);
103
+ return changed.filter((file) => pattern.test(file));
104
+ }
105
+ export function newLines(before, after, ignore) {
106
+ const ignored = ignore === undefined ? undefined : new RegExp(ignore);
107
+ const seen = new Set(before.split("\n").map((line) => line.trim()));
108
+ return after
109
+ .split("\n")
110
+ .map((line) => line.trim())
111
+ .filter((line) => line && !seen.has(line) && !ignored?.test(line));
112
+ }
113
+ async function execute(root, gate, args) {
114
+ const started = performance.now();
115
+ const [name = ""] = gate.run;
116
+ // A gate that cannot start fails alone: the other gates of the turn still report.
117
+ let command;
118
+ try {
119
+ command = commandOf(root, name);
120
+ }
121
+ catch (error) {
122
+ return { ok: false, output: messageOf(error), ms: performance.now() - started, timedOut: false };
123
+ }
124
+ return new Promise((resolve) => {
125
+ execFile(command.file, [...command.args, ...args], {
126
+ cwd: root,
127
+ timeout: gate.timeoutSeconds * 1000,
128
+ maxBuffer: MAX_OUTPUT_MB * 1024 * 1024,
129
+ env: { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0" },
130
+ }, (error, stdout, stderr) => {
131
+ resolve({
132
+ ok: !error,
133
+ output: outputOf(root, gate, command, error, `${stdout}${stderr}`),
134
+ ms: performance.now() - started,
135
+ timedOut: error?.killed === true && error.code !== "ERR_CHILD_PROCESS_STDIO_MAXBUFFER",
136
+ });
137
+ });
138
+ });
139
+ }
140
+ function outputOf(root, gate, command, error, printed) {
141
+ if (error?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER")
142
+ return `Printed more than ${MAX_OUTPUT_MB} MB: too much for the end of a turn. Make it quieter, or move it to CI.`;
143
+ if (error?.killed === true)
144
+ return `Out of time after ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
145
+ if (error?.code === "ENOENT")
146
+ return command.missing;
147
+ // Some tools colour despite NO_COLOR, and absolute paths only cost the agent tokens.
148
+ const said = stripVTControlCharacters(printed).split(`${root}${sep}`).join("").trim();
149
+ if (said || !error)
150
+ return said;
151
+ return `exit code ${String(error.code)}, no output`;
152
+ }
153
+ /** Runs a compared gate on the whole project, as the turn starts. */
154
+ export function wholeProject(root, gate) {
155
+ return execute(root, gate, gate.run.slice(1));
156
+ }
157
+ /**
158
+ * Runs a gate on the turn. A compared gate fails on the lines of output the turn added, and on any exit code but 0:
159
+ * the same crash at the start and at the end of a turn prints no new line. A gate out of time is neither.
160
+ */
161
+ export async function check(root, gate, files, turn, baseline) {
162
+ const { ok, output, ms, timedOut } = await execute(root, gate, argumentsOf(gate, files, turn));
163
+ const ran = { name: gate.name, ms, report: ok ? output : undefined };
164
+ if (timedOut)
165
+ return { ...ran, ok, output, timedOut };
166
+ if (!isCompared(gate) || !ok)
167
+ return { ...ran, ok, output };
168
+ if (baseline === undefined)
169
+ return { ...ran, ok: true, output: "" };
170
+ const added = newLines(baseline, output, gate.ignoreLines);
171
+ return { ...ran, ok: added.length === 0, output: added.join("\n") };
172
+ }
@@ -0,0 +1,53 @@
1
+ import { createHash } from "node:crypto";
2
+ import { failed } from "./run.js";
3
+ import { waiveLines } from "./waive-line.js";
4
+ /** The gates the agent's last message waives, in order: a later line for the same gate wins. */
5
+ export function waivesOf(message) {
6
+ return [...message.matchAll(waiveLines())].map(([, gate = "", ...titles]) => ({
7
+ gate,
8
+ reason: (titles.find((title) => title !== undefined) ?? "").trim(),
9
+ }));
10
+ }
11
+ /**
12
+ * The fingerprint of a report, the same while the report says the same: numbers do not count, since an edit above a
13
+ * problem moves its line, and a runner prints how long it took.
14
+ */
15
+ export function fingerprint(report) {
16
+ const said = report
17
+ .split("\n")
18
+ .map((line) => line.trim().replace(/\d+/g, "0"))
19
+ .filter(Boolean)
20
+ .join("\n");
21
+ return createHash("sha256").update(said).digest("hex").slice(0, 16);
22
+ }
23
+ const NOTHING_YET = { count: 0, waivers: {}, reports: {} };
24
+ /**
25
+ * Decides whether a stop sends the agent back: a red gate it did not waive does, until the turn reaches its cap. A
26
+ * waiver binds to the report the agent saw, the one of the last check, or of this one when it waived before it was
27
+ * sent back, and falls when the report changes. A waive line for a gate that is not red is let go.
28
+ */
29
+ export function judge(turn, said, gates, max, before = NOTHING_YET) {
30
+ const red = turn.outcomes.filter(failed);
31
+ const reports = Object.fromEntries(red.map(({ name, output }) => [name, fingerprint(output)]));
32
+ const declared = { ...before.waivers };
33
+ for (const { gate, reason } of said) {
34
+ const report = before.reports[gate] ?? reports[gate];
35
+ if (report !== undefined && reports[gate] !== undefined)
36
+ declared[gate] = { reason, report };
37
+ }
38
+ const waivers = Object.fromEntries(Object.entries(declared).filter(([gate, { report }]) => reports[gate] === report));
39
+ const open = red.filter(({ name }) => waivers[name] === undefined);
40
+ const sendBack = open.length > 0 && before.count < max;
41
+ const count = before.count + (sendBack ? 1 : 0);
42
+ return {
43
+ sendBack,
44
+ count,
45
+ max,
46
+ open,
47
+ waived: Object.entries(waivers).map(([name, { reason }]) => ({ name, reason })),
48
+ fallen: Object.keys(declared).filter((gate) => reports[gate] !== undefined && waivers[gate] === undefined),
49
+ unknown: [...new Set(said.map(({ gate }) => gate).filter((gate) => !gates.includes(gate)))],
50
+ gates,
51
+ state: { count, waivers, reports },
52
+ };
53
+ }
@@ -0,0 +1,94 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { cpSync, existsSync, mkdtempSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+ /** Runs git in the repo, and gives what it printed, trimmed. */
6
+ function git(root, args, { env = process.env, input } = {}) {
7
+ return execFileSync("git", args, { cwd: root, encoding: "utf8", env, input, stdio: "pipe" }).trim();
8
+ }
9
+ // One NUL after each path, which git otherwise quotes and escapes when it holds an accent.
10
+ function paths(printed) {
11
+ return printed.split("\0").filter(Boolean);
12
+ }
13
+ export function repoRoot(cwd) {
14
+ try {
15
+ return git(cwd, ["rev-parse", "--show-toplevel"]);
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ }
21
+ /** Every file of the repo, tracked or not, the ignored ones left out. */
22
+ export function listFiles(root) {
23
+ return paths(git(root, ["ls-files", "-z", "--cached", "--others", "--exclude-standard"]));
24
+ }
25
+ // A commit that no branch points to, with a fixed identity so it works where git has none configured.
26
+ function commitOf(root, tree, message) {
27
+ const identity = {
28
+ ...process.env,
29
+ GIT_AUTHOR_NAME: "gates",
30
+ GIT_AUTHOR_EMAIL: "turn@gates.invalid",
31
+ GIT_COMMITTER_NAME: "gates",
32
+ GIT_COMMITTER_EMAIL: "turn@gates.invalid",
33
+ };
34
+ return git(root, ["commit-tree", tree, "-m", message], { env: identity });
35
+ }
36
+ /**
37
+ * The tree of the working tree, untracked files included and ignored files left out, from the files given or every
38
+ * file of the repo. It changes neither the index nor the files. A file gone since it was listed is left out: another
39
+ * hook may write in the tree as the agent stops, and `git add` dies on a file it listed and cannot stat.
40
+ */
41
+ export function workingTree(root, files = listFiles(root)) {
42
+ const dir = mkdtempSync(join(tmpdir(), "gates-index-"));
43
+ const env = { ...process.env, GIT_INDEX_FILE: join(dir, "index") };
44
+ try {
45
+ // Seeded from the real index, git hashes only the files changed since it was written: hashing every file of a
46
+ // large repo takes seconds, twice per turn. The copy keeps the date of the real index, since git trusts a file's
47
+ // size and date only when the index is older than the file: a newer date would hide a same-size rewrite.
48
+ const realIndex = resolve(root, git(root, ["rev-parse", "--git-path", "index"]));
49
+ if (existsSync(realIndex))
50
+ cpSync(realIndex, env.GIT_INDEX_FILE, { preserveTimestamps: true });
51
+ git(root, ["update-index", "--add", "--remove", "-z", "--stdin"], {
52
+ env,
53
+ input: files.map((file) => `${file}\0`).join(""),
54
+ });
55
+ return git(root, ["write-tree"], { env });
56
+ }
57
+ finally {
58
+ rmSync(dir, { recursive: true, force: true });
59
+ }
60
+ }
61
+ /** Records the working tree as a commit that no branch points to, for the tools given the turn, with its tree. */
62
+ export function snapshot(root) {
63
+ const tree = workingTree(root);
64
+ return { commit: commitOf(root, tree, "gates turn"), tree };
65
+ }
66
+ /**
67
+ * A commit with no file: compared with it, every file of the repo is new. A commit rather than the bare empty tree,
68
+ * since the tools given the turn, such as jscpd, resolve a commit and not a tree.
69
+ */
70
+ export function emptyCommit(root) {
71
+ return commitOf(root, git(root, ["hash-object", "-t", "tree", "--stdin"], { input: "" }), "gates empty");
72
+ }
73
+ export function lastCommit(root) {
74
+ try {
75
+ return git(root, ["rev-parse", "--verify", "--quiet", "HEAD"]);
76
+ }
77
+ catch {
78
+ return emptyCommit(root);
79
+ }
80
+ }
81
+ // A rewrite of the history lets git prune the snapshots no branch points to.
82
+ export function hasCommit(root, commit) {
83
+ try {
84
+ git(root, ["cat-file", "-e", `${commit}^{commit}`]);
85
+ return true;
86
+ }
87
+ catch {
88
+ return false;
89
+ }
90
+ }
91
+ /** The files that differ between two commits or trees, the deleted ones included. */
92
+ export function changedSince(root, start, end = workingTree(root)) {
93
+ return paths(git(root, ["diff", "-z", "--name-only", start, end])).sort();
94
+ }
@@ -0,0 +1,93 @@
1
+ import { writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { isRecord, isStringArray, isStringRecord, readJsonFile } from "./json.js";
5
+ function isGatesFiles(value) {
6
+ return (isRecord(value) &&
7
+ (value.shared === undefined || typeof value.shared === "string") &&
8
+ (value.local === undefined || typeof value.local === "string"));
9
+ }
10
+ const EMPTY = { turns: {} };
11
+ function stateFile(session) {
12
+ return join(tmpdir(), `gates-session-${session.replace(/[^\w-]/g, "")}.json`);
13
+ }
14
+ function isWaiver(value) {
15
+ return isRecord(value) && typeof value.reason === "string" && typeof value.report === "string";
16
+ }
17
+ function isSendBacks(value) {
18
+ return (isRecord(value) &&
19
+ typeof value.count === "number" &&
20
+ isRecord(value.waivers) &&
21
+ Object.values(value.waivers).every(isWaiver) &&
22
+ isStringRecord(value.reports));
23
+ }
24
+ function isTurnState(value) {
25
+ return (isRecord(value) &&
26
+ typeof value.start === "string" &&
27
+ isStringRecord(value.baselines) &&
28
+ isGatesFiles(value.config) &&
29
+ typeof value.checked === "boolean" &&
30
+ (value.sendBacks === undefined || isSendBacks(value.sendBacks)));
31
+ }
32
+ function isSessionState(value) {
33
+ return (isRecord(value) &&
34
+ (value.current === undefined || typeof value.current === "string") &&
35
+ isRecord(value.turns) &&
36
+ Object.values(value.turns).every(isTurnState) &&
37
+ (value.told === undefined || (isRecord(value.told) && Object.values(value.told).every(isStringArray))));
38
+ }
39
+ function readSession(session) {
40
+ const state = readJsonFile(stateFile(session));
41
+ return isSessionState(state) ? state : EMPTY;
42
+ }
43
+ function writeSession(session, state) {
44
+ writeFileSync(stateFile(session), JSON.stringify(state));
45
+ }
46
+ /** The turn of a repo: the one in progress, or one interrupted before it was checked. */
47
+ export function readTurn(session, root) {
48
+ return readSession(session).turns[root];
49
+ }
50
+ /**
51
+ * Records the turn of a repo, as the one in progress. The checked turns of the other repos go: only the one in
52
+ * progress is read again, by its retry.
53
+ */
54
+ export function writeTurn(session, root, turn) {
55
+ const { turns, told } = readSession(session);
56
+ const unchecked = Object.entries(turns).filter(([, kept]) => !kept.checked);
57
+ writeSession(session, { told, current: root, turns: { ...Object.fromEntries(unchecked), [root]: turn } });
58
+ }
59
+ /** Ends the turn in progress without a check, as a prompt from a folder with no gates, or a failed start, does. */
60
+ export function forgetTurn(session) {
61
+ const { current, ...state } = readSession(session);
62
+ if (current !== undefined)
63
+ writeSession(session, state);
64
+ }
65
+ /**
66
+ * Whether the agent is yet to be told that the repo misses these tools, in this session: once told, a list is not
67
+ * told again until it changes, since asking at every prompt someone who cannot install a tool only gets in the way.
68
+ */
69
+ export function tellOnce(session, root, missing) {
70
+ const state = readSession(session);
71
+ const told = state.told?.[root] ?? [];
72
+ if (told.join("\n") === missing.join("\n"))
73
+ return false;
74
+ writeSession(session, { ...state, told: { ...state.told, [root]: missing } });
75
+ return missing.length > 0;
76
+ }
77
+ /** Forgets what the agent was told of missing tools, so a session that starts again, or resumes, is told again. */
78
+ export function forgetTold(session) {
79
+ const { told, ...state } = readSession(session);
80
+ if (told !== undefined)
81
+ writeSession(session, state);
82
+ }
83
+ /**
84
+ * The repo of the turn a check is about, whatever folder the agent stops in. A check that follows its own turn start
85
+ * finds it unchecked, and the retry of a turn sent back finds it checked: any other check has no turn in progress.
86
+ */
87
+ export function turnRoot(session, retry) {
88
+ const { current, turns } = readSession(session);
89
+ if (current === undefined)
90
+ return undefined;
91
+ const turn = turns[current];
92
+ return turn && (!turn.checked || retry) ? current : undefined;
93
+ }
@@ -0,0 +1,15 @@
1
+ // The waive line on its own, with no import: the engine reads it, and the display hooks of Claude Code hide it, the mod
2
+ // among them, which runs with no Node.
3
+ /** The tag that opens a waive line: the plugin's name, so the display can hide the line without hiding anything else. */
4
+ export const WAIVE_TAG = "deterministic-gates";
5
+ // A markdown link reference definition, which Codex hides: [deterministic-gates:<gate>]: waive "<reason>". The
6
+ // reason may also sit between single quotes or parentheses, as a link title may.
7
+ const WAIVE_SOURCE = `^ {0,3}\\[${WAIVE_TAG}:([^\\]\\s]+)\\]:[ \\t]*waive[ \\t]+(?:"([^"]*)"|'([^']*)'|\\(([^)]*)\\))[ \\t]*$`;
8
+ /** Every waive line of a text, its gate and its reason captured. */
9
+ export function waiveLines() {
10
+ return new RegExp(WAIVE_SOURCE, "gm");
11
+ }
12
+ /** The text with its waive lines taken out, line ending included; the same text when it holds none. */
13
+ export function hideWaives(text) {
14
+ return text.replace(new RegExp(`${WAIVE_SOURCE}\\r?\\n?`, "gm"), "");
15
+ }
@@ -0,0 +1,57 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { mkdtempSync, rmSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { isRecord, readJsonFile } from "../core/json.js";
6
+ import { packageScript } from "../core/run.js";
7
+ // jscpd compared with the tree the turn started from. Its own console report lists every clone of the repo, the old
8
+ // ones included, so this prints only the clones the turn added, one per line.
9
+ function refuse() {
10
+ throw new Error("Not a jscpd report.");
11
+ }
12
+ function place(value) {
13
+ if (!isRecord(value))
14
+ refuse();
15
+ const { name, start, end } = value;
16
+ if (typeof name !== "string" || typeof start !== "number" || typeof end !== "number")
17
+ refuse();
18
+ return `${name}:${start}-${end}`;
19
+ }
20
+ export function newClones(report) {
21
+ if (!isRecord(report) || !Array.isArray(report.duplicates))
22
+ refuse();
23
+ return report.duplicates.flatMap((clone) => {
24
+ if (!isRecord(clone))
25
+ refuse();
26
+ const line = `${place(clone.firstFile)} ~ ${place(clone.secondFile)}`;
27
+ return clone.isNew === true ? [line] : [];
28
+ });
29
+ }
30
+ function main(root, turn) {
31
+ const jscpd = packageScript(root, "jscpd");
32
+ if (jscpd === undefined)
33
+ throw new Error("jscpd is not installed in node_modules: install the dependencies of the repo.");
34
+ const output = mkdtempSync(join(tmpdir(), "gates-jscpd-"));
35
+ try {
36
+ try {
37
+ execFileSync(process.execPath, [jscpd, "--baseline-from-ref", turn, "--reporters", "json,silent", "--output", output], { cwd: root, stdio: "pipe" });
38
+ }
39
+ catch (error) {
40
+ // What jscpd said, without the stack of this script around it.
41
+ const said = isRecord(error) && typeof error.stderr === "string" ? error.stderr.trim() : String(error);
42
+ console.log(`jscpd failed: ${said}`);
43
+ process.exitCode = 1;
44
+ return;
45
+ }
46
+ const clones = newClones(readJsonFile(join(output, "jscpd-report.json")));
47
+ if (!clones.length)
48
+ return;
49
+ console.log(`New clones: factor each one out.\n${clones.join("\n")}`);
50
+ process.exitCode = 1;
51
+ }
52
+ finally {
53
+ rmSync(output, { recursive: true, force: true });
54
+ }
55
+ }
56
+ if (import.meta.main)
57
+ main(process.cwd(), process.argv[2] ?? "HEAD");
@@ -0,0 +1,31 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ // The cheapest green is to silence the rule. This prints the rule suppressions the turn added to the changed files,
4
+ // one per line, compared with the file as the turn started: the ones already there are the owner's business.
5
+ /** The ways to silence a rule in the languages of the catalog: linters, type checkers, formatters, scanners. */
6
+ const SUPPRESSIONS = /eslint-disable|@ts-(ignore|expect-error|nocheck)|prettier-ignore|biome-ignore|\bnoqa\b|type:\s*ignore|pylint:\s*disable|fmt:\s*(off|skip)|\bnosec\b|\bnolint\b|go:nolint|coverage:\s*ignore|pragma:\s*no cover/;
7
+ /** The suppressions in the lines the file holds now and did not hold as the turn started. */
8
+ export function newSuppressions(before, after) {
9
+ const seen = new Set((before ?? "").split("\n").map((line) => line.trim()));
10
+ return after.split("\n").flatMap((text, index) => {
11
+ const line = text.trim();
12
+ return line && !seen.has(line) && SUPPRESSIONS.test(line) ? [{ line: index + 1, text: line }] : [];
13
+ });
14
+ }
15
+ function atTurnStart(root, turn, file) {
16
+ try {
17
+ return execFileSync("git", ["show", `${turn}:${file}`], { cwd: root, encoding: "utf8", stdio: "pipe" });
18
+ }
19
+ catch {
20
+ return undefined;
21
+ }
22
+ }
23
+ function main(root, turn, files) {
24
+ const found = files.flatMap((file) => newSuppressions(atTurnStart(root, turn, file), readFileSync(file, "utf8")).map(({ line, text }) => `${file}:${line}: ${text}`));
25
+ if (!found.length)
26
+ return;
27
+ console.log(`New rule suppressions: fix the code, never the check.\n${found.join("\n")}`);
28
+ process.exitCode = 1;
29
+ }
30
+ if (import.meta.main)
31
+ main(process.cwd(), process.argv[2] ?? "HEAD", process.argv.slice(3));
@@ -0,0 +1,109 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { dirname, extname, join, resolve } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { listFiles } from "../core/snapshot.js";
6
+ // The node:test tests that a change can break: those that import a changed file, directly or through other files.
7
+ // Node has no "related" mode of its own, where Vitest has one.
8
+ const EXTENSIONS = [".ts", ".mts", ".cts", ".js", ".mjs", ".cjs"];
9
+ const EXTENSION = `\\.(${EXTENSIONS.map((extension) => extension.slice(1)).join("|")})`;
10
+ /** Node's own naming of test files, the TypeScript ones included. */
11
+ const NODE_TESTS = new RegExp(`(\\.test|[-_]test|^test|/test)${EXTENSION}$|/test/.*${EXTENSION}$|(^|/)test-[^/]*${EXTENSION}$`);
12
+ /** Fails on a changed file no test reaches, which the related tests alone pass in silence. */
13
+ const REQUIRE_TESTS = "--require-tests";
14
+ // An import of types only runs nothing: the type check is the gate that covers it.
15
+ const SPECIFIERS = /(?:^|[\s;])(?:import|export)\b(?!\s+type\b)[^'"]*?\bfrom\s*['"]([^'"]+)['"]|(?:^|[\s;])import\s*['"]([^'"]+)['"]/g;
16
+ // A relative specifier, resolved as Node would among the files of the repo, with the TypeScript file an import of
17
+ // its .js output names.
18
+ function resolveImport(files, from, specifier) {
19
+ if (!specifier.startsWith("."))
20
+ return undefined;
21
+ const base = resolve(dirname(from), specifier);
22
+ const candidates = [
23
+ base,
24
+ ...EXTENSIONS.map((extension) => base + extension),
25
+ ...(base.endsWith(".js") ? [base.replace(/\.js$/, ".ts")] : []),
26
+ ...(base.endsWith(".mjs") ? [base.replace(/\.mjs$/, ".mts")] : []),
27
+ ...EXTENSIONS.map((extension) => join(base, `index${extension}`)),
28
+ ];
29
+ return candidates.find((candidate) => files.has(candidate));
30
+ }
31
+ function importsOf(files, file) {
32
+ let text;
33
+ try {
34
+ text = readFileSync(file, "utf8");
35
+ }
36
+ catch {
37
+ return [];
38
+ }
39
+ return [...text.matchAll(SPECIFIERS)].flatMap(([, named, bare]) => {
40
+ const resolved = resolveImport(files, file, named ?? bare ?? "");
41
+ return resolved === undefined ? [] : [resolved];
42
+ });
43
+ }
44
+ /**
45
+ * For each test file of the repo, by the given naming, the changed files it imports, directly or not. A changed test
46
+ * file reaches itself.
47
+ */
48
+ function reachedBy(root, changed, tests) {
49
+ const files = listFiles(root);
50
+ const known = new Set(files.map((file) => resolve(root, file)));
51
+ const changedByPath = new Map(changed.map((file) => [resolve(root, file), file]));
52
+ const imports = new Map();
53
+ const walk = (file, seen, reached) => {
54
+ if (seen.has(file))
55
+ return;
56
+ seen.add(file);
57
+ const name = changedByPath.get(file);
58
+ if (name !== undefined)
59
+ reached.add(name);
60
+ if (!imports.has(file))
61
+ imports.set(file, importsOf(known, file));
62
+ for (const imported of imports.get(file) ?? [])
63
+ walk(imported, seen, reached);
64
+ };
65
+ return new Map(files
66
+ .filter((file) => tests.test(file))
67
+ .map((file) => {
68
+ const reached = new Set();
69
+ walk(resolve(root, file), new Set(), reached);
70
+ return [file, reached];
71
+ }));
72
+ }
73
+ // The tests that reach a changed file, in order.
74
+ function testsReaching(reached) {
75
+ return [...reached]
76
+ .filter(([, files]) => files.size)
77
+ .map(([test]) => test)
78
+ .sort();
79
+ }
80
+ /** The test files of the repo, by the given naming, that import one of the changed files, directly or not. */
81
+ export function relatedTests(root, changed, tests) {
82
+ return testsReaching(reachedBy(root, changed, tests));
83
+ }
84
+ function main(args) {
85
+ const option = args.indexOf("--tests");
86
+ const tests = option === -1 ? NODE_TESTS : new RegExp(args[option + 1] ?? "");
87
+ const rest = option === -1 ? args : [...args.slice(0, option), ...args.slice(option + 2)];
88
+ const requireTests = rest.includes(REQUIRE_TESTS);
89
+ const changed = rest.filter((arg) => arg !== REQUIRE_TESTS);
90
+ const reached = reachedBy(process.cwd(), changed, tests);
91
+ const tested = new Set([...reached.values()].flatMap((files) => [...files]));
92
+ const untested = requireTests ? changed.filter((file) => !tested.has(file)) : [];
93
+ for (const file of untested)
94
+ console.log(`No test reaches ${file}: write one that imports it.`);
95
+ if (untested.length)
96
+ process.exitCode = 1;
97
+ const related = testsReaching(reached);
98
+ if (!related.length)
99
+ return;
100
+ // Run as a test runner of its own, even from inside another node --test, as the tests of this engine do.
101
+ const { NODE_TEST_CONTEXT: _nested, ...env } = process.env;
102
+ // Beside this file, with its extension: .ts in the repo, .js in the npm package.
103
+ const reporter = pathToFileURL(join(import.meta.dirname, `test-reporter${extname(import.meta.filename)}`)).href;
104
+ const run = spawnSync(process.execPath, ["--test", `--test-reporter=${reporter}`, "--test-reporter-destination=stdout", ...related], { stdio: "inherit", env });
105
+ if (run.status !== 0)
106
+ process.exitCode = run.status ?? 1;
107
+ }
108
+ if (import.meta.main)
109
+ main(process.argv.slice(2));