@tayomi/deterministic-gates 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,28 +19,36 @@ const SOURCE_CHARS = 200;
19
19
  function cut(text, chars) {
20
20
  return text.length > chars ? `${text.slice(0, chars)}…` : text;
21
21
  }
22
+ /**
23
+ * The errors, each on one line: a key, its file, code and source line, with a count after one its file already has
24
+ * on the same source; then, after a tab, the first line of its message. An error of no file is kept as it is.
25
+ */
26
+ export function strictErrorLines(errors) {
27
+ const seen = new Map();
28
+ return errors.map((error) => {
29
+ const source = typeof error === "string" ? "" : error.source.replaceAll("\t", " ").trim();
30
+ const found = typeof error === "string" ? error : `${error.file}: error ${error.code} at \`${cut(source, SOURCE_CHARS)}\``;
31
+ const count = (seen.get(found) ?? 0) + 1;
32
+ seen.set(found, count);
33
+ const key = count === 1 ? found : `${found} (${count})`;
34
+ return typeof error === "string" ? key : `${key}\t${cut(error.message, MESSAGE_CHARS)}`;
35
+ });
36
+ }
22
37
  /** The errors tsc printed, each on one line, as the gate compares them. */
23
38
  export function typeErrors(printed, sources) {
24
39
  const lines = new Map();
25
40
  const sourceLine = (file, line) => {
26
41
  if (!lines.has(file))
27
42
  lines.set(file, (sources(file) ?? "").split("\n"));
28
- return (lines.get(file)?.[line - 1] ?? "").replaceAll("\t", " ").trim();
43
+ return lines.get(file)?.[line - 1] ?? "";
29
44
  };
30
- const seen = new Map();
31
- const errors = [];
32
- for (const line of printed) {
45
+ return strictErrorLines(printed
33
46
  // The lines under an error explain it, and name its first failing member.
34
- if (!line.trim() || /^\s/.test(line))
35
- continue;
36
- const [, file, at, code, message = ""] = POSITION.exec(line) ?? [];
37
- const found = file === undefined ? line : `${file}: error ${code} at \`${cut(sourceLine(file, Number(at)), SOURCE_CHARS)}\``;
38
- const count = (seen.get(found) ?? 0) + 1;
39
- seen.set(found, count);
40
- const key = count === 1 ? found : `${found} (${count})`;
41
- errors.push(file === undefined ? key : `${key}\t${cut(message, MESSAGE_CHARS)}`);
42
- }
43
- return errors;
47
+ .filter((line) => line.trim() && !/^\s/.test(line))
48
+ .map((line) => {
49
+ const [, file, at, code = "", message = ""] = POSITION.exec(line) ?? [];
50
+ return file === undefined ? line : { file, code, source: sourceLine(file, Number(at)), message };
51
+ }));
44
52
  }
45
53
  /** What to print for each line of tsc in watch mode: nothing until a compilation ends, then its errors. */
46
54
  export function watching(sources) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tayomi/deterministic-gates",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Deterministic backpressure for coding agents: gates that run on what each turn changed and send the agent back until they pass.",
5
5
  "type": "module",
6
6
  "license": "MIT",
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
  }),
@@ -1,5 +1,5 @@
1
1
  import { existsSync, readFileSync } from "node:fs";
2
- import { join } from "node:path";
2
+ import { isAbsolute, join } from "node:path";
3
3
  import { isRecord, isStringArray, messageOf } from "./json.ts";
4
4
  import { repoRoot } from "./snapshot.ts";
5
5
 
@@ -21,7 +21,7 @@ const FIELDS = new Set([
21
21
  "timeoutSeconds",
22
22
  "watch",
23
23
  ]);
24
- const WATCH_FIELDS = new Set(["run", "cycleStart", "cycleEnd", "failed"]);
24
+ const WATCH_FIELDS = new Set(["run", "cycleStart", "cycleEnd", "failed", "sync", "frozen"]);
25
25
 
26
26
  /** In the arguments of a gate: the changed files it looks at, and the commit of the turn start. */
27
27
  export const FILES = "{files}";
@@ -50,6 +50,10 @@ export interface Watch {
50
50
  cycleEnd: string;
51
51
  /** Absent on a compared gate, which fails on the lines the last cycle added to the one the turn started on. */
52
52
  failed?: string;
53
+ /** A file of the repo the watch opens a cycle for each time its date changes, such as the tsconfig it reads. */
54
+ sync: string;
55
+ /** The files the watch lists once as it starts, and never again, such as the specs of ng test. */
56
+ frozen?: string;
53
57
  }
54
58
 
55
59
  /** A gate that keeps a watch. */
@@ -147,18 +151,24 @@ function isPattern(value: unknown): value is string {
147
151
  }
148
152
 
