@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,217 @@
1
+ import { execFile, type ExecFileException } 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, type Gate, isCompared, TURN } from "./config.ts";
6
+ import { isRecord, messageOf, readJsonFile } from "./json.ts";
7
+
8
+ export interface Outcome {
9
+ name: string;
10
+ ok: boolean;
11
+ ms: number;
12
+ output: string;
13
+ report: string | undefined;
14
+ /** Stopped for lack of time: neither green nor red, since nobody knows what it would have said. */
15
+ timedOut?: boolean;
16
+ }
17
+
18
+ /** A gate that judged the turn and found a problem: the only kind that sends the agent back. */
19
+ export function failed(outcome: Outcome): boolean {
20
+ return !outcome.ok && !outcome.timedOut;
21
+ }
22
+
23
+ const ENGINE = resolve(import.meta.dirname, "..", "..");
24
+ const MAX_OUTPUT_MB = 16;
25
+ const ENGINE_PREFIX = "{engine}/";
26
+
27
+ /** A script of this engine: its .ts source, or the .js it is built to when the engine runs from its npm package. */
28
+ function engineScript(name: string): string {
29
+ const file = resolve(ENGINE, name);
30
+ return file.endsWith(".ts") && !existsSync(file) ? `${file.slice(0, -".ts".length)}.js` : file;
31
+ }
32
+
33
+ /** How a gate's command starts: the program to execute, the arguments before the gate's own, and why it may be missing. */
34
+ export interface Command {
35
+ file: string;
36
+ args: string[];
37
+ missing: string;
38
+ }
39
+
40
+ // A script of the repo runs on the interpreter of its extension.
41
+ const INTERPRETERS: [RegExp, string][] = [
42
+ [/\.(ts|js|mjs)$/, process.execPath],
43
+ [/\.py$/, "python3"],
44
+ ];
45
+
46
+ /** The script of a package of the repo's node_modules, or nothing when the repo does not have the package. */
47
+ export function packageScript(root: string, name: string): string | undefined {
48
+ const dir = resolve(root, "node_modules", name);
49
+ const manifest = readJsonFile(resolve(dir, "package.json"));
50
+ if (manifest === undefined) return undefined;
51
+ const bin = isRecord(manifest) ? manifest.bin : undefined;
52
+ const commands = isRecord(bin) ? bin : {};
53
+ const script = typeof bin === "string" ? bin : (commands[name] ?? Object.values(commands)[0]);
54
+ if (typeof script !== "string") throw new Error(`${name} has no command.`);
55
+ return resolve(dir, script);
56
+ }
57
+
58
+ /**
59
+ * Resolves the first word of a gate's command, in this order: a script of this engine under {engine}/, a script of the
60
+ * 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
61
+ * on the PATH.
62
+ */
63
+ export function commandOf(root: string, name: string): Command {
64
+ if (name.startsWith(ENGINE_PREFIX)) {
65
+ return { file: process.execPath, args: [engineScript(name.slice(ENGINE_PREFIX.length))], missing: "" };
66
+ }
67
+ const interpreter = INTERPRETERS.find(([extension]) => extension.test(name))?.[1];
68
+ if (interpreter !== undefined) {
69
+ return {
70
+ file: interpreter,
71
+ args: [resolve(root, name)],
72
+ missing: `${interpreter} is not installed, and ${name} needs it.`,
73
+ };
74
+ }
75
+ const script = packageScript(root, name);
76
+ if (script !== undefined) return { file: process.execPath, args: [script], missing: "" };
77
+ if (name.includes("/")) return { file: resolve(root, name), args: [], missing: `${name} does not exist.` };
78
+ return {
79
+ file: name,
80
+ args: [],
81
+ missing: `${name} is not installed: it is neither a package of node_modules nor a program on the PATH.`,
82
+ };
83
+ }
84
+
85
+ // A program by its path, or by its name on the PATH, that the system would execute.
86
+ function executable(file: string): boolean {
87
+ const candidates = isAbsolute(file)
88
+ ? [file]
89
+ : (process.env.PATH ?? "").split(delimiter).map((dir) => join(dir, file));
90
+ return candidates.some((candidate) => {
91
+ try {
92
+ accessSync(candidate, constants.X_OK);
93
+ return true;
94
+ } catch {
95
+ return false;
96
+ }
97
+ });
98
+ }
99
+
100
+ /**
101
+ * Why the program of a gate cannot run on this machine, or nothing when it can: looked up as the gate would start it,
102
+ * without starting it. A command the engine cannot resolve is left to the run, which reports it.
103
+ */
104
+ export function missingTool(root: string, gate: Gate): string | undefined {
105
+ let command: Command;
106
+ try {
107
+ command = commandOf(root, gate.run[0] ?? "");
108
+ } catch {
109
+ return undefined;
110
+ }
111
+ return command.missing && !executable(command.file) ? command.missing : undefined;
112
+ }
113
+
114
+ export function argumentsOf(gate: Gate, files: string[], turn: string): string[] {
115
+ return gate.run.slice(1).flatMap((argument) => (argument === FILES ? files : [argument.replaceAll(TURN, turn)]));
116
+ }
117
+
118
+ /** Whether the gate is given the changed files, where another reads the whole project. */
119
+ export function givenFiles(gate: Gate): boolean {
120
+ return gate.run.includes(FILES);
121
+ }
122
+
123
+ export function filesOf(gate: Gate, changed: string[]): string[] {
124
+ const pattern = new RegExp(gate.files);
125
+ return changed.filter((file) => pattern.test(file));
126
+ }
127
+
128
+ export function newLines(before: string, after: string, ignore?: string): string[] {
129
+ const ignored = ignore === undefined ? undefined : new RegExp(ignore);
130
+ const seen = new Set(before.split("\n").map((line) => line.trim()));
131
+ return after
132
+ .split("\n")
133
+ .map((line) => line.trim())
134
+ .filter((line) => line && !seen.has(line) && !ignored?.test(line));
135
+ }
136
+
137
+ interface Executed {
138
+ ok: boolean;
139
+ output: string;
140
+ ms: number;
141
+ timedOut: boolean;
142
+ }
143
+
144
+ async function execute(root: string, gate: Gate, args: string[]): Promise<Executed> {
145
+ const started = performance.now();
146
+ const [name = ""] = gate.run;
147
+ // A gate that cannot start fails alone: the other gates of the turn still report.
148
+ let command: Command;
149
+ try {
150
+ command = commandOf(root, name);
151
+ } catch (error) {
152
+ return { ok: false, output: messageOf(error), ms: performance.now() - started, timedOut: false };
153
+ }
154
+ return new Promise((resolve) => {
155
+ execFile(
156
+ command.file,
157
+ [...command.args, ...args],
158
+ {
159
+ cwd: root,
160
+ timeout: gate.timeoutSeconds * 1000,
161
+ maxBuffer: MAX_OUTPUT_MB * 1024 * 1024,
162
+ env: { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0" },
163
+ },
164
+ (error, stdout, stderr) => {
165
+ resolve({
166
+ ok: !error,
167
+ output: outputOf(root, gate, command, error, `${stdout}${stderr}`),
168
+ ms: performance.now() - started,
169
+ timedOut: error?.killed === true && error.code !== "ERR_CHILD_PROCESS_STDIO_MAXBUFFER",
170
+ });
171
+ },
172
+ );
173
+ });
174
+ }
175
+
176
+ function outputOf(
177
+ root: string,
178
+ gate: Gate,
179
+ command: Command,
180
+ error: ExecFileException | null,
181
+ printed: string,
182
+ ): string {
183
+ if (error?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER")
184
+ return `Printed more than ${MAX_OUTPUT_MB} MB: too much for the end of a turn. Make it quieter, or move it to CI.`;
185
+ if (error?.killed === true)
186
+ return `Out of time after ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
187
+ if (error?.code === "ENOENT") return command.missing;
188
+ // Some tools colour despite NO_COLOR, and absolute paths only cost the agent tokens.
189
+ const said = stripVTControlCharacters(printed).split(`${root}${sep}`).join("").trim();
190
+ if (said || !error) return said;
191
+ return `exit code ${String(error.code)}, no output`;
192
+ }
193
+
194
+ /** Runs a compared gate on the whole project, as the turn starts. */
195
+ export function wholeProject(root: string, gate: Gate): Promise<{ ok: boolean; output: string }> {
196
+ return execute(root, gate, gate.run.slice(1));
197
+ }
198
+
199
+ /**
200
+ * 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:
201
+ * the same crash at the start and at the end of a turn prints no new line. A gate out of time is neither.
202
+ */
203
+ export async function check(
204
+ root: string,
205
+ gate: Gate,
206
+ files: string[],
207
+ turn: string,
208
+ baseline: string | undefined,
209
+ ): Promise<Outcome> {
210
+ const { ok, output, ms, timedOut } = await execute(root, gate, argumentsOf(gate, files, turn));
211
+ const ran = { name: gate.name, ms, report: ok ? output : undefined };
212
+ if (timedOut) return { ...ran, ok, output, timedOut };
213
+ if (!isCompared(gate) || !ok) return { ...ran, ok, output };
214
+ if (baseline === undefined) return { ...ran, ok: true, output: "" };
215
+ const added = newLines(baseline, output, gate.ignoreLines);
216
+ return { ...ran, ok: added.length === 0, output: added.join("\n") };
217
+ }
@@ -0,0 +1,87 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { CheckedTurn } from "./check.ts";
3
+ import { failed, type Outcome } from "./run.ts";
4
+ import type { SendBacks, Waiver } from "./turn-state.ts";
5
+ import { waiveLines } from "./waive-line.ts";
6
+
7
+ /** A gate the agent's last message waives, with why. */
8
+ export interface Said {
9
+ gate: string;
10
+ reason: string;
11
+ }
12
+
13
+ /** The gates the agent's last message waives, in order: a later line for the same gate wins. */
14
+ export function waivesOf(message: string): Said[] {
15
+ return [...message.matchAll(waiveLines())].map(([, gate = "", ...titles]) => ({
16
+ gate,
17
+ reason: (titles.find((title) => title !== undefined) ?? "").trim(),
18
+ }));
19
+ }
20
+
21
+ /**
22
+ * The fingerprint of a report, the same while the report says the same: numbers do not count, since an edit above a
23
+ * problem moves its line, and a runner prints how long it took.
24
+ */
25
+ export function fingerprint(report: string): string {
26
+ const said = report
27
+ .split("\n")
28
+ .map((line) => line.trim().replace(/\d+/g, "0"))
29
+ .filter(Boolean)
30
+ .join("\n");
31
+ return createHash("sha256").update(said).digest("hex").slice(0, 16);
32
+ }
33
+
34
+ /** What a stop decides, and why, for the owner and the agent. */
35
+ export interface Judged {
36
+ sendBack: boolean;
37
+ /** Send-backs of the turn, this one included. */
38
+ count: number;
39
+ max: number;
40
+ /** The red gates not waived: the ones the agent is sent back for. */
41
+ open: Outcome[];
42
+ waived: { name: string; reason: string }[];
43
+ /** Gates waived before whose report changed since: the agent judges them again. */
44
+ fallen: string[];
45
+ /** Names a waive line gives that no gate of the turn has, and the names of the gates of the turn. */
46
+ unknown: string[];
47
+ gates: string[];
48
+ state: SendBacks;
49
+ }
50
+
51
+ const NOTHING_YET: SendBacks = { count: 0, waivers: {}, reports: {} };
52
+
53
+ /**
54
+ * Decides whether a stop sends the agent back: a red gate it did not waive does, until the turn reaches its cap. A
55
+ * waiver binds to the report the agent saw, the one of the last check, or of this one when it waived before it was
56
+ * sent back, and falls when the report changes. A waive line for a gate that is not red is let go.
57
+ */
58
+ export function judge(
59
+ turn: CheckedTurn,
60
+ said: Said[],
61
+ gates: string[],
62
+ max: number,
63
+ before: SendBacks = NOTHING_YET,
64
+ ): Judged {
65
+ const red = turn.outcomes.filter(failed);
66
+ const reports = Object.fromEntries(red.map(({ name, output }) => [name, fingerprint(output)]));
67
+ const declared: Record<string, Waiver> = { ...before.waivers };
68
+ for (const { gate, reason } of said) {
69
+ const report = before.reports[gate] ?? reports[gate];
70
+ if (report !== undefined && reports[gate] !== undefined) declared[gate] = { reason, report };
71
+ }
72
+ const waivers = Object.fromEntries(Object.entries(declared).filter(([gate, { report }]) => reports[gate] === report));
73
+ const open = red.filter(({ name }) => waivers[name] === undefined);
74
+ const sendBack = open.length > 0 && before.count < max;
75
+ const count = before.count + (sendBack ? 1 : 0);
76
+ return {
77
+ sendBack,
78
+ count,
79
+ max,
80
+ open,
81
+ waived: Object.entries(waivers).map(([name, { reason }]) => ({ name, reason })),
82
+ fallen: Object.keys(declared).filter((gate) => reports[gate] !== undefined && waivers[gate] === undefined),
83
+ unknown: [...new Set(said.map(({ gate }) => gate).filter((gate) => !gates.includes(gate)))],
84
+ gates,
85
+ state: { count, waivers, reports },
86
+ };
87
+ }
@@ -0,0 +1,105 @@
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
+
6
+ interface GitOptions {
7
+ env?: NodeJS.ProcessEnv;
8
+ input?: string;
9
+ }
10
+
11
+ /** Runs git in the repo, and gives what it printed, trimmed. */
12
+ function git(root: string, args: string[], { env = process.env, input }: GitOptions = {}): string {
13
+ return execFileSync("git", args, { cwd: root, encoding: "utf8", env, input, stdio: "pipe" }).trim();
14
+ }
15
+
16
+ // One NUL after each path, which git otherwise quotes and escapes when it holds an accent.
17
+ function paths(printed: string): string[] {
18
+ return printed.split("\0").filter(Boolean);
19
+ }
20
+
21
+ export function repoRoot(cwd: string): string | undefined {
22
+ try {
23
+ return git(cwd, ["rev-parse", "--show-toplevel"]);
24
+ } catch {
25
+ return undefined;
26
+ }
27
+ }
28
+
29
+ /** Every file of the repo, tracked or not, the ignored ones left out. */
30
+ export function listFiles(root: string): string[] {
31
+ return paths(git(root, ["ls-files", "-z", "--cached", "--others", "--exclude-standard"]));
32
+ }
33
+
34
+ // A commit that no branch points to, with a fixed identity so it works where git has none configured.
35
+ function commitOf(root: string, tree: string, message: string): string {
36
+ const identity = {
37
+ ...process.env,
38
+ GIT_AUTHOR_NAME: "gates",
39
+ GIT_AUTHOR_EMAIL: "turn@gates.invalid",
40
+ GIT_COMMITTER_NAME: "gates",
41
+ GIT_COMMITTER_EMAIL: "turn@gates.invalid",
42
+ };
43
+ return git(root, ["commit-tree", tree, "-m", message], { env: identity });
44
+ }
45
+
46
+ /**
47
+ * The tree of the working tree, untracked files included and ignored files left out, from the files given or every
48
+ * file of the repo. It changes neither the index nor the files. A file gone since it was listed is left out: another
49
+ * hook may write in the tree as the agent stops, and `git add` dies on a file it listed and cannot stat.
50
+ */
51
+ export function workingTree(root: string, files = listFiles(root)): string {
52
+ const dir = mkdtempSync(join(tmpdir(), "gates-index-"));
53
+ const env = { ...process.env, GIT_INDEX_FILE: join(dir, "index") };
54
+ try {
55
+ // Seeded from the real index, git hashes only the files changed since it was written: hashing every file of a
56
+ // large repo takes seconds, twice per turn. The copy keeps the date of the real index, since git trusts a file's
57
+ // size and date only when the index is older than the file: a newer date would hide a same-size rewrite.
58
+ const realIndex = resolve(root, git(root, ["rev-parse", "--git-path", "index"]));
59
+ if (existsSync(realIndex)) cpSync(realIndex, env.GIT_INDEX_FILE, { preserveTimestamps: true });
60
+ git(root, ["update-index", "--add", "--remove", "-z", "--stdin"], {
61
+ env,
62
+ input: files.map((file) => `${file}\0`).join(""),
63
+ });
64
+ return git(root, ["write-tree"], { env });
65
+ } finally {
66
+ rmSync(dir, { recursive: true, force: true });
67
+ }
68
+ }
69
+
70
+ /** Records the working tree as a commit that no branch points to, for the tools given the turn, with its tree. */
71
+ export function snapshot(root: string): { commit: string; tree: string } {
72
+ const tree = workingTree(root);
73
+ return { commit: commitOf(root, tree, "gates turn"), tree };
74
+ }
75
+
76
+ /**
77
+ * A commit with no file: compared with it, every file of the repo is new. A commit rather than the bare empty tree,
78
+ * since the tools given the turn, such as jscpd, resolve a commit and not a tree.
79
+ */
80
+ export function emptyCommit(root: string): string {
81
+ return commitOf(root, git(root, ["hash-object", "-t", "tree", "--stdin"], { input: "" }), "gates empty");
82
+ }
83
+
84
+ export function lastCommit(root: string): string {
85
+ try {
86
+ return git(root, ["rev-parse", "--verify", "--quiet", "HEAD"]);
87
+ } catch {
88
+ return emptyCommit(root);
89
+ }
90
+ }
91
+
92
+ // A rewrite of the history lets git prune the snapshots no branch points to.
93
+ export function hasCommit(root: string, commit: string): boolean {
94
+ try {
95
+ git(root, ["cat-file", "-e", `${commit}^{commit}`]);
96
+ return true;
97
+ } catch {
98
+ return false;
99
+ }
100
+ }
101
+
102
+ /** The files that differ between two commits or trees, the deleted ones included. */
103
+ export function changedSince(root: string, start: string, end = workingTree(root)): string[] {
104
+ return paths(git(root, ["diff", "-z", "--name-only", start, end])).sort();
105
+ }
@@ -0,0 +1,153 @@
1
+ import { writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import type { GatesFiles } from "./config.ts";
5
+ import { isRecord, isStringArray, isStringRecord, readJsonFile } from "./json.ts";
6
+
7
+ /** A red gate the agent chose to leave, with why, bound to the fingerprint of the report it saw. */
8
+ export interface Waiver {
9
+ reason: string;
10
+ report: string;
11
+ }
12
+
13
+ /**
14
+ * What the stops of a turn have told the agent so far: how many times it was sent back, the gates it waived, and the
15
+ * fingerprint of each red report of the last check, which a waiver read at the next stop is bound to.
16
+ */
17
+ export interface SendBacks {
18
+ count: number;
19
+ waivers: Record<string, Waiver>;
20
+ reports: Record<string, string>;
21
+ }
22
+
23
+ /**
24
+ * What a turn started from: the commit, the reports of its compared gates, and the gates files themselves, since a
25
+ * turn is checked with the gates it started with. A turn the owner interrupts never reaches its check: it stays
26
+ * unchecked until the next turn of its repo. Once checked, what its stops told the agent.
27
+ */
28
+ export interface TurnState {
29
+ start: string;
30
+ baselines: Record<string, string>;
31
+ config: GatesFiles;
32
+ checked: boolean;
33
+ sendBacks?: SendBacks;
34
+ }
35
+
36
+ function isGatesFiles(value: unknown): value is GatesFiles {
37
+ return (
38
+ isRecord(value) &&
39
+ (value.shared === undefined || typeof value.shared === "string") &&
40
+ (value.local === undefined || typeof value.local === "string")
41
+ );
42
+ }
43
+
44
+ /**
45
+ * The turns of a session, one per repo, and the repo of the turn in progress. The agent may stop in another folder
46
+ * than the one it started in, and a prompt from a folder with no gates starts a turn no check looks for. With them,
47
+ * the tools each repo was missing when the agent was last told, so it is not asked again at every prompt.
48
+ */
49
+ interface SessionState {
50
+ current?: string;
51
+ turns: Record<string, TurnState>;
52
+ told?: Record<string, string[]>;
53
+ }
54
+
55
+ const EMPTY: SessionState = { turns: {} };
56
+
57
+ function stateFile(session: string): string {
58
+ return join(tmpdir(), `gates-session-${session.replace(/[^\w-]/g, "")}.json`);
59
+ }
60
+
61
+ function isWaiver(value: unknown): value is Waiver {
62
+ return isRecord(value) && typeof value.reason === "string" && typeof value.report === "string";
63
+ }
64
+
65
+ function isSendBacks(value: unknown): value is SendBacks {
66
+ return (
67
+ isRecord(value) &&
68
+ typeof value.count === "number" &&
69
+ isRecord(value.waivers) &&
70
+ Object.values(value.waivers).every(isWaiver) &&
71
+ isStringRecord(value.reports)
72
+ );
73
+ }
74
+
75
+ function isTurnState(value: unknown): value is TurnState {
76
+ return (
77
+ isRecord(value) &&
78
+ typeof value.start === "string" &&
79
+ isStringRecord(value.baselines) &&
80
+ isGatesFiles(value.config) &&
81
+ typeof value.checked === "boolean" &&
82
+ (value.sendBacks === undefined || isSendBacks(value.sendBacks))
83
+ );
84
+ }
85
+
86
+ function isSessionState(value: unknown): value is SessionState {
87
+ return (
88
+ isRecord(value) &&
89
+ (value.current === undefined || typeof value.current === "string") &&
90
+ isRecord(value.turns) &&
91
+ Object.values(value.turns).every(isTurnState) &&
92
+ (value.told === undefined || (isRecord(value.told) && Object.values(value.told).every(isStringArray)))
93
+ );
94
+ }
95
+
96
+ function readSession(session: string): SessionState {
97
+ const state = readJsonFile(stateFile(session));
98
+ return isSessionState(state) ? state : EMPTY;
99
+ }
100
+
101
+ function writeSession(session: string, state: SessionState): void {
102
+ writeFileSync(stateFile(session), JSON.stringify(state));
103
+ }
104
+
105
+ /** The turn of a repo: the one in progress, or one interrupted before it was checked. */
106
+ export function readTurn(session: string, root: string): TurnState | undefined {
107
+ return readSession(session).turns[root];
108
+ }
109
+
110
+ /**
111
+ * Records the turn of a repo, as the one in progress. The checked turns of the other repos go: only the one in
112
+ * progress is read again, by its retry.
113
+ */
114
+ export function writeTurn(session: string, root: string, turn: TurnState): void {
115
+ const { turns, told } = readSession(session);
116
+ const unchecked = Object.entries(turns).filter(([, kept]) => !kept.checked);
117
+ writeSession(session, { told, current: root, turns: { ...Object.fromEntries(unchecked), [root]: turn } });
118
+ }
119
+
120
+ /** Ends the turn in progress without a check, as a prompt from a folder with no gates, or a failed start, does. */
121
+ export function forgetTurn(session: string): void {
122
+ const { current, ...state } = readSession(session);
123
+ if (current !== undefined) writeSession(session, state);
124
+ }
125
+
126
+ /**
127
+ * Whether the agent is yet to be told that the repo misses these tools, in this session: once told, a list is not
128
+ * told again until it changes, since asking at every prompt someone who cannot install a tool only gets in the way.
129
+ */
130
+ export function tellOnce(session: string, root: string, missing: string[]): boolean {
131
+ const state = readSession(session);
132
+ const told = state.told?.[root] ?? [];
133
+ if (told.join("\n") === missing.join("\n")) return false;
134
+ writeSession(session, { ...state, told: { ...state.told, [root]: missing } });
135
+ return missing.length > 0;
136
+ }
137
+
138
+ /** Forgets what the agent was told of missing tools, so a session that starts again, or resumes, is told again. */
139
+ export function forgetTold(session: string): void {
140
+ const { told, ...state } = readSession(session);
141
+ if (told !== undefined) writeSession(session, state);
142
+ }
143
+
144
+ /**
145
+ * The repo of the turn a check is about, whatever folder the agent stops in. A check that follows its own turn start
146
+ * finds it unchecked, and the retry of a turn sent back finds it checked: any other check has no turn in progress.
147
+ */
148
+ export function turnRoot(session: string, retry: boolean): string | undefined {
149
+ const { current, turns } = readSession(session);
150
+ if (current === undefined) return undefined;
151
+ const turn = turns[current];
152
+ return turn && (!turn.checked || retry) ? current : undefined;
153
+ }
@@ -0,0 +1,19 @@
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
+
4
+ /** The tag that opens a waive line: the plugin's name, so the display can hide the line without hiding anything else. */
5
+ export const WAIVE_TAG = "deterministic-gates";
6
+
7
+ // A markdown link reference definition, which Codex hides: [deterministic-gates:<gate>]: waive "<reason>". The
8
+ // reason may also sit between single quotes or parentheses, as a link title may.
9
+ const WAIVE_SOURCE = `^ {0,3}\\[${WAIVE_TAG}:([^\\]\\s]+)\\]:[ \\t]*waive[ \\t]+(?:"([^"]*)"|'([^']*)'|\\(([^)]*)\\))[ \\t]*$`;
10
+
11
+ /** Every waive line of a text, its gate and its reason captured. */
12
+ export function waiveLines(): RegExp {
13
+ return new RegExp(WAIVE_SOURCE, "gm");
14
+ }
15
+
16
+ /** The text with its waive lines taken out, line ending included; the same text when it holds none. */
17
+ export function hideWaives(text: string): string {
18
+ return text.replace(new RegExp(`${WAIVE_SOURCE}\\r?\\n?`, "gm"), "");
19
+ }
@@ -0,0 +1,58 @@
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.ts";
6
+ import { packageScript } from "../core/run.ts";
7
+
8
+ // jscpd compared with the tree the turn started from. Its own console report lists every clone of the repo, the old
9
+ // ones included, so this prints only the clones the turn added, one per line.
10
+
11
+ function refuse(): never {
12
+ throw new Error("Not a jscpd report.");
13
+ }
14
+ function place(value: unknown): string {
15
+ if (!isRecord(value)) refuse();
16
+ const { name, start, end } = value;
17
+ if (typeof name !== "string" || typeof start !== "number" || typeof end !== "number") refuse();
18
+ return `${name}:${start}-${end}`;
19
+ }
20
+
21
+ export function newClones(report: unknown): string[] {
22
+ if (!isRecord(report) || !Array.isArray(report.duplicates)) refuse();
23
+ return report.duplicates.flatMap((clone: unknown) => {
24
+ if (!isRecord(clone)) refuse();
25
+ const line = `${place(clone.firstFile)} ~ ${place(clone.secondFile)}`;
26
+ return clone.isNew === true ? [line] : [];
27
+ });
28
+ }
29
+
30
+ function main(root: string, turn: string): void {
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(
38
+ process.execPath,
39
+ [jscpd, "--baseline-from-ref", turn, "--reporters", "json,silent", "--output", output],
40
+ { cwd: root, stdio: "pipe" },
41
+ );
42
+ } catch (error) {
43
+ // What jscpd said, without the stack of this script around it.
44
+ const said = isRecord(error) && typeof error.stderr === "string" ? error.stderr.trim() : String(error);
45
+ console.log(`jscpd failed: ${said}`);
46
+ process.exitCode = 1;
47
+ return;
48
+ }
49
+ const clones = newClones(readJsonFile(join(output, "jscpd-report.json")));
50
+ if (!clones.length) return;
51
+ console.log(`New clones: factor each one out.\n${clones.join("\n")}`);
52
+ process.exitCode = 1;
53
+ } finally {
54
+ rmSync(output, { recursive: true, force: true });
55
+ }
56
+ }
57
+
58
+ if (import.meta.main) main(process.cwd(), process.argv[2] ?? "HEAD");
@@ -0,0 +1,44 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+
4
+ // The cheapest green is to silence the rule. This prints the rule suppressions the turn added to the changed files,
5
+ // one per line, compared with the file as the turn started: the ones already there are the owner's business.
6
+
7
+ /** The ways to silence a rule in the languages of the catalog: linters, type checkers, formatters, scanners. */
8
+ const SUPPRESSIONS =
9
+ /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/;
10
+
11
+ export interface Suppression {
12
+ line: number;
13
+ text: string;
14
+ }
15
+
16
+ /** The suppressions in the lines the file holds now and did not hold as the turn started. */
17
+ export function newSuppressions(before: string | undefined, after: string): Suppression[] {
18
+ const seen = new Set((before ?? "").split("\n").map((line) => line.trim()));
19
+ return after.split("\n").flatMap((text, index) => {
20
+ const line = text.trim();
21
+ return line && !seen.has(line) && SUPPRESSIONS.test(line) ? [{ line: index + 1, text: line }] : [];
22
+ });
23
+ }
24
+
25
+ function atTurnStart(root: string, turn: string, file: string): string | undefined {
26
+ try {
27
+ return execFileSync("git", ["show", `${turn}:${file}`], { cwd: root, encoding: "utf8", stdio: "pipe" });
28
+ } catch {
29
+ return undefined;
30
+ }
31
+ }
32
+
33
+ function main(root: string, turn: string, files: string[]): void {
34
+ const found = files.flatMap((file) =>
35
+ newSuppressions(atTurnStart(root, turn, file), readFileSync(file, "utf8")).map(
36
+ ({ line, text }) => `${file}:${line}: ${text}`,
37
+ ),
38
+ );
39
+ if (!found.length) return;
40
+ console.log(`New rule suppressions: fix the code, never the check.\n${found.join("\n")}`);
41
+ process.exitCode = 1;
42
+ }
43
+
44
+ if (import.meta.main) main(process.cwd(), process.argv[2] ?? "HEAD", process.argv.slice(3));