@tayomi/deterministic-gates 0.4.2 → 0.5.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.
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,13 +196,19 @@ 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
- // A compared gate with no report from the turn start can only count its exit code: a green it did not earn is said.
203
+ // A compared gate with no report from the turn start can only count its exit code, and a watch has none: a green it
204
+ // did not earn is said.
185
205
  const uncompared = results
186
206
  .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`);
207
+ .map(({ gate }) =>
208
+ keepsWatch(gate)
209
+ ? `${gate.name} not judged: no report from the turn start to compare its cycle with`
210
+ : `${gate.name} not compared: no report from the turn start, only its exit code counted`,
211
+ );
188
212
  // Only a gate the turn concerned is named: one that would not have run anyway costs nothing to miss.
189
213
  const notRun = missing
190
214
  .filter(({ gate }) => filesOf(gate, changed).length)
@@ -10,7 +10,8 @@ const LOCAL_GATES_FILE = ".gates.local.json";
10
10
  const DEFAULT_MAX_TIMEOUT_SECONDS = 45;
11
11
  // The times a turn sends the agent back: enough for a fix that breaks another gate, never a loop.
12
12
  const DEFAULT_MAX_SEND_BACKS = 5;
13
- const FIELDS = new Set(["name", "severity", "files", "run", "compare", "ignoreLines", "timeoutSeconds"]);
13
+ const FIELDS = new Set(["name", "severity", "files", "run", "compare", "ignoreLines", "timeoutSeconds", "watch"]);
14
+ const WATCH_FIELDS = new Set(["run", "cycleStart", "cycleEnd", "failed"]);
14
15
 
15
16
  /** In the arguments of a gate: the changed files it looks at, and the commit of the turn start. */
16
17
  export const FILES = "{files}";
@@ -24,6 +25,26 @@ export interface Gate {
24
25
  compare?: "turn-start";
25
26
  ignoreLines?: string;
26
27
  timeoutSeconds: number;
28
+ watch?: Watch;
29
+ }
30
+
31
+ /**
32
+ * A long-running command a gate keeps between turns, such as a test watch, with the patterns of its output that open
33
+ * a cycle, close one, and mark a failure. The gate's own run stays the one-shot command, for a check of the whole repo.
34
+ */
35
+ export interface Watch {
36
+ run: string[];
37
+ cycleStart: string;
38
+ cycleEnd: string;
39
+ /** Absent on a compared gate, which fails on the lines the last cycle added to the one the turn started on. */
40
+ failed?: string;
41
+ }
42
+
43
+ /** A gate that keeps a watch. */
44
+ export type WatchedGate = Gate & { watch: Watch };
45
+
46
+ export function keepsWatch(gate: Gate): gate is WatchedGate {
47
+ return gate.watch !== undefined;
27
48
  }
28
49
 
29
50
  type Entry = Record<string, unknown> & { name: string };
@@ -113,8 +134,27 @@ function isPattern(value: unknown): value is string {
113
134
  }
114
135
  }
115
136
 
137
+ function toWatch(watch: unknown, compared: boolean): Watch {
138
+ if (!isRecord(watch)) return refuse("watch holds run, cycleStart, cycleEnd and failed");
139
+ const unknown = Object.keys(watch).find((key) => !WATCH_FIELDS.has(key));
140
+ if (unknown !== undefined) refuse(`unknown field watch.${unknown}`);
141
+ const { run, cycleStart, cycleEnd, failed } = watch;
142
+ if (!isStringArray(run) || !run.length) refuse("watch.run is a non-empty list of strings");
143
+ if (run.some((argument) => argument.includes(FILES) || argument.includes(TURN)))
144
+ refuse(`a watch outlives the turn: its run takes neither ${FILES} nor ${TURN}`);
145
+ const pattern = (field: string, value: unknown): string =>
146
+ isPattern(value) ? value : refuse(`watch.${field} is a regular expression on a line of its output`);
147
+ if (compared && failed !== undefined) refuse("a compared watch fails on the lines its cycle added: no watch.failed");
148
+ return {
149
+ run,
150
+ cycleStart: pattern("cycleStart", cycleStart),
151
+ cycleEnd: pattern("cycleEnd", cycleEnd),
152
+ ...(compared ? {} : { failed: pattern("failed", failed) }),
153
+ };
154
+ }
155
+
116
156
  function toGate(entry: Entry, maxTimeoutSeconds: number): Gate {
117
- const { name, severity, files, run, compare, ignoreLines, timeoutSeconds = maxTimeoutSeconds } = entry;
157
+ const { name, severity, files, run, compare, ignoreLines, watch, timeoutSeconds = maxTimeoutSeconds } = entry;
118
158
  const unknown = Object.keys(entry).find((key) => !FIELDS.has(key));
119
159
  if (unknown !== undefined) refuse(`unknown field ${unknown}`);
120
160
  if (!/^[a-z][a-z0-9-]*$/.test(name)) refuse("a name is lowercase words joined by hyphens");
@@ -136,6 +176,7 @@ function toGate(entry: Entry, maxTimeoutSeconds: number): Gate {
136
176
  timeoutSeconds: Math.min(timeoutSeconds, maxTimeoutSeconds),
137
177
  ...(compare === undefined ? {} : { compare }),
138
178
  ...(ignoreLines === undefined ? {} : { ignoreLines }),
179
+ ...(watch === undefined ? {} : { watch: toWatch(watch, compare !== undefined) }),
139
180
  };
140
181
  }
141
182
 
@@ -4,18 +4,26 @@ import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import type { Gate } from "./config.ts";
6
6
  import { isRecord, isStringRecord, readJsonFile } from "./json.ts";
7
+ import { ENGINE_VERSION } from "./run.ts";
7
8
 
8
9
  // A turn almost always starts from the tree the previous turn ended on, so it reuses the reports of that tree
9
10
  // instead of running the compared gates again while the prompt waits. A report is the output of one command on one
10
- // tree, so the reports of a tree are kept by command, whatever the gate is called.
11
+ // tree, so the reports of a tree are kept by command, whatever the gate is called. A helper of the engine may print
12
+ // its report otherwise from one version to the next: the reports of another version are not reused.
11
13
 
12
14
  interface Cache {
15
+ engine: string;
13
16
  tree: string;
14
17
  reports: Record<string, string>;
15
18
  }
16
19
 
17
20
  function isCache(value: unknown): value is Cache {
18
- return isRecord(value) && typeof value.tree === "string" && isStringRecord(value.reports);
21
+ return (
22
+ isRecord(value) &&
23
+ typeof value.engine === "string" &&
24
+ typeof value.tree === "string" &&
25
+ isStringRecord(value.reports)
26
+ );
19
27
  }
20
28
 
21
29
  function cacheFile(root: string): string {
@@ -29,7 +37,7 @@ function commandOf(gate: Gate): string {
29
37
 
30
38
  function readCache(root: string): Cache | undefined {
31
39
  const cache = readJsonFile(cacheFile(root));
32
- return isCache(cache) ? cache : undefined;
40
+ return isCache(cache) && cache.engine === ENGINE_VERSION ? cache : undefined;
33
41
  }
34
42
 
35
43
  export function cachedReports(root: string, tree: string): (gate: Gate) => string | undefined {
@@ -41,6 +49,7 @@ export function cachedReports(root: string, tree: string): (gate: Gate) => strin
41
49
  export function cacheReports(root: string, tree: string, reports: (readonly [Gate, string])[]): void {
42
50
  const kept = readCache(root);
43
51
  const cache: Cache = {
52
+ engine: ENGINE_VERSION,
44
53
  tree,
45
54
  reports: {
46
55
  ...(kept?.tree === tree ? kept.reports : {}),
package/src/core/run.ts CHANGED
@@ -21,6 +21,11 @@ export function failed(outcome: Outcome): boolean {
21
21
  }
22
22
 
23
23
  const ENGINE = resolve(import.meta.dirname, "..", "..");
24
+ const manifest = readJsonFile(join(ENGINE, "package.json"));
25
+ /** The version of this engine: what its helpers print, so what a report holds, may change from one to the next. */
26
+ export const ENGINE_VERSION = isRecord(manifest) ? String(manifest.version) : "";
27
+ /** What a tool runs with: no colour, which some tools print anyway. */
28
+ export const TOOL_ENV = { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0" };
24
29
  const MAX_OUTPUT_MB = 16;
25
30
  const ENGINE_PREFIX = "{engine}/";
26
31
 
@@ -97,20 +102,24 @@ function executable(file: string): boolean {
97
102
  });
98
103
  }
99
104
 
100
- /**
101
- * Why the program of a gate cannot run on this machine, or nothing when it can: looked up as the gate would start it,
102
- * without starting it. A command the engine cannot resolve is left to the run, which reports it.
103
- */
104
- export function missingTool(root: string, gate: Gate): string | undefined {
105
+ function missingProgram(root: string, name: string): string | undefined {
105
106
  let command: Command;
106
107
  try {
107
- command = commandOf(root, gate.run[0] ?? "");
108
+ command = commandOf(root, name);
108
109
  } catch {
109
110
  return undefined;
110
111
  }
111
112
  return command.missing && !executable(command.file) ? command.missing : undefined;
112
113
  }
113
114
 
115
+ /**
116
+ * Why the program of a gate, or of its watch, cannot run on this machine, or nothing when they can: looked up as the
117
+ * gate would start it, without starting it. A command the engine cannot resolve is left to the run, which reports it.
118
+ */
119
+ export function missingTool(root: string, gate: Gate): string | undefined {
120
+ return missingProgram(root, gate.run[0] ?? "") ?? (gate.watch && missingProgram(root, gate.watch.run[0] ?? ""));
121
+ }
122
+
114
123
  export function argumentsOf(gate: Gate, files: string[], turn: string): string[] {
115
124
  return gate.run.slice(1).flatMap((argument) => (argument === FILES ? files : [argument.replaceAll(TURN, turn)]));
116
125
  }
@@ -159,7 +168,7 @@ async function execute(root: string, gate: Gate, args: string[]): Promise<Execut
159
168
  cwd: root,
160
169
  timeout: gate.timeoutSeconds * 1000,
161
170
  maxBuffer: MAX_OUTPUT_MB * 1024 * 1024,
162
- env: { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0" },
171
+ env: TOOL_ENV,
163
172
  },
164
173
  (error, stdout, stderr) => {
165
174
  resolve({
@@ -185,12 +194,16 @@ function outputOf(
185
194
  if (error?.killed === true)
186
195
  return `Out of time after ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
