@tayomi/deterministic-gates 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,7 +9,7 @@
9
9
  "name": "deterministic-gates",
10
10
  "source": "./",
11
11
  "description": "Gates that run on what each turn changed and send the agent back until they pass.",
12
- "version": "0.7.0"
12
+ "version": "0.8.1"
13
13
  }
14
14
  ]
15
15
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/claude-code-plugin-manifest.json",
3
3
  "name": "deterministic-gates",
4
- "version": "0.7.0",
4
+ "version": "0.8.1",
5
5
  "description": "Deterministic backpressure for coding agents: gates that run on what each turn changed and send the agent back until they pass.",
6
6
  "author": {
7
7
  "name": "Pierre Moati",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "deterministic-gates",
3
- "version": "0.7.0",
3
+ "version": "0.8.1",
4
4
  "description": "Deterministic backpressure for coding agents: gates that run on what each turn changed and send the agent back until they pass.",
5
5
  "author": {
6
6
  "name": "Pierre Moati",
@@ -3,7 +3,7 @@
3
3
  "description": "Gates for an Angular project tested with Vitest through the Angular builder, ng test. Each tool comes from the repo's node_modules, so its version is the one the lockfile pins.",
4
4
  "gates": [
5
5
  {
6
- "description": "Runs the unit tests in a watch kept warm between turns, since ng test builds the whole application before a single test runs. At the stop, it waits for the watch to finish with the turn's changes, then fails on a build that does not compile, and on every red spec, the ones the change did not rerun included. The whole check runs ng test once, without a watch. The watch is asked for a cycle through tsconfig.spec.json, and starts again when a spec is created or deleted, since ng test lists its specs once.",
6
+ "description": "Runs the unit tests in a watch kept warm between turns, since ng test builds the whole application before a single test runs. At the stop, it waits for the watch to finish with the turn's changes, then fails on a build that does not compile, and on every red spec, the ones the change did not rerun included. The whole check runs ng test once, without a watch. The watch is asked for a cycle through tsconfig.spec.json, and starts again when a spec is created or deleted, since ng test lists its specs once. Angular 21 does not rebuild for a tsconfig: give its watch.sync a spec.",
7
7
  "requires": [
8
8
  {
9
9
  "tool": "@angular/cli",
@@ -34,7 +34,7 @@
34
34
  }
35
35
  },
36
36
  {
37
- "description": "Builds the application in a watch kept warm between turns, which type-checks every template, the ones of a component no spec reaches included: tsc alone never reads a template. At the stop, it fails on a build that does not compile, with the file and line of each error. Built without optimization into node_modules/.cache, so the dist of the project stays as it is. The whole check builds once, without a watch. The watch is asked for a cycle through tsconfig.app.json.",
37
+ "description": "Builds the application in a watch kept warm between turns, which type-checks every template, the ones of a component no spec reaches included: tsc alone never reads a template. At the stop, it fails on a build that does not compile, with the file and line of each error. Built without optimization into node_modules/.cache, so the dist of the project stays as it is. The whole check builds once, without a watch. The watch is asked for a cycle through src/main.ts.",
38
38
  "requires": [
39
39
  {
40
40
  "tool": "@angular/cli",
@@ -61,7 +61,7 @@
61
61
  "cycleStart": "Changes detected\\. Rebuilding",
62
62
  "cycleEnd": "Application bundle generation (complete|failed)",
63
63
  "failed": "Application bundle generation failed",
64
- "sync": "tsconfig.app.json"
64
+ "sync": "src/main.ts"
65
65
  }
66
66
  }
67
67
  },
@@ -85,7 +85,7 @@
85
85
  }
86
86
  },
87
87
  {
88
- "description": "Fails on the strict template errors the turn added, never on the ones already there, for a project that turned strictTemplates off: it compiles the templates with strictTemplates and strictNullChecks forced on top of the project's options, through the API of the Angular compiler, so a binding that may be null is reported even when the TypeScript has strict errors of its own. The build gate checks the templates with the project's own options. An error is not new when moved, or reported with the same message in another file the turn did not change, or on a changed line as long as its file has no more errors of its code than at the turn start. It checks tsconfig.app.json: give its -p the tsconfig of the application.",
88
+ "description": "Fails on the strict errors the turn added, in the TypeScript and in the templates, never on the ones already there, for a project that turned strict options off: it compiles the application through the API of the Angular compiler, with strictTemplates and each option of TypeScript its run lists forced on top of the project's own. Add or remove an option there, written as tsc takes it: one TypeScript does not know is refused. On an Angular project, it stands for the no-new-strict-errors of the TypeScript catalog, which reads no template. The compiler stays between turns and checks again when asked, reusing what it compiled: it is asked through its tsconfig, the one of -p. The build gate checks with the project's own options. An error is not new when moved, or reported with the same message in another file the turn did not change, or on a changed line as long as its file has no more errors of its code than at the turn start. It checks tsconfig.app.json: give its -p, and its watch.sync, the tsconfig of the application.",
89
89
  "requires": [
90
90
  {
91
91
  "tool": "@angular/compiler-cli",
@@ -97,12 +97,31 @@
97
97
  }
98
98
  ],
99
99
  "gate": {
100
- "name": "no-new-strict-template-errors",
100
+ "name": "no-new-strict-errors",
101
101
  "severity": "error",
102
102
  "files": "(\\.(ts|html)|(^|/)tsconfig[^/]*\\.json)$",
103
- "run": ["{engine}/src/helpers/template-errors.ts", "-p", "tsconfig.app.json", "--strictNullChecks"],
103
+ "run": [
104
+ "{engine}/src/helpers/angular-errors.ts",
105
+ "-p",
106
+ "tsconfig.app.json",
107
+ "--strictNullChecks",
108
+ "--strictPropertyInitialization"
109
+ ],
104
110
  "compare": "turn-start",
105
- "lineKey": "^((?<file>.+?): error (?:TS|NG)\\d+) at [^\\t]*"
111
+ "lineKey": "^((?<file>.+?): error (?:TS|NG)\\d+) at [^\\t]*",
112
+ "watch": {
113
+ "run": [
114
+ "{engine}/src/helpers/angular-errors.ts",
115
+ "--watch",
116
+ "-p",
117
+ "tsconfig.app.json",
118
+ "--strictNullChecks",
119
+ "--strictPropertyInitialization"
120
+ ],
121
+ "cycleStart": "^Type check started$",
122
+ "cycleEnd": "^Type check done$",
123
+ "sync": "tsconfig.app.json"
124
+ }
106
125
  }
107
126
  }
108
127
  ]
@@ -47,7 +47,7 @@ summary { cursor: pointer; color: var(--muted); }
47
47
  <p>Gates for an Angular project tested with Vitest through the Angular builder, ng test. Each tool comes from the repo's node_modules, so its version is the one the lockfile pins.</p>
48
48
  <article id="angular/tests">
49
49
  <h3><code>angular/tests</code></h3>
50
- <p>Runs the unit tests in a watch kept warm between turns, since ng test builds the whole application before a single test runs. At the stop, it waits for the watch to finish with the turn's changes, then fails on a build that does not compile, and on every red spec, the ones the change did not rerun included. The whole check runs ng test once, without a watch. The watch is asked for a cycle through tsconfig.spec.json, and starts again when a spec is created or deleted, since ng test lists its specs once.</p>
50
+ <p>Runs the unit tests in a watch kept warm between turns, since ng test builds the whole application before a single test runs. At the stop, it waits for the watch to finish with the turn's changes, then fails on a build that does not compile, and on every red spec, the ones the change did not rerun included. The whole check runs ng test once, without a watch. The watch is asked for a cycle through tsconfig.spec.json, and starts again when a spec is created or deleted, since ng test lists its specs once. Angular 21 does not rebuild for a tsconfig: give its watch.sync a spec.</p>
51
51
  <dl>
52
52
  <dt>Runs</dt><dd><code>@angular/cli test --watch=false</code></dd>
53
53
  <dt>When the turn changes</dt><dd><code>\.(ts|html|css)$</code></dd>
@@ -76,7 +76,7 @@ summary { cursor: pointer; color: var(--muted); }
76
76
  </article>
77
77
  <article id="angular/build">
78
78
  <h3><code>angular/build</code></h3>
79
- <p>Builds the application in a watch kept warm between turns, which type-checks every template, the ones of a component no spec reaches included: tsc alone never reads a template. At the stop, it fails on a build that does not compile, with the file and line of each error. Built without optimization into node_modules/.cache, so the dist of the project stays as it is. The whole check builds once, without a watch. The watch is asked for a cycle through tsconfig.app.json.</p>
79
+ <p>Builds the application in a watch kept warm between turns, which type-checks every template, the ones of a component no spec reaches included: tsc alone never reads a template. At the stop, it fails on a build that does not compile, with the file and line of each error. Built without optimization into node_modules/.cache, so the dist of the project stays as it is. The whole check builds once, without a watch. The watch is asked for a cycle through src/main.ts.</p>
80
80
  <dl>
81
81
  <dt>Runs</dt><dd><code>@angular/cli build --optimization=false --output-path=node_modules/.cache/gates/build</code></dd>
82
82
  <dt>When the turn changes</dt><dd><code>\.(ts|html|css|scss|sass|less)$</code></dd>
@@ -103,7 +103,7 @@ summary { cursor: pointer; color: var(--muted); }
103
103
  &quot;cycleStart&quot;: &quot;Changes detected\\. Rebuilding&quot;,
104
104
  &quot;cycleEnd&quot;: &quot;Application bundle generation (complete|failed)&quot;,
105
105
  &quot;failed&quot;: &quot;Application bundle generation failed&quot;,
106
- &quot;sync&quot;: &quot;tsconfig.app.json&quot;
106
+ &quot;sync&quot;: &quot;src/main.ts&quot;
107
107
  }
