@tayomi/deterministic-gates 0.6.1 → 0.7.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.
@@ -19,28 +19,36 @@ const SOURCE_CHARS = 200;
19
19
  function cut(text, chars) {
20
20
  return text.length > chars ? `${text.slice(0, chars)}…` : text;
21
21
  }
22
+ /**
23
+ * The errors, each on one line: a key, its file, code and source line, with a count after one its file already has
24
+ * on the same source; then, after a tab, the first line of its message. An error of no file is kept as it is.
25
+ */
26
+ export function strictErrorLines(errors) {
27
+ const seen = new Map();
28
+ return errors.map((error) => {
29
+ const source = typeof error === "string" ? "" : error.source.replaceAll("\t", " ").trim();
30
+ const found = typeof error === "string" ? error : `${error.file}: error ${error.code} at \`${cut(source, SOURCE_CHARS)}\``;
31
+ const count = (seen.get(found) ?? 0) + 1;
32
+ seen.set(found, count);
33
+ const key = count === 1 ? found : `${found} (${count})`;
34
+ return typeof error === "string" ? key : `${key}\t${cut(error.message, MESSAGE_CHARS)}`;
35
+ });
36
+ }
22
37
  /** The errors tsc printed, each on one line, as the gate compares them. */
23
38
  export function typeErrors(printed, sources) {
24
39
  const lines = new Map();
25
40
  const sourceLine = (file, line) => {
26
41
  if (!lines.has(file))
27
42
  lines.set(file, (sources(file) ?? "").split("\n"));
28
- return (lines.get(file)?.[line - 1] ?? "").replaceAll("\t", " ").trim();
43
+ return lines.get(file)?.[line - 1] ?? "";
29
44
  };
30
- const seen = new Map();
31
- const errors = [];
32
- for (const line of printed) {
45
+ return strictErrorLines(printed
33
46
  // The lines under an error explain it, and name its first failing member.
34
- if (!line.trim() || /^\s/.test(line))
35
- continue;
36
- const [, file, at, code, message = ""] = POSITION.exec(line) ?? [];
37
- const found = file === undefined ? line : `${file}: error ${code} at \`${cut(sourceLine(file, Number(at)), SOURCE_CHARS)}\``;
38
- const count = (seen.get(found) ?? 0) + 1;
39
- seen.set(found, count);
40
- const key = count === 1 ? found : `${found} (${count})`;
41
- errors.push(file === undefined ? key : `${key}\t${cut(message, MESSAGE_CHARS)}`);
42
- }
43
- return errors;
47
+ .filter((line) => line.trim() && !/^\s/.test(line))
48
+ .map((line) => {
49
+ const [, file, at, code = "", message = ""] = POSITION.exec(line) ?? [];
50
+ return file === undefined ? line : { file, code, source: sourceLine(file, Number(at)), message };
51
+ }));
44
52
  }
45
53
  /** What to print for each line of tsc in watch mode: nothing until a compilation ends, then its errors. */
46
54
  export function watching(sources) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tayomi/deterministic-gates",
3
- "version": "0.6.1",
3
+ "version": "0.7.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
  "type": "module",
6
6
  "license": "MIT",
@@ -1,5 +1,5 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
- import { join } from "node:path";
2
+ import { isAbsolute, join } from "node:path";
3
3
  import { isRecord, isStringArray, messageOf } from "./json.ts";
4
4
  import { repoRoot } from "./snapshot.ts";
5
5
 
@@ -21,7 +21,7 @@ const FIELDS = new Set([
21
21
  "timeoutSeconds",
22
22
  "watch",
23
23
  ]);
24
- const WATCH_FIELDS = new Set(["run", "cycleStart", "cycleEnd", "failed"]);
24
+ const WATCH_FIELDS = new Set(["run", "cycleStart", "cycleEnd", "failed", "sync", "frozen"]);
25
25
 
26
26
  /** In the arguments of a gate: the changed files it looks at, and the commit of the turn start. */
27
27
  export const FILES = "{files}";
@@ -50,6 +50,10 @@ export interface Watch {
50
50
  cycleEnd: string;
51
51
  /** Absent on a compared gate, which fails on the lines the last cycle added to the one the turn started on. */
52
52
  failed?: string;
53
+ /** A file of the repo the watch opens a cycle for each time its date changes, such as the tsconfig it reads. */
54
+ sync: string;
55
+ /** The files the watch lists once as it starts, and never again, such as the specs of ng test. */
56
+ frozen?: string;
53
57
  }