149
153
  function toWatch(watch: unknown, compared: boolean): Watch {
150
- if (!isRecord(watch)) return refuse("watch holds run, cycleStart, cycleEnd and failed");
154
+ if (!isRecord(watch)) return refuse("watch holds run, cycleStart, cycleEnd, failed and sync");
151
155
  const unknown = Object.keys(watch).find((key) => !WATCH_FIELDS.has(key));
152
156
  if (unknown !== undefined) refuse(`unknown field watch.${unknown}`);
153
- const { run, cycleStart, cycleEnd, failed } = watch;
157
+ const { run, cycleStart, cycleEnd, failed, sync, frozen } = watch;
154
158
  if (!isStringArray(run) || !run.length) refuse("watch.run is a non-empty list of strings");
155
159
  if (run.some((argument) => argument.includes(FILES) || argument.includes(TURN)))
156
160
  refuse(`a watch outlives the turn: its run takes neither ${FILES} nor ${TURN}`);
157
161
  const pattern = (field: string, value: unknown): string =>
158
162
  isPattern(value) ? value : refuse(`watch.${field} is a regular expression on a line of its output`);
159
163
  if (compared && failed !== undefined) refuse("a compared watch fails on the lines its cycle added: no watch.failed");
164
+ if (typeof sync !== "string" || !sync || isAbsolute(sync) || sync.split(/[\\/]/).includes(".."))
165
+ refuse("watch.sync is a file of the repo the watch opens a cycle for when its date changes, such as its tsconfig");
166
+ if (frozen !== undefined && !isPattern(frozen))
167
+ refuse("watch.frozen is a regular expression on the files the watch lists only as it starts");
160
168
  return {
161
169
  run,
170
+ sync,
171
+ ...(frozen === undefined ? {} : { frozen }),
162
172
  cycleStart: pattern("cycleStart", cycleStart),
163
173
  cycleEnd: pattern("cycleEnd", cycleEnd),
164
174
  ...(compared ? {} : { failed: pattern("failed", failed) }),
package/src/core/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
  /**
@@ -137,10 +147,17 @@ export function filesOf(gate: Gate, changed: string[]): string[] {
137
147
  /**
138
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
139
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
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.
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.
142
153
  */
143
- export function newLines(before: string, after: string, ignore?: string, key?: string): string[] {
154
+ export function newLines(
155
+ before: string,
156
+ after: string,
157
+ ignore?: string,
158
+ key?: string,
159
+ changed: string[] = [],
160
+ ): string[] {
144
161
  const ignored = ignore === undefined ? undefined : new RegExp(ignore);
145
162
  const keyed = key === undefined ? undefined : new RegExp(key);
146
163
  const lines = (text: string) =>
@@ -150,6 +167,7 @@ export function newLines(before: string, after: string, ignore?: string, key?: s
150
167
  .filter(Boolean);
151
168
  const keyOf = (line: string) => keyed?.exec(line)?.[0] ?? line;
152
169
  const placeOf = (line: string) => keyed?.exec(line)?.[1];
170
+ const written = (line: string) => changed.includes(keyed?.exec(line)?.groups?.file ?? "");
153
171
  const restOf = (line: string) => line.replace(keyOf(line), "").trim();
154
172
  const old = lines(before);
155
173
  const now = lines(after);
@@ -163,7 +181,7 @@ export function newLines(before: string, after: string, ignore?: string, key?: s
163
181
  };
164
182
  return now
165
183
  .filter((line) => !oldKeys.has(keyOf(line)) && !ignored?.test(line))
166
- .filter((line) => !restOf(line) || !stillOld((was) => restOf(was) === restOf(line)))
184
+ .filter((line) => !restOf(line) || written(line) || !stillOld((was) => restOf(was) === restOf(line)))
167
185
  .filter((line) => placeOf(line) === undefined || !stillOld((was) => placeOf(was) === placeOf(line)));
168
186
  }
169
187
 
@@ -192,7 +210,7 @@ async function execute(root: string, gate: Gate, args: string[]): Promise<Execut
192
210
  cwd: root,
193
211
  timeout: gate.timeoutSeconds * 1000,
194
212
  maxBuffer: MAX_OUTPUT_MB * 1024 * 1024,
195
- env: TOOL_ENV,
213
+ env: toolEnv(root),
196
214
  },
197
215
  (error, stdout, stderr) => {
198
216
  resolve({
@@ -228,9 +246,18 @@ export function cleaned(root: string, printed: string): string {
228
246
  return stripVTControlCharacters(printed).split(`${root}${sep}`).join("").trim();
229
247
  }
230
248
 
231
- /** Runs a compared gate on the whole project, as the turn starts. */
232
- export function wholeProject(root: string, gate: Gate): Promise<{ ok: boolean; output: string }> {
233
- 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 };
234
261
  }
235
262
 
236
263
  /**
@@ -248,15 +275,20 @@ export async function check(
248
275
  const ran = { name: gate.name, ms, report: ok ? output : undefined };
249
276
  if (timedOut) return { ...ran, ok, output, timedOut };
250
277
  if (!isCompared(gate) || !ok) return { ...ran, ok, output };
251
- return { ...ran, ...addedLines(gate, output, baseline) };
278
+ return { ...ran, ...addedLines(gate, output, baseline, files) };
252
279
  }
253
280
 
254
281
  /**
255
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
256
283
  * start. Without that report, nothing counts but the exit code.
257
284
  */
258
- 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 } {
259
291
  if (baseline === undefined) return { ok: true, output: "" };
260
- const added = newLines(baseline, output, gate.ignoreLines, gate.lineKey);
292
+ const added = newLines(baseline, output, gate.ignoreLines, gate.lineKey, changed);
261
293
  return { ok: added.length === 0, output: added.join("\n") };
262
294
  }