@tayomi/deterministic-gates 0.4.1 → 0.5.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,280 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync, } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { createInterface } from "node:readline";
7
+ import { setTimeout as sleep } from "node:timers/promises";
8
+ import { isCompared } from "./config.js";
9
+ import { addedLines, cleaned, commandOf, TOOL_ENV } from "./run.js";
10
+ // Once a cycle closes, the lines a watch prints after it, such as the errors of a failed build, come within this long.
11
+ const QUIET_MS = 1000;
12
+ // A change no cycle started after in this long is one the watch does not look at, such as a spec its build leaves out:
13
+ // it cannot change the last cycle, which then judges the turn.
14
+ const UNSEEN_MS = 5000;
15
+ const POLL_MS = 100;
16
+ // What a watch that stopped leaves the agent: enough to see the error, not the whole history of the session.
17
+ const LAST_LINES = 20;
18
+ // A prompt waits this long at most for a compared watch to settle, under the 60 s its hook has.
19
+ const TURN_START_MS = 45_000;
20
+ const PREFIX = "gates-watch-";
21
+ // A start that holds its lock longer than this died on the way: the next hook takes the lock over.
22
+ const STALE_START_MS = 10_000;
23
+ // A watch stops by itself after this long without a prompt nor a stop on its repo, as for a session left open. The
24
+ // tests of the engine shorten it.
25
+ const IDLE_MS = 30 * 60 * 1000;
26
+ function idleMs() {
27
+ return Number(process.env.GATES_WATCH_IDLE_MS) || IDLE_MS;
28
+ }
29
+ /** Records a prompt or a stop on the repo of a watch, which keeps it from stopping for idleness. */
30
+ function touch(folder) {
31
+ writeFileSync(join(folder, "activity"), "");
32
+ }
33
+ /** Records a stop on the repo of the watch of a gate, if it has one, whether the stop judges it or not. */
34
+ export function keepWatch(root, gate) {
35
+ const folder = folderOf(root, gate);
36
+ if (existsSync(folder))
37
+ touch(folder);
38
+ }
39
+ /** Where a watch keeps its process, its output and the sessions that use it, outside the repo: one per repo and gate. */
40
+ function folderOf(root, gate) {
41
+ const key = createHash("sha256").update(`${root}\0${gate.name}`).digest("hex").slice(0, 16);
42
+ return join(tmpdir(), `${PREFIX}${key}`);
43
+ }
44
+ // A file per session that uses the watch: two hooks at once each write their own, and neither loses the other's.
45
+ function sessionFile(folder, session) {
46
+ return join(folder, "sessions", session.replace(/[^\w-]/g, ""));
47
+ }
48
+ function register(folder, session) {
49
+ mkdirSync(join(folder, "sessions"), { recursive: true });
50
+ writeFileSync(sessionFile(folder, session), "");
51
+ }
52
+ /** Whether the watch runs, has stopped on its own, was stopped for idleness, or was never started. */
53
+ function stateOf(folder) {
54
+ let pid;
55
+ try {
56
+ pid = Number(readFileSync(join(folder, "pid"), "utf8"));
57
+ }
58
+ catch {
59
+ return "absent";
60
+ }
61
+ try {
62
+ if (!pid)
63
+ return "stopped";
64
+ process.kill(pid, 0);
65
+ return "running";
66
+ }
67
+ catch {
68
+ return existsSync(join(folder, "idle")) ? "idle" : "stopped";
69
+ }
70
+ }
71
+ /**
72
+ * Starts the watch of a gate in the background, unless it already runs, and records that the session uses it: it
73
+ * outlives the hook that starts it, until no session uses it.
74
+ */
75
+ export function startWatch(session, root, gate) {
76
+ const folder = folderOf(root, gate);
77
+ mkdirSync(folder, { recursive: true });
78
+ touch(folder);
79
+ // The sessions of a watch that starts again still use it.
80
+ register(folder, session);
81
+ if (stateOf(folder) === "running")
82
+ return;
83
+ // Two hooks at once, such as two sessions starting, start one watch: the other only registers its session.
84
+ const lock = join(folder, "starting");
85
+ if (Date.now() - changedAt(lock) >= STALE_START_MS)
86
+ rmSync(lock, { force: true });
87
+ try {
88
+ closeSync(openSync(lock, "wx"));
89
+ }
90
+ catch {
91
+ return;
92
+ }
93
+ try {
94
+ // Another hook may have started it between the look above and the lock.
95
+ if (stateOf(folder) !== "running")
96
+ launch(folder, root, gate.watch);
97
+ }
98
+ finally {
99
+ rmSync(lock, { force: true });
100
+ }
101
+ }
102
+ function launch(folder, root, watch) {
103
+ rmSync(join(folder, "idle"), { force: true });
104
+ const [name = "", ...args] = watch.run;
105
+ const command = commandOf(root, name);
106
+ const supervisor = commandOf(root, "{engine}/src/core/watch.ts");
107
+ const watched = [
108
+ join(folder, "activity"),
109
+ String(idleMs()),
110
+ watch.cycleStart,
111
+ command.file,
112
+ ...command.args,
113
+ ...args,
114
+ ];
115
+ const log = openSync(join(folder, "output.log"), "w");
116
+ const child = spawn(supervisor.file, [...supervisor.args, ...watched], {
117
+ cwd: root,
118
+ detached: true,
119
+ stdio: ["ignore", log, log],
120
+ env: TOOL_ENV,
121
+ });
122
+ closeSync(log);
123
+ child.on("error", () => { });
124
+ child.unref();
125
+ writeFileSync(join(folder, "pid"), String(child.pid ?? ""));
126
+ }
127
+ /** The last cycle of a watch: its lines since it opened, and whether it is still open. */
128
+ function lastCycle(printed, watch) {
129
+ const lines = printed.split("\n");
130
+ if (lines.at(-1) === "")
131
+ lines.pop();
132
+ const opens = new RegExp(watch.cycleStart);
133
+ const closes = new RegExp(watch.cycleEnd);
134
+ // The start of the watch opens the first cycle, and lines after the one that closes it still belong to it.
135
+ const cycle = lines.slice(lines.findLastIndex((line) => opens.test(line)) + 1);
136
+ return { open: !cycle.some((line) => closes.test(line)), lines: cycle };
137
+ }
138
+ function changedAt(path) {
139
+ try {
140
+ return statSync(path).mtimeMs;
141
+ }
142
+ catch {
143
+ return 0;
144
+ }
145
+ }
146
+ function readLog(log) {
147
+ try {
148
+ return readFileSync(log, "utf8");
149
+ }
150
+ catch {
151
+ return "";
152
+ }
153
+ }
154
+ /**
155
+ * Waits for the watch of a gate to settle: no cycle open, and for a quiet while neither new output nor a new change to
156
+ * one of the files. A watch no hook started, as when the hooks were installed mid-session, starts now, and so does one
157
+ * stopped for idleness, as during a turn longer than the idle delay: it is not to blame.
158
+ */
159
+ async function settle(session, root, gate, files, limitMs) {
160
+ const started = performance.now();
161
+ const folder = folderOf(root, gate);
162
+ const log = join(folder, "output.log");
163
+ if (["absent", "idle"].includes(stateOf(folder)))
164
+ startWatch(session, root, gate);
165
+ touch(folder);
166
+ for (;;) {
167
+ // Read once the watch is known stopped, so its last lines are in.
168
+ const stopped = stateOf(folder) === "stopped";
169
+ const printed = readLog(log);
170
+ const ms = performance.now() - started;
171
+ if (stopped) {
172
+ const last = cleaned(root, printed
173
+ .split("\n")
174
+ .slice(-LAST_LINES - 1)
175
+ .join("\n"));
176
+ return {
177
+ ms,
178
+ stopped: last ? `The watch stopped. Its last lines:\n${last}` : "The watch stopped, with no output.",
179
+ };
180
+ }
181
+ // A cycle that started after the last change read it, however long the watch took to see it.
182
+ const changed = Math.max(0, ...files.map((file) => changedAt(join(root, file))));
183
+ const seen = changedAt(join(folder, "cycle")) >= changed || Date.now() - changed >= UNSEEN_MS;
184
+ const cycle = lastCycle(printed, gate.watch);
185
+ if (seen && !cycle.open && Date.now() - changedAt(log) >= QUIET_MS)
186
+ return { ms, cycle: cleaned(root, cycle.lines.join("\n")) };
187
+ if (ms >= limitMs)
188
+ return { ms, timedOut: true };
189
+ await sleep(POLL_MS);
190
+ }
191
+ }
192
+ /**
193
+ * Judges a turn on the last cycle of the watch of a gate, once the watch has settled with the files of the turn the
194
+ * gate looks at: on its failed lines, or for a compared gate, on the lines it added to the report of the turn start.
195
+ * Not settled in the time of the gate: out of time, neither green nor red. A watch that stopped fails, with the last
196
+ * lines it printed.
197
+ */
198
+ export async function judgeWatch(session, root, gate, files, baseline) {
199
+ const settled = await settle(session, root, gate, files, gate.timeoutSeconds * 1000);
200
+ const { name } = gate;
201
+ const { ms } = settled;
202
+ if ("stopped" in settled)
203
+ return { name, ok: false, ms, output: settled.stopped, report: undefined };
204
+ if ("timedOut" in settled) {
205
+ const output = `The watch did not settle within ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
206
+ return { name, ok: false, ms, output, report: undefined, timedOut: true };
207
+ }
208
+ const { cycle } = settled;
209
+ const fails = new RegExp(gate.watch.failed ?? "(?!)");
210
+ const judged = isCompared(gate)
211
+ ? addedLines(gate, cycle, baseline)
212
+ : { ok: !cycle.split("\n").some((line) => fails.test(line)), output: cycle };
213
+ return { name, ms, ...judged, report: judged.ok ? cycle : undefined };
214
+ }
215
+ /**
216
+ * The report a compared watch gives the turn start: its last cycle, once it settles in the time a prompt can wait.
217
+ * Nothing when it does not, and the turn then counts nothing as new.
218
+ */
219
+ export async function watchReport(session, root, gate) {
220
+ const settled = await settle(session, root, gate, [], Math.min(gate.timeoutSeconds * 1000, TURN_START_MS));
221
+ return "cycle" in settled ? settled.cycle : undefined;
222
+ }
223
+ /** Stops each watch the session was the last to use, in any repo: the watch and every process it started. */
224
+ export function endSession(session) {
225
+ for (const entry of readdirSync(tmpdir())) {
226
+ if (!entry.startsWith(PREFIX))
227
+ continue;
228
+ const folder = join(tmpdir(), entry);
229
+ const file = sessionFile(folder, session);
230
+ if (!existsSync(file))
231
+ continue;
232
+ rmSync(file, { force: true });
233
+ if (!readdirSync(join(folder, "sessions")).length)
234
+ stop(folder);
235
+ }
236
+ }
237
+ function stop(folder) {
238
+ if (stateOf(folder) !== "running")
239
+ return;
240
+ try {
241
+ process.kill(-Number(readFileSync(join(folder, "pid"), "utf8")), "SIGTERM");
242
+ }
243
+ catch { }
244
+ }
245
+ /**
246
+ * The supervisor of a watch, which this module runs as when the engine starts one: it runs the watch, its output
247
+ * going where its own goes, and stops it with every process it started once its repo has had no prompt nor stop for
248
+ * the idle delay. Started detached, it leads a process group of its own, so stopping the group stops the watch and
249
+ * the tools under it.
250
+ */
251
+ function supervise(activity, idle, cycleStart, file, args) {
252
+ // The time the last cycle started, which the stop compares with the changes of the turn. The start opens the first.
253
+ const cycle = join(dirname(activity), "cycle");
254
+ const opens = new RegExp(cycleStart);
255
+ writeFileSync(cycle, "");
256
+ const watch = spawn(file, args, { stdio: ["ignore", "pipe", "pipe"] });
257
+ const forward = (line) => {
258
+ // Printed before the time is kept, so a stop that sees the time also finds the cycle in the output.
259
+ console.log(line);
260
+ if (opens.test(line))
261
+ writeFileSync(cycle, "");
262
+ };
263
+ createInterface({ input: watch.stdout }).on("line", forward);
264
+ createInterface({ input: watch.stderr }).on("line", forward);
265
+ watch.on("error", (error) => {
266
+ console.log(error.message);
267
+ process.exit(1);
268
+ });
269
+ watch.on("close", (code) => process.exit(code ?? 1));
270
+ setInterval(() => {
271
+ if (Date.now() - changedAt(activity) < idle)
272
+ return;
273
+ writeFileSync(join(dirname(activity), "idle"), "");
274
+ process.kill(-process.pid, "SIGTERM");
275
+ }, Math.min(idle / 4, 10_000));
276
+ }
277
+ if (import.meta.main) {
278
+ const [activity = "", idle = "", cycleStart = "", file = "", ...args] = process.argv.slice(2);
279
+ supervise(activity, Number(idle), cycleStart, file, args);
280
+ }
@@ -0,0 +1,47 @@
1
+ import { spawn } from "node:child_process";
2
+ import { extname, join } from "node:path";
3
+ import { createInterface } from "node:readline";
4
+ import { commandOf } from "../core/run.js";
5
+ import { COUNTS, HEADER } from "./vitest-state-reporter.js";
6
+ // The watch of an Angular project tested with Vitest: ng test in watch mode, with the reporter of the engine that
7
+ // prints the state of every spec at each run, and NG_TEST_LOG, which makes Angular say when a run ends. A change that
8
+ // leaves the build as it was reruns no spec, so no state prints: the last one is printed again, so that the cycle
9
+ // still tells which specs are red.
10
+ const NO_RERUN = /No test specifications to rerun/;
11
+ /**
12
+ * What to print for each line of the watch: the line, and before a run that reruns no spec, the last state of the
13
+ * specs, so that the cycle still tells which specs are red.
14
+ */
15
+ export function replaying() {
16
+ let state = [];
17
+ let reading;
18
+ return (line) => {
19
+ if (line === HEADER)
20
+ reading = [];
21
+ reading?.push(line);
22
+ if (reading !== undefined && line.startsWith(COUNTS)) {
23
+ state = reading;
24
+ reading = undefined;
25
+ }
26
+ return NO_RERUN.test(line) ? [...state, line] : [line];
27
+ };
28
+ }
29
+ function main(root, args) {
30
+ const ng = commandOf(root, "@angular/cli");
31
+ if (ng.missing) {
32
+ console.log(ng.missing);
33
+ process.exit(1);
34
+ }
35
+ const reporter = join(import.meta.dirname, `vitest-state-reporter${extname(import.meta.filename)}`);
36
+ const watch = spawn(ng.file, [...ng.args, "test", "--watch", `--reporters=${reporter}`, ...args], {
37
+ env: { ...process.env, NG_TEST_LOG: "1" },
38
+ stdio: ["ignore", "pipe", "pipe"],
39
+ });
40
+ const replay = replaying();
41
+ const forward = (line) => console.log(replay(line).join("\n"));
42
+ createInterface({ input: watch.stdout }).on("line", forward);
43
+ createInterface({ input: watch.stderr }).on("line", forward);
44
+ watch.on("exit", (code) => process.exit(code ?? 1));
45
+ }
46
+ if (import.meta.main)
47
+ main(process.cwd(), process.argv.slice(2));
@@ -0,0 +1,72 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createInterface } from "node:readline";
3
+ import { commandOf } from "../core/run.js";
4
+ // tsc, with the options it is given, such as strict ones a project turned off, printing its errors so that a gate can
5
+ // compare them with the ones of the turn start: one line per error, with its file and none of its line and column, so
6
+ // an error a change moves down is not new, and a count after an error its file already has, so one more of it is.
7
+ // With --watch, tsc keeps watching, and each compilation prints between a line that starts it and one that ends it.
8
+ const STARTS = /Starting (compilation in watch mode|incremental compilation)/;
9
+ const ENDS = /Found \d+ errors?\. Watching for file changes/;
10
+ const POSITION = /^(.+)\(\d+,\d+\): (error TS\d+: .*)$/;
11
+ /** The errors tsc printed, each on one line, as the gate compares them. */
12
+ export function typeErrors(printed) {
13
+ const errors = [];
14
+ for (const line of printed) {
15
+ if (!line.trim())
16
+ continue;
17
+ // The lines under an error explain it.
18
+ if (/^\s/.test(line) && errors.length)
19
+ errors.push(`${errors.pop()} ${line.trim()}`);
20
+ else
21
+ errors.push(line.replace(POSITION, "$1: $2"));
22
+ }
23
+ const seen = new Map();
24
+ return errors.map((error) => {
25
+ const count = (seen.get(error) ?? 0) + 1;
26
+ seen.set(error, count);
27
+ return count === 1 ? error : `${error} (${count})`;
28
+ });
29
+ }
30
+ /** What to print for each line of tsc in watch mode: nothing until a compilation ends, then its errors. */
31
+ export function watching() {
32
+ let compiled = [];
33
+ return (line) => {
34
+ if (STARTS.test(line)) {
35
+ compiled = [];
36
+ return ["Type check started"];
37
+ }
38
+ if (ENDS.test(line))
39
+ return [...typeErrors(compiled), "Type check done"];
40
+ compiled.push(line);
41
+ return [];
42
+ };
43
+ }
44
+ function main(root, args) {
45
+ const tsc = commandOf(root, "typescript");
46
+ if (tsc.missing) {
47
+ console.log(tsc.missing);
48
+ process.exit(1);
49
+ }
50
+ const watch = args.includes("--watch");
51
+ const options = ["--noEmit", "--pretty", "false", ...(watch ? ["--preserveWatchOutput"] : []), ...args];
52
+ const child = spawn(tsc.file, [...tsc.args, ...options], { stdio: ["ignore", "pipe", "inherit"] });
53
+ const printed = [];
54
+ const print = watching();
55
+ createInterface({ input: child.stdout }).on("line", (line) => {
56
+ if (watch)
57
+ for (const shown of print(line))
58
+ console.log(shown);
59
+ else
60
+ printed.push(line);
61
+ });
62
+ child.on("close", (code) => {
63
+ // 1 and 2 are tsc saying it found errors: the gate counts them, so only a tsc that broke fails.
64
+ if (watch || code === null || code > 2) {
65
+ console.log(printed.join("\n"));
66
+ process.exit(code ?? 1);
67
+ }
68
+ console.log(typeErrors(printed).join("\n"));
69
+ });
70
+ }
71
+ if (import.meta.main)
72
+ main(process.cwd(), process.argv.slice(2));
@@ -0,0 +1,26 @@
1
+ import { relative } from "node:path";
2
+ /** The header of the state, which the watch helper of the engine looks for. */
3
+ export const HEADER = "Spec states:";
4
+ export const COUNTS = "Specs:";
5
+ function indented(error) {
6
+ return (error.message ?? "").split("\n").map((line) => ` ${line}`);
7
+ }
8
+ function failuresOf(module) {
9
+ const spec = relative(process.cwd(), module.moduleId);
10
+ const lines = module.errors().flatMap((error) => [`FAIL ${spec}`, ...indented(error)]);
11
+ for (const test of module.children.allTests()) {
12
+ const { state, errors = [] } = test.result();
13
+ if (state === "failed")
14
+ lines.push(`FAIL ${spec} > ${test.fullName}`, ...errors.flatMap(indented));
15
+ }
16
+ return lines;
17
+ }
18
+ export default class StateReporter {
19
+ failures = new Map();
20
+ onTestRunEnd(modules) {
21
+ for (const module of modules)
22
+ this.failures.set(module.moduleId, failuresOf(module));
23
+ const red = [...this.failures.values()].filter((lines) => lines.length);
24
+ console.log([HEADER, ...red.flat(), `${COUNTS} ${red.length} red of ${this.failures.size}`].join("\n"));
25
+ }
26
+ }
@@ -1,9 +1,15 @@
1
- import { checkTurn, startTurn } from "../core/check.js";
1
+ import { checkTurn, startSession, startTurn } from "../core/check.js";
2
2
  import { configuredRoot, gatesOf } from "../core/config.js";
3
3
  import { isRecord, messageOf, parseJson } from "../core/json.js";
4
4
  import { broken, failures, summary, toolsMissing, toolsToInstall } from "../core/report.js";
5
5
  import { judge, waivesOf } from "../core/send-back.js";
6
+ import { endSession } from "../core/watch.js";
6
7
  import { forgetTold, forgetTurn, readTurn, tellOnce, turnRoot, writeTurn } from "../core/turn-state.js";
8
+ /** The events the plugin hooks, each named as the CLI takes it. */
9
+ export const HOOK_EVENTS = ["session-start", "turn-start", "check", "session-end"];
10
+ export function isHookEvent(word) {
11
+ return HOOK_EVENTS.some((event) => event === word);
12
+ }
7
13
  export function parseHookInput(text) {
8
14
  const input = parseJson(text);
9
15
  if (!isRecord(input))
@@ -56,6 +62,18 @@ export function stopOutput(turn, judged) {
56
62
  function cannotRun(error) {
57
63
  return { systemMessage: broken(messageOf(error)) };
58
64
  }
65
+ /**
66
+ * A session that starts starts the watches of its repo. Whatever stops them is told at the prompt, which reads the
67
+ * same gates.
68
+ */
69
+ function sessionHook(session, cwd) {
70
+ try {
71
+ const root = configuredRoot(cwd);
72
+ if (root !== undefined)
73
+ startSession(session, root);
74
+ }
75
+ catch { }
76
+ }
59
77
  /**
60
78
  * A prompt ends the turn in progress; from a folder with no gates, or when the turn cannot start, no check will look
61
79
  * for a new one. When the gates of the repo miss tools, the agent is asked once to install them.
@@ -113,6 +131,12 @@ export async function handleHook(event, text) {
113
131
  if (event === "session-start") {
114
132
  if (source !== "compact")
115
133
  forgetTold(session);
134
+ sessionHook(session, cwd);
135
+ return undefined;
136
+ }
137
+ // Codex gives a session that ends 3 s at most: the hook only stops the watches no other session uses.
138
+ if (event === "session-end") {
139
+ endSession(session);
116
140
  return undefined;
117
141
  }
118
142
  return event === "turn-start" ? promptHook(session, cwd) : stopHook(session, cwd, retry, message);
package/hooks/hooks.json CHANGED
@@ -33,6 +33,17 @@
33
33
  }
34
34
  ]
35
35
  }
36
+ ],
37
+ "SessionEnd": [
38
+ {
39
+ "hooks": [
40
+ {
41
+ "type": "command",
42
+ "command": "node \"${CLAUDE_PLUGIN_ROOT}/src/cli.ts\" hook session-end",
43
+ "timeout": 3
44
+ }
45
+ ]
46
+ }
36
47
  ]
37
48
  }
38
49
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tayomi/deterministic-gates",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
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
  "type": "module",
6
6
  "license": "MIT",
package/src/cli.ts CHANGED
@@ -5,7 +5,7 @@ import { configuredRoot } from "./core/config.ts";
5
5
  import { messageOf } from "./core/json.ts";
6
6
  import { broken, reports, summary } from "./core/report.ts";
7
7
  import { failed } from "./core/run.ts";
8
- import { handleHook } from "./hook/hook.ts";
8
+ import { HOOK_EVENTS, handleHook, isHookEvent } from "./hook/hook.ts";
9
9
 
10
10
  function readStdin(): string {
11
11
  try {
@@ -15,8 +15,8 @@ function readStdin(): string {
15
15
  }
16
16
  }
17
17
 
18
- /** What the command prints when it is called with words it does not know. */
19
- export const USAGE = "Usage: node src/cli.ts hook <session-start|turn-start|check>, or node src/cli.ts check";
18
+ /** What the command prints when it is called with words it does not know, named by the bin of the npm package. */
19
+ export const USAGE = `Usage: deterministic-gates check, or deterministic-gates hook <${HOOK_EVENTS.join("|")}>`;
20
20
 
21
21
  // The helpers of the engine run only on import.meta.main, which came with Node 24.2: below, they are a silent green.
22
22
  const [major = 0, minor = 0] = process.versions.node.split(".").map(Number);
@@ -32,7 +32,7 @@ async function main([command, event]: string[]): Promise<void> {
32
32
  console.error(oldNode);
33
33
  process.exitCode = 2;
34
34
  }
35
- } else if (command === "hook" && (event === "session-start" || event === "turn-start" || event === "check")) {
35
+ } else if (command === "hook" && isHookEvent(event)) {
36
36
  const output = await handleHook(event, readStdin());
37
37
  if (output) console.log(JSON.stringify(output));
38
38
  } else if (command === "check" && event === undefined) {
package/src/core/check.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { changedGatesFiles, type Gate, type Gates, gatesOf, isCompared, readGatesFiles } from "./config.ts";
3
+ import { changedGatesFiles, type Gate, type Gates, gatesOf, isCompared, keepsWatch, readGatesFiles } from "./config.ts";
4
4
  import { cachedReports, cacheReports } from "./report-cache.ts";
5
5
  import { check, filesOf, givenFiles, missingTool, type Outcome, wholeProject } from "./run.ts";
6
6
  import { changedSince, emptyCommit, hasCommit, lastCommit, snapshot, workingTree } from "./snapshot.ts";
7
7
  import { readTurn, type TurnState, writeTurn } from "./turn-state.ts";
8
+ import { judgeWatch, keepWatch, startWatch, watchReport } from "./watch.ts";
8
9
 
9
10
  export interface CheckedTurn {
10
11
  changed: string[];
@@ -41,6 +42,16 @@ function runnable(gates: Gate[], missing: Missing[]): Gate[] {
41
42
  return gates.filter((gate) => !missing.some((tool) => tool.gate === gate));
42
43
  }
43
44
 
45
+ function startWatches(session: string, root: string, gates: Gate[]): void {
46
+ for (const gate of gates) if (keepsWatch(gate)) startWatch(session, root, gate);
47
+ }
48
+
49
+ /** Starts the watches of the gates of a repo that are not running yet, so their first build runs before a turn. */
50
+ export function startSession(session: string, root: string): void {
51
+ const { gates } = gatesOf(readGatesFiles(root));
52
+ startWatches(session, root, runnable(gates, missingTools(root, gates)));
53
+ }
54
+
44
55
  /**
45
56
  * Records the commit a turn starts from, and the reports its compared gates will compare with. After an interrupted
46
57
  * turn, the next one of the repo starts where it did, so its check also covers what the interrupted one changed.
@@ -52,6 +63,7 @@ export async function startTurn(session: string, root: string): Promise<string[]
52
63
  const missing = missingTools(root, gates);
53
64
  const told = missing.map(({ gate, why }) => `${gate.name}: ${why}`);
54
65
  const compared = runnable(gates, missing).filter(isCompared);
66
+ startWatches(session, root, runnable(gates, missing));
55
67
  const interrupted = readTurn(session, root);
56
68
  if (interrupted?.checked === false) {
57
69
  writeTurn(session, root, interrupted);
@@ -60,12 +72,12 @@ export async function startTurn(session: string, root: string): Promise<string[]
60
72
  const { commit: start, tree } = snapshot(root);
61
73
  const cached = cachedReports(root, tree);
62
74
  const baselines = await Promise.all(
63
- compared.map(async (gate) => {
75
+ compared.map(async (gate): Promise<{ gate: Gate; ok: boolean; output?: string }> => {
64
76
  const cachedReport = cached(gate);
65
- return {
66
- gate,
67
- ...(cachedReport === undefined ? await wholeProject(root, gate) : { ok: true, output: cachedReport }),
68
- };
77
+ if (cachedReport !== undefined) return { gate, ok: true, output: cachedReport };
78
+ if (!keepsWatch(gate)) return { gate, ...(await wholeProject(root, gate)) };
79
+ const output = await watchReport(session, root, gate);
80
+ return { gate, ok: output !== undefined, output };
69
81
  }),
70
82
  );
71
83
  // A report from a command that broke still serves this turn, since checking too much beats leaving a hole, but it
@@ -73,11 +85,13 @@ export async function startTurn(session: string, root: string): Promise<string[]
73
85
  cacheReports(
74
86
  root,
75
87
  tree,
76
- baselines.filter(({ ok }) => ok).map(({ gate, output }) => [gate, output] as const),
88
+ baselines.flatMap(({ gate, ok, output }) => (ok && output !== undefined ? [[gate, output] as const] : [])),
77
89
  );
78
90
  writeTurn(session, root, {
79
91
  start,
80
- baselines: Object.fromEntries(baselines.map(({ gate, output }) => [gate.name, output])),
92
+ baselines: Object.fromEntries(
93
+ baselines.flatMap(({ gate, output }) => (output === undefined ? [] : [[gate.name, output]])),
94
+ ),
81
95
  config,
82
96
  checked: false,
83
97
  });
@@ -87,7 +101,8 @@ export async function startTurn(session: string, root: string): Promise<string[]
87
101
  /**
88
102
  * Runs, in parallel, each gate that looks at a changed file. A deleted file counts as changed, since a gate that
89
103
  * 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.
104
+ * is skipped when none is. At the end of a turn of a session, a gate that keeps a watch is judged on it instead of
105
+ * running.
91
106
  */
92
107
  function runGates(
93
108
  root: string,
@@ -95,12 +110,15 @@ function runGates(
95
110
  changed: string[],
96
111
  turn: string,
97
112
  baselines: Baselines,
113
+ session?: string,
98
114
  ): Promise<Result[]> {
99
115
  return Promise.all(
100
116
  gates.map(async (gate) => {
101
117
  const matching = filesOf(gate, changed);
102
118
  const files = givenFiles(gate) ? matching.filter((file) => existsSync(join(root, file))) : matching;
103
119
  if (!files.length) return { gate };
120
+ if (session !== undefined && keepsWatch(gate))
121
+ return { gate, outcome: await judgeWatch(session, root, gate, matching, baselines(gate)) };
104
122
  return { gate, outcome: await check(root, gate, files, turn, baselines(gate)) };
105
123
  }),
106
124
  );
@@ -178,7 +196,8 @@ export async function checkTurn(session: string, root: string): Promise<CheckedT
178
196
  const changed = changedSince(root, turn.start, end);
179
197
  const { gates, refused, showAllPasses } = gatesOf(turn.config);
180
198
  const missing = missingTools(root, gates);
181
- const results = await runGates(root, runnable(gates, missing), changed, turn.start, baselines);
199
+ for (const gate of gates) if (keepsWatch(gate)) keepWatch(root, gate);
200
+ const results = await runGates(root, runnable(gates, missing), changed, turn.start, baselines, session);
182
201
  cacheReports(root, end, endReports(results, baselines));
183
202
  writeTurn(session, root, { ...turn, checked: true });
184
203
  // A compared gate with no report from the turn start can only count its exit code: a green it did not earn is said.