@tayomi/deterministic-gates 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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.0"
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.0",
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.0",
4
4
  "description": "Deterministic backpressure for coding agents: gates that run on what each turn changed and send the agent back until they pass.",
5
5
  "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 in another file with the same message, 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;^(.+?: 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 in another file with the same message, 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": "^(.+?: error TS\\d+) at [^\\t]*",
112
113
  "watch": {
113
114
  "run": [
114
115
  "{engine}/src/helpers/type-errors.ts",
@@ -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
  }
@@ -110,13 +110,37 @@ export function filesOf(gate, changed) {
110
110
  const pattern = new RegExp(gate.files);
111
111
  return changed.filter((file) => pattern.test(file));
112
112
  }
113
- export function newLines(before, after, ignore) {
113
+ /**
114
+ * 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
115
+ * 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
116
+ * when it says the same as such a line, that problem reported elsewhere; then when the first group of the key, its
117
+ * place, is the one of such a line, that problem changed where it is.
118
+ */
119
+ export function newLines(before, after, ignore, key) {
114
120
  const ignored = ignore === undefined ? undefined : new RegExp(ignore);
115
- const seen = new Set(before.split("\n").map((line) => line.trim()));
116
- return after
121
+ const keyed = key === undefined ? undefined : new RegExp(key);
122
+ const lines = (text) => text
117
123
  .split("\n")
118
124
  .map((line) => line.trim())
119
- .filter((line) => line && !seen.has(line) && !ignored?.test(line));
125
+ .filter(Boolean);
126
+ const keyOf = (line) => keyed?.exec(line)?.[0] ?? line;
127
+ const placeOf = (line) => keyed?.exec(line)?.[1];
128
+ const restOf = (line) => line.replace(keyOf(line), "").trim();
129
+ const old = lines(before);
130
+ const now = lines(after);
131
+ const oldKeys = new Set(old.map(keyOf));
132
+ const nowKeys = new Set(now.map(keyOf));
133
+ const gone = old.filter((line) => !nowKeys.has(keyOf(line)));
134
+ const stillOld = (same) => {
135
+ const at = gone.findIndex(same);
136
+ if (at !== -1)
137
+ gone.splice(at, 1);
138
+ return at !== -1;
139
+ };
140
+ return now
141
+ .filter((line) => !oldKeys.has(keyOf(line)) && !ignored?.test(line))
142
+ .filter((line) => !restOf(line) || !stillOld((was) => restOf(was) === restOf(line)))
143
+ .filter((line) => placeOf(line) === undefined || !stillOld((was) => placeOf(was) === placeOf(line)));
120
144
  }
121
145
  async function execute(root, gate, args) {
122
146
  const started = performance.now();
@@ -185,6 +209,6 @@ export async function check(root, gate, files, turn, baseline) {
185
209
  export function addedLines(gate, output, baseline) {
186
210
  if (baseline === undefined)
187
211
  return { ok: true, output: "" };
188
- const added = newLines(baseline, output, gate.ignoreLines);
212
+ const added = newLines(baseline, output, gate.ignoreLines, gate.lineKey);
189
213
  return { ok: added.length === 0, output: added.join("\n") };
190
214
  }
@@ -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.0",
4
4
  "description": "Deterministic backpressure for coding agents: gates that run on what each turn changed and send the agent back until they pass.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -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
@@ -134,13 +134,37 @@ export function filesOf(gate: Gate, changed: string[]): string[] {
134
134
  return changed.filter((file) => pattern.test(file));
135
135
  }
136
136
 
137
- export function newLines(before: string, after: string, ignore?: string): string[] {
137
+ /**
138
+ * 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
139
+ * 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
140
+ * when it says the same as such a line, that problem reported elsewhere; then when the first group of the key, its
141
+ * place, is the one of such a line, that problem changed where it is.
142
+ */
143
+ export function newLines(before: string, after: string, ignore?: string, key?: string): string[] {
138
144
  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));
145
+ const keyed = key === undefined ? undefined : new RegExp(key);
146
+ const lines = (text: string) =>
147
+ text
148
+ .split("\n")
149
+ .map((line) => line.trim())
150
+ .filter(Boolean);
151
+ const keyOf = (line: string) => keyed?.exec(line)?.[0] ?? line;
152
+ const placeOf = (line: string) => keyed?.exec(line)?.[1];
153
+ const restOf = (line: string) => line.replace(keyOf(line), "").trim();
154
+ const old = lines(before);
155
+ const now = lines(after);
156
+ const oldKeys = new Set(old.map(keyOf));
157
+ const nowKeys = new Set(now.map(keyOf));
158
+ const gone = old.filter((line) => !nowKeys.has(keyOf(line)));
159
+ const stillOld = (same: (was: string) => boolean) => {
160
+ const at = gone.findIndex(same);
161
+ if (at !== -1) gone.splice(at, 1);
162
+ return at !== -1;
163
+ };
164
+ return now
165
+ .filter((line) => !oldKeys.has(keyOf(line)) && !ignored?.test(line))
166
+ .filter((line) => !restOf(line) || !stillOld((was) => restOf(was) === restOf(line)))
167
+ .filter((line) => placeOf(line) === undefined || !stillOld((was) => placeOf(was) === placeOf(line)));
144
168
  }
145
169
 
146
170
  interface Executed {
@@ -233,6 +257,6 @@ export async function check(
233
257
  */
234
258
  export function addedLines(gate: Gate, output: string, baseline: string | undefined): { ok: boolean; output: string } {
235
259
  if (baseline === undefined) return { ok: true, output: "" };
236
- const added = newLines(baseline, output, gate.ignoreLines);
260
+ const added = newLines(baseline, output, gate.ignoreLines, gate.lineKey);
237
261
  return { ok: added.length === 0, output: added.join("\n") };
238
262
  }
@@ -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