@tayomi/deterministic-gates 0.3.0 → 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.
@@ -9,7 +9,7 @@
9
9
  "name": "deterministic-gates",
10
10
  "source": "./",
11
11
  "description": "Gates that run on what each turn changed and send the agent back until they pass.",
12
- "version": "0.3.0"
12
+ "version": "0.4.1"
13
13
  }
14
14
  ]
15
15
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/claude-code-plugin-manifest.json",
3
3
  "name": "deterministic-gates",
4
- "version": "0.3.0",
4
+ "version": "0.4.1",
5
5
  "description": "Deterministic backpressure for coding agents: gates that run on what each turn changed and send the agent back until they pass.",
6
6
  "author": {
7
7
  "name": "Pierre Moati",
@@ -9,5 +9,6 @@
9
9
  },
10
10
  "repository": "https://github.com/mopi1402/tayomi-deterministic-gates",
11
11
  "license": "MIT",
12
- "keywords": ["coding-agents", "quality-gates", "backpressure", "hooks"]
12
+ "keywords": ["coding-agents", "quality-gates", "backpressure", "hooks"],
13
+ "hooks": "./hooks/claude.json"
13
14
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "deterministic-gates",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "Deterministic backpressure for coding agents: gates that run on what each turn changed and send the agent back until they pass.",
5
5
  "author": {
6
6
  "name": "Pierre Moati",
@@ -12,7 +12,7 @@
12
12
  "interface": {
13
13
  "displayName": "Deterministic Gates",
14
14
  "shortDescription": "Runs the gates of the repo on what each turn changed, and sends the agent back until they pass.",
15
- "longDescription": "Deterministic backpressure for coding agents. At the end of each turn, the gates of the repo run on the files the turn changed: a linter, a type checker, the related tests, a dead-code finder. A gate is a tool, never a model. If a gate fails, the agent is sent back once with the report. The gates live in .gates.json; the catalog of the plugin lists the ones worth copying.",
15
+ "longDescription": "Deterministic backpressure for coding agents. At the end of each turn, the gates of the repo run on the files the turn changed: a linter, a type checker, the related tests, a dead-code finder. A gate is a tool, never a model. If a gate fails, the agent is sent back with the report until it fixes the gate or says why it leaves it. The gates live in .gates.json; the catalog of the plugin lists the ones worth copying.",
16
16
  "developerName": "Pierre Moati",
17
17
  "category": "Developer Tools",
18
18
  "websiteURL": "https://github.com/mopi1402/tayomi-deterministic-gates"
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  # deterministic-gates
4
4
 
5
- Deterministic backpressure for coding agents. At the end of each turn, the gates run on what the agent changed. A gate is a tool, never a model: a linter, a type checker, the related tests, a dead-code finder. If a gate fails, the agent is sent back with the report until it fixes the gate or says why it leaves it, while the context is fresh.
5
+ Deterministic backpressure for coding agents. [At the end of each turn](docs/adr/0001-check-at-the-stop.md), the gates run on what the agent changed. A gate is a tool, never a model: a linter, a type checker, the related tests, a dead-code finder. If a gate fails, the agent is sent back with the report until it fixes the gate or says why it leaves it, while the context is fresh: it still holds what it just wrote, so the fix is cheap, where a review or a CI run finds the same problem once that context is gone.
6
6
 
7
7
  CI stays the authority for slow and full checks. The gates catch what the agent just wrote, so the review sees what slipped through.
8
8
 
@@ -41,7 +41,9 @@ Codex runs no hook you have not reviewed: in a session, open `/hooks` and trust
41
41
 
42
42
  ## Configure the gates
43
43
 
44
- The gates of a repo live in `.gates.json` at its root, committed. Each one names a command, and the files that make it run:
44
+ The gates of a repo live in `.gates.json` at its root, committed. The quickest start is `catalog/`: one file per technology, each gate with what it catches and the tools it requires, and `catalog/index.html` is the same content as a page. Copy a gate into `.gates.json`, install what it requires, and adapt its `files` to the layout of the repo.
45
+
46
+ A gate names a command, and the files that make it run:
45
47
 
46
48
  ```json
47
49
  {
@@ -56,57 +58,37 @@ The gates of a repo live in `.gates.json` at its root, committed. Each one names
56
58
  }
57
59
  ```
58
60
 
59
- | Field | Meaning |
60
- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
61
- | `name` | Lowercase words joined by hyphens. |
62
- | `severity` | `error` sends the agent back. `off` never runs. There is no warning, because nobody acts on one. |
63
- | `files` | A regular expression on the repo-relative paths. The gate runs when the turn changed a match, a deleted file included. |
64
- | `run` | The command, then its arguments. See below. |
65
- | `compare` | `turn-start`: the command runs on the whole project as the turn starts, and only the lines of output the turn added fail the gate. For a tool that exits with 0 when it finds problems. |
66
- | `ignoreLines` | A regular expression for lines of output that never count as new, such as a header with a total. |
67
- | `timeoutSeconds` | Less time for this gate than the check has, never more. |
68
-
69
- The first word of `run` is looked up in this order, so a gate can run Node, Python, Go or any other program:
70
-
71
- 1. a script of this engine under `{engine}/`, such as `{engine}/src/helpers/new-clones.ts`;
72
- 2. a script of the repo by its path, run on the interpreter of its extension: `.ts`, `.js` and `.mjs` on Node, `.py` on `python3`;
73
- 3. a package of the repo's `node_modules`, run through its command, such as `eslint`;
74
- 4. a program: by its path in the repo, such as `.venv/bin/ruff`, or by its name on the `PATH`, such as `go`, `gofmt` or `ruff`.
75
-
76
- A tool the repo pins beats one on the `PATH`, so write the pinned form when there is one, such as `["uv", "run", "ruff", ...]`. A gate whose program is not installed never runs, and the other gates still do. As a prompt arrives, the agent is asked to install the tool and you are told which gates are off. It is asked once, and again only when the list of missing tools changes or the session starts again.
77
-
78
- A gate whose entry is wrong, such as with an unknown field, is left out and named in the summary, and the other gates still run.
79
-
80
- Next to `gates`, `maxTimeoutSeconds` is the time the gates of a check have, all together: 45 seconds by default. They start at once, and a gate still running then is stopped. It shows out of time, neither green nor red, and never sends the agent back, since nobody knows what it would have said. A slower check belongs in CI.
81
-
82
- The summary names the six slowest green gates and counts the rest, as in `... +5`. Set `"showAllPasses": true` next to `gates` to name every one of them, six to a line. A value in `.gates.local.json` wins, so each developer can choose for themselves.
83
-
84
- Next to `gates`, `maxSendBacks` is the most times a turn sends the agent back: 5 by default, and 0 never sends it back. Past it, the agent hands back and the summary says why. A value in `.gates.local.json` wins.
61
+ - `name`: lowercase words joined by hyphens.
62
+ - `severity`: `error` sends the agent back when the gate fails, `off` turns the gate off.
63
+ - `files`: a regular expression on the repo-relative paths. The gate runs when the turn changed a match.
64
+ - `run`: the command, then its arguments. `{files}` expands to the changed files the gate looks at.
85
65
 
86
- In the arguments, `{files}` expands to the changed files the gate looks at, and `{turn}` to the commit that holds the tree as the turn started.
66
+ A gate whose tool is not installed does not run: as the next prompt arrives, the agent is asked to install it.
87
67
 
88
- ## Pick gates from the catalog
89
-
90
- `catalog/` lists the gates worth copying into a repo, one file per technology, each entry with what the gate catches and the tools it requires; `catalog/index.html` is the same content as a page. The engine reads only `.gates.json`: copy a gate there, install what it requires, and adapt its `files` to the layout of the repo.
91
-
92
- ## Override the gates for yourself
93
-
94
- Each developer can add `.gates.local.json` next to `.gates.json`, and add it to `.gitignore`. A local entry with the name of a shared gate changes only the fields it gives, such as `{ "name": "typecheck", "timeoutSeconds": 20 }`. Any other local entry adds a gate.
68
+ [docs/configuration.md](docs/configuration.md) gives the rest: every field of a gate, how `run` finds its program, the settings of the whole check, and the overrides each developer keeps in `.gates.local.json`.
95
69
 
96
70
  ## How a turn is checked
97
71
 
98
72
  1. When a prompt arrives, the engine records the working tree as a commit that no branch points to, without touching the index, the files or any branch.
99
73
  2. When the agent stops, it records the tree again and lists the files the turn changed.
100
74
  3. Each gate with a matching file runs, all of them in parallel, with the gates as the turn started.
101
- 4. If a gate fails, the agent is sent back with the reports, told to fix the code and never the check. Each stop is checked again from the turn start, so a fix that breaks another gate is caught. The agent is sent back until each red gate is fixed or waived, up to `maxSendBacks` times a turn.
102
- 5. The agent may leave a gate red only when it cannot be fixed, when fixing it goes against what you asked, or when you have to settle a question first. It then writes, in its last message, one line per gate: `[deterministic-gates:<gate>]: waive "<reason>"`. Codex hides the line, as markdown does, and Claude Code shows it. The summary shows the gate in orange, with the reason under it. A waiver lasts the turn, and falls when the report of its gate changes. `check`, and so CI, never reads one: a gate that fails there fails.
75
+ 4. If a gate fails, the agent is sent back with the reports, told to fix the code and never the check. Each stop is checked again from the turn start, so a fix that breaks another gate is caught, up to 5 times a turn by default ([`maxSendBacks`](docs/configuration.md#the-settings-of-the-whole-check)).
76
+ 5. The agent may instead waive a red gate, with a reason you see in orange in the summary: for the turn only, and never in CI. [docs/turn.md](docs/turn.md#the-waivers) says when and how.
77
+
78
+ Each stop ends with a summary, such as:
79
+
80
+ ```
81
+ ● gates 2/3 gates green in 5.1 s · the agent is sent back to fix it (1 of 5)
82
+ ✗ tests 5.0 s
83
+ ✓ clones 900 ms ✓ lint 300 ms
84
+ ```
103
85
 
104
86
  [docs/turn.md](docs/turn.md) draws the rest: where the start comes from, how a compared gate reads its report, what the engine keeps between turns, and what the lock covers.
105
87
 
106
- To check the whole repo, as before adopting the gates or in a pre-push hook:
88
+ To check the whole repo, as before adopting the gates, in a pre-push hook or in CI:
107
89
 
108
90
  ```
109
- node src/cli.ts check
91
+ npx @tayomi/deterministic-gates check
110
92
  ```
111
93
 
112
94
  Every gate runs on every file that matches, and the command exits with 1 when a gate fails.
@@ -121,7 +103,9 @@ pnpm integration
121
103
 
122
104
  This repo runs under its own gates, in its `.gates.json`, and no gate runs a whole test suite at the end of a turn: that is what `pnpm check`, `pnpm integration` and `node src/cli.ts check` are for.
123
105
 
124
- `integration/` holds a sample project per catalog. The integration tests play an agent's turn on each, with no agent and no model: a clean change passes every gate, and each gate catches the fault written for it. To add a gate to a catalog, edit its file, write its fault, and run `pnpm catalog` to regenerate the page.
106
+ `integration/` holds a sample project per catalog. The integration tests play an agent's turn on each, with no agent and no model: a clean change passes every gate, and each gate catches the fault written for it. A gate whose tool is not installed fails its test, with how to install it: every tool the catalogs require is needed. To add a gate to a catalog, edit its file, write its fault, and run `pnpm catalog` to regenerate the page.
107
+
108
+ CI runs `pnpm check` and `pnpm integration` on every push and pull request, with the tool of every catalog gate installed. A tool a new gate requires is added to `.github/workflows/ci.yml`.
125
109
 
126
110
  ## License
127
111
 
@@ -0,0 +1,65 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { checkAll } from "./core/check.js";
4
+ import { configuredRoot } from "./core/config.js";
5
+ import { messageOf } from "./core/json.js";
6
+ import { broken, reports, summary } from "./core/report.js";
7
+ import { failed } from "./core/run.js";
8
+ import { handleHook } from "./hook/hook.js";
9
+ function readStdin() {
10
+ try {
11
+ return readFileSync(0, "utf8");
12
+ }
13
+ catch {
14
+ return "";
15
+ }
16
+ }
17
+ /** What the command prints when it is called with words it does not know. */
18
+ export const USAGE = "Usage: node src/cli.ts hook <session-start|turn-start|check>, or node src/cli.ts check";
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 = major < 24 || (major === 24 && minor < 2)
22
+ ? `Node 24.2 or later is needed, this is ${process.versions.node}.`
23
+ : undefined;
24
+ async function main([command, event]) {
25
+ if (oldNode !== undefined) {
26
+ if (command === "hook")
27
+ console.log(JSON.stringify({ systemMessage: broken(oldNode) }));
28
+ else {
29
+ console.error(oldNode);
30
+ process.exitCode = 2;
31
+ }
32
+ }
33
+ else if (command === "hook" && (event === "session-start" || event === "turn-start" || event === "check")) {
34
+ const output = await handleHook(event, readStdin());
35
+ if (output)
36
+ console.log(JSON.stringify(output));
37
+ }
38
+ else if (command === "check" && event === undefined) {
39
+ const root = configuredRoot(process.cwd());
40
+ if (root === undefined) {
41
+ console.error("Not in a git repository, or no .gates.json in it.");
42
+ process.exitCode = 2;
43
+ }
44
+ else {
45
+ try {
46
+ const all = await checkAll(root);
47
+ console.log([summary(all), ...reports(all.outcomes)].join("\n\n"));
48
+ if (all.outcomes.some(failed))
49
+ process.exitCode = 1;
50
+ }
51
+ catch (error) {
52
+ console.error(`Could not run: ${messageOf(error)}`);
53
+ process.exitCode = 2;
54
+ }
55
+ }
56
+ }
57
+ else {
58
+ console.error(USAGE);
59
+ process.exitCode = 2;
60
+ }
61
+ }
62
+ // Run as a program, never as a test imports it. Below Node 24.2, import.meta.main is undefined: the program runs then,
63
+ // to say that Node is too old.
64
+ if (import.meta.main !== false)
65
+ await main(process.argv.slice(2));
@@ -0,0 +1,157 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { changedGatesFiles, gatesOf, isCompared, readGatesFiles } from "./config.js";
4
+ import { cachedReports, cacheReports } from "./report-cache.js";
5
+ import { check, filesOf, givenFiles, missingTool, wholeProject } from "./run.js";
6
+ import { changedSince, emptyCommit, hasCommit, lastCommit, snapshot, workingTree } from "./snapshot.js";
7
+ import { readTurn, writeTurn } from "./turn-state.js";
8
+ function missingTools(root, gates) {
9
+ return gates.flatMap((gate) => {
10
+ const why = missingTool(root, gate);
11
+ return why === undefined ? [] : [{ gate, why }];
12
+ });
13
+ }
14
+ function runnable(gates, missing) {
15
+ return gates.filter((gate) => !missing.some((tool) => tool.gate === gate));
16
+ }
17
+ /**
18
+ * Records the commit a turn starts from, and the reports its compared gates will compare with. After an interrupted
19
+ * turn, the next one of the repo starts where it did, so its check also covers what the interrupted one changed.
20
+ * Gives, gate by gate, the tools this machine misses to run the gates of the repo.
21
+ */
22
+ export async function startTurn(session, root) {
23
+ const config = readGatesFiles(root);
24
+ const { gates } = gatesOf(config);
25
+ const missing = missingTools(root, gates);
26
+ const told = missing.map(({ gate, why }) => `${gate.name}: ${why}`);
27
+ const compared = runnable(gates, missing).filter(isCompared);
28
+ const interrupted = readTurn(session, root);
29
+ if (interrupted?.checked === false) {
30
+ writeTurn(session, root, interrupted);
31
+ return told;
32
+ }
33
+ const { commit: start, tree } = snapshot(root);
34
+ const cached = cachedReports(root, tree);
35
+ const baselines = await Promise.all(compared.map(async (gate) => {
36
+ const cachedReport = cached(gate);
37
+ return {
38
+ gate,
39
+ ...(cachedReport === undefined ? await wholeProject(root, gate) : { ok: true, output: cachedReport }),
40
+ };
41
+ }));
42
+ // A report from a command that broke still serves this turn, since checking too much beats leaving a hole, but it
43
+ // is never kept for the next one.
44
+ cacheReports(root, tree, baselines.filter(({ ok }) => ok).map(({ gate, output }) => [gate, output]));
45
+ writeTurn(session, root, {
46
+ start,
47
+ baselines: Object.fromEntries(baselines.map(({ gate, output }) => [gate.name, output])),
48
+ config,
49
+ checked: false,
50
+ });
51
+ return told;
52
+ }
53
+ /**
54
+ * Runs, in parallel, each gate that looks at a changed file. A deleted file counts as changed, since a gate that
55
+ * reads the whole project may break on it, but is never named: a gate given {files} looks at the files left, and
56
+ * is skipped when none is.
57
+ */
58
+ function runGates(root, gates, changed, turn, baselines) {
59
+ return Promise.all(gates.map(async (gate) => {
60
+ const matching = filesOf(gate, changed);
61
+ const files = givenFiles(gate) ? matching.filter((file) => existsSync(join(root, file))) : matching;
62
+ if (!files.length)
63
+ return { gate };
64
+ return { gate, outcome: await check(root, gate, files, turn, baselines(gate)) };
65
+ }));
66
+ }
67
+ function checkedTurn(changed, results, started, notes, showAllPasses) {
68
+ return {
69
+ changed,
70
+ outcomes: results.flatMap(({ outcome }) => (outcome ? [outcome] : [])),
71
+ skipped: results.filter(({ outcome }) => !outcome).map(({ gate }) => gate.name),
72
+ ms: performance.now() - started,
73
+ note: notes.join("\n") || undefined,
74
+ ...(showAllPasses ? { showAllPasses } : {}),
75
+ };
76
+ }
77
+ /**
78
+ * Runs each gate on every file of the repo, as if one turn had written it all: a compared gate counts every line
79
+ * of its report, and a gate given the turn gets the empty tree. The state of the repo, for the owner or an agent
80
+ * asked to clean it up, where the hook only ever judges a turn.
81
+ */
82
+ export async function checkAll(root) {
83
+ const started = performance.now();
84
+ const empty = emptyCommit(root);
85
+ const files = changedSince(root, empty);
86
+ const { gates, refused, showAllPasses } = gatesOf(readGatesFiles(root));
87
+ const results = await runGates(root, gates, files, empty, () => "");
88
+ return checkedTurn(files, results, started, refusedNotes(refused), showAllPasses);
89
+ }
90
+ // A report holds for the tree a turn ends on only if the gate ran clean on the whole project. A gate that failed
91
+ // keeps the report it started from, so what the turn added stays new until it is fixed, and a gate that did not run
92
+ // keeps none: it may still read a changed file its pattern misses, as knip reads tsconfig.json.
93
+ function endReports(results, baselines) {
94
+ return results.flatMap(({ gate, outcome }) => {
95
+ if (!isCompared(gate) || !outcome)
96
+ return [];
97
+ const report = outcome.ok ? outcome.report : baselines(gate);
98
+ return report === undefined ? [] : [[gate, report]];
99
+ });
100
+ }
101
+ /**
102
+ * Runs each gate that looks at a file the turn changed, with the gates as the turn started: an agent that weakens
103
+ * them mid-turn changes the next turn, never its own. Without a recorded start, the turn runs from the last commit
104
+ * with the gates of now; with a start git no longer has, from the last commit with the gates and the reports it
105
+ * started with: checking too much beats leaving a hole.
106
+ */
107
+ export async function checkTurn(session, root) {
108
+ const recorded = readTurn(session, root);
109
+ const kept = recorded !== undefined && hasCommit(root, recorded.start) ? recorded : undefined;
110
+ const startNote = recorded === undefined
111
+ ? "no turn start recorded: checked every change since the last commit"
112
+ : kept === undefined
113
+ ? "turn start lost (history rewritten?): checked every change since the last commit"
114
+ : undefined;
115
+ const now = readGatesFiles(root);
116
+ const turn = {
117
+ start: kept?.start ?? lastCommit(root),
118
+ baselines: recorded?.baselines ?? {},
119
+ config: recorded?.config ?? now,
120
+ checked: false,
121
+ // What the earlier stops of the turn told the agent goes on, so its send-backs and waivers add up.
122
+ ...(recorded?.sendBacks ? { sendBacks: recorded.sendBacks } : {}),
123
+ };
124
+ const baselines = (gate) => turn.baselines[gate.name];
125
+ const started = performance.now();
126
+ const end = workingTree(root);
127
+ const changed = changedSince(root, turn.start, end);
128
+ const { gates, refused, showAllPasses } = gatesOf(turn.config);
129
+ const missing = missingTools(root, gates);
130
+ const results = await runGates(root, runnable(gates, missing), changed, turn.start, baselines);
131
+ cacheReports(root, end, endReports(results, baselines));
132
+ writeTurn(session, root, { ...turn, checked: true });
133
+ // A compared gate with no report from the turn start can only count its exit code: a green it did not earn is said.
134
+ const uncompared = results
135
+ .filter(({ gate, outcome }) => outcome && isCompared(gate) && baselines(gate) === undefined)
136
+ .map(({ gate }) => `${gate.name} not compared: no report from the turn start, only its exit code counted`);
137
+ // Only a gate the turn concerned is named: one that would not have run anyway costs nothing to miss.
138
+ const notRun = missing
139
+ .filter(({ gate }) => filesOf(gate, changed).length)
140
+ .map(({ gate, why }) => `${gate.name} not run: ${why}`);
141
+ const notes = [
142
+ ...(startNote ? [startNote] : []),
143
+ ...configNote(changedGatesFiles(turn.config, now)),
144
+ ...uncompared,
145
+ ...refusedNotes(refused),
146
+ ...notRun,
147
+ ];
148
+ return checkedTurn(changed, results, started, notes, showAllPasses);
149
+ }
150
+ function refusedNotes(refused) {
151
+ return refused.map(({ name, why }) => `${name} not run, its entry is wrong: ${why}`);
152
+ }
153
+ function configNote(changedFiles) {
154
+ if (!changedFiles.length)
155
+ return [];
156
+ return [`the turn changed ${changedFiles.join(" and ")}: checked with the gates as the turn started`];
157
+ }
@@ -0,0 +1,180 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { isRecord, isStringArray, messageOf } from "./json.js";
4
+ import { repoRoot } from "./snapshot.js";
5
+ const GATES_FILE = ".gates.json";
6
+ const LOCAL_GATES_FILE = ".gates.local.json";
7
+ // The time the gates of a check have, all together: they start at once, so each one stops at the latest when it ends.
8
+ const DEFAULT_MAX_TIMEOUT_SECONDS = 45;
9
+ // The times a turn sends the agent back: enough for a fix that breaks another gate, never a loop.
10
+ const DEFAULT_MAX_SEND_BACKS = 5;
11
+ const FIELDS = new Set(["name", "severity", "files", "run", "compare", "ignoreLines", "timeoutSeconds"]);
12
+ /** In the arguments of a gate: the changed files it looks at, and the commit of the turn start. */
13
+ export const FILES = "{files}";
14
+ export const TURN = "{turn}";
15
+ /** A gate that fails on the lines of output the turn added, with the report of the turn start to compare with. */
16
+ export function isCompared(gate) {
17
+ return gate.compare === "turn-start";
18
+ }
19
+ // The problem of one gate: the gate is left out, never the others.
20
+ function refuse(problem) {
21
+ throw new Error(problem);
22
+ }
23
+ function fileOf(text, file) {
24
+ if (text === undefined)
25
+ return { entries: [] };
26
+ let parsed;
27
+ try {
28
+ parsed = JSON.parse(text);
29
+ }
30
+ catch (error) {
31
+ throw new Error(`${file} is not valid JSON: ${messageOf(error)}.`);
32
+ }
33
+ const { gates = [], maxTimeoutSeconds, showAllPasses, maxSendBacks, ...others } = isRecord(parsed) ? parsed : { others: true };
34
+ if (!Array.isArray(gates) || Object.keys(others).length)
35
+ throw new Error(`${file} holds "gates", a list of gates, "maxTimeoutSeconds", the most seconds a gate may take, ` +
36
+ `"showAllPasses", to name every green gate, and "maxSendBacks", the most times a turn sends the agent back.`);
37
+ const entries = gates.map((entry) => {
38
+ if (!isRecord(entry) || typeof entry.name !== "string")
39
+ throw new Error(`${file}: every gate has a name.`);
40
+ return { ...entry, name: entry.name };
41
+ });
42
+ return {
43
+ entries,
44
+ ...(maxTimeoutSeconds === undefined ? {} : { maxTimeoutSeconds }),
45
+ ...(showAllPasses === undefined ? {} : { showAllPasses }),
46
+ ...(maxSendBacks === undefined ? {} : { maxSendBacks }),
47
+ };
48
+ }
49
+ // The local file's own value wins, as for the fields of a gate.
50
+ function maxTimeoutOf(shared, local) {
51
+ const max = local.maxTimeoutSeconds ?? shared.maxTimeoutSeconds ?? DEFAULT_MAX_TIMEOUT_SECONDS;
52
+ if (typeof max !== "number" || max <= 0)
53
+ throw new Error("maxTimeoutSeconds is a positive number.");
54
+ return max;
55
+ }
56
+ // Off by default: the summary names the slowest passes and counts the rest.
57
+ function showAllPassesOf(shared, local) {
58
+ const show = local.showAllPasses ?? shared.showAllPasses ?? false;
59
+ if (typeof show !== "boolean")
60
+ throw new Error("showAllPasses is true or false.");
61
+ return show;
62
+ }
63
+ // 0 never sends the agent back: the owner only sees the summary.
64
+ function maxSendBacksOf(shared, local) {
65
+ const max = local.maxSendBacks ?? shared.maxSendBacks ?? DEFAULT_MAX_SEND_BACKS;
66
+ if (typeof max !== "number" || !Number.isInteger(max) || max < 0)
67
+ throw new Error("maxSendBacks is a whole number, 0 or more.");
68
+ return max;
69
+ }
70
+ function isPattern(value) {
71
+ if (typeof value !== "string")
72
+ return false;
73
+ try {
74
+ new RegExp(value);
75
+ return true;
76
+ }
77
+ catch {
78
+ return false;
79
+ }
80
+ }
81
+ function toGate(entry, maxTimeoutSeconds) {
82
+ const { name, severity, files, run, compare, ignoreLines, timeoutSeconds = maxTimeoutSeconds } = entry;
83
+ const unknown = Object.keys(entry).find((key) => !FIELDS.has(key));
84
+ if (unknown !== undefined)
85
+ refuse(`unknown field ${unknown}`);
86
+ if (!/^[a-z][a-z0-9-]*$/.test(name))
87
+ refuse("a name is lowercase words joined by hyphens");
88
+ if (severity !== "error" && severity !== "off")
89
+ refuse('severity is "error" or "off": a warning sends nobody back to fix it');
90
+ if (!isPattern(files))
91
+ refuse("files is a regular expression on the repo-relative paths");
92
+ if (!isStringArray(run) || !run.length)
93
+ refuse("run is a non-empty list of strings");
94
+ if (compare !== undefined && compare !== "turn-start")
95
+ refuse('compare is "turn-start"');
96
+ if (compare !== undefined && run.includes(FILES))
97
+ refuse(`a compared gate reads the whole project: it takes no ${FILES}`);
98
+ if (ignoreLines !== undefined && !isPattern(ignoreLines))
99
+ refuse("ignoreLines is a regular expression");
100
+ if (typeof timeoutSeconds !== "number" || timeoutSeconds <= 0)
101
+ refuse("timeoutSeconds is a positive number");
102
+ return {
103
+ name,
104
+ severity,
105
+ files,
106
+ run,
107
+ // A gate may stop sooner than the others, never later.
108
+ timeoutSeconds: Math.min(timeoutSeconds, maxTimeoutSeconds),
109
+ ...(compare === undefined ? {} : { compare }),
110
+ ...(ignoreLines === undefined ? {} : { ignoreLines }),
111
+ };
112
+ }
113
+ /**
114
+ * Reads the shared gates and the developer's own. A local entry named like a shared one changes only the fields it
115
+ * gives, such as {"name": "lint", "severity": "off"}. Any other local entry adds a gate. A gate with a problem of its
116
+ * own is left out, and the others still run: only a file that cannot be read stops them all.
117
+ */
118
+ export function readGates(shared, local) {
119
+ const sharedFile = fileOf(shared, GATES_FILE);
120
+ const localFile = fileOf(local, LOCAL_GATES_FILE);
121
+ const max = maxTimeoutOf(sharedFile, localFile);
122
+ const merged = new Map(sharedFile.entries.map((entry) => [entry.name, entry]));
123
+ for (const entry of localFile.entries)
124
+ merged.set(entry.name, { ...merged.get(entry.name), ...entry });
125
+ const read = {
126
+ gates: [],
127
+ refused: [],
128
+ showAllPasses: showAllPassesOf(sharedFile, localFile),
129
+ maxSendBacks: maxSendBacksOf(sharedFile, localFile),
130
+ };
131
+ for (const entry of merged.values()) {
132
+ if (entry.severity === "off")
133
+ continue;
134
+ try {
135
+ read.gates.push(toGate(entry, max));
136
+ }
137
+ catch (error) {
138
+ read.refused.push({ name: entry.name, why: messageOf(error) });
139
+ }
140
+ }
141
+ return read;
142
+ }
143
+ /** The gates of the two files, refusing the first gate with a problem, as a catalog does. */
144
+ export function parseGates(shared, local) {
145
+ const { gates, refused } = readGates(shared, local);
146
+ const [first] = refused;
147
+ if (first !== undefined)
148
+ throw new Error(`Gate ${first.name}: ${first.why}.`);
149
+ return gates;
150
+ }
151
+ function readIfPresent(path) {
152
+ try {
153
+ return readFileSync(path, "utf8");
154
+ }
155
+ catch (error) {
156
+ if (error.code === "ENOENT")
157
+ return undefined;
158
+ throw error;
159
+ }
160
+ }
161
+ export function readGatesFiles(root) {
162
+ return { shared: readIfPresent(join(root, GATES_FILE)), local: readIfPresent(join(root, LOCAL_GATES_FILE)) };
163
+ }
164
+ export function gatesOf({ shared, local }) {
165
+ return readGates(shared, local);
166
+ }
167
+ /** The gates files a turn changed, by name: a turn is checked with the gates it started with, whatever it did to them. */
168
+ export function changedGatesFiles(before, after) {
169
+ return [
170
+ ...(before.shared === after.shared ? [] : [GATES_FILE]),
171
+ ...(before.local === after.local ? [] : [LOCAL_GATES_FILE]),
172
+ ];
173
+ }
174
+ /** The repo to check from a working directory, or nothing outside git or in a repo with no gates file. */
175
+ export function configuredRoot(cwd) {
176
+ const root = repoRoot(cwd);
177
+ if (root === undefined)
178
+ return undefined;
179
+ return [GATES_FILE, LOCAL_GATES_FILE].some((file) => existsSync(join(root, file))) ? root : undefined;
180
+ }
@@ -0,0 +1,32 @@
1
+ import { readFileSync } from "node:fs";
2
+ export function isRecord(value) {
3
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4
+ }
5
+ export function isStringRecord(value) {
6
+ return isRecord(value) && Object.values(value).every((entry) => typeof entry === "string");
7
+ }
8
+ export function isStringArray(value) {
9
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
10
+ }
11
+ /** The message of whatever was thrown. */
12
+ export function messageOf(error) {
13
+ return error instanceof Error ? error.message : String(error);
14
+ }
15
+ /** What the text holds as JSON, or nothing when it is not JSON. */
16
+ export function parseJson(text) {
17
+ try {
18
+ return JSON.parse(text);
19
+ }
20
+ catch {
21
+ return undefined;
22
+ }
23
+ }
24
+ /** What the file holds as JSON, or nothing when it cannot be read or is not JSON. */
25
+ export function readJsonFile(path) {
26
+ try {
27
+ return parseJson(readFileSync(path, "utf8"));
28
+ }
29
+ catch {
30
+ return undefined;
31
+ }
32
+ }
@@ -0,0 +1,35 @@
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 { isRecord, isStringRecord, readJsonFile } from "./json.js";
6
+ function isCache(value) {
7
+ return isRecord(value) && typeof value.tree === "string" && isStringRecord(value.reports);
8
+ }
9
+ function cacheFile(root) {
10
+ const repo = createHash("sha256").update(root).digest("hex").slice(0, 16);
11
+ return join(tmpdir(), `gates-reports-${repo}.json`);
12
+ }
13
+ function commandOf(gate) {
14
+ return JSON.stringify(gate.run);
15
+ }
16
+ function readCache(root) {
17
+ const cache = readJsonFile(cacheFile(root));
18
+ return isCache(cache) ? cache : undefined;
19
+ }
20
+ export function cachedReports(root, tree) {
21
+ const cache = readCache(root);
22
+ return (gate) => (cache?.tree === tree ? cache.reports[commandOf(gate)] : undefined);
23
+ }
24
+ /** Keeps reports for a tree, with the ones already kept for that tree, and in place of the ones of another tree. */
25
+ export function cacheReports(root, tree, reports) {
26
+ const kept = readCache(root);
27
+ const cache = {
28
+ tree,
29
+ reports: {
30
+ ...(kept?.tree === tree ? kept.reports : {}),
31
+ ...Object.fromEntries(reports.map(([gate, report]) => [commandOf(gate), report])),
32
+ },
33
+ };
34
+ writeFileSync(cacheFile(root), JSON.stringify(cache));
35
+ }