@tayomi/deterministic-gates 0.5.1 → 0.6.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.5.1"
12
+ "version": "0.6.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.5.1",
4
+ "version": "0.6.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.5.1",
3
+ "version": "0.6.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",
@@ -437,7 +437,7 @@ summary { cursor: pointer; color: var(--muted); }
437
437
  </article>
438
438
  <article id="typescript/no-new-strict-errors">
439
439
  <h3><code>typescript/no-new-strict-errors</code></h3>
440
- <p>Type-checks the project with strictNullChecks and strictPropertyInitialization on, and fails only on the errors the turn added: a project that turned them off, with more errors than it can fix at once, stops growing new ones. An error is told by its file, code and message, so one a change moves to another line is not new. tsc keeps watching between turns; without the watch, it runs at each prompt and stop instead. Refused when tsconfig.json only references others, as in an Angular project, since tsc would check no file: give it -p and a tsconfig. The whole check counts every error.</p>
440
+ <p>Type-checks the project with strictNullChecks and strictPropertyInitialization on, and fails only on the errors the turn added: a project that turned them off, with more errors than it can fix at once, stops growing new ones. An error is told by its file, code and source line, since tsc prints the types of a message otherwise from one compilation to the next: one a change moves to another line is not new, nor one tsc reports with the same message in another file the turn did not change, nor one on a line the turn changed, as long as its file has no more errors of its code than at the turn start. The agent still reads the message. tsc keeps watching between turns; without the watch, it runs at each prompt and stop instead. Refused when tsconfig.json only references others, as in an Angular project, since tsc would check no file: give it -p and a tsconfig. The whole check counts every error.</p>
441
441
  <dl>
442
442
  <dt>Runs</dt><dd><code>{engine}/src/helpers/type-errors.ts --strictNullChecks --strictPropertyInitialization</code></dd>
443
443
  <dt>When the turn changes</dt><dd><code>(\.(ts|tsx)|^tsconfig.*\.json)$</code></dd>
@@ -453,6 +453,7 @@ summary { cursor: pointer; color: var(--muted); }
453
453
  &quot;--strictPropertyInitialization&quot;
454
454
  ],
455
455
  &quot;compare&quot;: &quot;turn-start&quot;,
456
+ &quot;lineKey&quot;: &quot;^((?&lt;file&gt;.+?): error TS\\d+) at [^\\t]*&quot;,
456
457
  &quot;watch&quot;: {
457
458
  &quot;run&quot;: [
458
459
  &quot;{engine}/src/helpers/type-errors.ts&quot;,
@@ -96,7 +96,7 @@
96
96
  }
97
97
  },