108
108
  }</code></pre></details>
109
109
  </article>
@@ -128,26 +128,40 @@ summary { cursor: pointer; color: var(--muted); }
128
128
  ]
129
129
  }</code></pre></details>
130
130
  </article>
131
- <article id="angular/no-new-strict-template-errors">
132
- <h3><code>angular/no-new-strict-template-errors</code></h3>
133
- <p>Fails on the strict template errors the turn added, never on the ones already there, for a project that turned strictTemplates off: it compiles the templates with strictTemplates and strictNullChecks forced on top of the project's options, through the API of the Angular compiler, so a binding that may be null is reported even when the TypeScript has strict errors of its own. The build gate checks the templates with the project's own options. An error is not new when moved, or reported with the same message in another file the turn did not change, or on a changed line as long as its file has no more errors of its code than at the turn start. It checks tsconfig.app.json: give its -p the tsconfig of the application.</p>
131
+ <article id="angular/no-new-strict-errors">
132
+ <h3><code>angular/no-new-strict-errors</code></h3>
133
+ <p>Fails on the strict errors the turn added, in the TypeScript and in the templates, never on the ones already there, for a project that turned strict options off: it compiles the application through the API of the Angular compiler, with strictTemplates and each option of TypeScript its run lists forced on top of the project's own. Add or remove an option there, written as tsc takes it: one TypeScript does not know is refused. On an Angular project, it stands for the no-new-strict-errors of the TypeScript catalog, which reads no template. The compiler stays between turns and checks again when asked, reusing what it compiled: it is asked through its tsconfig, the one of -p. The build gate checks with the project's own options. An error is not new when moved, or reported with the same message in another file the turn did not change, or on a changed line as long as its file has no more errors of its code than at the turn start. It checks tsconfig.app.json: give its -p, and its watch.sync, the tsconfig of the application.</p>
134
134
  <dl>