187
196
  if (error?.code === "ENOENT") return command.missing;
188
- // Some tools colour despite NO_COLOR, and absolute paths only cost the agent tokens.
189
- const said = stripVTControlCharacters(printed).split(`${root}${sep}`).join("").trim();
197
+ const said = cleaned(root, printed);
190
198
  if (said || !error) return said;
191
199
  return `exit code ${String(error.code)}, no output`;
192
200
  }
193
201
 
202
+ /** What a tool printed, for the agent: some tools colour despite NO_COLOR, and absolute paths only cost it tokens. */
203
+ export function cleaned(root: string, printed: string): string {
204
+ return stripVTControlCharacters(printed).split(`${root}${sep}`).join("").trim();
205
+ }
206
+
194
207
  /** Runs a compared gate on the whole project, as the turn starts. */
195
208
  export function wholeProject(root: string, gate: Gate): Promise<{ ok: boolean; output: string }> {
196
209
  return execute(root, gate, gate.run.slice(1));
@@ -211,7 +224,15 @@ export async function check(
211
224
  const ran = { name: gate.name, ms, report: ok ? output : undefined };
212
225
  if (timedOut) return { ...ran, ok, output, timedOut };
213
226
  if (!isCompared(gate) || !ok) return { ...ran, ok, output };
214
- if (baseline === undefined) return { ...ran, ok: true, output: "" };
227
+ return { ...ran, ...addedLines(gate, output, baseline) };
228
+ }
229
+
230
+ /**
231
+ * Judges the output of a compared gate that ran clean: it fails on the lines the turn added to the report of the turn
232
+ * start. Without that report, nothing counts but the exit code.
233
+ */
234
+ export function addedLines(gate: Gate, output: string, baseline: string | undefined): { ok: boolean; output: string } {
235
+ if (baseline === undefined) return { ok: true, output: "" };
215
236
  const added = newLines(baseline, output, gate.ignoreLines);
216
- return { ...ran, ok: added.length === 0, output: added.join("\n") };
237
+ return { ok: added.length === 0, output: added.join("\n") };
217
238
  }
@@ -0,0 +1,313 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import {
4
+ closeSync,
5
+ existsSync,
6
+ mkdirSync,
7
+ openSync,
8
+ readdirSync,
9
+ readFileSync,
10
+ rmSync,
11
+ statSync,
12
+ writeFileSync,
13
+ } from "node:fs";
14
+ import { tmpdir } from "node:os";
15
+ import { dirname, join } from "node:path";
16
+ import { createInterface } from "node:readline";
17
+ import { setTimeout as sleep } from "node:timers/promises";
18
+ import { type Gate, isCompared, type Watch, type WatchedGate } from "./config.ts";
19
+ import { addedLines, cleaned, commandOf, ENGINE_VERSION, type Outcome, TOOL_ENV } from "./run.ts";
20
+
21
+ // Once a cycle closes, the lines a watch prints after it, such as the errors of a failed build, come within this long.
22
+ const QUIET_MS = 1000;
23
+ // 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:
24
+ // it cannot change the last cycle, which then judges the turn.
25
+ const UNSEEN_MS = 5000;
26
+ const POLL_MS = 100;
27
+ // What a watch that stopped leaves the agent: enough to see the error, not the whole history of the session.
28
+ const LAST_LINES = 20;
29
+ // A prompt waits this long at most for a compared watch to settle, under the 60 s its hook has.
30
+ const TURN_START_MS = 45_000;
31
+
32
+ const PREFIX = "gates-watch-";
33
+ // A start that holds its lock longer than this died on the way: the next hook takes the lock over.
34
+ const STALE_START_MS = 10_000;
35
+ // A watch stops by itself after this long without a prompt nor a stop on its repo, as for a session left open. The
36
+ // tests of the engine shorten it.
37
+ const IDLE_MS = 30 * 60 * 1000;
38
+
39
+ function idleMs(): number {
40
+ return Number(process.env.GATES_WATCH_IDLE_MS) || IDLE_MS;
41
+ }
42
+
43
+ /** Records a prompt or a stop on the repo of a watch, which keeps it from stopping for idleness. */
44
+ function touch(folder: string): void {
45
+ writeFileSync(join(folder, "activity"), "");
46
+ }
47
+
48
+ /** Records a stop on the repo of the watch of a gate, if it has one, whether the stop judges it or not. */
49
+ export function keepWatch(root: string, gate: Gate): void {
50
+ const folder = folderOf(root, gate);
51
+ if (existsSync(folder)) touch(folder);
52
+ }
53
+
54
+ /**
55
+ * Where a watch keeps its process, its output and the sessions that use it, outside the repo: one per repo, gate and
56
+ * engine version, since a helper of the engine may print its cycles otherwise from one version to the next.
57
+ */
58
+ function folderOf(root: string, gate: Gate): string {
59
+ const key = createHash("sha256").update(`${root}\0${gate.name}\0${ENGINE_VERSION}`).digest("hex").slice(0, 16);
60
+ return join(tmpdir(), `${PREFIX}${key}`);
61
+ }
62
+
63
+ // A file per session that uses the watch: two hooks at once each write their own, and neither loses the other's.
64
+ function sessionFile(folder: string, session: string): string {
65
+ return join(folder, "sessions", session.replace(/[^\w-]/g, ""));
66
+ }
67
+
68
+ function register(folder: string, session: string): void {
69
+ mkdirSync(join(folder, "sessions"), { recursive: true });
70
+ writeFileSync(sessionFile(folder, session), "");
71
+ }
72
+
73
+ /** Whether the watch runs, has stopped on its own, was stopped for idleness, or was never started. */
74
+ function stateOf(folder: string): "running" | "stopped" | "idle" | "absent" {
75
+ let pid: number;
76
+ try {
77
+ pid = Number(readFileSync(join(folder, "pid"), "utf8"));
78
+ } catch {
79
+ return "absent";
80
+ }
81
+ try {
82
+ if (!pid) return "stopped";
83
+ process.kill(pid, 0);
84
+ return "running";
85
+ } catch {
86
+ return existsSync(join(folder, "idle")) ? "idle" : "stopped";
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Starts the watch of a gate in the background, unless it already runs, and records that the session uses it: it
92
+ * outlives the hook that starts it, until no session uses it.
93
+ */
94
+ export function startWatch(session: string, root: string, gate: WatchedGate): void {
95
+ const folder = folderOf(root, gate);
96
+ mkdirSync(folder, { recursive: true });
97
+ touch(folder);
98
+ // The sessions of a watch that starts again still use it.
99
+ register(folder, session);
100
+ if (stateOf(folder) === "running") return;
101
+ // Two hooks at once, such as two sessions starting, start one watch: the other only registers its session.
102
+ const lock = join(folder, "starting");
103
+ if (Date.now() - changedAt(lock) >= STALE_START_MS) rmSync(lock, { force: true });
104
+ try {
105
+ closeSync(openSync(lock, "wx"));
106
+ } catch {
107
+ return;
108
+ }
109
+ try {
110
+ // Another hook may have started it between the look above and the lock.
111
+ if (stateOf(folder) !== "running") launch(folder, root, gate.watch);
112
+ } finally {
113
+ rmSync(lock, { force: true });
114
+ }
115
+ }
116
+
117
+ function launch(folder: string, root: string, watch: Watch): void {
118
+ rmSync(join(folder, "idle"), { force: true });
119
+ const [name = "", ...args] = watch.run;
120
+ const command = commandOf(root, name);
121
+ const supervisor = commandOf(root, "{engine}/src/core/watch.ts");
122
+ const watched = [
123
+ join(folder, "activity"),
124
+ String(idleMs()),
125
+ watch.cycleStart,
126
+ command.file,
127
+ ...command.args,
128
+ ...args,
129
+ ];
130
+ const log = openSync(join(folder, "output.log"), "w");
131
+ const child = spawn(supervisor.file, [...supervisor.args, ...watched], {
132
+ cwd: root,
133
+ detached: true,
134
+ stdio: ["ignore", log, log],
135
+ env: TOOL_ENV,
136
+ });
137
+ closeSync(log);
138
+ child.on("error", () => {});
139
+ child.unref();
140
+ writeFileSync(join(folder, "pid"), String(child.pid ?? ""));
141
+ }
142
+
143
+ /** The last cycle of a watch: its lines since it opened, and whether it is still open. */
144
+ function lastCycle(printed: string, watch: Watch): { open: boolean; lines: string[] } {
145
+ const lines = printed.split("\n");
146
+ if (lines.at(-1) === "") lines.pop();
147
+ const opens = new RegExp(watch.cycleStart);
148
+ const closes = new RegExp(watch.cycleEnd);
149
+ // The start of the watch opens the first cycle, and lines after the one that closes it still belong to it.
150
+ const cycle = lines.slice(lines.findLastIndex((line) => opens.test(line)) + 1);
151
+ return { open: !cycle.some((line) => closes.test(line)), lines: cycle };
152
+ }
153
+
154
+ function changedAt(path: string): number {
155
+ try {
156
+ return statSync(path).mtimeMs;
157
+ } catch {
158
+ return 0;
159
+ }
160
+ }
161
+
162
+ function readLog(log: string): string {
163
+ try {
164
+ return readFileSync(log, "utf8");
165
+ } catch {
166
+ return "";
167
+ }
168
+ }
169
+
170
+ /** Where a watch is once it has settled, with the lines of its last cycle, or once it can no longer settle. */
171
+ type Settled = { ms: number } & ({ cycle: string } | { stopped: string } | { timedOut: true });
172
+
173
+ /**
174
+ * 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
175
+ * one of the files. A watch no hook started, as when the hooks were installed mid-session, starts now, and so does one
176
+ * stopped for idleness, as during a turn longer than the idle delay: it is not to blame.
177
+ */
178
+ async function settle(
179
+ session: string,
180
+ root: string,
181
+ gate: WatchedGate,
182
+ files: string[],
183
+ limitMs: number,
184
+ ): Promise<Settled> {
185
+ const started = performance.now();
186
+ const folder = folderOf(root, gate);
187
+ const log = join(folder, "output.log");
188
+ if (["absent", "idle"].includes(stateOf(folder))) startWatch(session, root, gate);
189
+ touch(folder);
190
+ for (;;) {
191
+ // Read once the watch is known stopped, so its last lines are in.
192
+ const stopped = stateOf(folder) === "stopped";
193
+ const printed = readLog(log);
194
+ const ms = performance.now() - started;
195
+ if (stopped) {
196
+ const last = cleaned(
197
+ root,
198
+ printed
199
+ .split("\n")
200
+ .slice(-LAST_LINES - 1)
201
+ .join("\n"),
202
+ );
203
+ return {
204
+ ms,
205
+ stopped: last ? `The watch stopped. Its last lines:\n${last}` : "The watch stopped, with no output.",
206
+ };
207
+ }
208
+ // A cycle that started after the last change read it, however long the watch took to see it.
209
+ const changed = Math.max(0, ...files.map((file) => changedAt(join(root, file))));
210
+ const seen = changedAt(join(folder, "cycle")) >= changed || Date.now() - changed >= UNSEEN_MS;
211
+ const cycle = lastCycle(printed, gate.watch);
212
+ if (seen && !cycle.open && Date.now() - changedAt(log) >= QUIET_MS)
213
+ return { ms, cycle: cleaned(root, cycle.lines.join("\n")) };
214
+ if (ms >= limitMs) return { ms, timedOut: true };
215
+ await sleep(POLL_MS);
216
+ }
217
+ }
218
+
219
+ /**
220
+ * 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
221
+ * gate looks at: on its failed lines, or for a compared gate, on the lines it added to the report of the turn start.
222
+ * Not settled in the time of the gate: out of time, neither green nor red. A watch that stopped fails, with the last
223
+ * lines it printed.
224
+ */
225
+ export async function judgeWatch(
226
+ session: string,
227
+ root: string,
228
+ gate: WatchedGate,
229
+ files: string[],
230
+ baseline: string | undefined,
231
+ ): Promise<Outcome> {
232
+ const settled = await settle(session, root, gate, files, gate.timeoutSeconds * 1000);
233
+ const { name } = gate;
234
+ const { ms } = settled;
235
+ if ("stopped" in settled) return { name, ok: false, ms, output: settled.stopped, report: undefined };
236
+ if ("timedOut" in settled) {
237
+ const output = `The watch did not settle within ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
238
+ return { name, ok: false, ms, output, report: undefined, timedOut: true };
239
+ }
240
+ const { cycle } = settled;
241
+ const fails = new RegExp(gate.watch.failed ?? "(?!)");
242
+ const judged = isCompared(gate)
243
+ ? addedLines(gate, cycle, baseline)
244
+ : { ok: !cycle.split("\n").some((line) => fails.test(line)), output: cycle };
245
+ return { name, ms, ...judged, report: judged.ok ? cycle : undefined };
246
+ }
247
+
248
+ /**
249
+ * The report a compared watch gives the turn start: its last cycle, once it settles in the time a prompt can wait.
250
+ * Nothing when it does not, and the turn then counts nothing as new.
251
+ */
252
+ export async function watchReport(session: string, root: string, gate: WatchedGate): Promise<string | undefined> {
253
+ const settled = await settle(session, root, gate, [], Math.min(gate.timeoutSeconds * 1000, TURN_START_MS));
254
+ return "cycle" in settled ? settled.cycle : undefined;
255
+ }
256
+
257
+ /** Stops each watch the session was the last to use, in any repo: the watch and every process it started. */
258
+ export function endSession(session: string): void {
259
+ for (const entry of readdirSync(tmpdir())) {
260
+ if (!entry.startsWith(PREFIX)) continue;
261
+ const folder = join(tmpdir(), entry);
262
+ const file = sessionFile(folder, session);
263
+ if (!existsSync(file)) continue;
264
+ rmSync(file, { force: true });
265
+ if (!readdirSync(join(folder, "sessions")).length) stop(folder);
266
+ }
267
+ }
268
+
269
+ function stop(folder: string): void {
270
+ if (stateOf(folder) !== "running") return;
271
+ try {
272
+ process.kill(-Number(readFileSync(join(folder, "pid"), "utf8")), "SIGTERM");
273
+ } catch {}
274
+ }
275
+
276
+ /**
277
+ * The supervisor of a watch, which this module runs as when the engine starts one: it runs the watch, its output
278
+ * going where its own goes, and stops it with every process it started once its repo has had no prompt nor stop for
279
+ * the idle delay. Started detached, it leads a process group of its own, so stopping the group stops the watch and
280
+ * the tools under it.
281
+ */
282
+ function supervise(activity: string, idle: number, cycleStart: string, file: string, args: string[]): void {
283
+ // The time the last cycle started, which the stop compares with the changes of the turn. The start opens the first.
284
+ const cycle = join(dirname(activity), "cycle");
285
+ const opens = new RegExp(cycleStart);
286
+ writeFileSync(cycle, "");
287
+ const watch = spawn(file, args, { stdio: ["ignore", "pipe", "pipe"] });
288
+ const forward = (line: string) => {
289
+ // Printed before the time is kept, so a stop that sees the time also finds the cycle in the output.
290
+ console.log(line);
291
+ if (opens.test(line)) writeFileSync(cycle, "");
292
+ };
293
+ createInterface({ input: watch.stdout }).on("line", forward);
294
+ createInterface({ input: watch.stderr }).on("line", forward);
295
+ watch.on("error", (error) => {
296
+ console.log(error.message);
297
+ process.exit(1);
298
+ });
299
+ watch.on("close", (code) => process.exit(code ?? 1));
300
+ setInterval(
301
+ () => {
302
+ if (Date.now() - changedAt(activity) < idle) return;
303
+ writeFileSync(join(dirname(activity), "idle"), "");
304
+ process.kill(-process.pid, "SIGTERM");
305
+ },
306
+ Math.min(idle / 4, 10_000),
307
+ );
308
+ }
309
+
310
+ if (import.meta.main) {
311
+ const [activity = "", idle = "", cycleStart = "", file = "", ...args] = process.argv.slice(2);
312
+ supervise(activity, Number(idle), cycleStart, file, args);
313
+ }