@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,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,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));
@@ -0,0 +1,118 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { pathToFileURL } from "node:url";
5
+ import { listFiles } from "../core/snapshot.ts";
6
+
7
+ // The node:test tests that a change can break: those that import a changed file, directly or through other files.
8
+ // Node has no "related" mode of its own, where Vitest has one.
9
+
10
+ const EXTENSIONS = [".ts", ".mts", ".cts", ".js", ".mjs", ".cjs"];
11
+ const EXTENSION = `\\.(${EXTENSIONS.map((extension) => extension.slice(1)).join("|")})`;
12
+
13
+ /** Node's own naming of test files, the TypeScript ones included. */
14
+ const NODE_TESTS = new RegExp(
15
+ `(\\.test|[-_]test|^test|/test)${EXTENSION}$|/test/.*${EXTENSION}$|(^|/)test-[^/]*${EXTENSION}$`,
16
+ );
17
+
18
+ /** Fails on a changed file no test reaches, which the related tests alone pass in silence. */
19
+ const REQUIRE_TESTS = "--require-tests";
20
+
21
+ // An import of types only runs nothing: the type check is the gate that covers it.
22
+ const SPECIFIERS =
23
+ /(?:^|[\s;])(?:import|export)\b(?!\s+type\b)[^'"]*?\bfrom\s*['"]([^'"]+)['"]|(?:^|[\s;])import\s*['"]([^'"]+)['"]/g;
24
+
25
+ // A relative specifier, resolved as Node would among the files of the repo, with the TypeScript file an import of
26
+ // its .js output names.
27
+ function resolveImport(files: Set<string>, from: string, specifier: string): string | undefined {
28
+ if (!specifier.startsWith(".")) return undefined;
29
+ const base = resolve(dirname(from), specifier);
30
+ const candidates = [
31
+ base,
32
+ ...EXTENSIONS.map((extension) => base + extension),
33
+ ...(base.endsWith(".js") ? [base.replace(/\.js$/, ".ts")] : []),
34
+ ...(base.endsWith(".mjs") ? [base.replace(/\.mjs$/, ".mts")] : []),
35
+ ...EXTENSIONS.map((extension) => join(base, `index${extension}`)),
36
+ ];
37
+ return candidates.find((candidate) => files.has(candidate));
38
+ }
39
+
40
+ function importsOf(files: Set<string>, file: string): string[] {
41
+ let text: string;
42
+ try {
43
+ text = readFileSync(file, "utf8");
44
+ } catch {
45
+ return [];
46
+ }
47
+ return [...text.matchAll(SPECIFIERS)].flatMap(([, named, bare]) => {
48
+ const resolved = resolveImport(files, file, named ?? bare ?? "");
49
+ return resolved === undefined ? [] : [resolved];
50
+ });
51
+ }
52
+
53
+ /**
54
+ * For each test file of the repo, by the given naming, the changed files it imports, directly or not. A changed test
55
+ * file reaches itself.
56
+ */
57
+ function reachedBy(root: string, changed: string[], tests: RegExp): Map<string, Set<string>> {
58
+ const files = listFiles(root);
59
+ const known = new Set(files.map((file) => resolve(root, file)));
60
+ const changedByPath = new Map(changed.map((file) => [resolve(root, file), file]));
61
+ const imports = new Map<string, string[]>();
62
+ const walk = (file: string, seen: Set<string>, reached: Set<string>): void => {
63
+ if (seen.has(file)) return;
64
+ seen.add(file);
65
+ const name = changedByPath.get(file);
66
+ if (name !== undefined) reached.add(name);
67
+ if (!imports.has(file)) imports.set(file, importsOf(known, file));
68
+ for (const imported of imports.get(file) ?? []) walk(imported, seen, reached);
69
+ };
70
+ return new Map(
71
+ files
72
+ .filter((file) => tests.test(file))
73
+ .map((file) => {
74
+ const reached = new Set<string>();
75
+ walk(resolve(root, file), new Set(), reached);
76
+ return [file, reached] as const;
77
+ }),
78
+ );
79
+ }
80
+
81
+ // The tests that reach a changed file, in order.
82
+ function testsReaching(reached: Map<string, Set<string>>): string[] {
83
+ return [...reached]
84
+ .filter(([, files]) => files.size)
85
+ .map(([test]) => test)
86
+ .sort();
87
+ }
88
+
89
+ /** The test files of the repo, by the given naming, that import one of the changed files, directly or not. */
90
+ export function relatedTests(root: string, changed: string[], tests: RegExp): string[] {
91
+ return testsReaching(reachedBy(root, changed, tests));
92
+ }
93
+
94
+ function main(args: string[]): void {
95
+ const option = args.indexOf("--tests");
96
+ const tests = option === -1 ? NODE_TESTS : new RegExp(args[option + 1] ?? "");
97
+ const rest = option === -1 ? args : [...args.slice(0, option), ...args.slice(option + 2)];
98
+ const requireTests = rest.includes(REQUIRE_TESTS);
99
+ const changed = rest.filter((arg) => arg !== REQUIRE_TESTS);
100
+ const reached = reachedBy(process.cwd(), changed, tests);
101
+ const tested = new Set([...reached.values()].flatMap((files) => [...files]));
102
+ const untested = requireTests ? changed.filter((file) => !tested.has(file)) : [];
103
+ for (const file of untested) console.log(`No test reaches ${file}: write one that imports it.`);
104
+ if (untested.length) process.exitCode = 1;
105
+ const related = testsReaching(reached);
106
+ if (!related.length) return;
107
+ // Run as a test runner of its own, even from inside another node --test, as the tests of this engine do.
108
+ const { NODE_TEST_CONTEXT: _nested, ...env } = process.env;
109
+ const reporter = pathToFileURL(join(import.meta.dirname, "test-reporter.ts")).href;
110
+ const run = spawnSync(
111
+ process.execPath,
112
+ ["--test", `--test-reporter=${reporter}`, "--test-reporter-destination=stdout", ...related],
113
+ { stdio: "inherit", env },
114
+ );
115
+ if (run.status !== 0) process.exitCode = run.status ?? 1;
116
+ }
117
+
118
+ if (import.meta.main) main(process.argv.slice(2));
@@ -0,0 +1,71 @@
1
+ import { relative } from "node:path";
2
+
3
+ // The reporter of the related tests: one trace per distinct failure, with every test it hit, where Node's own
4
+ // reporters print the same trace once per test file. A module that does not compile fails every test file that
5
+ // imports it, with the same error each time.
6
+
7
+ interface TestEvent {
8
+ type: string;
9
+ data: {
10
+ name: string;
11
+ nesting: number;
12
+ file?: string;
13
+ message?: string;
14
+ details?: { error?: Error & { failureType?: string; cause?: unknown } };
15
+ counts?: { tests: number; failed: number };
16
+ };
17
+ }
18
+
19
+ // The frames of Node itself, and what it prints around an exception nothing caught.
20
+ const NOISE =
21
+ /^(\s+at .*\((node:|<anonymous>)|\s+at node:|node:internal\/|\s+triggerUncaughtException\(| code: '|\}$|Node\.js v\d)/;
22
+
23
+ function cleaned(text: string): string {
24
+ const lines = text.split("\n");
25
+ // The caret under triggerUncaughtException, and the blank line after it.
26
+ if (lines[0]?.startsWith("node:internal/")) lines.splice(0, 4);
27
+ const cwd = process.cwd();
28
+ return lines
29
+ .filter((line) => !NOISE.test(line))
30
+ .map((line) => line.split(`file://${cwd}/`).join("").split(`${cwd}/`).join(""))
31
+ .join("\n")
32
+ .trimEnd();
33
+ }
34
+
35
+ function traceOf(error: Error & { cause?: unknown }): string {
36
+ const { cause } = error;
37
+ return cleaned(cause instanceof Error ? (cause.stack ?? cause.message) : String(cause ?? error.message));
38
+ }
39
+
40
+ /** Prints each distinct failure once, with the tests it hit, then the counts. */
41
+ export default async function* report(source: AsyncIterable<TestEvent>): AsyncGenerator<string> {
42
+ const stderr = new Map<string, string>();
43
+ const names = new Map<string, string[]>();
44
+ const hits = new Map<string, string[]>();
45
+ let counts = "";
46
+ const hit = (trace: string, label: string) => hits.set(trace, [...(hits.get(trace) ?? []), label]);
47
+ for await (const { type, data } of source) {
48
+ const file = data.file === undefined ? data.name : relative(process.cwd(), data.file);
49
+ if (type === "test:stderr") {
50
+ stderr.set(file, (stderr.get(file) ?? "") + (data.message ?? ""));
51
+ } else if (type === "test:start") {
52
+ const path = names.get(file) ?? [];
53
+ path.length = data.nesting;
54
+ path.push(data.name);
55
+ names.set(file, path);
56
+ } else if (type === "test:fail") {
57
+ const error = data.details?.error;
58
+ if (error === undefined || error.failureType === "subtestsFailed") continue;
59
+ // A file that could not run: its error went to stderr, with nothing in the failure.
60
+ if (data.nesting === 0 && data.name === file && !(error.cause instanceof Error)) {
61
+ hit(cleaned(stderr.get(file) ?? error.message), file);
62
+ } else {
63
+ hit(traceOf(error), `${file}: ${(names.get(file) ?? []).slice(0, data.nesting + 1).join(" > ")}`);
64
+ }
65
+ } else if (type === "test:summary" && data.counts) {
66
+ counts = `${data.counts.tests} tests, ${data.counts.failed} failed`;
67
+ }
68
+ }
69
+ for (const [trace, labels] of hits) yield `✖ ${labels.join(", ")}\n${trace}\n\n`;
70
+ yield `${counts}\n`;
71
+ }
@@ -0,0 +1,144 @@
1
+ import { type CheckedTurn, checkTurn, startTurn } from "../core/check.ts";
2
+ import { configuredRoot, gatesOf } from "../core/config.ts";
3
+ import { isRecord, messageOf, parseJson } from "../core/json.ts";
4
+ import { broken, failures, summary, toolsMissing, toolsToInstall } from "../core/report.ts";
5
+ import { type Judged, judge, waivesOf } from "../core/send-back.ts";
6
+ import { forgetTold, forgetTurn, readTurn, tellOnce, turnRoot, writeTurn } from "../core/turn-state.ts";
7
+
8
+ export interface HookInput {
9
+ session_id?: string;
10
+ stop_hook_active?: boolean;
11
+ cwd?: string;
12
+ source?: string;
13
+ last_assistant_message?: string;
14
+ }
15
+
16
+ export interface HookOutput {
17
+ decision?: "block";
18
+ reason?: string;
19
+ systemMessage: string;
20
+ hookSpecificOutput?: { hookEventName: "UserPromptSubmit"; additionalContext: string };
21
+ }
22
+
23
+ export type HookEvent = "session-start" | "turn-start" | "check";
24
+
25
+ export function parseHookInput(text: string): HookInput {
26
+ const input = parseJson(text);
27
+ if (!isRecord(input)) return {};
28
+ const { session_id, stop_hook_active, cwd, source, last_assistant_message } = input;
29
+ return {
30
+ ...(typeof session_id === "string" ? { session_id } : {}),
31
+ ...(typeof stop_hook_active === "boolean" ? { stop_hook_active } : {}),
32
+ ...(typeof cwd === "string" ? { cwd } : {}),
33
+ ...(typeof source === "string" ? { source } : {}),
34
+ ...(typeof last_assistant_message === "string" ? { last_assistant_message } : {}),
35
+ };
36
+ }
37
+
38
+ function sendBacks(count: number): string {
39
+ return count === 1 ? "1 send-back" : `${count} send-backs`;
40
+ }
41
+
42
+ // How the stop ends, after the totals: sent back, stopped by the cap, or handed back once the agent was sent back.
43
+ function ending({ sendBack, count, max, open }: Judged): string {
44
+ if (sendBack) return `the agent is sent back to fix it (${count} of ${max})`;
45
+ if (open.length) return max === 0 ? "send-backs are off" : `stopped after ${sendBacks(count)}`;
46
+ return count ? `after ${sendBacks(count)}` : "";
47
+ }
48
+
49
+ // What the agent is told besides the reports: where it stands, and what became of its waive lines.
50
+ function told({ count, max, waived, fallen, unknown, gates }: Judged): string[] {
51
+ const names = (list: string[]) => list.join(", ");
52
+ return [
53
+ `This is send-back ${count} of ${max}.`,
54
+ ...(waived.length ? [`Waived this turn, not to fix: ${names(waived.map(({ name }) => name))}.`] : []),
55
+ ...(fallen.length
56
+ ? [`Your waiver of ${names(fallen)} no longer holds: its report changed. Fix it, or waive it again.`]
57
+ : []),
58
+ ...(unknown.length ? [`No gate is named ${names(unknown)}. The gates of this turn: ${names(gates)}.`] : []),
59
+ ];
60
+ }
61
+
62
+ /**
63
+ * A red gate the agent did not waive sends it back with the reports, until the turn reaches its cap: a fix that
64
+ * breaks another gate is caught, and a gate the agent cannot satisfy never loops. The owner sees each stop, the
65
+ * waived gates with their reasons, and why the turn ended.
66
+ */
67
+ export function stopOutput(turn: CheckedTurn, judged: Judged): HookOutput {
68
+ const systemMessage = summary(turn, ending(judged), judged.waived);
69
+ if (!judged.sendBack) return { systemMessage };
70
+ return { decision: "block", reason: failures({ ...turn, outcomes: judged.open }, told(judged)), systemMessage };
71
+ }
72
+
73
+ // When the gates cannot run, such as with a gates file that does not parse, only the owner is told: a crash would
74
+ // show them a stack trace at best, and the agent is not to blame.
75
+ function cannotRun(error: unknown): HookOutput {
76
+ return { systemMessage: broken(messageOf(error)) };
77
+ }
78
+
79
+ /**
80
+ * A prompt ends the turn in progress; from a folder with no gates, or when the turn cannot start, no check will look
81
+ * for a new one. When the gates of the repo miss tools, the agent is asked once to install them.
82
+ */
83
+ async function promptHook(session: string, cwd: string): Promise<HookOutput | undefined> {
84
+ try {
85
+ forgetTurn(session);
86
+ const root = configuredRoot(cwd);
87
+ if (root === undefined) return undefined;
88
+ const missing = await startTurn(session, root);
89
+ if (!tellOnce(session, root, missing)) return undefined;
90
+ return {
91
+ systemMessage: toolsMissing(missing),
92
+ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: toolsToInstall(missing) },
93
+ };
94
+ } catch (error) {
95
+ return cannotRun(error);
96
+ }
97
+ }
98
+
99
+ /**
100
+ * A stop checks the repo its turn started in, whatever folder the agent stops in, or that folder's repo otherwise,
101
+ * reads the gates the agent's last message waives, and records what it told the agent for the next stop of the turn.
102
+ */
103
+ async function stopHook(
104
+ session: string,
105
+ cwd: string,
106
+ retry: boolean,
107
+ message: string,
108
+ ): Promise<HookOutput | undefined> {
109
+ const root = turnRoot(session, retry) ?? configuredRoot(cwd);
110
+ if (root === undefined) return undefined;
111
+ try {
112
+ const checked = await checkTurn(session, root);
113
+ const turn = readTurn(session, root);
114
+ if (turn === undefined) throw new Error("the turn was not recorded after its check.");
115
+ const { gates, refused, maxSendBacks } = gatesOf(turn.config);
116
+ const names = [...gates.map(({ name }) => name), ...refused.map(({ name }) => name)];
117
+ const judged = judge(checked, waivesOf(message), names, maxSendBacks, turn.sendBacks);
118
+ writeTurn(session, root, { ...turn, sendBacks: judged.state });
119
+ return stopOutput(checked, judged);
120
+ } catch (error) {
121
+ return cannotRun(error);
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Handles a hook event of a coding agent: Claude Code and Codex send the same input and read the same output. It does
127
+ * nothing outside git, or in a repo with no gates file.
128
+ */
129
+ export async function handleHook(event: HookEvent, text: string): Promise<HookOutput | undefined> {
130
+ const {
131
+ session_id: session,
132
+ stop_hook_active: retry = false,
133
+ cwd = process.cwd(),
134
+ source,
135
+ last_assistant_message: message = "",
136
+ } = parseHookInput(text);
137
+ if (session === undefined) return undefined;
138
+ // A session that starts, resumes or is cleared asks again for the missing tools; a compaction goes on as it was.
139
+ if (event === "session-start") {
140
+ if (source !== "compact") forgetTold(session);
141
+ return undefined;
142
+ }
143
+ return event === "turn-start" ? promptHook(session, cwd) : stopHook(session, cwd, retry, message);
144
+ }
package/src/testing.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { mkdtempSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import type { CheckedTurn } from "./core/check.ts";
6
+ import type { Outcome } from "./core/run.ts";
7
+
8
+ // What the tests of the engine build again and again: a repo of their own, its commits, its gates, and a turn. It
9
+ // runs git by itself: every test imports this file, so a module of the engine imported here would make every test
10
+ // related to it.
11
+
12
+ export function git(repo: string, args: string[]): string {
13
+ return execFileSync("git", args, { cwd: repo, encoding: "utf8", stdio: "pipe" }).trim();
14
+ }
15
+
16
+ /** A fresh git repo in a temporary folder, for the test to remove. */
17
+ export function tempRepo(): string {
18
+ const repo = mkdtempSync(join(tmpdir(), "gates-test-"));
19
+ git(repo, ["init", "--quiet", "--template="]);
20
+ return repo;
21
+ }
22
+
23
+ /** Commits every file, with an identity git may not have on the machine. */
24
+ export function commitAll(repo: string, message: string): void {
25
+ git(repo, ["add", "--all"]);
26
+ git(repo, ["-c", "user.name=test", "-c", "user.email=test@test.invalid", "commit", "--quiet", "-m", message]);
27
+ }
28
+
29
+ export function writeGates(repo: string, ...gates: object[]): void {
30
+ writeFileSync(join(repo, ".gates.json"), JSON.stringify({ gates }));
31
+ }
32
+
33
+ export function outcome(name: string, ok: boolean, ms = 10): Outcome {
34
+ return { name, ok, ms, output: `${name} report`, report: `${name} report` };
35
+ }
36
+
37
+ export function ran(outcomes: Outcome[], skipped: string[] = [], ms = 20): CheckedTurn {
38
+ return { changed: ["src/a.ts"], outcomes, skipped, ms };
39
+ }