135
- <dt>Runs</dt><dd><code>{engine}/src/helpers/template-errors.ts -p tsconfig.app.json --strictNullChecks</code></dd>
135
+ <dt>Runs</dt><dd><code>{engine}/src/helpers/angular-errors.ts -p tsconfig.app.json --strictNullChecks --strictPropertyInitialization</code></dd>
136
136
  <dt>When the turn changes</dt><dd><code>(\.(ts|html)|(^|/)tsconfig[^/]*\.json)$</code></dd>
137
137
  <dt>Fails on</dt><dd>only the output lines the turn added</dd><dt>Requires</dt><dd><ul><li><code>@angular/compiler-cli</code>: npm install --save-dev @angular/compiler-cli</li><li><code>typescript</code>: npm install --save-dev typescript</li></ul></dd>
138
138
  </dl>
139
139
  <details><summary>Definition to copy into .gates.json</summary><pre><code>{
140
- &quot;name&quot;: &quot;no-new-strict-template-errors&quot;,
140
+ &quot;name&quot;: &quot;no-new-strict-errors&quot;,
141
141
  &quot;severity&quot;: &quot;error&quot;,
142
142
  &quot;files&quot;: &quot;(\\.(ts|html)|(^|/)tsconfig[^/]*\\.json)$&quot;,
143
143
  &quot;run&quot;: [
144
- &quot;{engine}/src/helpers/template-errors.ts&quot;,
144
+ &quot;{engine}/src/helpers/angular-errors.ts&quot;,
145
145
  &quot;-p&quot;,
146
146
  &quot;tsconfig.app.json&quot;,
147
- &quot;--strictNullChecks&quot;
147
+ &quot;--strictNullChecks&quot;,
148
+ &quot;--strictPropertyInitialization&quot;
148
149
  ],
149
150
  &quot;compare&quot;: &quot;turn-start&quot;,
150
- &quot;lineKey&quot;: &quot;^((?&lt;file&gt;.+?): error (?:TS|NG)\\d+) at [^\\t]*&quot;
151
+ &quot;lineKey&quot;: &quot;^((?&lt;file&gt;.+?): error (?:TS|NG)\\d+) at [^\\t]*&quot;,
152
+ &quot;watch&quot;: {
153
+ &quot;run&quot;: [
154
+ &quot;{engine}/src/helpers/angular-errors.ts&quot;,
155
+ &quot;--watch&quot;,
156
+ &quot;-p&quot;,
157
+ &quot;tsconfig.app.json&quot;,
158
+ &quot;--strictNullChecks&quot;,
159
+ &quot;--strictPropertyInitialization&quot;
160
+ ],
161
+ &quot;cycleStart&quot;: &quot;^Type check started$&quot;,
162
+ &quot;cycleEnd&quot;: &quot;^Type check done$&quot;,
163
+ &quot;sync&quot;: &quot;tsconfig.app.json&quot;
164
+ }
151
165
  }</code></pre></details>