98
98
  {
99
- "description": "Type-checks the project with strictNullChecks and strictPropertyInitialization on, and fails only on the errors the turn added: a project that turned them off, with more errors than it can fix at once, stops growing new ones. An error is told by its file, code and message, so one a change moves to another line is not new. tsc keeps watching between turns; without the watch, it runs at each prompt and stop instead. Refused when tsconfig.json only references others, as in an Angular project, since tsc would check no file: give it -p and a tsconfig. The whole check counts every error.",
99
+ "description": "Type-checks the project with strictNullChecks and strictPropertyInitialization on, and fails only on the errors the turn added: a project that turned them off, with more errors than it can fix at once, stops growing new ones. An error is told by its file, code and source line, since tsc prints the types of a message otherwise from one compilation to the next: one a change moves to another line is not new, nor one tsc reports with the same message in another file the turn did not change, nor one on a line the turn changed, as long as its file has no more errors of its code than at the turn start. The agent still reads the message. tsc keeps watching between turns; without the watch, it runs at each prompt and stop instead. Refused when tsconfig.json only references others, as in an Angular project, since tsc would check no file: give it -p and a tsconfig. The whole check counts every error.",
100
100
  "requires": [
101
101
  {
102
102
  "tool": "typescript",
@@ -109,6 +109,7 @@
109
109
  "files": "(\\.(ts|tsx)|^tsconfig.*\\.json)$",
110
110
  "run": ["{engine}/src/helpers/type-errors.ts", "--strictNullChecks", "--strictPropertyInitialization"],
111
111
  "compare": "turn-start",
112
+ "lineKey": "^((?<file>.+?): error TS\\d+) at [^\\t]*",
112
113
  "watch": {
113
114
  "run": [
114
115
  "{engine}/src/helpers/type-errors.ts",
@@ -5,7 +5,7 @@ import { cachedReports, cacheReports } from "./report-cache.js";
5
5
  import { check, filesOf, givenFiles, missingTool, wholeProject } from "./run.js";
6
6
  import { changedSince, emptyCommit, hasCommit, lastCommit, snapshot, workingTree } from "./snapshot.js";
7
7
  import { readTurn, writeTurn } from "./turn-state.js";
8
- import { judgeWatch, keepWatch, startWatch, watchReport } from "./watch.js";
8
+ import { judgeWatch, keepWatch, startWatch, TURN_START_MS, watchReport } from "./watch.js";
9
9
  function missingTools(root, gates) {
10
10
  return gates.flatMap((gate) => {
11
11
  const why = missingTool(root, gate);
@@ -43,13 +43,15 @@ export async function startTurn(session, root) {
43
43
  return told;
44
44
  }
45
45
  const { commit: start, tree } = snapshot(root);
46
+ // The turn starts before its reports are ready: a hook stopped for lack of time leaves it, never the turn before.
47
+ writeTurn(session, root, { start, baselines: {}, config, checked: false });
46
48
  const cached = cachedReports(root, tree);
47
49
  const baselines = await Promise.all(compared.map(async (gate) => {
48
50
  const cachedReport = cached(gate);
49
51
  if (cachedReport !== undefined)
50
52
  return { gate, ok: true, output: cachedReport };
51
53
  if (!keepsWatch(gate))
52
- return { gate, ...(await wholeProject(root, gate)) };
54
+ return { gate, ...(await wholeProject(root, gate, TURN_START_MS)) };
53
55
  const output = await watchReport(session, root, gate);
54
56
  return { gate, ok: output !== undefined, output };
55
57
  }));
@@ -8,7 +8,17 @@ const LOCAL_GATES_FILE = ".gates.local.json";
8
8
  const DEFAULT_MAX_TIMEOUT_SECONDS = 45;
9
9
  // The times a turn sends the agent back: enough for a fix that breaks another gate, never a loop.
10
10
  const DEFAULT_MAX_SEND_BACKS = 5;
11
- const FIELDS = new Set(["name", "severity", "files", "run", "compare", "ignoreLines", "timeoutSeconds", "watch"]);
11
+ const FIELDS = new Set([
12
+ "name",
13
+ "severity",
14
+ "files",
15
+ "run",
16
+ "compare",
17
+ "ignoreLines",
18
+ "lineKey",
19
+ "timeoutSeconds",
20
+ "watch",
21
+ ]);
12
22
  const WATCH_FIELDS = new Set(["run", "cycleStart", "cycleEnd", "failed"]);
13
23
  /** In the arguments of a gate: the changed files it looks at, and the commit of the turn start. */
14
24
  export const FILES = "{files}";
@@ -104,7 +114,7 @@ function toWatch(watch, compared) {
104
114
  };
105
115
  }
106
116
  function toGate(entry, maxTimeoutSeconds) {
107
- const { name, severity, files, run, compare, ignoreLines, watch, timeoutSeconds = maxTimeoutSeconds } = entry;
117
+ const { name, severity, files, run, compare, ignoreLines, lineKey, watch, timeoutSeconds = maxTimeoutSeconds, } = entry;
108
118
  const unknown = Object.keys(entry).find((key) => !FIELDS.has(key));
109
119
  if (unknown !== undefined)
110
120
  refuse(`unknown field ${unknown}`);
@@ -122,6 +132,10 @@ function toGate(entry, maxTimeoutSeconds) {
122
132
  refuse(`a compared gate reads the whole project: it takes no ${FILES}`);
123
133
  if (ignoreLines !== undefined && !isPattern(ignoreLines))
124
134
  refuse("ignoreLines is a regular expression");
135
+ if (lineKey !== undefined && !isPattern(lineKey))
136
+ refuse("lineKey is a regular expression");
137
+ if (lineKey !== undefined && compare === undefined)
138
+ refuse("lineKey tells apart the lines of a compared gate: it takes compare");
125
139
  if (typeof timeoutSeconds !== "number" || timeoutSeconds <= 0)
126
140
  refuse("timeoutSeconds is a positive number");
127
141
  return {
@@ -133,6 +147,7 @@ function toGate(entry, maxTimeoutSeconds) {
133
147
  timeoutSeconds: Math.min(timeoutSeconds, maxTimeoutSeconds),
134
148
  ...(compare === undefined ? {} : { compare }),
135
149
  ...(ignoreLines === undefined ? {} : { ignoreLines }),
150
+ ...(lineKey === undefined ? {} : { lineKey }),
136
151
  ...(watch === undefined ? {} : { watch: toWatch(watch, compare !== undefined) }),
137
152
  };
138
153
  }
@@ -12,8 +12,19 @@ const ENGINE = resolve(import.meta.dirname, "..", "..");
12
12
  const manifest = readJsonFile(join(ENGINE, "package.json"));
13
13
  /** The version of this engine: what its helpers print, so what a report holds, may change from one to the next. */
14
14
  export const ENGINE_VERSION = isRecord(manifest) ? String(manifest.version) : "";
15
- /** What a tool runs with: no colour, which some tools print anyway. */
16
- export const TOOL_ENV = { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0" };
15
+ /**
16
+ * What a tool of a repo runs with: no colour, which some tools print anyway, and the commands of its node_modules
17
+ * first on the PATH, as npx and the package managers run them, so that a tool finds the Node the repo pins.
18
+ */
19
+ export function toolEnv(root) {
20
+ const path = [join(root, "node_modules", ".bin"), ...(process.env.PATH ? [process.env.PATH] : [])];
21
+ return { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0", PATH: path.join(delimiter) };
22
+ }
23
+ /** The Node a script of the repo or of its packages runs on: the one the repo pins in its node_modules, as npx finds it, or the one of the engine. */
24
+ function repoNode(root) {
25
+ const pinned = join(root, "node_modules", ".bin", "node");
26
+ return executable(pinned) ? pinned : process.execPath;
27
+ }
17
28
  const MAX_OUTPUT_MB = 16;
18
29
  const ENGINE_PREFIX = "{engine}/";
19
30
  /** A script of this engine: its .ts source, or the .js it is built to when the engine runs from its npm package. */
@@ -23,8 +34,8 @@ function engineScript(name) {
23
34
  }
24
35
  // A script of the repo runs on the interpreter of its extension.
25
36
  const INTERPRETERS = [
26
- [/\.(ts|js|mjs)$/, process.execPath],
27
- [/\.py$/, "python3"],
37
+ [/\.(ts|js|mjs)$/, repoNode],
38
+ [/\.py$/, () => "python3"],
28
39
  ];
29
40
  /** The script of a package of the repo's node_modules, or nothing when the repo does not have the package. */
30
41
  export function packageScript(root, name) {
@@ -48,7 +59,7 @@ export function commandOf(root, name) {
48
59
  if (name.startsWith(ENGINE_PREFIX)) {
49
60
  return { file: process.execPath, args: [engineScript(name.slice(ENGINE_PREFIX.length))], missing: "" };
50
61
  }
51
- const interpreter = INTERPRETERS.find(([extension]) => extension.test(name))?.[1];
62
+ const interpreter = INTERPRETERS.find(([extension]) => extension.test(name))?.[1](root);
52
63
  if (interpreter !== undefined) {
53
64
  return {
54
65
  file: interpreter,
@@ -58,7 +69,7 @@ export function commandOf(root, name) {
58
69
  }
59
70
  const script = packageScript(root, name);
60
71
  if (script !== undefined)
61
- return { file: process.execPath, args: [script], missing: "" };
72
+ return { file: repoNode(root), args: [script], missing: "" };
62
73
  if (name.includes("/"))
63
74
  return { file: resolve(root, name), args: [], missing: `${name} does not exist.` };
64
75
  return {
@@ -68,10 +79,8 @@ export function commandOf(root, name) {
68
79
  };
69
80
  }
70
81
  // A program by its path, or by its name on the PATH, that the system would execute.
71
- function executable(file) {
72
- const candidates = isAbsolute(file)
73
- ? [file]
74
- : (process.env.PATH ?? "").split(delimiter).map((dir) => join(dir, file));
82
+ function executable(file, path = process.env.PATH ?? "") {
83
+ const candidates = isAbsolute(file) ? [file] : path.split(delimiter).map((dir) => join(dir, file));
75
84
  return candidates.some((candidate) => {
76
85
  try {
77
86
  accessSync(candidate, constants.X_OK);
@@ -90,7 +99,7 @@ function missingProgram(root, name) {
90
99
  catch {
91
100
  return undefined;
92
101
  }
93
- return command.missing && !executable(command.file) ? command.missing : undefined;
102
+ return command.missing && !executable(command.file, toolEnv(root).PATH) ? command.missing : undefined;
94
103
  }
95
104
  /**
96
105
  * Why the program of a gate, or of its watch, cannot run on this machine, or nothing when they can: looked up as the
@@ -110,13 +119,39 @@ export function filesOf(gate, changed) {
110
119
  const pattern = new RegExp(gate.files);
111
120
  return changed.filter((file) => pattern.test(file));
112
121
  }
113
- export function newLines(before, after, ignore) {
122
+ /**
123
+ * The lines of output a turn added, less the ignored ones. With a key, a line is told by the part the key matches. A
124
+ * line of a new key is still an old one, each line of the turn start whose key went standing for one line only: first
125
+ * when it says the same as such a line, that problem reported elsewhere, unless the group of the key named file names
126
+ * a file the turn changed, where the agent may have written it; then when the first group of the key, its place, is
127
+ * the one of such a line, that problem changed where it is.
128
+ */
129
+ export function newLines(before, after, ignore, key, changed = []) {
114
130
  const ignored = ignore === undefined ? undefined : new RegExp(ignore);
115
- const seen = new Set(before.split("\n").map((line) => line.trim()));
116
- return after
131
+ const keyed = key === undefined ? undefined : new RegExp(key);
132
+ const lines = (text) => text
117
133
  .split("\n")
118
134
  .map((line) => line.trim())
119
- .filter((line) => line && !seen.has(line) && !ignored?.test(line));
135
+ .filter(Boolean);
136
+ const keyOf = (line) => keyed?.exec(line)?.[0] ?? line;
137
+ const placeOf = (line) => keyed?.exec(line)?.[1];
138
+ const written = (line) => changed.includes(keyed?.exec(line)?.groups?.file ?? "");
139
+ const restOf = (line) => line.replace(keyOf(line), "").trim();
140
+ const old = lines(before);
141
+ const now = lines(after);
142
+ const oldKeys = new Set(old.map(keyOf));
143
+ const nowKeys = new Set(now.map(keyOf));
144
+ const gone = old.filter((line) => !nowKeys.has(keyOf(line)));
145
+ const stillOld = (same) => {
146
+ const at = gone.findIndex(same);
147
+ if (at !== -1)
148
+ gone.splice(at, 1);
149
+ return at !== -1;
150
+ };
151
+ return now
152
+ .filter((line) => !oldKeys.has(keyOf(line)) && !ignored?.test(line))
153
+ .filter((line) => !restOf(line) || written(line) || !stillOld((was) => restOf(was) === restOf(line)))
154
+ .filter((line) => placeOf(line) === undefined || !stillOld((was) => placeOf(was) === placeOf(line)));
120
155
  }
121
156
  async function execute(root, gate, args) {
122
157
  const started = performance.now();
@@ -134,7 +169,7 @@ async function execute(root, gate, args) {
134
169
  cwd: root,
135
170
  timeout: gate.timeoutSeconds * 1000,
136
171
  maxBuffer: MAX_OUTPUT_MB * 1024 * 1024,
137
- env: TOOL_ENV,
172
+ env: toolEnv(root),
138
173
  }, (error, stdout, stderr) => {
139
174
  resolve({
140
175
  ok: !error,
@@ -161,9 +196,14 @@ function outputOf(root, gate, command, error, printed) {
161
196
  export function cleaned(root, printed) {
162
197
  return stripVTControlCharacters(printed).split(`${root}${sep}`).join("").trim();
163
198
  }
164
- /** Runs a compared gate on the whole project, as the turn starts. */
165
- export function wholeProject(root, gate) {
166
- return execute(root, gate, gate.run.slice(1));
199
+ /**
200
+ * Runs a compared gate on the whole project, as the turn starts, in the time the gate has or less: nothing when it
201
+ * runs out of it, since its lines would all be new at the stop.
202
+ */
203
+ export async function wholeProject(root, gate, ms = gate.timeoutSeconds * 1000) {
204
+ const timeoutSeconds = Math.min(gate.timeoutSeconds, ms / 1000);
205
+ const { ok, output, timedOut } = await execute(root, { ...gate, timeoutSeconds }, gate.run.slice(1));
206
+ return timedOut ? { ok: false } : { ok, output };
167
207
  }
168
208
  /**
169
209
  * Runs a gate on the turn. A compared gate fails on the lines of output the turn added, and on any exit code but 0:
@@ -176,15 +216,15 @@ export async function check(root, gate, files, turn, baseline) {
176
216
  return { ...ran, ok, output, timedOut };
177
217
  if (!isCompared(gate) || !ok)
178
218
  return { ...ran, ok, output };
179
- return { ...ran, ...addedLines(gate, output, baseline) };
219
+ return { ...ran, ...addedLines(gate, output, baseline, files) };
180
220
  }
181
221
  /**
182
222
  * Judges the output of a compared gate that ran clean: it fails on the lines the turn added to the report of the turn
183
223
  * start. Without that report, nothing counts but the exit code.
184
224
  */
185
- export function addedLines(gate, output, baseline) {
225
+ export function addedLines(gate, output, baseline, changed) {
186
226
  if (baseline === undefined)
187
227
  return { ok: true, output: "" };
188
- const added = newLines(baseline, output, gate.ignoreLines);
228
+ const added = newLines(baseline, output, gate.ignoreLines, gate.lineKey, changed);
189
229
  return { ok: added.length === 0, output: added.join("\n") };
190
230
  }
@@ -6,7 +6,7 @@ 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
- import { addedLines, cleaned, commandOf, ENGINE_VERSION, TOOL_ENV } from "./run.js";
9
+ import { addedLines, cleaned, commandOf, ENGINE_VERSION, toolEnv } from "./run.js";
10
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
11
  const QUIET_MS = 1000;
12
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:
@@ -15,8 +15,8 @@ const UNSEEN_MS = 5000;
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;
18
- // A prompt waits this long at most for a compared watch to settle, under the 60 s its hook has.
19
- const TURN_START_MS = 45_000;
18
+ // A prompt waits this long at most for the reports of its compared gates, under the 60 s its hook has.
19
+ export const TURN_START_MS = 45_000;
20
20
  const PREFIX = "gates-watch-";
21
21
  // A start that holds its lock longer than this died on the way: the next hook takes the lock over.
22
22
  const STALE_START_MS = 10_000;
@@ -120,7 +120,7 @@ function launch(folder, root, watch) {
120
120
  cwd: root,
121
121
  detached: true,
122
122
  stdio: ["ignore", log, log],
123
- env: TOOL_ENV,
123
+ env: toolEnv(root),
124
124
  });
125
125
  closeSync(log);
126
126
  child.on("error", () => { });
@@ -211,7 +211,7 @@ export async function judgeWatch(session, root, gate, files, baseline) {
211
211
  const { cycle } = settled;
212
212
  const fails = new RegExp(gate.watch.failed ?? "(?!)");
213
213
  const judged = isCompared(gate)
214
- ? addedLines(gate, cycle, baseline)
214
+ ? addedLines(gate, cycle, baseline, files)
215
215
  : { ok: !cycle.split("\n").some((line) => fails.test(line)), output: cycle };
216
216
  return { name, ms, ...judged, report: judged.ok ? cycle : undefined };
217
217
  }
@@ -4,25 +4,48 @@ import { createInterface } from "node:readline";
4
4
  import { commandOf } from "../core/run.js";
5
5
  import { COUNTS, HEADER } from "./vitest-state-reporter.js";
6
6
  // The watch of an Angular project tested with Vitest: ng test in watch mode, with the reporter of the engine that
7
- // prints the state of every spec at each run, and NG_TEST_LOG, which makes Angular say when a run ends. A change that
8
- // leaves the build as it was reruns no spec, so no state prints: the last one is printed again, so that the cycle
9
- // still tells which specs are red.
7
+ // prints the state of every spec at each run, and NG_TEST_LOG, which makes Angular say when a run ends. It prints
8
+ // only what judges a run: the build also prints the files it built, a table longer than the report of the specs in a
9
+ // large project, whose names change at each build.
10
10
  const NO_RERUN = /No test specifications to rerun/;
11
+ const KEPT = [/Changes detected\. Rebuilding/, /bundle generation failed/, NO_RERUN];
12
+ const ENDS = /Test run finished with success/;
13
+ // Angular says why a run ended, and says all tests passed of a run with failed specs.
14
+ const REASON = /\s*Reason: .*$/;
15
+ const ERROR = /^\S+ \[ERROR\] /;
16
+ // What a watch that stopped leaves, so that a crash still says why.
17
+ const LAST_LINES = 20;
11
18
  /**
12
- * What to print for each line of the watch: the line, and before a run that reruns no spec, the last state of the
13
- * specs, so that the cycle still tells which specs are red.
19
+ * What to print for each line of ng test: the lines that open a run, the state of the specs, the errors of a build
20
+ * that failed, with the lines under each, and the line that ends a run, less its reason. A change that leaves the
21
+ * build as it was reruns no spec, so no state prints: the last one is printed again, so that the cycle still tells
22
+ * which specs are red.
14
23
  */
15
- export function replaying() {
24
+ export function reporting() {
16
25
  let state = [];
17
26
  let reading;
27
+ let inError = false;
18
28
  return (line) => {
19
29
  if (line === HEADER)
20
30
  reading = [];
21
- reading?.push(line);
22
- if (reading !== undefined && line.startsWith(COUNTS)) {
23
- state = reading;
24
- reading = undefined;
31
+ if (reading !== undefined) {
32
+ reading.push(line);
33
+ if (line.startsWith(COUNTS)) {
34
+ state = reading;
35
+ reading = undefined;
36
+ }
37
+ return [line];
25
38
  }
39
+ if (ERROR.test(line))
40
+ inError = true;
41
+ else if (line.trim() && !/^\s/.test(line))
42
+ inError = false;
43
+ if (inError)
44
+ return [line];
45
+ if (ENDS.test(line))
46
+ return [line.replace(REASON, "")];
47
+ if (!KEPT.some((kept) => kept.test(line)))
48
+ return [];
26
49
  return NO_RERUN.test(line) ? [...state, line] : [line];
27
50
  };
28
51
  }
@@ -37,11 +60,21 @@ function main(root, args) {
37
60
  env: { ...process.env, NG_TEST_LOG: "1" },
38
61
  stdio: ["ignore", "pipe", "pipe"],
39
62
  });
40
- const replay = replaying();
41
- const forward = (line) => console.log(replay(line).join("\n"));
63
+ const report = reporting();
64
+ const last = [];
65
+ const forward = (line) => {
66
+ last.push(line);
67
+ if (last.length > LAST_LINES)
68
+ last.shift();
69
+ for (const shown of report(line))
70
+ console.log(shown);
71
+ };
42
72
  createInterface({ input: watch.stdout }).on("line", forward);
43
73
  createInterface({ input: watch.stderr }).on("line", forward);
44
- watch.on("exit", (code) => process.exit(code ?? 1));
74
+ watch.on("exit", (code) => {
75
+ console.log(["ng test stopped. Its last lines:", ...last].join("\n"));
76
+ process.exit(code ?? 1);
77
+ });
45
78
  }
46
79
  if (import.meta.main)
47
80
  main(process.cwd(), process.argv.slice(2));
@@ -1,103 +1,49 @@
1
1
  import { spawn } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { resolve } from "node:path";
2
4
  import { createInterface } from "node:readline";
3
5
  import { checkingTsc } from "./tsc.js";
4
6
  // tsc, with the options it is given, such as strict ones a project turned off, printing its errors so that a gate can
5
- // compare them with the ones of the turn start: one line per error, with its file and none of its line and column, so
6
- // an error a change moves down is not new, and a count after an error its file already has, so one more of it is.
7
- // tsc orders the members of a union as it happened to create them, which differs between the first compilation of a
8
- // watch and the next ones: each union prints sorted, untruncated, and without the lines under the error, which name its
9
- // first failing member, so the same error always prints the same.
7
+ // compare them with the ones of the turn start. tsc prints the same error otherwise from one compilation to the next:
8
+ // a watch checks again only the files a change reaches, with types created in another order, so the members of a
9
+ // union, the properties of an object, and the file of an error tsc reports once per type, all change. Each error is
10
+ // then one line: a key the gate compares, its file, code and source line, so an error a change moves down is not new,
11
+ // with a count after one its file already has on the same source, so one more of it is; then, after a tab, the first
12
+ // line of its message, for the agent alone.
10
13
  // With --watch, tsc keeps watching, and each compilation prints between a line that starts it and one that ends it.
11
14
  const STARTS = /Starting (compilation in watch mode|incremental compilation)/;
12
15
  const ENDS = /Found \d+ errors?\. Watching for file changes/;
13
- const POSITION = /^(.+)\(\d+,\d+\): (error TS\d+: .*)$/;
14
- const OPENS = { "(": ")", "[": "]", "{": "}", "<": ">" };
15
- // A property, parameter or index signature before its type, in an object, a tuple or a parameter list.
16
- const LABEL = /^((?:\.\.\.)?(?:[\w$]+|"[^"]*"|\[[^\]]*\])\??: )(.*)$/s;
17
- /** Where the bracket or the string that starts at index ends, or the index itself for any other character. */
18
- function skipped(text, index) {
19
- const char = text[index] ?? "";
20
- if (char === '"' || char === "`") {
21
- let end = index + 1;
22
- while (end < text.length && text[end] !== char)
23
- end += text[end] === "\\" ? 2 : 1;
24
- return end;
25
- }
26
- const close = OPENS[char];
27
- if (close === undefined)
28
- return index;
29
- let end = index + 1;
30
- // The arrow of a function type closes no bracket.
31
- while (end < text.length && text[end] !== close)
32
- end = text.startsWith("=>", end) ? end + 2 : skipped(text, end) + 1;
33
- return end;
34
- }
35
- /** The parts of a text between a separator that no bracket nor string encloses. */
36
- function split(text, separator) {
37
- const parts = [];
38
- let start = 0;
39
- for (let index = 0; index < text.length; index = skipped(text, index) + 1) {
40
- if (text.startsWith("=>", index))
41
- index++;
42
- else if (text.startsWith(separator, index)) {
43
- parts.push(text.slice(start, index));
44
- start = index + separator.length;
45
- index += separator.length - 1;
46
- }
47
- }
48
- return [...parts, text.slice(start)];
49
- }
50
- /** A type as tsc prints it, with the members of each union and intersection sorted, at every depth. */
51
- function sortedType(type) {
52
- // A function type outside any bracket returns all the rest: a union of function types puts each in parentheses.
53
- const [parameters = "", ...returned] = split(type, " => ");
54
- if (returned.length)
55
- return `${sortedInside(parameters)} => ${sortedType(returned.join(" => "))}`;
56
- const sorted = (members) => (members.length > 1 ? members.sort() : members);
57
- const union = split(type, " | ").map((member) => sorted(split(member, " & ").map(sortedInside)).join(" & "));
58
- return sorted(union).join(" | ");
59
- }
60
- /** A type with the content of each of its brackets sorted. */
61
- function sortedInside(type) {
62
- let out = "";
63
- for (let index = 0; index < type.length;) {
64
- const end = skipped(type, index);
65
- const char = type[index] ?? "";
66
- if (OPENS[char] !== undefined) {
67
- const separator = char === "{" ? ";" : ",";
68
- const inner = split(type.slice(index + 1, end), separator).map((element) => {
69
- const [, before = "", trimmed = "", after = ""] = /^(\s*)(.*?)(\s*)$/s.exec(element) ?? [];
70
- const label = LABEL.exec(trimmed);
71
- return before + (label ? `${label[1]}${sortedType(label[2] ?? "")}` : sortedType(trimmed)) + after;
72
- });
73
- out += `${char}${inner.join(separator)}${type[end] ?? ""}`;
74
- }
75
- else
76
- out += type.slice(index, end + 1);
77
- index = end + 1;
78
- }
79
- return out;
16
+ const POSITION = /^(.+)\((\d+),\d+\): error (TS\d+): (.*)$/;
17
+ const MESSAGE_CHARS = 300;
18
+ const SOURCE_CHARS = 200;
19
+ function cut(text, chars) {
20
+ return text.length > chars ? `${text.slice(0, chars)}…` : text;
80
21
  }
81
22
  /** The errors tsc printed, each on one line, as the gate compares them. */
82
- export function typeErrors(printed) {
23
+ export function typeErrors(printed, sources) {
24
+ const lines = new Map();
25
+ const sourceLine = (file, line) => {
26
+ if (!lines.has(file))
27
+ lines.set(file, (sources(file) ?? "").split("\n"));
28
+ return (lines.get(file)?.[line - 1] ?? "").replaceAll("\t", " ").trim();
29
+ };
30
+ const seen = new Map();
83
31
  const errors = [];
84
32
  for (const line of printed) {
85
33
  // The lines under an error explain it, and name its first failing member.
86
34
  if (!line.trim() || /^\s/.test(line))
87
35
  continue;
88
- const located = line.replace(POSITION, "$1: $2");
89
- // tsc quotes each type it names.
90
- errors.push(located.replace(/'([^']*)'/g, (_quoted, type) => `'${sortedType(type)}'`));
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)}`);
91
42
  }
92
- const seen = new Map();
93
- return errors.map((error) => {
94
- const count = (seen.get(error) ?? 0) + 1;
95
- seen.set(error, count);
96
- return count === 1 ? error : `${error} (${count})`;
97
- });
43
+ return errors;
98
44
  }
99
45
  /** What to print for each line of tsc in watch mode: nothing until a compilation ends, then its errors. */
100
- export function watching() {
46
+ export function watching(sources) {
101
47
  let compiled = [];
102
48
  return (line) => {
103
49
  if (STARTS.test(line)) {
@@ -105,7 +51,7 @@ export function watching() {
105
51
  return ["Type check started"];
106
52
  }
107
53
  if (ENDS.test(line))
108
- return [...typeErrors(compiled), "Type check done"];
54
+ return [...typeErrors(compiled, sources), "Type check done"];
109
55
  compiled.push(line);
110
56
  return [];
111
57
  };
@@ -113,17 +59,18 @@ export function watching() {
113
59
  function main(root, args) {
114
60
  const tsc = checkingTsc(root, args);
115
61
  const watch = args.includes("--watch");
116
- const options = [
117
- "--noEmit",
118
- "--pretty",
119
- "false",
120
- "--noErrorTruncation",
121
- ...(watch ? ["--preserveWatchOutput"] : []),
122
- ...args,
123
- ];
62
+ const options = ["--noEmit", "--pretty", "false", ...(watch ? ["--preserveWatchOutput"] : []), ...args];
124
63
  const child = spawn(tsc.file, [...tsc.args, ...options], { stdio: ["ignore", "pipe", "inherit"] });
125
64
  const printed = [];
126
- const print = watching();
65
+ const sources = (file) => {
66
+ try {
67
+ return readFileSync(resolve(root, file), "utf8");
68
+ }
69
+ catch {
70
+ return undefined;
71
+ }
72
+ };
73
+ const print = watching(sources);
127
74
  createInterface({ input: child.stdout }).on("line", (line) => {
128
75
  if (watch)
129
76
  for (const shown of print(line))
@@ -137,7 +84,7 @@ function main(root, args) {
137
84
  console.log(printed.join("\n"));
138
85
  process.exit(code ?? 1);
139
86
  }
140
- console.log(typeErrors(printed).join("\n"));
87
+ console.log(typeErrors(printed, sources).join("\n"));
141
88
  });
142
89
  }
143
90
  if (import.meta.main)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tayomi/deterministic-gates",
3
- "version": "0.5.1",
3
+ "version": "0.6.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",
package/src/core/check.ts CHANGED
@@ -5,7 +5,7 @@ import { cachedReports, cacheReports } from "./report-cache.ts";
5
5
  import { check, filesOf, givenFiles, missingTool, type Outcome, wholeProject } from "./run.ts";
6
6
  import { changedSince, emptyCommit, hasCommit, lastCommit, snapshot, workingTree } from "./snapshot.ts";
7
7
  import { readTurn, type TurnState, writeTurn } from "./turn-state.ts";
8
- import { judgeWatch, keepWatch, startWatch, watchReport } from "./watch.ts";
8
+ import { judgeWatch, keepWatch, startWatch, TURN_START_MS, watchReport } from "./watch.ts";
9
9
 
10
10
  export interface CheckedTurn {
11
11
  changed: string[];
@@ -70,12 +70,14 @@ export async function startTurn(session: string, root: string): Promise<string[]
70
70
  return told;
71
71
  }
72
72
  const { commit: start, tree } = snapshot(root);
73
+ // The turn starts before its reports are ready: a hook stopped for lack of time leaves it, never the turn before.
74
+ writeTurn(session, root, { start, baselines: {}, config, checked: false });
73
75
  const cached = cachedReports(root, tree);
74
76
  const baselines = await Promise.all(
75
77
  compared.map(async (gate): Promise<{ gate: Gate; ok: boolean; output?: string }> => {
76
78
  const cachedReport = cached(gate);
77
79
  if (cachedReport !== undefined) return { gate, ok: true, output: cachedReport };
78
- if (!keepsWatch(gate)) return { gate, ...(await wholeProject(root, gate)) };
80
+ if (!keepsWatch(gate)) return { gate, ...(await wholeProject(root, gate, TURN_START_MS)) };
79
81
  const output = await watchReport(session, root, gate);
80
82
  return { gate, ok: output !== undefined, output };
81
83
  }),
@@ -10,7 +10,17 @@ const LOCAL_GATES_FILE = ".gates.local.json";
10
10
  const DEFAULT_MAX_TIMEOUT_SECONDS = 45;
11
11
  // The times a turn sends the agent back: enough for a fix that breaks another gate, never a loop.
12
12
  const DEFAULT_MAX_SEND_BACKS = 5;
13
- const FIELDS = new Set(["name", "severity", "files", "run", "compare", "ignoreLines", "timeoutSeconds", "watch"]);
13
+ const FIELDS = new Set([
14
+ "name",
15
+ "severity",
16
+ "files",
17
+ "run",
18
+ "compare",
19
+ "ignoreLines",
20
+ "lineKey",
21
+ "timeoutSeconds",
22
+ "watch",
23
+ ]);
14
24
  const WATCH_FIELDS = new Set(["run", "cycleStart", "cycleEnd", "failed"]);
15
25
 
16
26
  /** In the arguments of a gate: the changed files it looks at, and the commit of the turn start. */
@@ -24,6 +34,8 @@ export interface Gate {
24
34
  run: string[];
25
35
  compare?: "turn-start";
26
36
  ignoreLines?: string;
37
+ /** The part of a line of a compared gate that tells it apart, when the rest may print otherwise from run to run. */
38
+ lineKey?: string;
27
39
  timeoutSeconds: number;
28
40
  watch?: Watch;
29
41
  }
@@ -154,7 +166,17 @@ function toWatch(watch: unknown, compared: boolean): Watch {
154
166
  }
155
167
 
156
168
  function toGate(entry: Entry, maxTimeoutSeconds: number): Gate {
157
- const { name, severity, files, run, compare, ignoreLines, watch, timeoutSeconds = maxTimeoutSeconds } = entry;
169
+ const {
170
+ name,
171
+ severity,
172
+ files,
173
+ run,
174
+ compare,
175
+ ignoreLines,
176
+ lineKey,
177
+ watch,
178
+ timeoutSeconds = maxTimeoutSeconds,
179
+ } = entry;
158
180
  const unknown = Object.keys(entry).find((key) => !FIELDS.has(key));
159
181
  if (unknown !== undefined) refuse(`unknown field ${unknown}`);
160
182
  if (!/^[a-z][a-z0-9-]*$/.test(name)) refuse("a name is lowercase words joined by hyphens");
@@ -166,6 +188,9 @@ function toGate(entry: Entry, maxTimeoutSeconds: number): Gate {
166
188
  if (compare !== undefined && run.includes(FILES))
167
189
  refuse(`a compared gate reads the whole project: it takes no ${FILES}`);
168
190
  if (ignoreLines !== undefined && !isPattern(ignoreLines)) refuse("ignoreLines is a regular expression");
191
+ if (lineKey !== undefined && !isPattern(lineKey)) refuse("lineKey is a regular expression");
192
+ if (lineKey !== undefined && compare === undefined)
193
+ refuse("lineKey tells apart the lines of a compared gate: it takes compare");
169
194
  if (typeof timeoutSeconds !== "number" || timeoutSeconds <= 0) refuse("timeoutSeconds is a positive number");
170
195
  return {
171
196
  name,
@@ -176,6 +201,7 @@ function toGate(entry: Entry, maxTimeoutSeconds: number): Gate {
176
201
  timeoutSeconds: Math.min(timeoutSeconds, maxTimeoutSeconds),
177
202
  ...(compare === undefined ? {} : { compare }),
178
203
  ...(ignoreLines === undefined ? {} : { ignoreLines }),
204
+ ...(lineKey === undefined ? {} : { lineKey }),
179
205
  ...(watch === undefined ? {} : { watch: toWatch(watch, compare !== undefined) }),
180
206
  };
181
207
  }
package/src/core/run.ts CHANGED
@@ -24,8 +24,20 @@ const ENGINE = resolve(import.meta.dirname, "..", "..");
24
24
  const manifest = readJsonFile(join(ENGINE, "package.json"));
25
25
  /** The version of this engine: what its helpers print, so what a report holds, may change from one to the next. */
26
26
  export const ENGINE_VERSION = isRecord(manifest) ? String(manifest.version) : "";
27
- /** What a tool runs with: no colour, which some tools print anyway. */
28
- export const TOOL_ENV = { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0" };
27
+ /**
28
+ * What a tool of a repo runs with: no colour, which some tools print anyway, and the commands of its node_modules
29
+ * first on the PATH, as npx and the package managers run them, so that a tool finds the Node the repo pins.
30
+ */
31
+ export function toolEnv(root: string): NodeJS.ProcessEnv {
32
+ const path = [join(root, "node_modules", ".bin"), ...(process.env.PATH ? [process.env.PATH] : [])];
33
+ return { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0", PATH: path.join(delimiter) };
34
+ }
35
+
36
+ /** The Node a script of the repo or of its packages runs on: the one the repo pins in its node_modules, as npx finds it, or the one of the engine. */
37
+ function repoNode(root: string): string {
38
+ const pinned = join(root, "node_modules", ".bin", "node");
39
+ return executable(pinned) ? pinned : process.execPath;
40
+ }
29
41
  const MAX_OUTPUT_MB = 16;
30
42
  const ENGINE_PREFIX = "{engine}/";
31
43
 
@@ -43,9 +55,9 @@ export interface Command {
43
55
  }
44
56
 
45
57
  // A script of the repo runs on the interpreter of its extension.
46
- const INTERPRETERS: [RegExp, string][] = [
47
- [/\.(ts|js|mjs)$/, process.execPath],
48
- [/\.py$/, "python3"],
58
+ const INTERPRETERS: [RegExp, (root: string) => string][] = [
59
+ [/\.(ts|js|mjs)$/, repoNode],
60
+ [/\.py$/, () => "python3"],
49
61
  ];
50
62
 
51
63
  /** The script of a package of the repo's node_modules, or nothing when the repo does not have the package. */
@@ -69,7 +81,7 @@ export function commandOf(root: string, name: string): Command {
69
81
  if (name.startsWith(ENGINE_PREFIX)) {
70
82
  return { file: process.execPath, args: [engineScript(name.slice(ENGINE_PREFIX.length))], missing: "" };
71
83
  }
72
- const interpreter = INTERPRETERS.find(([extension]) => extension.test(name))?.[1];
84
+ const interpreter = INTERPRETERS.find(([extension]) => extension.test(name))?.[1](root);
73
85
  if (interpreter !== undefined) {
74
86
  return {
75
87
  file: interpreter,
@@ -78,7 +90,7 @@ export function commandOf(root: string, name: string): Command {
78
90
  };
79
91
  }
80
92
  const script = packageScript(root, name);
81
- if (script !== undefined) return { file: process.execPath, args: [script], missing: "" };
93
+ if (script !== undefined) return { file: repoNode(root), args: [script], missing: "" };
82
94
  if (name.includes("/")) return { file: resolve(root, name), args: [], missing: `${name} does not exist.` };
83
95
  return {
84
96
  file: name,
@@ -88,10 +100,8 @@ export function commandOf(root: string, name: string): Command {
88
100
  }
89
101
 
90
102
  // A program by its path, or by its name on the PATH, that the system would execute.
91
- function executable(file: string): boolean {
92
- const candidates = isAbsolute(file)
93
- ? [file]
94
- : (process.env.PATH ?? "").split(delimiter).map((dir) => join(dir, file));
103
+ function executable(file: string, path = process.env.PATH ?? ""): boolean {
104
+ const candidates = isAbsolute(file) ? [file] : path.split(delimiter).map((dir) => join(dir, file));
95
105
  return candidates.some((candidate) => {
96
106
  try {
97
107
  accessSync(candidate, constants.X_OK);
@@ -109,7 +119,7 @@ function missingProgram(root: string, name: string): string | undefined {
109
119
  } catch {
110
120
  return undefined;
111
121
  }
112
- return command.missing && !executable(command.file) ? command.missing : undefined;
122
+ return command.missing && !executable(command.file, toolEnv(root).PATH) ? command.missing : undefined;
113
123
  }
114
124
 
115
125
  /**
@@ -134,13 +144,45 @@ export function filesOf(gate: Gate, changed: string[]): string[] {
134
144
  return changed.filter((file) => pattern.test(file));
135
145
  }
136
146
 
137
- export function newLines(before: string, after: string, ignore?: string): string[] {
147
+ /**
148
+ * The lines of output a turn added, less the ignored ones. With a key, a line is told by the part the key matches. A
149
+ * line of a new key is still an old one, each line of the turn start whose key went standing for one line only: first
150
+ * when it says the same as such a line, that problem reported elsewhere, unless the group of the key named file names
151
+ * a file the turn changed, where the agent may have written it; then when the first group of the key, its place, is
152
+ * the one of such a line, that problem changed where it is.
153
+ */
154
+ export function newLines(
155
+ before: string,
156
+ after: string,
157
+ ignore?: string,
158
+ key?: string,
159
+ changed: string[] = [],
160
+ ): string[] {
138
161
  const ignored = ignore === undefined ? undefined : new RegExp(ignore);
139
- const seen = new Set(before.split("\n").map((line) => line.trim()));
140
- return after
141
- .split("\n")
142
- .map((line) => line.trim())
143
- .filter((line) => line && !seen.has(line) && !ignored?.test(line));
162
+ const keyed = key === undefined ? undefined : new RegExp(key);
163
+ const lines = (text: string) =>
164
+ text
165
+ .split("\n")
166
+ .map((line) => line.trim())
167
+ .filter(Boolean);
168
+ const keyOf = (line: string) => keyed?.exec(line)?.[0] ?? line;
169
+ const placeOf = (line: string) => keyed?.exec(line)?.[1];
170
+ const written = (line: string) => changed.includes(keyed?.exec(line)?.groups?.file ?? "");
171
+ const restOf = (line: string) => line.replace(keyOf(line), "").trim();
172
+ const old = lines(before);
173
+ const now = lines(after);
174
+ const oldKeys = new Set(old.map(keyOf));
175
+ const nowKeys = new Set(now.map(keyOf));
176
+ const gone = old.filter((line) => !nowKeys.has(keyOf(line)));
177
+ const stillOld = (same: (was: string) => boolean) => {
178
+ const at = gone.findIndex(same);
179
+ if (at !== -1) gone.splice(at, 1);
180
+ return at !== -1;
181
+ };
182
+ return now
183
+ .filter((line) => !oldKeys.has(keyOf(line)) && !ignored?.test(line))
184
+ .filter((line) => !restOf(line) || written(line) || !stillOld((was) => restOf(was) === restOf(line)))
185
+ .filter((line) => placeOf(line) === undefined || !stillOld((was) => placeOf(was) === placeOf(line)));
144
186
  }
145
187
 
146
188
  interface Executed {
@@ -168,7 +210,7 @@ async function execute(root: string, gate: Gate, args: string[]): Promise<Execut
168
210
  cwd: root,
169
211
  timeout: gate.timeoutSeconds * 1000,
170
212
  maxBuffer: MAX_OUTPUT_MB * 1024 * 1024,
171
- env: TOOL_ENV,
213
+ env: toolEnv(root),
172
214
  },
173
215
  (error, stdout, stderr) => {
174
216
  resolve({
@@ -204,9 +246,18 @@ export function cleaned(root: string, printed: string): string {
204
246
  return stripVTControlCharacters(printed).split(`${root}${sep}`).join("").trim();
205
247
  }
206
248
 
207
- /** Runs a compared gate on the whole project, as the turn starts. */
208
- export function wholeProject(root: string, gate: Gate): Promise<{ ok: boolean; output: string }> {
209
- return execute(root, gate, gate.run.slice(1));
249
+ /**
250
+ * Runs a compared gate on the whole project, as the turn starts, in the time the gate has or less: nothing when it
251
+ * runs out of it, since its lines would all be new at the stop.
252
+ */
253
+ export async function wholeProject(
254
+ root: string,
255
+ gate: Gate,
256
+ ms = gate.timeoutSeconds * 1000,
257
+ ): Promise<{ ok: boolean; output?: string }> {
258
+ const timeoutSeconds = Math.min(gate.timeoutSeconds, ms / 1000);
259
+ const { ok, output, timedOut } = await execute(root, { ...gate, timeoutSeconds }, gate.run.slice(1));
260
+ return timedOut ? { ok: false } : { ok, output };
210
261
  }
211
262
 
212
263
  /**
@@ -224,15 +275,20 @@ export async function check(
224
275
  const ran = { name: gate.name, ms, report: ok ? output : undefined };
225
276
  if (timedOut) return { ...ran, ok, output, timedOut };
226
277
  if (!isCompared(gate) || !ok) return { ...ran, ok, output };
227
- return { ...ran, ...addedLines(gate, output, baseline) };
278
+ return { ...ran, ...addedLines(gate, output, baseline, files) };
228
279
  }
229
280
 
230
281
  /**
231
282
  * Judges the output of a compared gate that ran clean: it fails on the lines the turn added to the report of the turn
232
283
  * start. Without that report, nothing counts but the exit code.
233
284
  */
234
- export function addedLines(gate: Gate, output: string, baseline: string | undefined): { ok: boolean; output: string } {
285
+ export function addedLines(
286
+ gate: Gate,
287
+ output: string,
288
+ baseline: string | undefined,
289
+ changed: string[],
290
+ ): { ok: boolean; output: string } {
235
291
  if (baseline === undefined) return { ok: true, output: "" };
236
- const added = newLines(baseline, output, gate.ignoreLines);
292
+ const added = newLines(baseline, output, gate.ignoreLines, gate.lineKey, changed);
237
293
  return { ok: added.length === 0, output: added.join("\n") };
238
294
  }
package/src/core/watch.ts CHANGED
@@ -16,7 +16,7 @@ import { dirname, join } from "node:path";
16
16
  import { createInterface } from "node:readline";
17
17
  import { setTimeout as sleep } from "node:timers/promises";
18
18
  import { type Gate, isCompared, type Watch, type WatchedGate } from "./config.ts";
19
- import { addedLines, cleaned, commandOf, ENGINE_VERSION, type Outcome, TOOL_ENV } from "./run.ts";
19
+ import { addedLines, cleaned, commandOf, ENGINE_VERSION, type Outcome, toolEnv } from "./run.ts";
20
20
 
21
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
22
  const QUIET_MS = 1000;
@@ -26,8 +26,8 @@ const UNSEEN_MS = 5000;
26
26
  const POLL_MS = 100;
27
27
  // What a watch that stopped leaves the agent: enough to see the error, not the whole history of the session.
28
28
  const LAST_LINES = 20;
29
- // A prompt waits this long at most for a compared watch to settle, under the 60 s its hook has.
30
- const TURN_START_MS = 45_000;
29
+ // A prompt waits this long at most for the reports of its compared gates, under the 60 s its hook has.
30
+ export const TURN_START_MS = 45_000;
31
31
 
32
32
  const PREFIX = "gates-watch-";
33
33
  // A start that holds its lock longer than this died on the way: the next hook takes the lock over.
@@ -132,7 +132,7 @@ function launch(folder: string, root: string, watch: Watch): void {
132
132
  cwd: root,
133
133
  detached: true,
134
134
  stdio: ["ignore", log, log],
135
- env: TOOL_ENV,
135
+ env: toolEnv(root),
136
136
  });
137
137
  closeSync(log);
138
138
  child.on("error", () => {});
@@ -240,7 +240,7 @@ export async function judgeWatch(
240
240
  const { cycle } = settled;
241
241
  const fails = new RegExp(gate.watch.failed ?? "(?!)");
242
242
  const judged = isCompared(gate)
243
- ? addedLines(gate, cycle, baseline)
243
+ ? addedLines(gate, cycle, baseline, files)
244
244
  : { ok: !cycle.split("\n").some((line) => fails.test(line)), output: cycle };
245
245
  return { name, ms, ...judged, report: judged.ok ? cycle : undefined };
246
246
  }
@@ -5,26 +5,44 @@ import { commandOf } from "../core/run.ts";
5
5
  import { COUNTS, HEADER } from "./vitest-state-reporter.ts";
6
6
 
7
7
  // The watch of an Angular project tested with Vitest: ng test in watch mode, with the reporter of the engine that
8
- // prints the state of every spec at each run, and NG_TEST_LOG, which makes Angular say when a run ends. A change that
9
- // leaves the build as it was reruns no spec, so no state prints: the last one is printed again, so that the cycle
10
- // still tells which specs are red.
8
+ // prints the state of every spec at each run, and NG_TEST_LOG, which makes Angular say when a run ends. It prints
9
+ // only what judges a run: the build also prints the files it built, a table longer than the report of the specs in a
10
+ // large project, whose names change at each build.
11
11
 
12
12
  const NO_RERUN = /No test specifications to rerun/;
13
+ const KEPT = [/Changes detected\. Rebuilding/, /bundle generation failed/, NO_RERUN];
14
+ const ENDS = /Test run finished with success/;
15
+ // Angular says why a run ended, and says all tests passed of a run with failed specs.
16
+ const REASON = /\s*Reason: .*$/;
17
+ const ERROR = /^\S+ \[ERROR\] /;
18
+ // What a watch that stopped leaves, so that a crash still says why.
19
+ const LAST_LINES = 20;
13
20
 
14
21
  /**
15
- * What to print for each line of the watch: the line, and before a run that reruns no spec, the last state of the
16
- * specs, so that the cycle still tells which specs are red.
22
+ * What to print for each line of ng test: the lines that open a run, the state of the specs, the errors of a build
23
+ * that failed, with the lines under each, and the line that ends a run, less its reason. A change that leaves the
24
+ * build as it was reruns no spec, so no state prints: the last one is printed again, so that the cycle still tells
25
+ * which specs are red.
17
26
  */
18
- export function replaying(): (line: string) => string[] {
27
+ export function reporting(): (line: string) => string[] {
19
28
  let state: string[] = [];
20
29
  let reading: string[] | undefined;
30
+ let inError = false;
21
31
  return (line) => {
22
32
  if (line === HEADER) reading = [];
23
- reading?.push(line);
24
- if (reading !== undefined && line.startsWith(COUNTS)) {
25
- state = reading;
26
- reading = undefined;
33
+ if (reading !== undefined) {
34
+ reading.push(line);
35
+ if (line.startsWith(COUNTS)) {
36
+ state = reading;
37
+ reading = undefined;
38
+ }
39
+ return [line];
27
40
  }
41
+ if (ERROR.test(line)) inError = true;
42
+ else if (line.trim() && !/^\s/.test(line)) inError = false;
43
+ if (inError) return [line];
44
+ if (ENDS.test(line)) return [line.replace(REASON, "")];
45
+ if (!KEPT.some((kept) => kept.test(line))) return [];
28
46
  return NO_RERUN.test(line) ? [...state, line] : [line];
29
47
  };
30
48
  }
@@ -40,11 +58,19 @@ function main(root: string, args: string[]): void {
40
58
  env: { ...process.env, NG_TEST_LOG: "1" },
41
59
  stdio: ["ignore", "pipe", "pipe"],
42
60
  });
43
- const replay = replaying();
44
- const forward = (line: string) => console.log(replay(line).join("\n"));
61
+ const report = reporting();
62
+ const last: string[] = [];
63
+ const forward = (line: string) => {
64
+ last.push(line);
65
+ if (last.length > LAST_LINES) last.shift();
66
+ for (const shown of report(line)) console.log(shown);
67
+ };
45
68
  createInterface({ input: watch.stdout }).on("line", forward);
46
69
  createInterface({ input: watch.stderr }).on("line", forward);
47
- watch.on("exit", (code) => process.exit(code ?? 1));
70
+ watch.on("exit", (code) => {
71
+ console.log(["ng test stopped. Its last lines:", ...last].join("\n"));
72
+ process.exit(code ?? 1);
73
+ });
48
74
  }
49
75
 
50
76
  if (import.meta.main) main(process.cwd(), process.argv.slice(2));
@@ -1,111 +1,63 @@
1
1
  import { spawn } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { resolve } from "node:path";
2
4
  import { createInterface } from "node:readline";
3
5
  import { checkingTsc } from "./tsc.ts";
4
6
 
5
7
  // tsc, with the options it is given, such as strict ones a project turned off, printing its errors so that a gate can
6
- // compare them with the ones of the turn start: one line per error, with its file and none of its line and column, so
7
- // an error a change moves down is not new, and a count after an error its file already has, so one more of it is.
8
- // tsc orders the members of a union as it happened to create them, which differs between the first compilation of a
9
- // watch and the next ones: each union prints sorted, untruncated, and without the lines under the error, which name its
10
- // first failing member, so the same error always prints the same.
8
+ // compare them with the ones of the turn start. tsc prints the same error otherwise from one compilation to the next:
9
+ // a watch checks again only the files a change reaches, with types created in another order, so the members of a
10
+ // union, the properties of an object, and the file of an error tsc reports once per type, all change. Each error is
11
+ // then one line: a key the gate compares, its file, code and source line, so an error a change moves down is not new,
12
+ // with a count after one its file already has on the same source, so one more of it is; then, after a tab, the first
13
+ // line of its message, for the agent alone.
11
14
  // With --watch, tsc keeps watching, and each compilation prints between a line that starts it and one that ends it.
12
15
 
13
16
  const STARTS = /Starting (compilation in watch mode|incremental compilation)/;
14
17
  const ENDS = /Found \d+ errors?\. Watching for file changes/;
15
- const POSITION = /^(.+)\(\d+,\d+\): (error TS\d+: .*)$/;
18
+ const POSITION = /^(.+)\((\d+),\d+\): error (TS\d+): (.*)$/;
19
+ const MESSAGE_CHARS = 300;
20
+ const SOURCE_CHARS = 200;
16
21
 
17
- const OPENS: Record<string, string> = { "(": ")", "[": "]", "{": "}", "<": ">" };
18
- // A property, parameter or index signature before its type, in an object, a tuple or a parameter list.
19
- const LABEL = /^((?:\.\.\.)?(?:[\w$]+|"[^"]*"|\[[^\]]*\])\??: )(.*)$/s;
22
+ /** The text of a file of the project, or nothing when it cannot be read. */
23
+ export type Sources = (file: string) => string | undefined;
20
24
 
21
- /** Where the bracket or the string that starts at index ends, or the index itself for any other character. */
22
- function skipped(text: string, index: number): number {
23
- const char = text[index] ?? "";
24
- if (char === '"' || char === "`") {
25
- let end = index + 1;
26
- while (end < text.length && text[end] !== char) end += text[end] === "\\" ? 2 : 1;
27
- return end;
28
- }
29
- const close = OPENS[char];
30
- if (close === undefined) return index;
31
- let end = index + 1;
32
- // The arrow of a function type closes no bracket.
33
- while (end < text.length && text[end] !== close) end = text.startsWith("=>", end) ? end + 2 : skipped(text, end) + 1;
34
- return end;
35
- }
36
-
37
- /** The parts of a text between a separator that no bracket nor string encloses. */
38
- function split(text: string, separator: string): string[] {
39
- const parts: string[] = [];
40
- let start = 0;
41
- for (let index = 0; index < text.length; index = skipped(text, index) + 1) {
42
- if (text.startsWith("=>", index)) index++;
43
- else if (text.startsWith(separator, index)) {
44
- parts.push(text.slice(start, index));
45
- start = index + separator.length;
46
- index += separator.length - 1;
47
- }
48
- }
49
- return [...parts, text.slice(start)];
50
- }
51
-
52
- /** A type as tsc prints it, with the members of each union and intersection sorted, at every depth. */
53
- function sortedType(type: string): string {
54
- // A function type outside any bracket returns all the rest: a union of function types puts each in parentheses.
55
- const [parameters = "", ...returned] = split(type, " => ");
56
- if (returned.length) return `${sortedInside(parameters)} => ${sortedType(returned.join(" => "))}`;
57
- const sorted = (members: string[]) => (members.length > 1 ? members.sort() : members);
58
- const union = split(type, " | ").map((member) => sorted(split(member, " & ").map(sortedInside)).join(" & "));
59
- return sorted(union).join(" | ");
60
- }
61
-
62
- /** A type with the content of each of its brackets sorted. */
63
- function sortedInside(type: string): string {
64
- let out = "";
65
- for (let index = 0; index < type.length;) {
66
- const end = skipped(type, index);
67
- const char = type[index] ?? "";
68
- if (OPENS[char] !== undefined) {
69
- const separator = char === "{" ? ";" : ",";
70
- const inner = split(type.slice(index + 1, end), separator).map((element) => {
71
- const [, before = "", trimmed = "", after = ""] = /^(\s*)(.*?)(\s*)$/s.exec(element) ?? [];
72
- const label = LABEL.exec(trimmed);
73
- return before + (label ? `${label[1]}${sortedType(label[2] ?? "")}` : sortedType(trimmed)) + after;
74
- });
75
- out += `${char}${inner.join(separator)}${type[end] ?? ""}`;
76
- } else out += type.slice(index, end + 1);
77
- index = end + 1;
78
- }
79
- return out;
25
+ function cut(text: string, chars: number): string {
26
+ return text.length > chars ? `${text.slice(0, chars)}…` : text;
80
27
  }
81
28
 
82
29
  /** The errors tsc printed, each on one line, as the gate compares them. */
83
- export function typeErrors(printed: string[]): string[] {
30
+ export function typeErrors(printed: string[], sources: Sources): string[] {
31
+ const lines = new Map<string, string[]>();
32
+ const sourceLine = (file: string, line: number) => {
33
+ if (!lines.has(file)) lines.set(file, (sources(file) ?? "").split("\n"));
34
+ return (lines.get(file)?.[line - 1] ?? "").replaceAll("\t", " ").trim();
35
+ };
36
+ const seen = new Map<string, number>();
84
37
  const errors: string[] = [];
85
38
  for (const line of printed) {
86
39
  // The lines under an error explain it, and name its first failing member.
87
40
  if (!line.trim() || /^\s/.test(line)) continue;
88
- const located = line.replace(POSITION, "$1: $2");
89
- // tsc quotes each type it names.
90
- errors.push(located.replace(/'([^']*)'/g, (_quoted, type: string) => `'${sortedType(type)}'`));
41
+ const [, file, at, code, message = ""] = POSITION.exec(line) ?? [];
42
+ const found =
43
+ file === undefined ? line : `${file}: error ${code} at \`${cut(sourceLine(file, Number(at)), SOURCE_CHARS)}\``;
44
+ const count = (seen.get(found) ?? 0) + 1;
45
+ seen.set(found, count);
46
+ const key = count === 1 ? found : `${found} (${count})`;
47
+ errors.push(file === undefined ? key : `${key}\t${cut(message, MESSAGE_CHARS)}`);
91
48
  }
92
- const seen = new Map<string, number>();
93
- return errors.map((error) => {
94
- const count = (seen.get(error) ?? 0) + 1;
95
- seen.set(error, count);
96
- return count === 1 ? error : `${error} (${count})`;
97
- });
49
+ return errors;
98
50
  }
99
51
 
100
52
  /** What to print for each line of tsc in watch mode: nothing until a compilation ends, then its errors. */
101
- export function watching(): (line: string) => string[] {
53
+ export function watching(sources: Sources): (line: string) => string[] {
102
54
  let compiled: string[] = [];
103
55
  return (line) => {
104
56
  if (STARTS.test(line)) {
105
57
  compiled = [];
106
58
  return ["Type check started"];
107
59
  }
108
- if (ENDS.test(line)) return [...typeErrors(compiled), "Type check done"];
60
+ if (ENDS.test(line)) return [...typeErrors(compiled, sources), "Type check done"];
109
61
  compiled.push(line);
110
62
  return [];
111
63
  };
@@ -114,17 +66,17 @@ export function watching(): (line: string) => string[] {
114
66
  function main(root: string, args: string[]): void {
115
67
  const tsc = checkingTsc(root, args);
116
68
  const watch = args.includes("--watch");
117
- const options = [
118
- "--noEmit",
119
- "--pretty",
120
- "false",
121
- "--noErrorTruncation",
122
- ...(watch ? ["--preserveWatchOutput"] : []),
123
- ...args,
124
- ];
69
+ const options = ["--noEmit", "--pretty", "false", ...(watch ? ["--preserveWatchOutput"] : []), ...args];
125
70
  const child = spawn(tsc.file, [...tsc.args, ...options], { stdio: ["ignore", "pipe", "inherit"] });
126
71
  const printed: string[] = [];
127
- const print = watching();
72
+ const sources: Sources = (file) => {
73
+ try {
74
+ return readFileSync(resolve(root, file), "utf8");
75
+ } catch {
76
+ return undefined;
77
+ }
78
+ };
79
+ const print = watching(sources);
128
80
  createInterface({ input: child.stdout }).on("line", (line) => {
129
81
  if (watch) for (const shown of print(line)) console.log(shown);
130
82
  else printed.push(line);
@@ -135,7 +87,7 @@ function main(root: string, args: string[]): void {
135
87
  console.log(printed.join("\n"));
136
88
  process.exit(code ?? 1);
137
89
  }
138
- console.log(typeErrors(printed).join("\n"));
90
+ console.log(typeErrors(printed, sources).join("\n"));
139
91
  });
140
92
  }
141
93