@tayomi/deterministic-gates 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,51 @@
1
+ import { createHash } from "node:crypto";
2
+ import { writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import type { Gate } from "./config.ts";
6
+ import { isRecord, isStringRecord, readJsonFile } from "./json.ts";
7
+
8
+ // A turn almost always starts from the tree the previous turn ended on, so it reuses the reports of that tree
9
+ // instead of running the compared gates again while the prompt waits. A report is the output of one command on one
10
+ // tree, so the reports of a tree are kept by command, whatever the gate is called.
11
+
12
+ interface Cache {
13
+ tree: string;
14
+ reports: Record<string, string>;
15
+ }
16
+
17
+ function isCache(value: unknown): value is Cache {
18
+ return isRecord(value) && typeof value.tree === "string" && isStringRecord(value.reports);
19
+ }
20
+
21
+ function cacheFile(root: string): string {
22
+ const repo = createHash("sha256").update(root).digest("hex").slice(0, 16);
23
+ return join(tmpdir(), `gates-reports-${repo}.json`);
24
+ }
25
+
26
+ function commandOf(gate: Gate): string {
27
+ return JSON.stringify(gate.run);
28
+ }
29
+
30
+ function readCache(root: string): Cache | undefined {
31
+ const cache = readJsonFile(cacheFile(root));
32
+ return isCache(cache) ? cache : undefined;
33
+ }
34
+
35
+ export function cachedReports(root: string, tree: string): (gate: Gate) => string | undefined {
36
+ const cache = readCache(root);
37
+ return (gate) => (cache?.tree === tree ? cache.reports[commandOf(gate)] : undefined);
38
+ }
39
+
40
+ /** Keeps reports for a tree, with the ones already kept for that tree, and in place of the ones of another tree. */
41
+ export function cacheReports(root: string, tree: string, reports: (readonly [Gate, string])[]): void {
42
+ const kept = readCache(root);
43
+ const cache: Cache = {
44
+ tree,
45
+ reports: {
46
+ ...(kept?.tree === tree ? kept.reports : {}),
47
+ ...Object.fromEntries(reports.map(([gate, report]) => [commandOf(gate), report])),
48
+ },
49
+ };
50
+ writeFileSync(cacheFile(root), JSON.stringify(cache));
51
+ }
@@ -0,0 +1,159 @@
1
+ import type { CheckedTurn } from "./check.ts";
2
+ import { failed, type Outcome } from "./run.ts";
3
+ import { WAIVE_TAG } from "./send-back.ts";
4
+
5
+ const LABEL = "● gates";
6
+ const SHOWN_PASSES = 6;
7
+ const REPORT_CHARS = 4000;
8
+ const HEAD_CHARS = 1000;
9
+
10
+ const TONES = { pass: "1;32", fail: "1;31", late: "1;33", warn: "1;38;5;208", dim: "2" } as const;
11
+ // The warning sign as text, never as the emoji some terminals draw without the variation selector.
12
+ const WARNING = "\u26A0\uFE0E";
13
+
14
+ /** A red gate the agent left on purpose, with the reason it gave. */
15
+ export interface Waived {
16
+ name: string;
17
+ reason: string;
18
+ }
19
+
20
+ function paint(tone: keyof typeof TONES, text: string): string {
21
+ return `\x1b[${TONES[tone]}m${text}\x1b[0m`;
22
+ }
23
+
24
+ /** Keeps the start and the end of a long report: tools put the problem at one or the other. */
25
+ export function excerpt(report: string): string {
26
+ if (report.length <= REPORT_CHARS) return report;
27
+ const cut = report.length - REPORT_CHARS;
28
+ return `${report.slice(0, HEAD_CHARS)}\n[... ${cut} characters cut ...]\n${report.slice(-(REPORT_CHARS - HEAD_CHARS))}`;
29
+ }
30
+
31
+ export function duration(ms: number): string {
32
+ return ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`;
33
+ }
34
+
35
+ function gateLine(mark: string, outcome: Outcome): string {
36
+ return `${mark} ${outcome.name} ${paint("dim", duration(outcome.ms))}`;
37
+ }
38
+
39
+ function skippedLine(skipped: string[]): string {
40
+ return paint("dim", `${skipped.map((name) => `- ${name}`).join(" ")} · no matching file changed`);
41
+ }
42
+
43
+ function nothingChecked({ changed, skipped }: CheckedTurn, after: string): string[] {
44
+ if (!changed.length) return [`${paint("pass", LABEL)}${after}`, `${paint("pass", "✓")} no file changed`];
45
+ const files = changed.length === 1 ? "1 changed file" : `${changed.length} changed files`;
46
+ return [
47
+ `${paint("pass", LABEL)} no gate looks at the ${files}${after}`,
48
+ ...(skipped.length ? [skippedLine(skipped)] : []),
49
+ ];
50
+ }
51
+
52
+ // The gate in orange, then the reason the agent gave, under a star.
53
+ function waivedLines(outcome: Outcome, reason: string): string[] {
54
+ return [
55
+ `${paint("warn", `${WARNING} ${outcome.name}`)} ${paint("dim", duration(outcome.ms))}`,
56
+ ` ${paint("warn", "*")} ${reason}`,
57
+ ];
58
+ }
59
+
60
+ // Every pass, as many to a line as the summary shows by default; or the slowest of them, with a count of the rest.
61
+ function passLines(passed: Outcome[], showAll: boolean): string[] {
62
+ const marked = passed.map((outcome) => gateLine(paint("pass", "✓"), outcome));
63
+ if (showAll)
64
+ return Array.from({ length: Math.ceil(marked.length / SHOWN_PASSES) }, (_, line) =>
65
+ marked.slice(line * SHOWN_PASSES, (line + 1) * SHOWN_PASSES).join(" "),
66
+ );
67
+ const rest = marked.length - SHOWN_PASSES;
68
+ return marked.length
69
+ ? [[...marked.slice(0, SHOWN_PASSES), ...(rest > 0 ? [paint("dim", `... +${rest}`)] : [])].join(" ")]
70
+ : [];
71
+ }
72
+
73
+ function resultLines(
74
+ { outcomes, skipped, ms, showAllPasses = false }: CheckedTurn,
75
+ after: string,
76
+ waived: Waived[],
77
+ ): string[] {
78
+ const slowest = (a: Outcome, b: Outcome) => b.ms - a.ms;
79
+ const reasons = new Map(waived.map(({ name, reason }) => [name, reason]));
80
+ const failing = outcomes.filter(failed).sort(slowest);
81
+ const red = failing.filter(({ name }) => !reasons.has(name));
82
+ const left = failing.filter(({ name }) => reasons.has(name));
83
+ const late = outcomes.filter((outcome) => outcome.timedOut).sort(slowest);
84
+ const passed = outcomes.filter((outcome) => outcome.ok).sort(slowest);
85
+ const leftOut = left.length ? ` · ${left.length} waived` : "";
86
+ const outOfTime = late.length ? ` · ${late.length} out of time` : "";
87
+ const notRun = skipped.length ? ` · ${skipped.length} skipped` : "";
88
+ const tone = red.length ? "fail" : left.length ? "warn" : late.length ? "late" : "pass";
89
+ const totals = `${passed.length}/${outcomes.length} gates green in ${duration(ms)}`;
90
+ return [
91
+ `${paint(tone, LABEL)} ${totals}${leftOut}${outOfTime}${notRun}${after}`,
92
+ ...red.map((outcome) => gateLine(paint("fail", "✗"), outcome)),
93
+ ...left.flatMap((outcome) => waivedLines(outcome, reasons.get(outcome.name) ?? "")),
94
+ ...late.map((outcome) => gateLine(paint("late", "⏱"), outcome)),
95
+ ...passLines(passed, showAllPasses),
96
+ ...(skipped.length ? [skippedLine(skipped)] : []),
97
+ ];
98
+ }
99
+
100
+ /**
101
+ * What the owner sees after every check, even when no gate ran, so a silent check never looks dead: one line of
102
+ * totals, with how the stop ends, each failure, each gate the agent waived with its reason, the passes slowest
103
+ * first, then the gates the turn did not concern.
104
+ */
105
+ export function summary(turn: CheckedTurn, ending = "", waived: Waived[] = []): string {
106
+ const after = ending ? ` · ${ending}` : "";
107
+ const lines = turn.outcomes.length ? resultLines(turn, after, waived) : nothingChecked(turn, after);
108
+ return [...lines, ...(turn.note ? [paint("dim", turn.note)] : [])].join("\n");
109
+ }
110
+
111
+ /** What the owner sees when the gates cannot run at all, such as with a gates file that does not parse. */
112
+ export function broken(reason: string): string {
113
+ return `${paint("fail", LABEL)} could not run: ${reason}`;
114
+ }
115
+
116
+ // The cheapest green is to silence the rule, and nothing in the engine judges a report. So the agent is told the one
117
+ // way out that is not a cheat: waive the gate, with a reason the owner reads and judges.
118
+ const CONDUCT = [
119
+ "Fix the code, never the check: a silenced rule (noqa, eslint-disable, nolint), a weakened gate or an edited",
120
+ ".gates.json does not pass this turn. If you can fix a problem, fix it. Leave a gate red only when it cannot be",
121
+ "fixed (the report is wrong, or fixing it would loop until the last send-back), when fixing it goes against what",
122
+ "the owner asked, or when the owner has to settle a question first. Then waive it in your final message, after a",
123
+ "blank line, one line per gate, its reason in one line:",
124
+ ].join(" ");
125
+
126
+ const WAIVE_SYNTAX = `[${WAIVE_TAG}:<gate>]: waive "<reason>"`;
127
+
128
+ /** What the owner sees when the gates of the repo miss tools on this machine, as the agent is asked to install them. */
129
+ export function toolsMissing(missing: string[]): string {
130
+ const gates = missing.length === 1 ? "1 gate is off" : `${missing.length} gates are off`;
131
+ const lines = missing.map((tool) => paint("dim", `- ${tool}`));
132
+ return [`${paint("fail", LABEL)} ${gates}, a tool is missing: the agent is asked to install it`, ...lines].join(
133
+ "\n",
134
+ );
135
+ }
136
+
137
+ /** What the agent is told when the gates of the repo miss tools: install them, or the gates that need them stay off. */
138
+ export function toolsToInstall(missing: string[]): string {
139
+ return [
140
+ "Some gates of this repo cannot run on this machine, for a missing tool:",
141
+ ...missing.map((tool) => `- ${tool}`),
142
+ "Install these tools first. If they cannot be installed, or the developer refuses, say so and go on with the",
143
+ "prompt: the gates that need them stay off until they are installed, and every other gate still runs.",
144
+ ].join("\n");
145
+ }
146
+
147
+ /** The report of each failed gate, under its name. */
148
+ export function reports(outcomes: Outcome[]): string[] {
149
+ return outcomes.filter(failed).map(({ name, output }) => `## ${name}\n${excerpt(output)}`);
150
+ }
151
+
152
+ /**
153
+ * What the agent gets when it is sent back: how to act on a failure, what the stop has to tell it, the note of the
154
+ * check, each failed report.
155
+ */
156
+ export function failures({ outcomes, note }: CheckedTurn, told: string[] = []): string {
157
+ const head = ["Gates fail on what this turn changed. Fix every problem before you hand back.", CONDUCT, WAIVE_SYNTAX];
158
+ return [...head, ...told, ...(note ? [note] : []), ...reports(outcomes)].join("\n\n");
159
+ }
@@ -0,0 +1,211 @@
1
+ import { execFile, type ExecFileException } from "node:child_process";
2
+ import { accessSync, constants } 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
+ /** How a gate's command starts: the program to execute, the arguments before the gate's own, and why it may be missing. */
28
+ export interface Command {
29
+ file: string;
30
+ args: string[];
31
+ missing: string;
32
+ }
33
+
34
+ // A script of the repo runs on the interpreter of its extension.
35
+ const INTERPRETERS: [RegExp, string][] = [
36
+ [/\.(ts|js|mjs)$/, process.execPath],
37
+ [/\.py$/, "python3"],
38
+ ];
39
+
40
+ /** The script of a package of the repo's node_modules, or nothing when the repo does not have the package. */
41
+ export function packageScript(root: string, name: string): string | undefined {
42
+ const dir = resolve(root, "node_modules", name);
43
+ const manifest = readJsonFile(resolve(dir, "package.json"));
44
+ if (manifest === undefined) return undefined;
45
+ const bin = isRecord(manifest) ? manifest.bin : undefined;
46
+ const commands = isRecord(bin) ? bin : {};
47
+ const script = typeof bin === "string" ? bin : (commands[name] ?? Object.values(commands)[0]);
48
+ if (typeof script !== "string") throw new Error(`${name} has no command.`);
49
+ return resolve(dir, script);
50
+ }
51
+
52
+ /**
53
+ * Resolves the first word of a gate's command, in this order: a script of this engine under {engine}/, a script of the
54
+ * 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
55
+ * on the PATH.
56
+ */
57
+ export function commandOf(root: string, name: string): Command {
58
+ if (name.startsWith(ENGINE_PREFIX)) {
59
+ return { file: process.execPath, args: [resolve(ENGINE, name.slice(ENGINE_PREFIX.length))], missing: "" };
60
+ }
61
+ const interpreter = INTERPRETERS.find(([extension]) => extension.test(name))?.[1];
62
+ if (interpreter !== undefined) {
63
+ return {
64
+ file: interpreter,
65
+ args: [resolve(root, name)],
66
+ missing: `${interpreter} is not installed, and ${name} needs it.`,
67
+ };
68
+ }
69
+ const script = packageScript(root, name);
70
+ if (script !== undefined) return { file: process.execPath, args: [script], missing: "" };
71
+ if (name.includes("/")) return { file: resolve(root, name), args: [], missing: `${name} does not exist.` };
72
+ return {
73
+ file: name,
74
+ args: [],
75
+ missing: `${name} is not installed: it is neither a package of node_modules nor a program on the PATH.`,
76
+ };
77
+ }
78
+
79
+ // A program by its path, or by its name on the PATH, that the system would execute.
80
+ function executable(file: string): boolean {
81
+ const candidates = isAbsolute(file)
82
+ ? [file]
83
+ : (process.env.PATH ?? "").split(delimiter).map((dir) => join(dir, file));
84
+ return candidates.some((candidate) => {
85
+ try {
86
+ accessSync(candidate, constants.X_OK);
87
+ return true;
88
+ } catch {
89
+ return false;
90
+ }
91
+ });
92
+ }
93
+
94
+ /**
95
+ * Why the program of a gate cannot run on this machine, or nothing when it can: looked up as the gate would start it,
96
+ * without starting it. A command the engine cannot resolve is left to the run, which reports it.
97
+ */
98
+ export function missingTool(root: string, gate: Gate): string | undefined {
99
+ let command: Command;
100
+ try {
101
+ command = commandOf(root, gate.run[0] ?? "");
102
+ } catch {
103
+ return undefined;
104
+ }
105
+ return command.missing && !executable(command.file) ? command.missing : undefined;
106
+ }
107
+
108
+ export function argumentsOf(gate: Gate, files: string[], turn: string): string[] {
109
+ return gate.run.slice(1).flatMap((argument) => (argument === FILES ? files : [argument.replaceAll(TURN, turn)]));
110
+ }
111
+
112
+ /** Whether the gate is given the changed files, where another reads the whole project. */
113
+ export function givenFiles(gate: Gate): boolean {
114
+ return gate.run.includes(FILES);
115
+ }
116
+
117
+ export function filesOf(gate: Gate, changed: string[]): string[] {
118
+ const pattern = new RegExp(gate.files);
119
+ return changed.filter((file) => pattern.test(file));
120
+ }
121
+
122
+ export function newLines(before: string, after: string, ignore?: string): string[] {
123
+ const ignored = ignore === undefined ? undefined : new RegExp(ignore);
124
+ const seen = new Set(before.split("\n").map((line) => line.trim()));
125
+ return after
126
+ .split("\n")
127
+ .map((line) => line.trim())
128
+ .filter((line) => line && !seen.has(line) && !ignored?.test(line));
129
+ }
130
+
131
+ interface Executed {
132
+ ok: boolean;
133
+ output: string;
134
+ ms: number;
135
+ timedOut: boolean;
136
+ }
137
+
138
+ async function execute(root: string, gate: Gate, args: string[]): Promise<Executed> {
139
+ const started = performance.now();
140
+ const [name = ""] = gate.run;
141
+ // A gate that cannot start fails alone: the other gates of the turn still report.
142
+ let command: Command;
143
+ try {
144
+ command = commandOf(root, name);
145
+ } catch (error) {
146
+ return { ok: false, output: messageOf(error), ms: performance.now() - started, timedOut: false };
147
+ }
148
+ return new Promise((resolve) => {
149
+ execFile(
150
+ command.file,
151
+ [...command.args, ...args],
152
+ {
153
+ cwd: root,
154
+ timeout: gate.timeoutSeconds * 1000,
155
+ maxBuffer: MAX_OUTPUT_MB * 1024 * 1024,
156
+ env: { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0" },
157
+ },
158
+ (error, stdout, stderr) => {
159
+ resolve({
160
+ ok: !error,
161
+ output: outputOf(root, gate, command, error, `${stdout}${stderr}`),
162
+ ms: performance.now() - started,
163
+ timedOut: error?.killed === true && error.code !== "ERR_CHILD_PROCESS_STDIO_MAXBUFFER",
164
+ });
165
+ },
166
+ );
167
+ });
168
+ }
169
+
170
+ function outputOf(
171
+ root: string,
172
+ gate: Gate,
173
+ command: Command,
174
+ error: ExecFileException | null,
175
+ printed: string,
176
+ ): string {
177
+ if (error?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER")
178
+ return `Printed more than ${MAX_OUTPUT_MB} MB: too much for the end of a turn. Make it quieter, or move it to CI.`;
179
+ if (error?.killed === true)
180
+ return `Out of time after ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
181
+ if (error?.code === "ENOENT") return command.missing;
182
+ // Some tools colour despite NO_COLOR, and absolute paths only cost the agent tokens.
183
+ const said = stripVTControlCharacters(printed).split(`${root}${sep}`).join("").trim();
184
+ if (said || !error) return said;
185
+ return `exit code ${String(error.code)}, no output`;
186
+ }
187
+
188
+ /** Runs a compared gate on the whole project, as the turn starts. */
189
+ export function wholeProject(root: string, gate: Gate): Promise<{ ok: boolean; output: string }> {
190
+ return execute(root, gate, gate.run.slice(1));
191
+ }
192
+
193
+ /**
194
+ * 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:
195
+ * the same crash at the start and at the end of a turn prints no new line. A gate out of time is neither.
196
+ */
197
+ export async function check(
198
+ root: string,
199
+ gate: Gate,
200
+ files: string[],
201
+ turn: string,
202
+ baseline: string | undefined,
203
+ ): Promise<Outcome> {
204
+ const { ok, output, ms, timedOut } = await execute(root, gate, argumentsOf(gate, files, turn));
205
+ const ran = { name: gate.name, ms, report: ok ? output : undefined };
206
+ if (timedOut) return { ...ran, ok, output, timedOut };
207
+ if (!isCompared(gate) || !ok) return { ...ran, ok, output };
208
+ if (baseline === undefined) return { ...ran, ok: true, output: "" };
209
+ const added = newLines(baseline, output, gate.ignoreLines);
210
+ return { ...ran, ok: added.length === 0, output: added.join("\n") };
211
+ }
@@ -0,0 +1,96 @@
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
+
6
+ /** The tag that opens a waive line: the plugin's name, so a mod can hide the line without hiding anything else. */
7
+ export const WAIVE_TAG = "deterministic-gates";
8
+
9
+ /** A gate the agent's last message waives, with why. */
10
+ export interface Said {
11
+ gate: string;
12
+ reason: string;
13
+ }
14
+
15
+ // A markdown link reference definition, which Codex hides: [deterministic-gates:<gate>]: waive "<reason>". The
16
+ // reason may also sit between single quotes or parentheses, as a link title may.
17
+ const WAIVE_LINE = new RegExp(
18
+ `^ {0,3}\\[${WAIVE_TAG}:([^\\]\\s]+)\\]:[ \\t]*waive[ \\t]+(?:"([^"]*)"|'([^']*)'|\\(([^)]*)\\))[ \\t]*$`,
19
+ "gm",
20
+ );
21
+
22
+ /** The gates the agent's last message waives, in order: a later line for the same gate wins. */
23
+ export function waivesOf(message: string): Said[] {
24
+ return [...message.matchAll(WAIVE_LINE)].map(([, gate = "", ...titles]) => ({
25
+ gate,
26
+ reason: (titles.find((title) => title !== undefined) ?? "").trim(),
27
+ }));
28
+ }
29
+
30
+ /**
31
+ * The fingerprint of a report, the same while the report says the same: numbers do not count, since an edit above a
32
+ * problem moves its line, and a runner prints how long it took.
33
+ */
34
+ export function fingerprint(report: string): string {
35
+ const said = report
36
+ .split("\n")
37
+ .map((line) => line.trim().replace(/\d+/g, "0"))
38
+ .filter(Boolean)
39
+ .join("\n");
40
+ return createHash("sha256").update(said).digest("hex").slice(0, 16);
41
+ }
42
+
43
+ /** What a stop decides, and why, for the owner and the agent. */
44
+ export interface Judged {
45
+ sendBack: boolean;
46
+ /** Send-backs of the turn, this one included. */
47
+ count: number;
48
+ max: number;
49
+ /** The red gates not waived: the ones the agent is sent back for. */
50
+ open: Outcome[];
51
+ waived: { name: string; reason: string }[];
52
+ /** Gates waived before whose report changed since: the agent judges them again. */
53
+ fallen: string[];
54
+ /** Names a waive line gives that no gate of the turn has, and the names of the gates of the turn. */
55
+ unknown: string[];
56
+ gates: string[];
57
+ state: SendBacks;
58
+ }
59
+
60
+ const NOTHING_YET: SendBacks = { count: 0, waivers: {}, reports: {} };
61
+
62
+ /**
63
+ * Decides whether a stop sends the agent back: a red gate it did not waive does, until the turn reaches its cap. A
64
+ * waiver binds to the report the agent saw, the one of the last check, or of this one when it waived before it was
65
+ * sent back, and falls when the report changes. A waive line for a gate that is not red is let go.
66
+ */
67
+ export function judge(
68
+ turn: CheckedTurn,
69
+ said: Said[],
70
+ gates: string[],
71
+ max: number,
72
+ before: SendBacks = NOTHING_YET,
73
+ ): Judged {
74
+ const red = turn.outcomes.filter(failed);
75
+ const reports = Object.fromEntries(red.map(({ name, output }) => [name, fingerprint(output)]));
76
+ const declared: Record<string, Waiver> = { ...before.waivers };
77
+ for (const { gate, reason } of said) {
78
+ const report = before.reports[gate] ?? reports[gate];
79
+ if (report !== undefined && reports[gate] !== undefined) declared[gate] = { reason, report };
80
+ }
81
+ const waivers = Object.fromEntries(Object.entries(declared).filter(([gate, { report }]) => reports[gate] === report));
82
+ const open = red.filter(({ name }) => waivers[name] === undefined);
83
+ const sendBack = open.length > 0 && before.count < max;
84
+ const count = before.count + (sendBack ? 1 : 0);
85
+ return {
86
+ sendBack,
87
+ count,
88
+ max,
89
+ open,
90
+ waived: Object.entries(waivers).map(([name, { reason }]) => ({ name, reason })),
91
+ fallen: Object.keys(declared).filter((gate) => reports[gate] !== undefined && waivers[gate] === undefined),
92
+ unknown: [...new Set(said.map(({ gate }) => gate).filter((gate) => !gates.includes(gate)))],
93
+ gates,
94
+ state: { count, waivers, reports },
95
+ };
96
+ }
@@ -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
+ }