54
58
 
55
59
  /** A gate that keeps a watch. */
@@ -147,18 +151,24 @@ function isPattern(value: unknown): value is string {
147
151
  }
148
152
 
149
153
  function toWatch(watch: unknown, compared: boolean): Watch {
150
- if (!isRecord(watch)) return refuse("watch holds run, cycleStart, cycleEnd and failed");
154
+ if (!isRecord(watch)) return refuse("watch holds run, cycleStart, cycleEnd, failed and sync");
151
155
  const unknown = Object.keys(watch).find((key) => !WATCH_FIELDS.has(key));
152
156
  if (unknown !== undefined) refuse(`unknown field watch.${unknown}`);
153
- const { run, cycleStart, cycleEnd, failed } = watch;
157
+ const { run, cycleStart, cycleEnd, failed, sync, frozen } = watch;
154
158
  if (!isStringArray(run) || !run.length) refuse("watch.run is a non-empty list of strings");
155
159
  if (run.some((argument) => argument.includes(FILES) || argument.includes(TURN)))
156
160
  refuse(`a watch outlives the turn: its run takes neither ${FILES} nor ${TURN}`);
157
161
  const pattern = (field: string, value: unknown): string =>
158
162
  isPattern(value) ? value : refuse(`watch.${field} is a regular expression on a line of its output`);
159
163
  if (compared && failed !== undefined) refuse("a compared watch fails on the lines its cycle added: no watch.failed");
164
+ if (typeof sync !== "string" || !sync || isAbsolute(sync) || sync.split(/[\\/]/).includes(".."))
165
+ refuse("watch.sync is a file of the repo the watch opens a cycle for when its date changes, such as its tsconfig");
166
+ if (frozen !== undefined && !isPattern(frozen))
167
+ refuse("watch.frozen is a regular expression on the files the watch lists only as it starts");
160
168
  return {
161
169
  run,
170
+ sync,
171
+ ...(frozen === undefined ? {} : { frozen }),
162
172
  cycleStart: pattern("cycleStart", cycleStart),
163
173
  cycleEnd: pattern("cycleEnd", cycleEnd),
164
174
  ...(compared ? {} : { failed: pattern("failed", failed) }),
package/src/core/watch.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
- import { createHash } from "node:crypto";
2
+ import { createHash, randomUUID } from "node:crypto";
3
3
  import {
4
4
  closeSync,
5
5
  existsSync,
@@ -7,22 +7,28 @@ import {
7
7
  openSync,
8
8
  readdirSync,
9
9
  readFileSync,
10
+ renameSync,
10
11
  rmSync,
11
12
  statSync,
13
+ utimesSync,
12
14
  writeFileSync,
13
15
  } from "node:fs";
14
16
  import { tmpdir } from "node:os";
15
- import { dirname, join } from "node:path";
17
+ import { join } from "node:path";
16
18
  import { createInterface } from "node:readline";
17
19
  import { setTimeout as sleep } from "node:timers/promises";
18
20
  import { type Gate, isCompared, type Watch, type WatchedGate } from "./config.ts";
19
21
  import { addedLines, cleaned, commandOf, ENGINE_VERSION, type Outcome, toolEnv } from "./run.ts";
22
+ import { listFiles } from "./snapshot.ts";
20
23
 
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;
24
+ // A watch that has not opened a cycle this long after the engine touched its sync file is touched again: it may look
25
+ // for changes only once its first cycle is over, as Angular and tsc do, and never see a touch made before. Each wait
26
+ // is twice the one before, since a watch on a busy machine takes seconds to say it opens a cycle, and a touch too
27
+ // many is a cycle too many. The wait changes no verdict, which only ever comes from a cycle the watch opened after a
28
+ // touch. The tests of the engine shorten it.
29
+ const RESYNC_MS = 1000;
30
+ // A watch that opens no cycle after this many touches, 31 s after the first, does not look at its sync file.
31
+ const SYNC_TOUCHES = 5;
26
32
  const POLL_MS = 100;
27
33
  // What a watch that stopped leaves the agent: enough to see the error, not the whole history of the session.
28
34
  const LAST_LINES = 20;
@@ -40,6 +46,10 @@ function idleMs(): number {
40
46
  return Number(process.env.GATES_WATCH_IDLE_MS) || IDLE_MS;
41
47
  }
42
48
 
49
+ function resyncMs(): number {
50
+ return Number(process.env.GATES_WATCH_RESYNC_MS) || RESYNC_MS;
51
+ }
52
+
43
53
  /** Records a prompt or a stop on the repo of a watch, which keeps it from stopping for idleness. */
44
54
  function touch(folder: string): void {
45
55
  writeFileSync(join(folder, "activity"), "");
@@ -70,23 +80,47 @@ function register(folder: string, session: string): void {
70
80
  writeFileSync(sessionFile(folder, session), "");
71
81
  }
72
82
 
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;
83
+ /** The process of the watch, as the engine recorded it when it started it, or nothing when it never did. */
84
+ function processOf(folder: string): string | undefined {
76
85
  try {
77
- pid = Number(readFileSync(join(folder, "pid"), "utf8"));
86
+ return readFileSync(join(folder, "pid"), "utf8");
78
87
  } catch {
79
- return "absent";
88
+ return undefined;
80
89
  }
90
+ }
91
+
92
+ /** Whether the watch runs, has stopped on its own, was stopped by the engine, or was never started. */
93
+ function stateOf(folder: string): "running" | "stopped" | "idle" | "absent" {
94
+ const recorded = processOf(folder);
95
+ if (recorded === undefined) return "absent";
81
96
  try {
82
- if (!pid) return "stopped";
83
- process.kill(pid, 0);
97
+ if (!Number(recorded)) return "stopped";
98
+ process.kill(Number(recorded), 0);
84
99
  return "running";
85
100
  } catch {
86
101
  return existsSync(join(folder, "idle")) ? "idle" : "stopped";
87
102
  }
88
103
  }
89
104
 
105
+ // Two hooks at once, such as two sessions starting, start one watch: only the one that holds the lock does.
106
+ function lockStart(folder: string): boolean {
107
+ const lock = join(folder, "starting");
108
+ // Only a lock that is there and old is taken over: removing one on the word of a look that found none would remove
109
+ // the lock another hook has just taken, and both would start a watch.
110
+ const taken = changedAt(lock);
111
+ if (taken && Date.now() - taken >= STALE_START_MS) rmSync(lock, { force: true });
112
+ try {
113
+ closeSync(openSync(lock, "wx"));
114
+ return true;
115
+ } catch {
116
+ return false;
117
+ }
118
+ }
119
+
120
+ function unlockStart(folder: string): void {
121
+ rmSync(join(folder, "starting"), { force: true });
122
+ }
123
+
90
124
  /**
91
125
  * Starts the watch of a gate in the background, unless it already runs, and records that the session uses it: it
92
126
  * outlives the hook that starts it, until no session uses it.
@@ -97,36 +131,37 @@ export function startWatch(session: string, root: string, gate: WatchedGate): vo
97
131
  touch(folder);
98
132
  // The sessions of a watch that starts again still use it.
99
133
  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
- }
134
+ if (stateOf(folder) === "running" || !lockStart(folder)) return;
109
135
  try {
110
136
  // Another hook may have started it between the look above and the lock.
111
137
  if (stateOf(folder) !== "running") launch(folder, root, gate.watch);
112
138
  } finally {
113
- rmSync(lock, { force: true });
139
+ unlockStart(folder);
114
140
  }
115
141
  }
116
142
 
143
+ /** The files of the repo the watch lists only as it starts, one per line. */
144
+ function frozenFiles(root: string, watch: Watch): string {
145
+ if (watch.frozen === undefined) return "";
146
+ const frozen = new RegExp(watch.frozen);
147
+ return listFiles(root)
148
+ .filter((file) => frozen.test(file))
149
+ .join("\n");
150
+ }
151
+
117
152
  function launch(folder: string, root: string, watch: Watch): void {
118
153
  rmSync(join(folder, "idle"), { force: true });
154
+ // The first cycle of a watch reads every file there is: it owes a cycle for none.
155
+ rmSync(join(folder, "owed"), { recursive: true, force: true });
156
+ // What the watch before this one left of its cycles.
157
+ for (const left of ["cycles", "cycle", "last"]) rmSync(join(folder, left), { force: true });
119
158
  const [name = "", ...args] = watch.run;
120
159
  const command = commandOf(root, name);
121
160
  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
- ];
161
+ const cycle = [watch.cycleStart, watch.cycleEnd];
162
+ const watched = [folder, String(idleMs()), ...cycle, command.file, ...command.args, ...args];
163
+ // Listed before the watch starts: a file created in between counts as one it may not know, never the other way.
164
+ writeFileSync(join(folder, "frozen"), frozenFiles(root, watch));
130
165
  const log = openSync(join(folder, "output.log"), "w");
131
166
  const child = spawn(supervisor.file, [...supervisor.args, ...watched], {
132
167
  cwd: root,
@@ -140,15 +175,28 @@ function launch(folder: string, root: string, watch: Watch): void {
140
175
  writeFileSync(join(folder, "pid"), String(child.pid ?? ""));
141
176
  }
142
177
 
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 };
178
+ /** The cycles of a watch since it started, as its supervisor counts them. */
179
+ interface Cycles {
180
+ /** How many cycles the watch opened, the one its start opens left out. */
181
+ opened: number;
182
+ /** Whether the last cycle is still open. */
183
+ open: boolean;
184
+ }
185
+
186
+ // A watch whose supervisor has written nothing yet is in the cycle its start opens.
187
+ function cyclesOf(folder: string): Cycles {
188
+ const [opened, state] = readText(join(folder, "cycles")).split(" ");
189
+ return { opened: Number(opened), open: state !== "closed" };
190
+ }
191
+
192
+ /** Gives the files their date again, as a change of nothing else, for a watch that looks at their date. */
193
+ function touchAgain(paths: string[]): void {
194
+ const now = new Date();
195
+ for (const path of paths) {
196
+ try {
197
+ utimesSync(path, now, now);
198
+ } catch {}
199
+ }
152
200
  }
153
201
 
154
202
  function changedAt(path: string): number {
@@ -159,21 +207,58 @@ function changedAt(path: string): number {
159
207
  }
160
208
  }
161
209
 
162
- function readLog(log: string): string {
210
+ function readText(path: string): string {
163
211
  try {
164
- return readFileSync(log, "utf8");
212
+ return readFileSync(path, "utf8");
165
213
  } catch {
166
214
  return "";
167
215
  }
168
216
  }
169
217
 
170
- /** Where a watch is once it has settled, with the lines of its last cycle, or once it can no longer settle. */
218
+ /** Writes a file at once, so that a hook reading it never finds half of it. */
219
+ function writeWhole(path: string, text: string): void {
220
+ writeFileSync(`${path}.new`, text);
221
+ renameSync(`${path}.new`, path);
222
+ }
223
+
224
+ /** Where a watch is once it has answered, with the lines of the cycle that judges, or once it no longer can. */
171
225
  type Settled = { ms: number } & ({ cycle: string } | { stopped: string } | { timedOut: true });
172
226
 
173
227
  /**
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.
228
+ * Starts the watch again when a file it lists only as it starts was created or deleted since: its first cycle then
229
+ * reads every file there is. Only one hook does, and only the watch it looked at: another session may be here too.
230
+ */
231
+ async function restartOnFrozenChange(session: string, root: string, gate: WatchedGate, folder: string): Promise<void> {
232
+ if (gate.watch.frozen === undefined || stateOf(folder) !== "running") return;
233
+ if (readText(join(folder, "frozen")) === frozenFiles(root, gate.watch) || !lockStart(folder)) return;
234
+ try {
235
+ if (stateOf(folder) !== "running" || readText(join(folder, "frozen")) === frozenFiles(root, gate.watch)) return;
236
+ // Stopped by the engine, so that another session waiting on the watch does not take it for one that broke.
237
+ writeFileSync(join(folder, "idle"), "");
238
+ stop(folder);
239
+ for (let waited = 0; stateOf(folder) === "running" && waited < STALE_START_MS / 2; waited += POLL_MS)
240
+ await sleep(POLL_MS);
241
+ if (stateOf(folder) !== "running") launch(folder, root, gate.watch);
242
+ } finally {
243
+ unlockStart(folder);
244
+ }
245
+ register(folder, session);
246
+ }
247
+
248
+ /**
249
+ * Asks the watch of a gate for a cycle that read the files of the turn, and waits for it, with no guess on how long a
250
+ * watch takes to see a change. Each round touches files, then waits for the watch to open a cycle after the touch,
251
+ * which only a watch that saw the touch does:
252
+ * 1. the files of the turn, so that a change it missed reaches it, and the sync file. A watch that does not look for
253
+ * changes yet sees neither, and both are touched again;
254
+ * 2. the sync file, once that cycle has closed: the cycle of round 1 may have been on its way before the touch, and
255
+ * this one opens after every change the watch then had waiting;
256
+ * 3. the sync file once more, since the cycle it opens ends the one of round 2, the one that judges, whose last lines
257
+ * may come after the line that closes it.
258
+ * A watch that opens no cycle however often it is touched does not look at its sync file, and is said so. A watch no
259
+ * hook started, as when the hooks were installed mid-session, starts now, and so does one the engine
260
+ * stopped, for idleness or to start it again: it is not to blame. One another session starts again meanwhile is asked
261
+ * again from the first round.
177
262
  */
178
263
  async function settle(
179
264
  session: string,
@@ -184,43 +269,97 @@ async function settle(
184
269
  ): Promise<Settled> {
185
270
  const started = performance.now();
186
271
  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);
272
+ const sync = join(root, gate.watch.sync);
273
+ if (!existsSync(sync)) {
274
+ const stopped = `The watch cannot be asked for a cycle: its watch.sync, ${gate.watch.sync}, does not exist.`;
275
+ return { ms: 0, stopped };
276
+ }
277
+ await restartOnFrozenChange(session, root, gate, folder);
278
+ const turn = files.map((file) => join(root, file)).filter((path) => existsSync(path));
279
+ const rounds = [[...turn, sync], [sync], [sync]];
280
+ let asked: string | undefined;
281
+ let round = 0;
282
+ // The cycles the watch had opened when the round touched its files, when it last did, and how many times: none
283
+ // before its first touch.
284
+ let touched: { opened: number; at: number; times: number } | undefined;
190
285
  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);
286
+ const state = stateOf(folder);
287
+ if (state === "absent" || state === "idle") startWatch(session, root, gate);
288
+ // Waiting on the watch is using it: it does not stop for idleness under a stop that waits.
289
+ touch(folder);
194
290
  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
- );
291
+ if (state === "stopped") {
292
+ // Read once the watch is known stopped, so its last lines are in: the ones its supervisor kept, or what the
293
+ // supervisor itself printed when it broke.
294
+ const printed = readText(join(folder, "last")) || readText(join(folder, "output.log"));
295
+ const last = cleaned(root, printed.trimEnd().split("\n").slice(-LAST_LINES).join("\n"));
203
296
  return {
204
297
  ms,
205
298
  stopped: last ? `The watch stopped. Its last lines:\n${last}` : "The watch stopped, with no output.",
206
299
  };
207
300
  }
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")) };
301
+ const running = processOf(folder);
302
+ if (running !== asked) {
303
+ asked = running;
304
+ round = 0;
305
+ touched = undefined;
306
+ }
307
+ const cycles = cyclesOf(folder);
308
+ if (state === "running" && touched === undefined) {
309
+ // A round starts once the cycle before it has closed.
310
+ if (!cycles.open) {
311
+ touchAgain(rounds[round] ?? []);
312
+ touched = { opened: cycles.opened, at: Date.now(), times: 1 };
313
+ }
314
+ } else if (touched !== undefined && cycles.opened > touched.opened) {
315
+ // Written before the count of the cycle that ended it: the cycle read is that one, or a later one.
316
+ if (round === rounds.length - 1) return { ms, cycle: cleaned(root, readText(join(folder, "cycle"))) };
317
+ round++;
318
+ touched = undefined;
319
+ continue;
320
+ } else if (touched !== undefined && Date.now() - touched.at >= resyncMs() * 2 ** (touched.times - 1)) {
321
+ if (touched.times === SYNC_TOUCHES) {
322
+ const stopped = `The watch opens no cycle when the date of its watch.sync, ${gate.watch.sync}, changes: give it a file the watch rebuilds for, such as a source file it reads.`;
323
+ return { ms, stopped };
324
+ }
325
+ touchAgain(rounds[round] ?? []);
326
+ touched = { ...touched, at: Date.now(), times: touched.times + 1 };
327
+ }
214
328
  if (ms >= limitMs) return { ms, timedOut: true };
215
329
  await sleep(POLL_MS);
216
330
  }
217
331
  }
218
332
 
219
333
  /**
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.
334
+ * The files the watch owes a cycle for: the ones of the stops it was out of time for, which no cycle is known to have
335
+ * read. Each such stop writes a list of its own, so two sessions never lose the files of each other.
336
+ */
337
+ function owedFiles(folder: string): { lists: string[]; files: string[] } {
338
+ const lists = readDir(join(folder, "owed")).map((name) => join(folder, "owed", name));
339
+ const files = lists.flatMap((list) => readText(list).split("\0").filter(Boolean));
340
+ return { lists, files: [...new Set(files)] };
341
+ }
342
+
343
+ function owe(folder: string, files: string[]): void {
344
+ mkdirSync(join(folder, "owed"), { recursive: true });
345
+ writeFileSync(join(folder, "owed", randomUUID()), files.join("\0"));
346
+ }
347
+
348
+ function readDir(folder: string): string[] {
349
+ try {
350
+ return readdirSync(folder);
351
+ } catch {
352
+ return [];
353
+ }
354
+ }
355
+
356
+ /**
357
+ * Judges a turn on a cycle of the watch of a gate that read the files of the turn the gate looks at: on its failed
358
+ * lines, or for a compared gate, on the lines it added to the report of the turn start. No such cycle in the time of
359
+ * the gate: out of time, neither green nor red, never judged on an older cycle. The watch then owes a cycle for these
360
+ * files, which the next stop it answers asks for with its own: a change it missed would otherwise stay unseen until
361
+ * the file changes again. Only a stop pays that debt, never the report of a turn start, which would make old a
362
+ * failure no turn was judged on. A watch that stopped fails, with the last lines it printed.
224
363
  */
225
364
  export async function judgeWatch(
226
365
  session: string,
@@ -229,24 +368,39 @@ export async function judgeWatch(
229
368
  files: string[],
230
369
  baseline: string | undefined,
231
370
  ): Promise<Outcome> {
232
- const settled = await settle(session, root, gate, files, gate.timeoutSeconds * 1000);
371
+ const folder = folderOf(root, gate);
372
+ const owed = owedFiles(folder);
373
+ const asked = [...new Set([...files, ...owed.files])];
374
+ const settled = await settle(session, root, gate, asked, gate.timeoutSeconds * 1000);
233
375
  const { name } = gate;
234
376
  const { ms } = settled;
235
377
  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.`;
378
+ if (!("cycle" in settled)) {
379
+ owe(folder, files);
380
+ const output = `The watch opened no cycle for the turn within ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
238
381
  return { name, ok: false, ms, output, report: undefined, timedOut: true };
239
382
  }
240
- const { cycle } = settled;
383
+ // Paid, less what a stop out of time meanwhile added: only the lists this stop asked for.
384
+ for (const list of owed.lists) rmSync(list, { force: true });
385
+ const judged = judgeCycle(gate, settled.cycle, baseline, asked);
386
+ return { name, ms, ...judged, report: judged.ok ? settled.cycle : undefined };
387
+ }
388
+
389
+ /** The verdict of a cycle: its failed lines, or for a compared gate, the lines it added to the report of the turn start. */
390
+ function judgeCycle(
391
+ gate: WatchedGate,
392
+ cycle: string,
393
+ baseline: string | undefined,
394
+ files: string[],
395
+ ): { ok: boolean; output: string } {
241
396
  const fails = new RegExp(gate.watch.failed ?? "(?!)");
242
- const judged = isCompared(gate)
397
+ return isCompared(gate)
243
398
  ? addedLines(gate, cycle, baseline, files)
244
399
  : { ok: !cycle.split("\n").some((line) => fails.test(line)), output: cycle };
245
- return { name, ms, ...judged, report: judged.ok ? cycle : undefined };
246
400
  }
247
401
 
248
402
  /**
249
- * The report a compared watch gives the turn start: its last cycle, once it settles in the time a prompt can wait.
403
+ * The report a compared watch gives the turn start: a cycle it opens once asked, in the time a prompt can wait.
250
404
  * Nothing when it does not, and the turn then counts nothing as new.
251
405
  */
252
406
  export async function watchReport(session: string, root: string, gate: WatchedGate): Promise<string | undefined> {
@@ -269,38 +423,67 @@ export function endSession(session: string): void {
269
423
  function stop(folder: string): void {
270
424
  if (stateOf(folder) !== "running") return;
271
425
  try {
272
- process.kill(-Number(readFileSync(join(folder, "pid"), "utf8")), "SIGTERM");
426
+ process.kill(-Number(processOf(folder)), "SIGTERM");
273
427
  } catch {}
274
428
  }
275
429
 
276
430
  /**
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.
431
+ * The supervisor of a watch, which this module runs as when the engine starts one: it runs the watch and stops it
432
+ * with every process it started once its repo has had no prompt nor stop for the idle delay. Started detached, it
433
+ * leads a process group of its own, so stopping the group stops the watch and the tools under it. It counts the
434
+ * cycles of the watch as it prints them, and keeps only the lines a hook reads: a watch prints thousands of lines per
435
+ * cycle for as long as a session lasts, which no hook could read again at each look.
281
436
  */
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, "");
437
+ function supervise(folder: string, idle: number, cycle: { start: string; end: string }, command: string[]): void {
438
+ const [file = "", ...args] = command;
439
+ const opens = new RegExp(cycle.start);
440
+ const closes = new RegExp(cycle.end);
287
441
  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, "");
442
+ // The start of the watch opens the first cycle, and lines after the one that closes a cycle still belong to it. A
443
+ // line that opens a cycle while one is open belongs to that one: Angular says it rebuilds as it starts to, and
444
+ // again once it has, and counting both would end a cycle before its first line.
445
+ let opened = 0;
446
+ let open = true;
447
+ // The lines of the cycle in progress, less the ones that say it opened, which tell the agent nothing.
448
+ let lines: string[] = [];
449
+ // What a watch that stopped leaves the agent.
450
+ const last: string[] = [];
451
+ const count = () => writeWhole(join(folder, "cycles"), `${opened} ${open ? "open" : "closed"}`);
452
+ const read = (line: string) => {
453
+ last.push(line);
454
+ if (last.length > LAST_LINES) last.shift();
455
+ if (closes.test(line)) {
456
+ if (open) {
457
+ open = false;
458
+ count();
459
+ }
460
+ } else if (!open && opens.test(line)) {
461
+ // Nothing is printed in a cycle any more once the next one has opened: its lines are whole, and written before
462
+ // the count that tells a hook of them.
463
+ writeWhole(join(folder, "cycle"), lines.join("\n"));
464
+ lines = [];
465
+ opened++;
466
+ open = true;
467
+ count();
468
+ }
469
+ if (!opens.test(line)) lines.push(line);
470
+ };
471
+ const end = (code: number) => {
472
+ writeWhole(join(folder, "last"), last.join("\n"));
473
+ process.exit(code);
292
474
  };
293
- createInterface({ input: watch.stdout }).on("line", forward);
294
- createInterface({ input: watch.stderr }).on("line", forward);
475
+ count();
476
+ createInterface({ input: watch.stdout }).on("line", read);
477
+ createInterface({ input: watch.stderr }).on("line", read);
295
478
  watch.on("error", (error) => {
296
- console.log(error.message);
297
- process.exit(1);
479
+ last.push(error.message);
480
+ end(1);
298
481
  });
299
- watch.on("close", (code) => process.exit(code ?? 1));
482
+ watch.on("close", (code) => end(code ?? 1));
300
483
  setInterval(
301
484
  () => {
302
- if (Date.now() - changedAt(activity) < idle) return;
303
- writeFileSync(join(dirname(activity), "idle"), "");
485
+ if (Date.now() - changedAt(join(folder, "activity")) < idle) return;
486
+ writeFileSync(join(folder, "idle"), "");
304
487
  process.kill(-process.pid, "SIGTERM");
305
488
  },
306
489
  Math.min(idle / 4, 10_000),
@@ -308,6 +491,6 @@ function supervise(activity: string, idle: number, cycleStart: string, file: str
308
491
  }
309
492
 
310
493
  if (import.meta.main) {
311
- const [activity = "", idle = "", cycleStart = "", file = "", ...args] = process.argv.slice(2);
312
- supervise(activity, Number(idle), cycleStart, file, args);
494
+ const [folder = "", idle = "", start = "", end = "", ...command] = process.argv.slice(2);
495
+ supervise(folder, Number(idle), { start, end }, command);
313
496
  }