@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,168 @@
1
+ import { readdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { basename, join } from "node:path";
3
+ import { type Gate, isCompared, parseGates } from "../core/config.ts";
4
+ import { isRecord, messageOf } from "../core/json.ts";
5
+
6
+ // The catalog lists the gates worth copying into a repo, one file per technology. It never runs by itself: the engine
7
+ // reads only .gates.json, and a developer or an agent copies from here what a repo needs.
8
+
9
+ export const CATALOG_DIR = join(import.meta.dirname, "..", "..", "catalog");
10
+ export const PAGE = join(CATALOG_DIR, "index.html");
11
+
12
+ export interface Requirement {
13
+ tool: string;
14
+ install: string;
15
+ }
16
+
17
+ export interface Entry {
18
+ id: string;
19
+ description: string;
20
+ requires: Requirement[];
21
+ gate: Gate;
22
+ definition: Record<string, unknown>;
23
+ }
24
+
25
+ export interface Catalog {
26
+ id: string;
27
+ title: string;
28
+ description: string;
29
+ entries: Entry[];
30
+ }
31
+
32
+ function isRequirement(value: unknown): value is Requirement {
33
+ return isRecord(value) && typeof value.tool === "string" && typeof value.install === "string";
34
+ }
35
+
36
+ function parseEntry(catalogId: string, value: unknown, index: number): Entry {
37
+ const definition = isRecord(value) && isRecord(value.gate) ? value.gate : {};
38
+ const id = `${catalogId}/${typeof definition.name === "string" ? definition.name : `#${index + 1}`}`;
39
+ function refuse(problem: string): never {
40
+ throw new Error(`${id}: ${problem}.`);
41
+ }
42
+ if (!isRecord(value)) refuse("an entry is an object");
43
+ const { description, requires } = value;
44
+ if (typeof description !== "string" || !description) refuse("description says what the gate catches");
45
+ if (!Array.isArray(requires) || !requires.every(isRequirement))
46
+ refuse("requires lists the tools to install, as {tool, install}");
47
+ let gate: Gate | undefined;
48
+ try {
49
+ [gate] = parseGates(JSON.stringify({ gates: [definition] }));
50
+ } catch (error) {
51
+ refuse(messageOf(error).replace(/\.$/, ""));
52
+ }
53
+ if (gate === undefined) refuse('a catalog gate has severity "error"');
54
+ return { id, description, requires, gate, definition };
55
+ }
56
+
57
+ export function parseCatalog(id: string, text: string): Catalog {
58
+ const parsed: unknown = JSON.parse(text);
59
+ if (!isRecord(parsed) || typeof parsed.title !== "string" || typeof parsed.description !== "string")
60
+ throw new Error(`${id}: a catalog has a title and a description.`);
61
+ if (!Array.isArray(parsed.gates)) throw new Error(`${id}: a catalog lists its gates.`);
62
+ const entries = parsed.gates.map((entry: unknown, index) => parseEntry(id, entry, index));
63
+ const seen = new Set<string>();
64
+ for (const entry of entries) {
65
+ if (seen.has(entry.id)) throw new Error(`${entry.id}: twice in the catalog.`);
66
+ seen.add(entry.id);
67
+ }
68
+ return { id, title: parsed.title, description: parsed.description, entries };
69
+ }
70
+
71
+ export function readCatalogs(dir: string): Catalog[] {
72
+ return readdirSync(dir)
73
+ .filter((file) => file.endsWith(".json"))
74
+ .sort()
75
+ .map((file) => parseCatalog(basename(file, ".json"), readFileSync(join(dir, file), "utf8")));
76
+ }
77
+
78
+ function escape(text: string): string {
79
+ return text.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
80
+ }
81
+
82
+ function linked(text: string): string {
83
+ return escape(text).replace(/https:\/\/[^\s,]+/g, (url) => `<a href="${url}">${url}</a>`);
84
+ }
85
+
86
+ function entryHtml(entry: Entry): string {
87
+ const { id, description, requires, gate, definition } = entry;
88
+ const compare = isCompared(gate) ? "<dt>Fails on</dt><dd>only the output lines the turn added</dd>" : "";
89
+ const tools = requires.map(({ tool, install }) => `<li><code>${escape(tool)}</code>: ${linked(install)}</li>`);
90
+ return `<article id="${escape(id)}">
91
+ <h3><code>${escape(id)}</code></h3>
92
+ <p>${escape(description)}</p>
93
+ <dl>
94
+ <dt>Runs</dt><dd><code>${escape(gate.run.join(" "))}</code></dd>
95
+ <dt>When the turn changes</dt><dd><code>${escape(gate.files)}</code></dd>
96
+ ${compare}<dt>Requires</dt><dd><ul>${tools.join("")}</ul></dd>
97
+ </dl>
98
+ <details><summary>Definition to copy into .gates.json</summary><pre><code>${escape(JSON.stringify(definition, null, 2))}</code></pre></details>
99
+ </article>`;
100
+ }
101
+
102
+ function catalogSection({ id, title, description, entries }: Catalog): string {
103
+ return `<section id="${escape(id)}">
104
+ <h2>${escape(title)}</h2>
105
+ <p>${escape(description)}</p>
106
+ ${entries.map(entryHtml).join("\n")}
107
+ </section>`;
108
+ }
109
+
110
+ const STYLE = `
111
+ :root { --bg: #fafaf9; --panel: #ffffff; --text: #1c1917; --muted: #57534e; --line: #e7e5e4; --code: #f5f5f4;
112
+ --link: #1d4ed8; }
113
+ @media (prefers-color-scheme: dark) {
114
+ :root { --bg: #1c1917; --panel: #262321; --text: #f5f5f4; --muted: #a8a29e; --line: #3f3a36; --code: #2f2a27;
115
+ --link: #93c5fd; }
116
+ }
117
+ * { box-sizing: border-box; }
118
+ body { margin: 0; background: var(--bg); color: var(--text); font: 16px/1.55 system-ui, sans-serif; }
119
+ main { max-width: 860px; margin: 0 auto; padding: 32px 16px 64px; }
120
+ h1 { margin: 0 0 8px; font-size: 1.9rem; }
121
+ h2 { margin: 48px 0 4px; font-size: 1.4rem; }
122
+ h3 { margin: 0; font-size: 1rem; }
123
+ p, dd, li { color: var(--muted); }
124
+ a { color: var(--link); }
125
+ nav { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 16px; }
126
+ nav a { padding: 4px 12px; border: 1px solid var(--line); border-radius: 999px; text-decoration: none; }
127
+ article { margin: 16px 0; padding: 16px; background: var(--panel); border: 1px solid var(--line); border-radius: 10px; }
128
+ dl { display: grid; grid-template-columns: max-content 1fr; gap: 4px 16px; margin: 12px 0; }
129
+ dt { font-weight: 600; }
130
+ dd { margin: 0; min-width: 0; }
131
+ dd ul { margin: 0; padding-left: 18px; }
132
+ code { font: 0.88em/1.4 ui-monospace, monospace; background: var(--code); padding: 1px 5px; border-radius: 4px;
133
+ overflow-wrap: anywhere; }
134
+ pre { overflow-x: auto; background: var(--code); padding: 12px; border-radius: 8px; }
135
+ pre code { padding: 0; }
136
+ summary { cursor: pointer; color: var(--muted); }
137
+ @media (max-width: 560px) { dl { grid-template-columns: 1fr; } dd { margin-bottom: 8px; } }
138
+ `;
139
+
140
+ /** The page a developer browses. It is generated from the catalog files, and a test fails when it falls behind them. */
141
+ export function catalogHtml(catalogs: Catalog[]): string {
142
+ const nav = catalogs.map(
143
+ ({ id, title, entries }) => `<a href="#${escape(id)}">${escape(title)} (${entries.length})</a>`,
144
+ );
145
+ return `<!doctype html>
146
+ <html lang="en">
147
+ <head>
148
+ <meta charset="utf-8">
149
+ <meta name="viewport" content="width=device-width, initial-scale=1">
150
+ <title>Gate catalog</title>
151
+ <style>${STYLE}</style>
152
+ </head>
153
+ <body>
154
+ <main>
155
+ <header>
156
+ <h1>Gate catalog</h1>
157
+ <p>The gates worth copying into a repo. Nothing here runs by itself: the engine reads only the repo's <code>.gates.json</code>. Copy the definition of a gate there, install what it requires, and adapt its <code>files</code> to the layout of the repo.</p>
158
+ <p>Generated from <code>catalog/*.json</code> by <code>pnpm catalog</code>: edit those files, never this page.</p>
159
+ <nav>${nav.join("")}</nav>
160
+ </header>
161
+ ${catalogs.map(catalogSection).join("\n")}
162
+ </main>
163
+ </body>
164
+ </html>
165
+ `;
166
+ }
167
+
168
+ if (import.meta.main) writeFileSync(PAGE, catalogHtml(readCatalogs(CATALOG_DIR)));
package/src/cli.ts ADDED
@@ -0,0 +1,53 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { checkAll } from "./core/check.ts";
3
+ import { configuredRoot } from "./core/config.ts";
4
+ import { messageOf } from "./core/json.ts";
5
+ import { broken, reports, summary } from "./core/report.ts";
6
+ import { failed } from "./core/run.ts";
7
+ import { handleHook } from "./hook/hook.ts";
8
+
9
+ function readStdin(): string {
10
+ try {
11
+ return readFileSync(0, "utf8");
12
+ } catch {
13
+ return "";
14
+ }
15
+ }
16
+
17
+ const [command, event] = process.argv.slice(2);
18
+
19
+ // The helpers of the engine run only on import.meta.main, which came with Node 24.2: below, they are a silent green.
20
+ const [major = 0, minor = 0] = process.versions.node.split(".").map(Number);
21
+ const oldNode =
22
+ major < 24 || (major === 24 && minor < 2)
23
+ ? `Node 24.2 or later is needed, this is ${process.versions.node}.`
24
+ : undefined;
25
+
26
+ if (oldNode !== undefined) {
27
+ if (command === "hook") console.log(JSON.stringify({ systemMessage: broken(oldNode) }));
28
+ else {
29
+ console.error(oldNode);
30
+ process.exitCode = 2;
31
+ }
32
+ } else if (command === "hook" && (event === "session-start" || event === "turn-start" || event === "check")) {
33
+ const output = await handleHook(event, readStdin());
34
+ if (output) console.log(JSON.stringify(output));
35
+ } else if (command === "check" && event === undefined) {
36
+ const root = configuredRoot(process.cwd());
37
+ if (root === undefined) {
38
+ console.error("Not in a git repository, or no .gates.json in it.");
39
+ process.exitCode = 2;
40
+ } else {
41
+ try {
42
+ const all = await checkAll(root);
43
+ console.log([summary(all), ...reports(all.outcomes)].join("\n\n"));
44
+ if (all.outcomes.some(failed)) process.exitCode = 1;
45
+ } catch (error) {
46
+ console.error(`Could not run: ${messageOf(error)}`);
47
+ process.exitCode = 2;
48
+ }
49
+ }
50
+ } else {
51
+ console.error("Usage: node src/cli.ts hook <session-start|turn-start|check>, or node src/cli.ts check");
52
+ process.exitCode = 2;
53
+ }
@@ -0,0 +1,209 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { changedGatesFiles, type Gate, type Gates, gatesOf, isCompared, readGatesFiles } from "./config.ts";
4
+ import { cachedReports, cacheReports } from "./report-cache.ts";
5
+ import { check, filesOf, givenFiles, missingTool, type Outcome, wholeProject } from "./run.ts";
6
+ import { changedSince, emptyCommit, hasCommit, lastCommit, snapshot, workingTree } from "./snapshot.ts";
7
+ import { readTurn, type TurnState, writeTurn } from "./turn-state.ts";
8
+
9
+ export interface CheckedTurn {
10
+ changed: string[];
11
+ outcomes: Outcome[];
12
+ skipped: string[];
13
+ ms: number;
14
+ note?: string;
15
+ showAllPasses?: boolean;
16
+ }
17
+
18
+ /** A gate of the turn, with its outcome when it ran. */
19
+ interface Result {
20
+ gate: Gate;
21
+ outcome?: Outcome;
22
+ }
23
+
24
+ /** The report a compared gate compares with, or nothing when the turn has none for it. */
25
+ type Baselines = (gate: Gate) => string | undefined;
26
+
27
+ /** A gate whose program this machine does not have, with why. It never runs, so it never sends the agent back. */
28
+ interface Missing {
29
+ gate: Gate;
30
+ why: string;
31
+ }
32
+
33
+ function missingTools(root: string, gates: Gate[]): Missing[] {
34
+ return gates.flatMap((gate) => {
35
+ const why = missingTool(root, gate);
36
+ return why === undefined ? [] : [{ gate, why }];
37
+ });
38
+ }
39
+
40
+ function runnable(gates: Gate[], missing: Missing[]): Gate[] {
41
+ return gates.filter((gate) => !missing.some((tool) => tool.gate === gate));
42
+ }
43
+
44
+ /**
45
+ * Records the commit a turn starts from, and the reports its compared gates will compare with. After an interrupted
46
+ * turn, the next one of the repo starts where it did, so its check also covers what the interrupted one changed.
47
+ * Gives, gate by gate, the tools this machine misses to run the gates of the repo.
48
+ */
49
+ export async function startTurn(session: string, root: string): Promise<string[]> {
50
+ const config = readGatesFiles(root);
51
+ const { gates } = gatesOf(config);
52
+ const missing = missingTools(root, gates);
53
+ const told = missing.map(({ gate, why }) => `${gate.name}: ${why}`);
54
+ const compared = runnable(gates, missing).filter(isCompared);
55
+ const interrupted = readTurn(session, root);
56
+ if (interrupted?.checked === false) {
57
+ writeTurn(session, root, interrupted);
58
+ return told;
59
+ }
60
+ const { commit: start, tree } = snapshot(root);
61
+ const cached = cachedReports(root, tree);
62
+ const baselines = await Promise.all(
63
+ compared.map(async (gate) => {
64
+ const cachedReport = cached(gate);
65
+ return {
66
+ gate,
67
+ ...(cachedReport === undefined ? await wholeProject(root, gate) : { ok: true, output: cachedReport }),
68
+ };
69
+ }),
70
+ );
71
+ // A report from a command that broke still serves this turn, since checking too much beats leaving a hole, but it
72
+ // is never kept for the next one.
73
+ cacheReports(
74
+ root,
75
+ tree,
76
+ baselines.filter(({ ok }) => ok).map(({ gate, output }) => [gate, output] as const),
77
+ );
78
+ writeTurn(session, root, {
79
+ start,
80
+ baselines: Object.fromEntries(baselines.map(({ gate, output }) => [gate.name, output])),
81
+ config,
82
+ checked: false,
83
+ });
84
+ return told;
85
+ }
86
+
87
+ /**
88
+ * Runs, in parallel, each gate that looks at a changed file. A deleted file counts as changed, since a gate that
89
+ * reads the whole project may break on it, but is never named: a gate given {files} looks at the files left, and
90
+ * is skipped when none is.
91
+ */
92
+ function runGates(
93
+ root: string,
94
+ gates: Gate[],
95
+ changed: string[],
96
+ turn: string,
97
+ baselines: Baselines,
98
+ ): Promise<Result[]> {
99
+ return Promise.all(
100
+ gates.map(async (gate) => {
101
+ const matching = filesOf(gate, changed);
102
+ const files = givenFiles(gate) ? matching.filter((file) => existsSync(join(root, file))) : matching;
103
+ if (!files.length) return { gate };
104
+ return { gate, outcome: await check(root, gate, files, turn, baselines(gate)) };
105
+ }),
106
+ );
107
+ }
108
+
109
+ function checkedTurn(
110
+ changed: string[],
111
+ results: Result[],
112
+ started: number,
113
+ notes: string[],
114
+ showAllPasses: boolean,
115
+ ): CheckedTurn {
116
+ return {
117
+ changed,
118
+ outcomes: results.flatMap(({ outcome }) => (outcome ? [outcome] : [])),
119
+ skipped: results.filter(({ outcome }) => !outcome).map(({ gate }) => gate.name),
120
+ ms: performance.now() - started,
121
+ note: notes.join("\n") || undefined,
122
+ ...(showAllPasses ? { showAllPasses } : {}),
123
+ };
124
+ }
125
+
126
+ /**
127
+ * Runs each gate on every file of the repo, as if one turn had written it all: a compared gate counts every line
128
+ * of its report, and a gate given the turn gets the empty tree. The state of the repo, for the owner or an agent
129
+ * asked to clean it up, where the hook only ever judges a turn.
130
+ */
131
+ export async function checkAll(root: string): Promise<CheckedTurn> {
132
+ const started = performance.now();
133
+ const empty = emptyCommit(root);
134
+ const files = changedSince(root, empty);
135
+ const { gates, refused, showAllPasses } = gatesOf(readGatesFiles(root));
136
+ const results = await runGates(root, gates, files, empty, () => "");
137
+ return checkedTurn(files, results, started, refusedNotes(refused), showAllPasses);
138
+ }
139
+
140
+ // A report holds for the tree a turn ends on only if the gate ran clean on the whole project. A gate that failed
141
+ // keeps the report it started from, so what the turn added stays new until it is fixed, and a gate that did not run
142
+ // keeps none: it may still read a changed file its pattern misses, as knip reads tsconfig.json.
143
+ function endReports(results: Result[], baselines: Baselines) {
144
+ return results.flatMap(({ gate, outcome }) => {
145
+ if (!isCompared(gate) || !outcome) return [];
146
+ const report = outcome.ok ? outcome.report : baselines(gate);
147
+ return report === undefined ? [] : [[gate, report] as const];
148
+ });
149
+ }
150
+
151
+ /**
152
+ * Runs each gate that looks at a file the turn changed, with the gates as the turn started: an agent that weakens
153
+ * them mid-turn changes the next turn, never its own. Without a recorded start, the turn runs from the last commit
154
+ * with the gates of now; with a start git no longer has, from the last commit with the gates and the reports it
155
+ * started with: checking too much beats leaving a hole.
156
+ */
157
+ export async function checkTurn(session: string, root: string): Promise<CheckedTurn> {
158
+ const recorded = readTurn(session, root);
159
+ const kept = recorded !== undefined && hasCommit(root, recorded.start) ? recorded : undefined;
160
+ const startNote =
161
+ recorded === undefined
162
+ ? "no turn start recorded: checked every change since the last commit"
163
+ : kept === undefined
164
+ ? "turn start lost (history rewritten?): checked every change since the last commit"
165
+ : undefined;
166
+ const now = readGatesFiles(root);
167
+ const turn: TurnState = {
168
+ start: kept?.start ?? lastCommit(root),
169
+ baselines: recorded?.baselines ?? {},
170
+ config: recorded?.config ?? now,
171
+ checked: false,
172
+ // What the earlier stops of the turn told the agent goes on, so its send-backs and waivers add up.
173
+ ...(recorded?.sendBacks ? { sendBacks: recorded.sendBacks } : {}),
174
+ };
175
+ const baselines: Baselines = (gate) => turn.baselines[gate.name];
176
+ const started = performance.now();
177
+ const end = workingTree(root);
178
+ const changed = changedSince(root, turn.start, end);
179
+ const { gates, refused, showAllPasses } = gatesOf(turn.config);
180
+ const missing = missingTools(root, gates);
181
+ const results = await runGates(root, runnable(gates, missing), changed, turn.start, baselines);
182
+ cacheReports(root, end, endReports(results, baselines));
183
+ writeTurn(session, root, { ...turn, checked: true });
184
+ // A compared gate with no report from the turn start can only count its exit code: a green it did not earn is said.
185
+ const uncompared = results
186
+ .filter(({ gate, outcome }) => outcome && isCompared(gate) && baselines(gate) === undefined)
187
+ .map(({ gate }) => `${gate.name} not compared: no report from the turn start, only its exit code counted`);
188
+ // Only a gate the turn concerned is named: one that would not have run anyway costs nothing to miss.
189
+ const notRun = missing
190
+ .filter(({ gate }) => filesOf(gate, changed).length)
191
+ .map(({ gate, why }) => `${gate.name} not run: ${why}`);
192
+ const notes = [
193
+ ...(startNote ? [startNote] : []),
194
+ ...configNote(changedGatesFiles(turn.config, now)),
195
+ ...uncompared,
196
+ ...refusedNotes(refused),
197
+ ...notRun,
198
+ ];
199
+ return checkedTurn(changed, results, started, notes, showAllPasses);
200
+ }
201
+
202
+ function refusedNotes(refused: Gates["refused"]): string[] {
203
+ return refused.map(({ name, why }) => `${name} not run, its entry is wrong: ${why}`);
204
+ }
205
+
206
+ function configNote(changedFiles: string[]): string[] {
207
+ if (!changedFiles.length) return [];
208
+ return [`the turn changed ${changedFiles.join(" and ")}: checked with the gates as the turn started`];
209
+ }
@@ -0,0 +1,225 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { isRecord, isStringArray, messageOf } from "./json.ts";
4
+ import { repoRoot } from "./snapshot.ts";
5
+
6
+ const GATES_FILE = ".gates.json";
7
+ const LOCAL_GATES_FILE = ".gates.local.json";
8
+
9
+ // The time the gates of a check have, all together: they start at once, so each one stops at the latest when it ends.
10
+ const DEFAULT_MAX_TIMEOUT_SECONDS = 45;
11
+ // The times a turn sends the agent back: enough for a fix that breaks another gate, never a loop.
12
+ const DEFAULT_MAX_SEND_BACKS = 5;
13
+ const FIELDS = new Set(["name", "severity", "files", "run", "compare", "ignoreLines", "timeoutSeconds"]);
14
+
15
+ /** In the arguments of a gate: the changed files it looks at, and the commit of the turn start. */
16
+ export const FILES = "{files}";
17
+ export const TURN = "{turn}";
18
+
19
+ export interface Gate {
20
+ name: string;
21
+ severity: "error" | "off";
22
+ files: string;
23
+ run: string[];
24
+ compare?: "turn-start";
25
+ ignoreLines?: string;
26
+ timeoutSeconds: number;
27
+ }
28
+
29
+ type Entry = Record<string, unknown> & { name: string };
30
+
31
+ /** A gate that fails on the lines of output the turn added, with the report of the turn start to compare with. */
32
+ export function isCompared(gate: Gate): boolean {
33
+ return gate.compare === "turn-start";
34
+ }
35
+
36
+ // The problem of one gate: the gate is left out, never the others.
37
+ function refuse(problem: string): never {
38
+ throw new Error(problem);
39
+ }
40
+
41
+ /**
42
+ * What a gates file holds: its gates, and when it says, the most seconds a gate may take, how passes show and the
43
+ * most times a turn sends the agent back.
44
+ */
45
+ interface GatesFile {
46
+ entries: Entry[];
47
+ maxTimeoutSeconds?: unknown;
48
+ showAllPasses?: unknown;
49
+ maxSendBacks?: unknown;
50
+ }
51
+
52
+ function fileOf(text: string | undefined, file: string): GatesFile {
53
+ if (text === undefined) return { entries: [] };
54
+ let parsed: unknown;
55
+ try {
56
+ parsed = JSON.parse(text);
57
+ } catch (error) {
58
+ throw new Error(`${file} is not valid JSON: ${messageOf(error)}.`);
59
+ }
60
+ const {
61
+ gates = [],
62
+ maxTimeoutSeconds,
63
+ showAllPasses,
64
+ maxSendBacks,
65
+ ...others
66
+ } = isRecord(parsed) ? parsed : { others: true };
67
+ if (!Array.isArray(gates) || Object.keys(others).length)
68
+ throw new Error(
69
+ `${file} holds "gates", a list of gates, "maxTimeoutSeconds", the most seconds a gate may take, ` +
70
+ `"showAllPasses", to name every green gate, and "maxSendBacks", the most times a turn sends the agent back.`,
71
+ );
72
+ const entries = gates.map((entry: unknown) => {
73
+ if (!isRecord(entry) || typeof entry.name !== "string") throw new Error(`${file}: every gate has a name.`);
74
+ return { ...entry, name: entry.name };
75
+ });
76
+ return {
77
+ entries,
78
+ ...(maxTimeoutSeconds === undefined ? {} : { maxTimeoutSeconds }),
79
+ ...(showAllPasses === undefined ? {} : { showAllPasses }),
80
+ ...(maxSendBacks === undefined ? {} : { maxSendBacks }),
81
+ };
82
+ }
83
+
84
+ // The local file's own value wins, as for the fields of a gate.
85
+ function maxTimeoutOf(shared: GatesFile, local: GatesFile): number {
86
+ const max = local.maxTimeoutSeconds ?? shared.maxTimeoutSeconds ?? DEFAULT_MAX_TIMEOUT_SECONDS;
87
+ if (typeof max !== "number" || max <= 0) throw new Error("maxTimeoutSeconds is a positive number.");
88
+ return max;
89
+ }
90
+
91
+ // Off by default: the summary names the slowest passes and counts the rest.
92
+ function showAllPassesOf(shared: GatesFile, local: GatesFile): boolean {
93
+ const show = local.showAllPasses ?? shared.showAllPasses ?? false;
94
+ if (typeof show !== "boolean") throw new Error("showAllPasses is true or false.");
95
+ return show;
96
+ }
97
+
98
+ // 0 never sends the agent back: the owner only sees the summary.
99
+ function maxSendBacksOf(shared: GatesFile, local: GatesFile): number {
100
+ const max = local.maxSendBacks ?? shared.maxSendBacks ?? DEFAULT_MAX_SEND_BACKS;
101
+ if (typeof max !== "number" || !Number.isInteger(max) || max < 0)
102
+ throw new Error("maxSendBacks is a whole number, 0 or more.");
103
+ return max;
104
+ }
105
+
106
+ function isPattern(value: unknown): value is string {
107
+ if (typeof value !== "string") return false;
108
+ try {
109
+ new RegExp(value);
110
+ return true;
111
+ } catch {
112
+ return false;
113
+ }
114
+ }
115
+
116
+ function toGate(entry: Entry, maxTimeoutSeconds: number): Gate {
117
+ const { name, severity, files, run, compare, ignoreLines, timeoutSeconds = maxTimeoutSeconds } = entry;
118
+ const unknown = Object.keys(entry).find((key) => !FIELDS.has(key));
119
+ if (unknown !== undefined) refuse(`unknown field ${unknown}`);
120
+ if (!/^[a-z][a-z0-9-]*$/.test(name)) refuse("a name is lowercase words joined by hyphens");
121
+ if (severity !== "error" && severity !== "off")
122
+ refuse('severity is "error" or "off": a warning sends nobody back to fix it');
123
+ if (!isPattern(files)) refuse("files is a regular expression on the repo-relative paths");
124
+ if (!isStringArray(run) || !run.length) refuse("run is a non-empty list of strings");
125
+ if (compare !== undefined && compare !== "turn-start") refuse('compare is "turn-start"');
126
+ if (compare !== undefined && run.includes(FILES))
127
+ refuse(`a compared gate reads the whole project: it takes no ${FILES}`);
128
+ if (ignoreLines !== undefined && !isPattern(ignoreLines)) refuse("ignoreLines is a regular expression");
129
+ if (typeof timeoutSeconds !== "number" || timeoutSeconds <= 0) refuse("timeoutSeconds is a positive number");
130
+ return {
131
+ name,
132
+ severity,
133
+ files,
134
+ run,
135
+ // A gate may stop sooner than the others, never later.
136
+ timeoutSeconds: Math.min(timeoutSeconds, maxTimeoutSeconds),
137
+ ...(compare === undefined ? {} : { compare }),
138
+ ...(ignoreLines === undefined ? {} : { ignoreLines }),
139
+ };
140
+ }
141
+
142
+ /**
143
+ * The gates a check runs, the ones it leaves out for a problem of their own, with why, how passes show, and the most
144
+ * times a turn sends the agent back.
145
+ */
146
+ export interface Gates {
147
+ gates: Gate[];
148
+ refused: { name: string; why: string }[];
149
+ showAllPasses: boolean;
150
+ maxSendBacks: number;
151
+ }
152
+
153
+ /**
154
+ * Reads the shared gates and the developer's own. A local entry named like a shared one changes only the fields it
155
+ * gives, such as {"name": "lint", "severity": "off"}. Any other local entry adds a gate. A gate with a problem of its
156
+ * own is left out, and the others still run: only a file that cannot be read stops them all.
157
+ */
158
+ export function readGates(shared: string | undefined, local?: string): Gates {
159
+ const sharedFile = fileOf(shared, GATES_FILE);
160
+ const localFile = fileOf(local, LOCAL_GATES_FILE);
161
+ const max = maxTimeoutOf(sharedFile, localFile);
162
+ const merged = new Map(sharedFile.entries.map((entry) => [entry.name, entry]));
163
+ for (const entry of localFile.entries) merged.set(entry.name, { ...merged.get(entry.name), ...entry });
164
+ const read: Gates = {
165
+ gates: [],
166
+ refused: [],
167
+ showAllPasses: showAllPassesOf(sharedFile, localFile),
168
+ maxSendBacks: maxSendBacksOf(sharedFile, localFile),
169
+ };
170
+ for (const entry of merged.values()) {
171
+ if (entry.severity === "off") continue;
172
+ try {
173
+ read.gates.push(toGate(entry, max));
174
+ } catch (error) {
175
+ read.refused.push({ name: entry.name, why: messageOf(error) });
176
+ }
177
+ }
178
+ return read;
179
+ }
180
+
181
+ /** The gates of the two files, refusing the first gate with a problem, as a catalog does. */
182
+ export function parseGates(shared: string | undefined, local?: string): Gate[] {
183
+ const { gates, refused } = readGates(shared, local);
184
+ const [first] = refused;
185
+ if (first !== undefined) throw new Error(`Gate ${first.name}: ${first.why}.`);
186
+ return gates;
187
+ }
188
+
189
+ function readIfPresent(path: string): string | undefined {
190
+ try {
191
+ return readFileSync(path, "utf8");
192
+ } catch (error) {
193
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
194
+ throw error;
195
+ }
196
+ }
197
+
198
+ /** The text of the two gates files, each absent when the repo does not have it. */
199
+ export interface GatesFiles {
200
+ shared?: string;
201
+ local?: string;
202
+ }
203
+
204
+ export function readGatesFiles(root: string): GatesFiles {
205
+ return { shared: readIfPresent(join(root, GATES_FILE)), local: readIfPresent(join(root, LOCAL_GATES_FILE)) };
206
+ }
207
+
208
+ export function gatesOf({ shared, local }: GatesFiles): Gates {
209
+ return readGates(shared, local);
210
+ }
211
+
212
+ /** The gates files a turn changed, by name: a turn is checked with the gates it started with, whatever it did to them. */
213
+ export function changedGatesFiles(before: GatesFiles, after: GatesFiles): string[] {
214
+ return [
215
+ ...(before.shared === after.shared ? [] : [GATES_FILE]),
216
+ ...(before.local === after.local ? [] : [LOCAL_GATES_FILE]),
217
+ ];
218
+ }
219
+
220
+ /** The repo to check from a working directory, or nothing outside git or in a repo with no gates file. */
221
+ export function configuredRoot(cwd: string): string | undefined {
222
+ const root = repoRoot(cwd);
223
+ if (root === undefined) return undefined;
224
+ return [GATES_FILE, LOCAL_GATES_FILE].some((file) => existsSync(join(root, file))) ? root : undefined;
225
+ }
@@ -0,0 +1,36 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ export function isRecord(value: unknown): value is Record<string, unknown> {
4
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5
+ }
6
+
7
+ export function isStringRecord(value: unknown): value is Record<string, string> {
8
+ return isRecord(value) && Object.values(value).every((entry) => typeof entry === "string");
9
+ }
10
+
11
+ export function isStringArray(value: unknown): value is string[] {
12
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
13
+ }
14
+
15
+ /** The message of whatever was thrown. */
16
+ export function messageOf(error: unknown): string {
17
+ return error instanceof Error ? error.message : String(error);
18
+ }
19
+
20
+ /** What the text holds as JSON, or nothing when it is not JSON. */
21
+ export function parseJson(text: string): unknown {
22
+ try {
23
+ return JSON.parse(text);
24
+ } catch {
25
+ return undefined;
26
+ }
27
+ }
28
+
29
+ /** What the file holds as JSON, or nothing when it cannot be read or is not JSON. */
30
+ export function readJsonFile(path: string): unknown {
31
+ try {
32
+ return parseJson(readFileSync(path, "utf8"));
33
+ } catch {
34
+ return undefined;
35
+ }
36
+ }