152
166
  </article>
153
167
  </section>
@@ -1,17 +1,21 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
- import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync, } from "node:fs";
3
+ import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync, } from "node:fs";
4
4
  import { tmpdir } from "node:os";
5
- import { dirname, join } from "node:path";
5
+ import { 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
10
  import { listFiles } from "./snapshot.js";
11
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.
12
+ // for changes only once its first cycle is over, as Angular and tsc do, and never see a touch made before. Each wait
13
+ // is twice the one before, since a watch on a busy machine takes seconds to say it opens a cycle, and a touch too
14
+ // many is a cycle too many. The wait changes no verdict, which only ever comes from a cycle the watch opened after a
15
+ // touch. The tests of the engine shorten it.
14
16
  const RESYNC_MS = 1000;
17
+ // A watch that opens no cycle after this many touches, 31 s after the first, does not look at its sync file.
18
+ const SYNC_TOUCHES = 5;
15
19
  const POLL_MS = 100;
16
20
  // What a watch that stopped leaves the agent: enough to see the error, not the whole history of the session.
17
21
  const LAST_LINES = 20;
@@ -26,6 +30,9 @@ const IDLE_MS = 30 * 60 * 1000;
26
30
  function idleMs() {
27
31
  return Number(process.env.GATES_WATCH_IDLE_MS) || IDLE_MS;
28
32
  }
33
+ function resyncMs() {
34
+ return Number(process.env.GATES_WATCH_RESYNC_MS) || RESYNC_MS;
35
+ }
29
36
  /** Records a prompt or a stop on the repo of a watch, which keeps it from stopping for idleness. */
30
37
  function touch(folder) {
31
38
  writeFileSync(join(folder, "activity"), "");
@@ -129,10 +136,14 @@ function launch(folder, root, watch) {
129
136
  rmSync(join(folder, "idle"), { force: true });
130
137
  // The first cycle of a watch reads every file there is: it owes a cycle for none.
131
138
  rmSync(join(folder, "owed"), { recursive: true, force: true });
139
+ // What the watch before this one left of its cycles.
140
+ for (const left of ["cycles", "cycle", "last"])
141
+ rmSync(join(folder, left), { force: true });
132
142
  const [name = "", ...args] = watch.run;
133
143
  const command = commandOf(root, name);
134
144
  const supervisor = commandOf(root, "{engine}/src/core/watch.ts");
135
- const watched = [join(folder, "activity"), String(idleMs()), command.file, ...command.args, ...args];
145
+ const cycle = [watch.cycleStart, watch.cycleEnd];
146
+ const watched = [folder, String(idleMs()), ...cycle, command.file, ...command.args, ...args];
136
147
  // Listed before the watch starts: a file created in between counts as one it may not know, never the other way.
137
148
  writeFileSync(join(folder, "frozen"), frozenFiles(root, watch));
138
149
  const log = openSync(join(folder, "output.log"), "w");
@@ -147,32 +158,10 @@ function launch(folder, root, watch) {
147
158
  child.unref();
148
159
  writeFileSync(join(folder, "pid"), String(child.pid ?? ""));
149
160
  }
150
- function cyclesOf(printed, watch) {
151
- const lines = printed.split("\n");
152
- if (lines.at(-1) === "")
153
- lines.pop();
154
- const opens = new RegExp(watch.cycleStart);
155
- const closes = new RegExp(watch.cycleEnd);
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
- };
161
+ // A watch whose supervisor has written nothing yet is in the cycle its start opens.
162
+ function cyclesOf(folder) {
163
+ const [opened, state] = readText(join(folder, "cycles")).split(" ");
164
+ return { opened: Number(opened), open: state !== "closed" };
176
165
  }
177
166
  /** Gives the files their date again, as a change of nothing else, for a watch that looks at their date. */
178
167
  function touchAgain(paths) {
@@ -192,14 +181,19 @@ function changedAt(path) {
192
181
  return 0;
193
182
  }
194
183
  }
195
- function readLog(log) {
184
+ function readText(path) {
196
185
  try {
197
- return readFileSync(log, "utf8");
186
+ return readFileSync(path, "utf8");
198
187
  }
199
188
  catch {
200
189
  return "";
201
190
  }
202
191
  }
192
+ /** Writes a file at once, so that a hook reading it never finds half of it. */
193
+ function writeWhole(path, text) {
194
+ writeFileSync(`${path}.new`, text);
195
+ renameSync(`${path}.new`, path);
196
+ }
203
197
  /**
204
198
  * Starts the watch again when a file it lists only as it starts was created or deleted since: its first cycle then
205
199
  * reads every file there is. Only one hook does, and only the watch it looked at: another session may be here too.
@@ -207,10 +201,10 @@ function readLog(log) {
207
201
  async function restartOnFrozenChange(session, root, gate, folder) {
208
202
  if (gate.watch.frozen === undefined || stateOf(folder) !== "running")
209
203
  return;
210
- if (readLog(join(folder, "frozen")) === frozenFiles(root, gate.watch) || !lockStart(folder))
204
+ if (readText(join(folder, "frozen")) === frozenFiles(root, gate.watch) || !lockStart(folder))
211
205
  return;
212
206
  try {
213
- if (stateOf(folder) !== "running" || readLog(join(folder, "frozen")) === frozenFiles(root, gate.watch))
207
+ if (stateOf(folder) !== "running" || readText(join(folder, "frozen")) === frozenFiles(root, gate.watch))
214
208
  return;
215
209
  // Stopped by the engine, so that another session waiting on the watch does not take it for one that broke.
216
210
  writeFileSync(join(folder, "idle"), "");
@@ -229,20 +223,23 @@ async function restartOnFrozenChange(session, root, gate, folder) {
229
223
  * 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
224
  * watch takes to see a change. Each round touches files, then waits for the watch to open a cycle after the touch,
231
225
  * which only a watch that saw the touch does:
232
- * 1. the sync file, which proves the watch now looks for changes;
226
+ * 1. the sync file alone. The cycle that follows proves the watch now looks for changes, whoever made it open: a
227
+ * watch may look for them only once its first cycle is over, as Angular and tsc do, and a touch made before is
228
+ * lost. Touched with the sync file in this round, the files of the turn could be lost with it, and a cycle the
229
+ * watch then opens for a change of someone else, another gate or another session, would answer for them;
233
230
  * 2. the files of the turn, so that a change it missed reaches it, then the sync file;
234
231
  * 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
232
  * this one opens after every change the watch then had waiting;
236
233
  * 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
234
  * 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
235
+ * 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
236
+ * hook started, as when the hooks were installed mid-session, starts now, and so does one the engine
239
237
  * stopped, for idleness or to start it again: it is not to blame. One another session starts again meanwhile is asked
240
238
  * again from the first round.
241
239
  */
242
240
  async function settle(session, root, gate, files, limitMs) {
243
241
  const started = performance.now();
244
242
  const folder = folderOf(root, gate);
245
- const log = join(folder, "output.log");
246
243
  const sync = join(root, gate.watch.sync);
247
244
  if (!existsSync(sync)) {
248
245
  const stopped = `The watch cannot be asked for a cycle: its watch.sync, ${gate.watch.sync}, does not exist.`;
@@ -253,7 +250,8 @@ async function settle(session, root, gate, files, limitMs) {
253
250
  const rounds = [[sync], ...(turn.length ? [[...turn, sync]] : []), [sync], [sync]];
254
251
  let asked;
255
252
  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.
253
+ // The cycles the watch had opened when the round touched its files, when it last did, and how many times: none
254
+ // before its first touch.
257
255
  let touched;
258
256
  for (;;) {
259
257
  const state = stateOf(folder);
@@ -261,14 +259,12 @@ async function settle(session, root, gate, files, limitMs) {
261
259
  startWatch(session, root, gate);
262
260
  // Waiting on the watch is using it: it does not stop for idleness under a stop that waits.
263
261
  touch(folder);
264
- // Read once the watch is known stopped, so its last lines are in.
265
- const printed = readLog(log);
266
262
  const ms = performance.now() - started;
267
263
  if (state === "stopped") {
268
- const last = cleaned(root, printed
269
- .split("\n")
270
- .slice(-LAST_LINES - 1)
271
- .join("\n"));
264
+ // Read once the watch is known stopped, so its last lines are in: the ones its supervisor kept, or what the
265
+ // supervisor itself printed when it broke.
266
+ const printed = readText(join(folder, "last")) || readText(join(folder, "output.log"));
267
+ const last = cleaned(root, printed.trimEnd().split("\n").slice(-LAST_LINES).join("\n"));
272
268
  return {
273
269
  ms,
274
270
  stopped: last ? `The watch stopped. Its last lines:\n${last}` : "The watch stopped, with no output.",
@@ -280,24 +276,29 @@ async function settle(session, root, gate, files, limitMs) {
280
276
  round = 0;
281
277
  touched = undefined;
282
278
  }
283
- const cycles = cyclesOf(printed, gate.watch);
279
+ const cycles = cyclesOf(folder);
284
280
  if (state === "running" && touched === undefined) {
285
281
  // A round starts once the cycle before it has closed.
286
282
  if (!cycles.open) {
287
283
  touchAgain(rounds[round] ?? []);
288
- touched = { opened: cycles.opened, at: Date.now() };
284
+ touched = { opened: cycles.opened, at: Date.now(), times: 1 };
289
285
  }
290
286
  }
291
287
  else if (touched !== undefined && cycles.opened > touched.opened) {
288
+ // Written before the count of the cycle that ended it: the cycle read is that one, or a later one.
292
289
  if (round === rounds.length - 1)
293
- return { ms, cycle: cleaned(root, cycles.complete.join("\n")) };
290
+ return { ms, cycle: cleaned(root, readText(join(folder, "cycle"))) };
294
291
  round++;
295
292
  touched = undefined;
296
293
  continue;
297
294
  }
298
- else if (touched !== undefined && Date.now() - touched.at >= RESYNC_MS) {
295
+ else if (touched !== undefined && Date.now() - touched.at >= resyncMs() * 2 ** (touched.times - 1)) {
296
+ if (touched.times === SYNC_TOUCHES) {
297
+ 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.`;
298
+ return { ms, stopped };
299
+ }
299
300
  touchAgain(rounds[round] ?? []);
300
- touched.at = Date.now();
301
+ touched = { ...touched, at: Date.now(), times: touched.times + 1 };
301
302
  }
302
303
  if (ms >= limitMs)
303
304
  return { ms, timedOut: true };
@@ -310,7 +311,7 @@ async function settle(session, root, gate, files, limitMs) {
310
311
  */
311
312
  function owedFiles(folder) {
312
313
  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
+ const files = lists.flatMap((list) => readText(list).split("\0").filter(Boolean));
314
315
  return { lists, files: [...new Set(files)] };
315
316
  }
316
317
  function owe(folder, files) {
@@ -391,29 +392,69 @@ function stop(folder) {
391
392
  catch { }
392
393
  }
393
394
  /**
394
- * The supervisor of a watch, which this module runs as when the engine starts one: it runs the watch, its output
395
- * going where its own goes, and stops it with every process it started once its repo has had no prompt nor stop for
396
- * the idle delay. Started detached, it leads a process group of its own, so stopping the group stops the watch and
397
- * the tools under it.
395
+ * The supervisor of a watch, which this module runs as when the engine starts one: it runs the watch and stops it
396
+ * with every process it started once its repo has had no prompt nor stop for the idle delay. Started detached, it
397
+ * leads a process group of its own, so stopping the group stops the watch and the tools under it. It counts the
398
+ * cycles of the watch as it prints them, and keeps only the lines a hook reads: a watch prints thousands of lines per
399
+ * cycle for as long as a session lasts, which no hook could read again at each look.
398
400
  */
399
- function supervise(activity, idle, file, args) {
401
+ function supervise(folder, idle, cycle, command) {
402
+ const [file = "", ...args] = command;
403
+ const opens = new RegExp(cycle.start);
404
+ const closes = new RegExp(cycle.end);
400
405
  const watch = spawn(file, args, { stdio: ["ignore", "pipe", "pipe"] });
401
- const forward = (line) => console.log(line);
402
- createInterface({ input: watch.stdout }).on("line", forward);
403
- createInterface({ input: watch.stderr }).on("line", forward);
406
+ // The start of the watch opens the first cycle, and lines after the one that closes a cycle still belong to it. A
407
+ // line that opens a cycle while one is open belongs to that one: Angular says it rebuilds as it starts to, and
408
+ // again once it has, and counting both would end a cycle before its first line.
409
+ let opened = 0;
410
+ let open = true;
411
+ // The lines of the cycle in progress, less the ones that say it opened, which tell the agent nothing.
412
+ let lines = [];
413
+ // What a watch that stopped leaves the agent.
414
+ const last = [];
415
+ const count = () => writeWhole(join(folder, "cycles"), `${opened} ${open ? "open" : "closed"}`);
416
+ const read = (line) => {
417
+ last.push(line);
418
+ if (last.length > LAST_LINES)
419
+ last.shift();
420
+ if (closes.test(line)) {
421
+ if (open) {
422
+ open = false;
423
+ count();
424
+ }
425
+ }
426
+ else if (!open && opens.test(line)) {
427
+ // Nothing is printed in a cycle any more once the next one has opened: its lines are whole, and written before
428
+ // the count that tells a hook of them.
429
+ writeWhole(join(folder, "cycle"), lines.join("\n"));
430
+ lines = [];
431
+ opened++;
432
+ open = true;
433
+ count();
434
+ }
435
+ if (!opens.test(line))
436
+ lines.push(line);
437
+ };
438
+ const end = (code) => {
439
+ writeWhole(join(folder, "last"), last.join("\n"));
440
+ process.exit(code);
441
+ };
442
+ count();
443
+ createInterface({ input: watch.stdout }).on("line", read);
444
+ createInterface({ input: watch.stderr }).on("line", read);
404
445
  watch.on("error", (error) => {
405
- console.log(error.message);
406
- process.exit(1);
446
+ last.push(error.message);
447
+ end(1);
407
448
  });
408
- watch.on("close", (code) => process.exit(code ?? 1));
449
+ watch.on("close", (code) => end(code ?? 1));
409
450
  setInterval(() => {
410
- if (Date.now() - changedAt(activity) < idle)
451
+ if (Date.now() - changedAt(join(folder, "activity")) < idle)
411
452
  return;
412
- writeFileSync(join(dirname(activity), "idle"), "");
453
+ writeFileSync(join(folder, "idle"), "");
413
454
  process.kill(-process.pid, "SIGTERM");
414
455
  }, Math.min(idle / 4, 10_000));
415
456
  }
416
457
  if (import.meta.main) {
417
- const [activity = "", idle = "", file = "", ...args] = process.argv.slice(2);
418
- supervise(activity, Number(idle), file, args);
458
+ const [folder = "", idle = "", start = "", end = "", ...command] = process.argv.slice(2);
459
+ supervise(folder, Number(idle), { start, end }, command);
419
460
  }