@tayomi/deterministic-gates 0.6.1 → 0.7.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.
@@ -1,17 +1,17 @@
1
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";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync, } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
  import { createInterface } from "node:readline";
7
7
  import { setTimeout as sleep } from "node:timers/promises";
8
8
  import { isCompared } from "./config.js";
9
9
  import { addedLines, cleaned, commandOf, ENGINE_VERSION, toolEnv } 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;
10
+ import { listFiles } from "./snapshot.js";
11
+ // A watch that has not opened a cycle this long after the engine touched its sync file is touched again: it may look
12
+ // for changes only once its first cycle is over, as Angular and tsc do, and never see a touch made before. The wait
13
+ // changes no verdict, which only ever comes from a cycle the watch opened after a touch.
14
+ const RESYNC_MS = 1000;
15
15
  const POLL_MS = 100;
16
16
  // What a watch that stopped leaves the agent: enough to see the error, not the whole history of the session.
17
17
  const LAST_LINES = 20;
@@ -52,25 +52,49 @@ function register(folder, session) {
52
52
  mkdirSync(join(folder, "sessions"), { recursive: true });
53
53
  writeFileSync(sessionFile(folder, session), "");
54
54
  }
55
- /** Whether the watch runs, has stopped on its own, was stopped for idleness, or was never started. */
56
- function stateOf(folder) {
57
- let pid;
55
+ /** The process of the watch, as the engine recorded it when it started it, or nothing when it never did. */
56
+ function processOf(folder) {
58
57
  try {
59
- pid = Number(readFileSync(join(folder, "pid"), "utf8"));
58
+ return readFileSync(join(folder, "pid"), "utf8");
60
59
  }
61
60
  catch {
62
- return "absent";
61
+ return undefined;
63
62
  }
63
+ }
64
+ /** Whether the watch runs, has stopped on its own, was stopped by the engine, or was never started. */
65
+ function stateOf(folder) {
66
+ const recorded = processOf(folder);
67
+ if (recorded === undefined)
68
+ return "absent";
64
69
  try {
65
- if (!pid)
70
+ if (!Number(recorded))
66
71
  return "stopped";
67
- process.kill(pid, 0);
72
+ process.kill(Number(recorded), 0);
68
73
  return "running";
69
74
  }
70
75
  catch {
71
76
  return existsSync(join(folder, "idle")) ? "idle" : "stopped";
72
77
  }
73
78
  }
79
+ // Two hooks at once, such as two sessions starting, start one watch: only the one that holds the lock does.
80
+ function lockStart(folder) {
81
+ const lock = join(folder, "starting");
82
+ // Only a lock that is there and old is taken over: removing one on the word of a look that found none would remove
83
+ // the lock another hook has just taken, and both would start a watch.
84
+ const taken = changedAt(lock);
85
+ if (taken && Date.now() - taken >= STALE_START_MS)
86
+ rmSync(lock, { force: true });
87
+ try {
88
+ closeSync(openSync(lock, "wx"));
89
+ return true;
90
+ }
91
+ catch {
92
+ return false;
93
+ }
94
+ }
95
+ function unlockStart(folder) {
96
+ rmSync(join(folder, "starting"), { force: true });
97
+ }
74
98
  /**
75
99
  * Starts the watch of a gate in the background, unless it already runs, and records that the session uses it: it
76
100
  * outlives the hook that starts it, until no session uses it.
@@ -81,40 +105,36 @@ export function startWatch(session, root, gate) {
81
105
  touch(folder);
82
106
  // The sessions of a watch that starts again still use it.
83
107
  register(folder, session);
84
- if (stateOf(folder) === "running")
85
- return;
86
- // Two hooks at once, such as two sessions starting, start one watch: the other only registers its session.
87
- const lock = join(folder, "starting");
88
- if (Date.now() - changedAt(lock) >= STALE_START_MS)
89
- rmSync(lock, { force: true });
90
- try {
91
- closeSync(openSync(lock, "wx"));
92
- }
93
- catch {
108
+ if (stateOf(folder) === "running" || !lockStart(folder))
94
109
  return;
95
- }
96
110
  try {
97
111
  // Another hook may have started it between the look above and the lock.
98
112
  if (stateOf(folder) !== "running")
99
113
  launch(folder, root, gate.watch);
100
114
  }
101
115
  finally {
102
- rmSync(lock, { force: true });
116
+ unlockStart(folder);
103
117
  }
104
118
  }
119
+ /** The files of the repo the watch lists only as it starts, one per line. */
120
+ function frozenFiles(root, watch) {
121
+ if (watch.frozen === undefined)
122
+ return "";
123
+ const frozen = new RegExp(watch.frozen);
124
+ return listFiles(root)
125
+ .filter((file) => frozen.test(file))
126
+ .join("\n");
127
+ }
105
128
  function launch(folder, root, watch) {
106
129
  rmSync(join(folder, "idle"), { force: true });
130
+ // The first cycle of a watch reads every file there is: it owes a cycle for none.
131
+ rmSync(join(folder, "owed"), { recursive: true, force: true });
107
132
  const [name = "", ...args] = watch.run;
108
133
  const command = commandOf(root, name);
109
134
  const supervisor = commandOf(root, "{engine}/src/core/watch.ts");
110
- const watched = [
111
- join(folder, "activity"),
112
- String(idleMs()),
113
- watch.cycleStart,
114
- command.file,
115
- ...command.args,
116
- ...args,
117
- ];
135
+ const watched = [join(folder, "activity"), String(idleMs()), command.file, ...command.args, ...args];
136
+ // Listed before the watch starts: a file created in between counts as one it may not know, never the other way.
137
+ writeFileSync(join(folder, "frozen"), frozenFiles(root, watch));
118
138
  const log = openSync(join(folder, "output.log"), "w");
119
139
  const child = spawn(supervisor.file, [...supervisor.args, ...watched], {
120
140
  cwd: root,
@@ -127,16 +147,42 @@ function launch(folder, root, watch) {
127
147
  child.unref();
128
148
  writeFileSync(join(folder, "pid"), String(child.pid ?? ""));
129
149
  }
130
- /** The last cycle of a watch: its lines since it opened, and whether it is still open. */
131
- function lastCycle(printed, watch) {
150
+ function cyclesOf(printed, watch) {
132
151
  const lines = printed.split("\n");
133
152
  if (lines.at(-1) === "")
134
153
  lines.pop();
135
154
  const opens = new RegExp(watch.cycleStart);
136
155
  const closes = new RegExp(watch.cycleEnd);
137
- // The start of the watch opens the first cycle, and lines after the one that closes it still belong to it.
138
- const cycle = lines.slice(lines.findLastIndex((line) => opens.test(line)) + 1);
139
- return { open: !cycle.some((line) => closes.test(line)), lines: cycle };
156
+ // The start of the watch opens the first cycle, and lines after the one that closes a cycle still belong to it. A
157
+ // line that opens a cycle while one is open belongs to that one: Angular says it rebuilds as it starts to, and
158
+ // again once it has, and counting both would end a cycle before its first line.
159
+ const starts = [];
160
+ let open = true;
161
+ lines.forEach((line, at) => {
162
+ if (closes.test(line))
163
+ open = false;
164
+ else if (!open && opens.test(line)) {
165
+ starts.push(at);
166
+ open = true;
167
+ }
168
+ });
169
+ const last = starts.at(-1);
170
+ return {
171
+ opened: starts.length,
172
+ open,
173
+ // Less the lines that say it opened, which tell the agent nothing.
174
+ complete: last === undefined ? [] : lines.slice((starts.at(-2) ?? -1) + 1, last).filter((line) => !opens.test(line)),
175
+ };
176
+ }
177
+ /** Gives the files their date again, as a change of nothing else, for a watch that looks at their date. */
178
+ function touchAgain(paths) {
179
+ const now = new Date();
180
+ for (const path of paths) {
181
+ try {
182
+ utimesSync(path, now, now);
183
+ }
184
+ catch { }
185
+ }
140
186
  }
141
187
  function changedAt(path) {
142
188
  try {
@@ -155,23 +201,70 @@ function readLog(log) {
155
201
  }
156
202
  }
157
203
  /**
158
- * 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
159
- * one of the files. A watch no hook started, as when the hooks were installed mid-session, starts now, and so does one
160
- * stopped for idleness, as during a turn longer than the idle delay: it is not to blame.
204
+ * Starts the watch again when a file it lists only as it starts was created or deleted since: its first cycle then
205
+ * reads every file there is. Only one hook does, and only the watch it looked at: another session may be here too.
206
+ */
207
+ async function restartOnFrozenChange(session, root, gate, folder) {
208
+ if (gate.watch.frozen === undefined || stateOf(folder) !== "running")
209
+ return;
210
+ if (readLog(join(folder, "frozen")) === frozenFiles(root, gate.watch) || !lockStart(folder))
211
+ return;
212
+ try {
213
+ if (stateOf(folder) !== "running" || readLog(join(folder, "frozen")) === frozenFiles(root, gate.watch))
214
+ return;
215
+ // Stopped by the engine, so that another session waiting on the watch does not take it for one that broke.
216
+ writeFileSync(join(folder, "idle"), "");
217
+ stop(folder);
218
+ for (let waited = 0; stateOf(folder) === "running" && waited < STALE_START_MS / 2; waited += POLL_MS)
219
+ await sleep(POLL_MS);
220
+ if (stateOf(folder) !== "running")
221
+ launch(folder, root, gate.watch);
222
+ }
223
+ finally {
224
+ unlockStart(folder);
225
+ }
226
+ register(folder, session);
227
+ }
228
+ /**
229
+ * 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
230
+ * watch takes to see a change. Each round touches files, then waits for the watch to open a cycle after the touch,
231
+ * which only a watch that saw the touch does:
232
+ * 1. the sync file, which proves the watch now looks for changes;
233
+ * 2. the files of the turn, so that a change it missed reaches it, then the sync file;
234
+ * 3. the sync file, once that cycle has closed: the cycle of round 2 may have been on its way before the touch, and
235
+ * this one opens after every change the watch then had waiting;
236
+ * 4. the sync file once more, since the cycle it opens ends the one of round 3, the one that judges, whose last lines
237
+ * may come after the line that closes it.
238
+ * A watch no hook started, as when the hooks were installed mid-session, starts now, and so does one the engine
239
+ * stopped, for idleness or to start it again: it is not to blame. One another session starts again meanwhile is asked
240
+ * again from the first round.
161
241
  */
162
242
  async function settle(session, root, gate, files, limitMs) {
163
243
  const started = performance.now();
164
244
  const folder = folderOf(root, gate);
165
245
  const log = join(folder, "output.log");
166
- if (["absent", "idle"].includes(stateOf(folder)))
167
- startWatch(session, root, gate);
168
- touch(folder);
246
+ const sync = join(root, gate.watch.sync);
247
+ if (!existsSync(sync)) {
248
+ const stopped = `The watch cannot be asked for a cycle: its watch.sync, ${gate.watch.sync}, does not exist.`;
249
+ return { ms: 0, stopped };
250
+ }
251
+ await restartOnFrozenChange(session, root, gate, folder);
252
+ const turn = files.map((file) => join(root, file)).filter((path) => existsSync(path));
253
+ const rounds = [[sync], ...(turn.length ? [[...turn, sync]] : []), [sync], [sync]];
254
+ let asked;
255
+ let round = 0;
256
+ // The cycles the watch had opened when the round touched its files, and when it did: none before its first touch.
257
+ let touched;
169
258
  for (;;) {
259
+ const state = stateOf(folder);
260
+ if (state === "absent" || state === "idle")
261
+ startWatch(session, root, gate);
262
+ // Waiting on the watch is using it: it does not stop for idleness under a stop that waits.
263
+ touch(folder);
170
264
  // Read once the watch is known stopped, so its last lines are in.
171
- const stopped = stateOf(folder) === "stopped";
172
265
  const printed = readLog(log);
173
266
  const ms = performance.now() - started;
174
- if (stopped) {
267
+ if (state === "stopped") {
175
268
  const last = cleaned(root, printed
176
269
  .split("\n")
177
270
  .slice(-LAST_LINES - 1)
@@ -181,42 +274,94 @@ async function settle(session, root, gate, files, limitMs) {
181
274
  stopped: last ? `The watch stopped. Its last lines:\n${last}` : "The watch stopped, with no output.",
182
275
  };
183
276
  }
184
- // A cycle that started after the last change read it, however long the watch took to see it.
185
- const changed = Math.max(0, ...files.map((file) => changedAt(join(root, file))));
186
- const seen = changedAt(join(folder, "cycle")) >= changed || Date.now() - changed >= UNSEEN_MS;
187
- const cycle = lastCycle(printed, gate.watch);
188
- if (seen && !cycle.open && Date.now() - changedAt(log) >= QUIET_MS)
189
- return { ms, cycle: cleaned(root, cycle.lines.join("\n")) };
277
+ const running = processOf(folder);
278
+ if (running !== asked) {
279
+ asked = running;
280
+ round = 0;
281
+ touched = undefined;
282
+ }
283
+ const cycles = cyclesOf(printed, gate.watch);
284
+ if (state === "running" && touched === undefined) {
285
+ // A round starts once the cycle before it has closed.
286
+ if (!cycles.open) {
287
+ touchAgain(rounds[round] ?? []);
288
+ touched = { opened: cycles.opened, at: Date.now() };
289
+ }
290
+ }
291
+ else if (touched !== undefined && cycles.opened > touched.opened) {
292
+ if (round === rounds.length - 1)
293
+ return { ms, cycle: cleaned(root, cycles.complete.join("\n")) };
294
+ round++;
295
+ touched = undefined;
296
+ continue;
297
+ }
298
+ else if (touched !== undefined && Date.now() - touched.at >= RESYNC_MS) {
299
+ touchAgain(rounds[round] ?? []);
300
+ touched.at = Date.now();
301
+ }
190
302
  if (ms >= limitMs)
191
303
  return { ms, timedOut: true };
192
304
  await sleep(POLL_MS);
193
305
  }
194
306
  }
195
307
  /**
196
- * 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
197
- * gate looks at: on its failed lines, or for a compared gate, on the lines it added to the report of the turn start.
198
- * Not settled in the time of the gate: out of time, neither green nor red. A watch that stopped fails, with the last
199
- * lines it printed.
308
+ * 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
309
+ * read. Each such stop writes a list of its own, so two sessions never lose the files of each other.
310
+ */
311
+ function owedFiles(folder) {
312
+ const lists = readDir(join(folder, "owed")).map((name) => join(folder, "owed", name));
313
+ const files = lists.flatMap((list) => readLog(list).split("\0").filter(Boolean));
314
+ return { lists, files: [...new Set(files)] };
315
+ }
316
+ function owe(folder, files) {
317
+ mkdirSync(join(folder, "owed"), { recursive: true });
318
+ writeFileSync(join(folder, "owed", randomUUID()), files.join("\0"));
319
+ }
320
+ function readDir(folder) {
321
+ try {
322
+ return readdirSync(folder);
323
+ }
324
+ catch {
325
+ return [];
326
+ }
327
+ }
328
+ /**
329
+ * 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
330
+ * 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
331
+ * the gate: out of time, neither green nor red, never judged on an older cycle. The watch then owes a cycle for these
332
+ * files, which the next stop it answers asks for with its own: a change it missed would otherwise stay unseen until
333
+ * the file changes again. Only a stop pays that debt, never the report of a turn start, which would make old a
334
+ * failure no turn was judged on. A watch that stopped fails, with the last lines it printed.
200
335
  */
201
336
  export async function judgeWatch(session, root, gate, files, baseline) {
202
- const settled = await settle(session, root, gate, files, gate.timeoutSeconds * 1000);
337
+ const folder = folderOf(root, gate);
338
+ const owed = owedFiles(folder);
339
+ const asked = [...new Set([...files, ...owed.files])];
340
+ const settled = await settle(session, root, gate, asked, gate.timeoutSeconds * 1000);
203
341
  const { name } = gate;
204
342
  const { ms } = settled;
205
343
  if ("stopped" in settled)
206
344
  return { name, ok: false, ms, output: settled.stopped, report: undefined };
207
- if ("timedOut" in settled) {
208
- const output = `The watch did not settle within ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
345
+ if (!("cycle" in settled)) {
346
+ owe(folder, files);
347
+ 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.`;
209
348
  return { name, ok: false, ms, output, report: undefined, timedOut: true };
210
349
  }
211
- const { cycle } = settled;
350
+ // Paid, less what a stop out of time meanwhile added: only the lists this stop asked for.
351
+ for (const list of owed.lists)
352
+ rmSync(list, { force: true });
353
+ const judged = judgeCycle(gate, settled.cycle, baseline, asked);
354
+ return { name, ms, ...judged, report: judged.ok ? settled.cycle : undefined };
355
+ }
356
+ /** The verdict of a cycle: its failed lines, or for a compared gate, the lines it added to the report of the turn start. */
357
+ function judgeCycle(gate, cycle, baseline, files) {
212
358
  const fails = new RegExp(gate.watch.failed ?? "(?!)");
213
- const judged = isCompared(gate)
359
+ return isCompared(gate)
214
360
  ? addedLines(gate, cycle, baseline, files)
215
361
  : { ok: !cycle.split("\n").some((line) => fails.test(line)), output: cycle };
216
- return { name, ms, ...judged, report: judged.ok ? cycle : undefined };
217
362
  }
218
363
  /**
219
- * The report a compared watch gives the turn start: its last cycle, once it settles in the time a prompt can wait.
364
+ * The report a compared watch gives the turn start: a cycle it opens once asked, in the time a prompt can wait.
220
365
  * Nothing when it does not, and the turn then counts nothing as new.
221
366
  */
222
367
  export async function watchReport(session, root, gate) {
@@ -241,7 +386,7 @@ function stop(folder) {
241
386
  if (stateOf(folder) !== "running")
242
387
  return;
243
388
  try {
244
- process.kill(-Number(readFileSync(join(folder, "pid"), "utf8")), "SIGTERM");
389
+ process.kill(-Number(processOf(folder)), "SIGTERM");
245
390
  }
246
391
  catch { }
247
392
  }
@@ -251,18 +396,9 @@ function stop(folder) {
251
396
  * the idle delay. Started detached, it leads a process group of its own, so stopping the group stops the watch and
252
397
  * the tools under it.
253
398
  */
254
- function supervise(activity, idle, cycleStart, file, args) {
255
- // The time the last cycle started, which the stop compares with the changes of the turn. The start opens the first.
256
- const cycle = join(dirname(activity), "cycle");
257
- const opens = new RegExp(cycleStart);
258
- writeFileSync(cycle, "");
399
+ function supervise(activity, idle, file, args) {
259
400
  const watch = spawn(file, args, { stdio: ["ignore", "pipe", "pipe"] });
260
- const forward = (line) => {
261
- // Printed before the time is kept, so a stop that sees the time also finds the cycle in the output.
262
- console.log(line);
263
- if (opens.test(line))
264
- writeFileSync(cycle, "");
265
- };
401
+ const forward = (line) => console.log(line);
266
402
  createInterface({ input: watch.stdout }).on("line", forward);
267
403
  createInterface({ input: watch.stderr }).on("line", forward);
268
404
  watch.on("error", (error) => {
@@ -278,6 +414,6 @@ function supervise(activity, idle, cycleStart, file, args) {
278
414
  }, Math.min(idle / 4, 10_000));
279
415
  }
280
416
  if (import.meta.main) {
281
- const [activity = "", idle = "", cycleStart = "", file = "", ...args] = process.argv.slice(2);
282
- supervise(activity, Number(idle), cycleStart, file, args);
417
+ const [activity = "", idle = "", file = "", ...args] = process.argv.slice(2);
418
+ supervise(activity, Number(idle), file, args);
283
419
  }
@@ -0,0 +1,85 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { createRequire } from "node:module";
10
+ import { join, relative } from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+ import { configOf, nothingChecked } from "./tsc.js";
13
+ import { strictErrorLines } from "./type-errors.js";
14
+ /** A code as Angular prints it: its own codes are negative, -99 then their number, as -998001 for NG8001. */
15
+ function codeOf(code) {
16
+ return code < 0 ? `NG${String(-code).slice(2)}` : `TS${code}`;
17
+ }
18
+ /** The errors of the templates, each on one line, as the gate compares them. */
19
+ export function templateErrors(root, diagnostics) {
20
+ return strictErrorLines(diagnostics.map(({ file, start = 0, code, messageText }) => {
21
+ const message = typeof messageText === "string" ? messageText : messageText.messageText;
22
+ if (file === undefined)
23
+ return message;
24
+ const line = file.text.slice(0, start).split("\n").length - 1;
25
+ return {
26
+ file: relative(root, file.fileName),
27
+ code: codeOf(code),
28
+ source: file.text.split("\n")[line] ?? "",
29
+ message: message.split("\n")[0] ?? "",
30
+ };
31
+ }));
32
+ }
33
+ /** The options forced on top of the project's: strict templates, and each --option the gate gives. */
34
+ function forced(args) {
35
+ const options = { strictTemplates: true };
36
+ for (const arg of args)
37
+ if (arg.startsWith("--") && arg !== "--project")
38
+ options[arg.slice(2)] = true;
39
+ return options;
40
+ }
41
+ /**
42
+ * The Angular compiler of the repo, once it is known to check files with the API this helper calls: otherwise, why
43
+ * not. That API is not a public one of Angular, so a version that changed it refuses the gate, never passes it green.
44
+ */
45
+ export async function compilerOf(root, args) {
46
+ const nothing = nothingChecked(root, args);
47
+ if (nothing)
48
+ return { refused: nothing };
49
+ const required = createRequire(join(root, "package.json"));
50
+ const ng = await import(__rewriteRelativeImportExtension(pathToFileURL(required.resolve("@angular/compiler-cli")).href));
51
+ const { version } = required("@angular/compiler-cli/package.json");
52
+ const program = ng.NgtscProgram?.prototype;
53
+ const missing = [
54
+ ["NgtscProgram", ng.NgtscProgram],
55
+ ["NgtscProgram.loadNgStructureAsync", program?.loadNgStructureAsync],
56
+ ["NgtscProgram.getNgSemanticDiagnostics", program?.getNgSemanticDiagnostics],
57
+ ["readConfiguration", ng.readConfiguration],
58
+ ["createCompilerHost", ng.createCompilerHost],
59
+ ].find(([, found]) => typeof found !== "function")?.[0];
60
+ if (missing !== undefined)
61
+ return {
62
+ refused: `The API of @angular/compiler-cli ${version} is not the one this gate knows: it has no ${missing}. Update deterministic-gates.`,
63
+ };
64
+ return {
65
+ compiler: {
66
+ async diagnostics() {
67
+ const config = ng.readConfiguration(configOf(root, args));
68
+ const options = { ...config.options, ...forced(args) };
69
+ const program = new ng.NgtscProgram(config.rootNames, options, ng.createCompilerHost({ options }));
70
+ await program.loadNgStructureAsync();
71
+ return program.getNgSemanticDiagnostics();
72
+ },
73
+ },
74
+ };
75
+ }
76
+ async function main(root, args) {
77
+ const found = await compilerOf(root, args);
78
+ if ("refused" in found) {
79
+ console.log(found.refused);
80
+ process.exit(1);
81
+ }
82
+ console.log(templateErrors(root, await found.compiler.diagnostics()).join("\n"));
83
+ }
84
+ if (import.meta.main)
85
+ await main(process.cwd(), process.argv.slice(2));
@@ -7,7 +7,7 @@ import { commandOf } from "../core/run.js";
7
7
  // project, checks no file, and tsc says nothing of it: the gate would be green without checking anything, so it is
8
8
  // refused, with the tsconfigs it references.
9
9
  /** The tsconfig tsc reads: the one of -p or --project, a folder meaning its tsconfig.json, or the one of the root. */
10
- function configOf(root, args) {
10
+ export function configOf(root, args) {
11
11
  const at = args.findIndex((arg) => arg === "-p" || arg === "--project");
12
12
  const given = at === -1 ? undefined : args[at + 1];
13
13
  if (given === undefined)
@@ -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.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",
@@ -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) }),