@tayomi/deterministic-gates 0.10.1 → 0.12.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.10.1"
12
+ "version": "0.12.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.10.1",
4
+ "version": "0.12.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.10.1",
3
+ "version": "0.12.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",
package/catalog/go.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "title": "Go",
3
- "description": "Gates for a Go module. The toolchain comes from the PATH. The first build of a cold cache is slow, which is why these gates allow 60 seconds.",
3
+ "description": "Gates for a Go module, or for a repo of several. The build, vet, test and lint gates run in each module the turn touched, from the folder of its go.mod, so a monorepo with no module at its root needs nothing more. In a module too large to read whole when the agent stops, write {dirs} in place of ./... to aim a gate at the folders the turn touched. The toolchain comes from the PATH. The first build of a cold cache is slow, which is why these gates allow 60 seconds.",
4
4
  "gates": [
5
5
  {
6
- "description": "Builds every package of the module.",
6
+ "description": "Builds every package of each module the turn touched.",
7
7
  "requires": [
8
8
  {
9
9
  "tool": "go",
@@ -14,11 +14,12 @@
14
14
  "name": "build",
15
15
  "severity": "error",
16
16
  "files": "(\\.go|(^|/)go\\.(mod|sum))$",
17
+ "each": "go.mod",
17
18
  "run": ["go", "build", "./..."]
18
19
  }
19
20
  },
20
21
  {
21
- "description": "Runs go vet on every package: the suspicious constructs the compiler accepts.",
22
+ "description": "Runs go vet on every package of each module the turn touched: the suspicious constructs the compiler accepts.",
22
23
  "requires": [
23
24
  {
24
25
  "tool": "go",
@@ -29,6 +30,7 @@
29
30
  "name": "vet",
30
31
  "severity": "error",
31
32
  "files": "(\\.go|(^|/)go\\.(mod|sum))$",
33
+ "each": "go.mod",
32
34
  "run": ["go", "vet", "./..."]
33
35
  }
34
36
  },
@@ -49,7 +51,7 @@
49
51
  }
50
52
  },
51
53
  {
52
- "description": "Runs the tests of every package. Go caches the result of a package that did not change, so only the packages the turn touched run again.",
54
+ "description": "Runs the tests of every package of each module the turn touched. Go caches the result of a package that did not change, so only the packages the turn touched run again.",
53
55
  "requires": [
54
56
  {
55
57
  "tool": "go",
@@ -60,11 +62,12 @@
60
62
  "name": "test",
61
63
  "severity": "error",
62
64
  "files": "(\\.go|(^|/)go\\.(mod|sum))$",
65
+ "each": "go.mod",
63
66
  "run": ["go", "test", "./..."]
64
67
  }
65
68
  },
66
69
  {
67
- "description": "Lints with golangci-lint, and reports only the issues created since the turn started (--new-from-rev).",
70
+ "description": "Lints each module the turn touched with golangci-lint, and reports only the issues created since the turn started (--new-from-rev).",
68
71
  "requires": [
69
72
  {
70
73
  "tool": "golangci-lint",
@@ -75,6 +78,7 @@
75
78
  "name": "lint",
76
79
  "severity": "error",
77
80
  "files": "\\.go$",
81
+ "each": "go.mod",
78
82
  "run": ["golangci-lint", "run", "--new-from-rev", "{turn}"]
79
83
  }
80
84
  },
@@ -170,10 +170,10 @@ summary { cursor: pointer; color: var(--muted); }
170
170
  </section>
171
171
  <section id="go">
172
172
  <h2>Go</h2>
173
- <p>Gates for a Go module. The toolchain comes from the PATH. The first build of a cold cache is slow, which is why these gates allow 60 seconds.</p>
173
+ <p>Gates for a Go module, or for a repo of several. The build, vet, test and lint gates run in each module the turn touched, from the folder of its go.mod, so a monorepo with no module at its root needs nothing more. In a module too large to read whole when the agent stops, write {dirs} in place of ./... to aim a gate at the folders the turn touched. The toolchain comes from the PATH. The first build of a cold cache is slow, which is why these gates allow 60 seconds.</p>
174
174
  <article id="go/build">
175
175
  <h3><code>go/build</code></h3>
176
- <p>Builds every package of the module.</p>
176
+ <p>Builds every package of each module the turn touched.</p>
177
177
  <dl>
178
178
  <dt>Runs</dt><dd><code>go build ./...</code></dd>
179
179
  <dt>When the turn changes</dt><dd><code>(\.go|(^|/)go\.(mod|sum))$</code></dd>
@@ -183,6 +183,7 @@ summary { cursor: pointer; color: var(--muted); }
183
183
  &quot;name&quot;: &quot;build&quot;,
184
184
  &quot;severity&quot;: &quot;error&quot;,
185
185
  &quot;files&quot;: &quot;(\\.go|(^|/)go\\.(mod|sum))$&quot;,
186
+ &quot;each&quot;: &quot;go.mod&quot;,
186
187
  &quot;run&quot;: [
187
188
  &quot;go&quot;,
188
189
  &quot;build&quot;,
@@ -192,7 +193,7 @@ summary { cursor: pointer; color: var(--muted); }
192
193
  </article>
193
194
  <article id="go/vet">
194
195
  <h3><code>go/vet</code></h3>
195
- <p>Runs go vet on every package: the suspicious constructs the compiler accepts.</p>
196
+ <p>Runs go vet on every package of each module the turn touched: the suspicious constructs the compiler accepts.</p>
196
197
  <dl>
197
198
  <dt>Runs</dt><dd><code>go vet ./...</code></dd>
198
199
  <dt>When the turn changes</dt><dd><code>(\.go|(^|/)go\.(mod|sum))$</code></dd>
@@ -202,6 +203,7 @@ summary { cursor: pointer; color: var(--muted); }
202
203
  &quot;name&quot;: &quot;vet&quot;,
203
204
  &quot;severity&quot;: &quot;error&quot;,
204
205
  &quot;files&quot;: &quot;(\\.go|(^|/)go\\.(mod|sum))$&quot;,
206
+ &quot;each&quot;: &quot;go.mod&quot;,
205
207
  &quot;run&quot;: [
206
208
  &quot;go&quot;,
207
209
  &quot;vet&quot;,
@@ -231,7 +233,7 @@ summary { cursor: pointer; color: var(--muted); }
231
233
  </article>
232
234
  <article id="go/test">
233
235
  <h3><code>go/test</code></h3>
234
- <p>Runs the tests of every package. Go caches the result of a package that did not change, so only the packages the turn touched run again.</p>
236
+ <p>Runs the tests of every package of each module the turn touched. Go caches the result of a package that did not change, so only the packages the turn touched run again.</p>
235
237
  <dl>
236
238
  <dt>Runs</dt><dd><code>go test ./...</code></dd>
237
239
  <dt>When the turn changes</dt><dd><code>(\.go|(^|/)go\.(mod|sum))$</code></dd>
@@ -241,6 +243,7 @@ summary { cursor: pointer; color: var(--muted); }
241
243
  &quot;name&quot;: &quot;test&quot;,
242
244
  &quot;severity&quot;: &quot;error&quot;,
243
245
  &quot;files&quot;: &quot;(\\.go|(^|/)go\\.(mod|sum))$&quot;,
246
+ &quot;each&quot;: &quot;go.mod&quot;,
244
247
  &quot;run&quot;: [
245
248
  &quot;go&quot;,
246
249
  &quot;test&quot;,
@@ -250,7 +253,7 @@ summary { cursor: pointer; color: var(--muted); }
250
253
  </article>
251
254
  <article id="go/lint">
252
255
  <h3><code>go/lint</code></h3>
253
- <p>Lints with golangci-lint, and reports only the issues created since the turn started (--new-from-rev).</p>
256
+ <p>Lints each module the turn touched with golangci-lint, and reports only the issues created since the turn started (--new-from-rev).</p>
254
257
  <dl>
255
258
  <dt>Runs</dt><dd><code>golangci-lint run --new-from-rev {turn}</code></dd>
256
259
  <dt>When the turn changes</dt><dd><code>\.go$</code></dd>
@@ -260,6 +263,7 @@ summary { cursor: pointer; color: var(--muted); }
260
263
  &quot;name&quot;: &quot;lint&quot;,
261
264
  &quot;severity&quot;: &quot;error&quot;,
262
265
  &quot;files&quot;: &quot;\\.go$&quot;,
266
+ &quot;each&quot;: &quot;go.mod&quot;,
263
267
  &quot;run&quot;: [
264
268
  &quot;golangci-lint&quot;,
265
269
  &quot;run&quot;,
package/dist/src/cli.js CHANGED
@@ -4,7 +4,6 @@ import { checkAll } from "./core/check.js";
4
4
  import { configuredRoot } from "./core/config.js";
5
5
  import { messageOf } from "./core/json.js";
6
6
  import { broken, reports, results, summary } from "./core/report.js";
7
- import { failed } from "./core/run.js";
8
7
  import { HOOK_EVENTS, handleHook, isHookEvent } from "./hook/hook.js";
9
8
  function readStdin() {
10
9
  try {
@@ -48,7 +47,8 @@ async function main([command, ...words]) {
48
47
  try {
49
48
  const all = await checkAll(root);
50
49
  console.log(json ? JSON.stringify(results(all), null, 2) : [summary(all), ...reports(all)].join("\n\n"));
51
- if (all.outcomes.some(failed))
50
+ // A gate out of time judged nothing: a CI never passes on it.
51
+ if (!all.outcomes.every(({ ok }) => ok))
52
52
  process.exitCode = 1;
53
53
  }
54
54
  catch (error) {
@@ -3,7 +3,8 @@ import { join } from "node:path";
3
3
  import { changedGatesFiles, gatesOf, isCompared, keepsWatch, readGatesFiles, } from "./config.js";
4
4
  import { headOf, movedSince, observed, thereOf } from "./head.js";
5
5
  import { cachedReports, cacheReports } from "./report-cache.js";
6
- import { check, filesOf, givenFiles, missingTool, namesFiles, wholeProject } from "./run.js";
6
+ import { dirsOf, projectsOf } from "./projects.js";
7
+ import { check, checkEach, filesOf, givenDirs, givenFiles, missingTool, namesFiles, wholeProject, } from "./run.js";
7
8
  import { changedSince, emptyCommit, hasCommit, lastCommit, sharedDir, snapshot, workingTree } from "./snapshot.js";
8
9
  import { readThere, readTurn, writeThere, writeTurn } from "./turn-state.js";
9
10
  import { judgeWatch, keepWatch, startWatch, TURN_START_MS, watchReport } from "./watch.js";
@@ -79,20 +80,41 @@ export async function startTurn(session, root) {
79
80
  /**
80
81
  * Runs, in parallel, each gate that looks at a changed file. A deleted file counts as changed, since a gate that
81
82
  * reads the whole project may break on it, but is never named: a gate given {files} looks at the files left, and
82
- * is skipped when none is. At the end of a turn of a session, a gate that keeps a watch is judged on it instead of
83
- * running. Elsewhere, the reports of the turn start are of code HEAD has left since.
83
+ * is skipped when none is. A gate given {dirs} looks at the folders of the changed files that are left, the folder
84
+ * of a deleted file among them, and is skipped when none is. At the end of a turn of a session, a gate that keeps a watch is judged on it instead of
85
+ * running. Elsewhere, the reports of the turn start are of code HEAD has left since. A gate that runs in each
86
+ * project looks at the files that have one, and is skipped when none has.
84
87
  */
85
88
  function runGates(root, gates, changed, turn, baselines, session, elsewhere = false) {
86
89
  return Promise.all(gates.map(async (gate) => {
87
90
  const matching = filesOf(gate, changed);
91
+ if (gate.each !== undefined) {
92
+ const projects = projectsIn(root, gate, gate.each, matching);
93
+ if (!projects.length)
94
+ return { gate };
95
+ // At the stop, someone waits: the time of the gate is for all its projects together.
96
+ return { gate, outcome: await checkEach(root, gate, projects, turn, session !== undefined) };
97
+ }
88
98
  const files = givenFiles(gate) ? matching.filter((file) => existsSync(join(root, file))) : matching;
89
- if (!files.length)
99
+ const dirs = givenDirs(gate) ? dirsOf(root, matching) : undefined;
100
+ if (!files.length || dirs?.length === 0)
90
101
  return { gate };
91
102
  if (session !== undefined && keepsWatch(gate))
92
103
  return { gate, outcome: await judgeWatch(session, root, gate, matching, baselines(gate), elsewhere) };
93
- return { gate, outcome: await check(root, gate, files, turn, baselines(gate), elsewhere) };
104
+ return { gate, outcome: await check(root, gate, files, turn, baselines(gate), elsewhere, dirs) };
94
105
  }));
95
106
  }
107
+ // The projects a gate runs in: a gate given {files} looks at the files left, a gate given {dirs} at the folders
108
+ // left, and either leaves out a project with none.
109
+ function projectsIn(root, gate, marker, matching) {
110
+ return projectsOf(root, marker, matching)
111
+ .map(({ dir, files }) => ({
112
+ dir,
113
+ files: givenFiles(gate) ? files.filter((file) => existsSync(join(root, dir, file))) : files,
114
+ ...(givenDirs(gate) ? { dirs: dirsOf(join(root, dir), files) } : {}),
115
+ }))
116
+ .filter(({ files, dirs }) => files.length && dirs?.length !== 0);
117
+ }
96
118
  function checkedTurn(changed, results, started, notes, { gates, prompts, maxTotalReportChars, showAllPasses }) {
97
119
  return {
98
120
  changed,
@@ -25,11 +25,15 @@ const FIELDS = new Set([
25
25
  "maxReportChars",
26
26
  "omitLines",
27
27
  "brokenExitCodes",
28
+ "each",
28
29
  ]);
29
30
  const WATCH_FIELDS = new Set(["run", "cycleStart", "cycleEnd", "failed", "sync", "frozen"]);
30
31
  /** In the arguments of a gate: the changed files it looks at, and the commit of the turn start. */
31
32
  export const FILES = "{files}";
33
+ export const DIRS = "{dirs}";
32
34
  export const TURN = "{turn}";
35
+ /** Before the first word of a command: a script of this engine, where another word names one of the repo. */
36
+ export const ENGINE_PREFIX = "{engine}/";
33
37
  /**
34
38
  * What the engine tells the agent that a repo may word again: as it sends it back, as it asks for missing tools, and
35
39
  * with the report of a gate the turn broke.
@@ -157,8 +161,8 @@ function toWatch(watch, compared) {
157
161
  const { run, cycleStart, cycleEnd, failed, sync, frozen } = watch;
158
162
  if (!isStringArray(run) || !run.length)
159
163
  refuse("watch.run is a non-empty list of strings");
160
- if (run.some((argument) => argument.includes(FILES) || argument.includes(TURN)))
161
- refuse(`a watch outlives the turn: its run takes neither ${FILES} nor ${TURN}`);
164
+ if (run.some((argument) => [FILES, DIRS, TURN].some((token) => argument.includes(token))))
165
+ refuse(`a watch outlives the turn: its run takes none of ${FILES}, ${DIRS} and ${TURN}`);
162
166
  const pattern = (field, value) => isPattern(value) ? value : refuse(`watch.${field} is a regular expression on a line of its output`);
163
167
  if (compared && failed !== undefined)
164
168
  refuse("a compared watch fails on the lines its cycle added: no watch.failed");
@@ -176,7 +180,7 @@ function toWatch(watch, compared) {
176
180
  };
177
181
  }
178
182
  function toGate(entry, maxTimeoutSeconds, reportChars) {
179
- const { name, severity, files, run, compare, ignoreLines, lineKey, watch, prompt, omitLines, brokenExitCodes, timeoutSeconds = maxTimeoutSeconds, maxReportChars = reportChars, } = entry;
183
+ const { name, severity, files, run, compare, ignoreLines, lineKey, watch, prompt, omitLines, brokenExitCodes, each, timeoutSeconds = maxTimeoutSeconds, maxReportChars = reportChars, } = entry;
180
184
  const unknown = Object.keys(entry).find((key) => !FIELDS.has(key));
181
185
  if (unknown !== undefined)
182
186
  refuse(`unknown field ${unknown}`);
@@ -190,8 +194,9 @@ function toGate(entry, maxTimeoutSeconds, reportChars) {
190
194
  refuse("run is a non-empty list of strings");
191
195
  if (compare !== undefined && compare !== "turn-start")
192
196
  refuse('compare is "turn-start"');
193
- if (compare !== undefined && run.includes(FILES))
194
- refuse(`a compared gate reads the whole project: it takes no ${FILES}`);
197
+ const narrowed = [FILES, DIRS].find((token) => run.includes(token));
198
+ if (compare !== undefined && narrowed !== undefined)
199
+ refuse(`a compared gate reads the whole project: it takes no ${narrowed}`);
195
200
  if (ignoreLines !== undefined && !isPattern(ignoreLines))
196
201
  refuse("ignoreLines is a regular expression");
197
202
  if (lineKey !== undefined && !isPattern(lineKey))
@@ -206,6 +211,17 @@ function toGate(entry, maxTimeoutSeconds, reportChars) {
206
211
  refuse("omitLines is a regular expression");
207
212
  if (brokenExitCodes !== undefined && !isExitCodes(brokenExitCodes))
208
213
  refuse("brokenExitCodes is a list of exit codes, each a whole number from 1 to 255");
214
+ if (each !== undefined) {
215
+ if (typeof each !== "string" || !each || each === "." || each === ".." || /[\\/]/.test(each))
216
+ refuse("each is the name of the file that marks a project, such as go.mod: a name, not a path");
217
+ if (compare !== undefined)
218
+ refuse("a compared gate reports on the whole repo as the turn starts, before its projects are known: it takes no each");
219
+ if (watch !== undefined)
220
+ refuse("a watch is kept for the whole repo, not for each project: it takes no each");
221
+ // Such a script takes the folder it runs in for the root of the repo: in a project, it would read nothing.
222
+ if (run[0]?.startsWith(ENGINE_PREFIX))
223
+ refuse("a script of the engine reads the repo from its root: it takes no each");
224
+ }
209
225
  const told = prompt === undefined ? undefined : (toPrompt(prompt) ?? refuse(`prompt is ${PROMPT_SHAPE}`));
210
226
  return {
211
227
  name,
@@ -222,6 +238,7 @@ function toGate(entry, maxTimeoutSeconds, reportChars) {
222
238
  ...(maxReportChars === undefined ? {} : { maxReportChars }),
223
239
  ...(omitLines === undefined ? {} : { omitLines }),
224
240
  ...(brokenExitCodes === undefined ? {} : { brokenExitCodes }),
241
+ ...(each === undefined ? {} : { each }),
225
242
  };
226
243
  }
227
244
  /**
@@ -0,0 +1,43 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ const ROOT = ".";
4
+ /**
5
+ * Groups the repo-relative files a gate looks at by project: the nearest folder above each, up to the root of the
6
+ * repo and never past it, that holds the marker now. A file with no marker above it is of no project, which is what
7
+ * leaves out the folders a gate has nothing to do in. A deleted file is looked up from the folder it was in.
8
+ */
9
+ export function projectsOf(root, marker, files) {
10
+ const holds = new Map();
11
+ const holdsMarker = (dir) => {
12
+ if (!holds.has(dir))
13
+ holds.set(dir, existsSync(join(root, dir, marker)));
14
+ return holds.get(dir) === true;
15
+ };
16
+ const projects = new Map();
17
+ for (const file of files) {
18
+ const folders = file.split("/").slice(0, -1);
19
+ // From the folder of the file up to the root, which no folder names.
20
+ const above = folders.map((_, depth) => folders.slice(0, folders.length - depth).join("/"));
21
+ const dir = [...above, ROOT].find(holdsMarker);
22
+ if (dir === undefined)
23
+ continue;
24
+ const inProject = dir === ROOT ? file : file.slice(dir.length + 1);
25
+ projects.set(dir, [...(projects.get(dir) ?? []), inProject]);
26
+ }
27
+ return [...projects]
28
+ .map(([dir, inProject]) => ({ dir, files: inProject }))
29
+ .sort((a, b) => (a.dir < b.dir ? -1 : a.dir > b.dir ? 1 : 0));
30
+ }
31
+ /**
32
+ * The folders of the files, each once and sorted, as a tool that runs in `base` is to be given them: with ./ in
33
+ * front, which a tool such as go needs to read a folder and not an import path, and a dot for `base` itself. A
34
+ * deleted file counts for its folder, since what is left there may break on it, but a folder that is gone is left
35
+ * out. A folder inside another stands next to it: what joins the two is for the tool to know.
36
+ */
37
+ export function dirsOf(base, files) {
38
+ const dirs = new Set(files.map((file) => file.split("/").slice(0, -1).join("/")));
39
+ return [...dirs]
40
+ .filter((dir) => existsSync(join(base, dir)))
41
+ .sort()
42
+ .map((dir) => (dir ? `./${dir}` : ROOT));
43
+ }
@@ -1,4 +1,4 @@
1
- import { failed } from "./run.js";
1
+ import { failed, notJudged, underFolder } from "./run.js";
2
2
  import { WAIVE_TAG } from "./waive-line.js";
3
3
  const LABEL = "● gates";
4
4
  const SHOWN_PASSES = 6;
@@ -35,8 +35,12 @@ export function excerpt(report, max = REPORT_CHARS) {
35
35
  export function duration(ms) {
36
36
  return ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`;
37
37
  }
38
+ // The gate, with the projects it concerns when it runs in each: one line whatever their number.
39
+ function named({ name, projects = [] }) {
40
+ return projects.length ? `${name} [${projects.join(", ")}]` : name;
41
+ }
38
42
  function gateLine(mark, outcome) {
39
- return `${mark} ${outcome.name} ${paint("dim", duration(outcome.ms))}`;
43
+ return `${mark} ${named(outcome)} ${paint("dim", duration(outcome.ms))}`;
40
44
  }
41
45
  function skippedLine(skipped) {
42
46
  return paint("dim", `${skipped.map((name) => `- ${name}`).join(" ")} · no matching file changed`);
@@ -53,7 +57,7 @@ function nothingChecked({ changed, skipped }, after) {
53
57
  // The gate in orange, then the reason the agent gave, under a star.
54
58
  function waivedLines(outcome, reason) {
55
59
  return [
56
- `${paint("warn", `${WARNING} ${outcome.name}`)} ${paint("dim", duration(outcome.ms))}`,
60
+ `${paint("warn", `${WARNING} ${named(outcome)}`)} ${paint("dim", duration(outcome.ms))}`,
57
61
  ` ${paint("warn", "*")} ${reason}`,
58
62
  ];
59
63
  }
@@ -188,20 +192,32 @@ export function toolsToInstall(missing, prompt) {
188
192
  /**
189
193
  * The report of each failed gate, under its name, how to act on one the turn broke, and the prompt of the repo for it:
190
194
  * less the lines the gate omits, each line a helper counts apart said once, in the characters it has, and in its share of a total when the reports have one.
195
+ * A gate that failed in several projects shares its characters between their blocks the same way, each under its
196
+ * folder, then names the projects it ran out of time for.
191
197
  */
192
198
  export function reports({ outcomes, wording = {} }) {
193
199
  const { gates = [], prompts, maxTotalReportChars = Infinity } = wording;
194
- const red = outcomes.filter(failed).map(({ name, output, broken }) => {
200
+ const all = outcomes.filter(failed);
201
+ const red = all.map(({ name, output, broken, blocks = [{ dir: ".", output }] }) => {
195
202
  const gate = gates.find((known) => known.name === name);
196
- const report = saidOnce(sent(output, gate?.omitLines));
203
+ const said = blocks.map((block) => ({ ...block, output: saidOnce(sent(block.output, gate?.omitLines)) }));
197
204
  const told = [
198
205
  ...(broken ? [worded(BROKEN_GATE, prompts?.brokenGate, "\n")] : []),
199
206
  ...(gate?.prompt ? [gate.prompt.text] : []),
200
207
  ];
201
- return { name, told, report, needs: Math.min(report.length, gate?.maxReportChars ?? REPORT_CHARS) };
208
+ const length = said.reduce((sum, block) => sum + block.output.length, 0);
209
+ return { name, told, said, needs: Math.min(length, gate?.maxReportChars ?? REPORT_CHARS) };
202
210
  });
203
211
  const given = shares(red.map(({ needs }) => needs), maxTotalReportChars);
204
- return red.map(({ name, told, report }, at) => [`## ${name}`, ...told, excerpt(report, given[at])].join("\n"));
212
+ return red.map(({ name, told, said }, at) => {
213
+ const each = shares(said.map((block) => block.output.length), given[at] ?? 0);
214
+ const { unjudged = [] } = all[at] ?? {};
215
+ const report = [
216
+ ...said.map((block, of) => underFolder({ ...block, output: excerpt(block.output, each[of]) })),
217
+ ...(unjudged.length ? [notJudged(unjudged)] : []),
218
+ ];
219
+ return [`## ${name}`, ...told, report.join("\n\n")].join("\n");
220
+ });
205
221
  }
206
222
  /**
207
223
  * What the agent gets when it is sent back: how to act on a failure, in the words of the engine or of the repo, how
@@ -221,12 +237,13 @@ function gateResult({ name, ok, ms, output, timedOut, broken }) {
221
237
  }
222
238
  /**
223
239
  * A check for a tool to read, such as a CI or a script, where the summary is for its owner and the send-back for the
224
- * agent: whether it passed, each gate with its status and its whole report, and the notes of the check.
240
+ * agent: whether it passed, which a gate out of time keeps it from, each gate with its status and its whole report, and
241
+ * the notes of the check.
225
242
  */
226
243
  export function results({ outcomes, skipped, ms, note }) {
227
244
  const gates = [
228
245
  ...outcomes.map(gateResult),
229
246
  ...skipped.map((name) => ({ name, status: "skipped" })),
230
247
  ];
231
- return { ok: !outcomes.some(failed), durationMs: Math.round(ms), gates, notes: note ? note.split("\n") : [] };
248
+ return { ok: outcomes.every(({ ok }) => ok), durationMs: Math.round(ms), gates, notes: note ? note.split("\n") : [] };
232
249
  }
@@ -1,8 +1,9 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { accessSync, constants, existsSync } from "node:fs";
3
+ import { availableParallelism } from "node:os";
3
4
  import { delimiter, isAbsolute, join, resolve, sep } from "node:path";
4
5
  import { stripVTControlCharacters } from "node:util";
5
- import { FILES, isCompared, TURN } from "./config.js";
6
+ import { DIRS, ENGINE_PREFIX, FILES, isCompared, TURN } from "./config.js";
6
7
  import { isRecord, messageOf, readJsonFile } from "./json.js";
7
8
  /** A gate that judged the turn and found a problem, or that broke: the only kinds that send the agent back. */
8
9
  export function failed(outcome) {
@@ -32,7 +33,6 @@ export function headed(own, lines, env = process.env) {
32
33
  return [...(env[PROMPT_REPLACED] ? [] : [own]), ...lines].join("\n");
33
34
  }
34
35
  const MAX_OUTPUT_MB = 16;
35
- const ENGINE_PREFIX = "{engine}/";
36
36
  /** A script of this engine: its .ts source, or the .js it is built to when the engine runs from its npm package. */
37
37
  function engineScript(name) {
38
38
  const file = resolve(ENGINE, name);
@@ -114,13 +114,23 @@ function missingProgram(root, name) {
114
114
  export function missingTool(root, gate) {
115
115
  return missingProgram(root, gate.run[0] ?? "") ?? (gate.watch && missingProgram(root, gate.watch.run[0] ?? ""));
116
116
  }
117
- export function argumentsOf(gate, files, turn) {
118
- return gate.run.slice(1).flatMap((argument) => (argument === FILES ? files : [argument.replaceAll(TURN, turn)]));
117
+ export function argumentsOf(gate, files, turn, dirs = []) {
118
+ return gate.run.slice(1).flatMap((argument) => {
119
+ if (argument === FILES)
120
+ return files;
121
+ if (argument === DIRS)
122
+ return dirs;
123
+ return [argument.replaceAll(TURN, turn)];
124
+ });
119
125
  }
120
126
  /** Whether the gate is given the changed files, where another reads the whole project. */
121
127
  export function givenFiles(gate) {
122
128
  return gate.run.includes(FILES);
123
129
  }
130
+ /** Whether the gate is given the folders of the changed files. */
131
+ export function givenDirs(gate) {
132
+ return gate.run.includes(DIRS);
133
+ }
124
134
  export function filesOf(gate, changed) {
125
135
  const pattern = new RegExp(gate.files);
126
136
  return changed.filter((file) => pattern.test(file));
@@ -159,7 +169,8 @@ export function newLines(before, after, ignore, key, changed = []) {
159
169
  .filter((line) => !restOf(line) || written(line) || !stillOld((was) => restOf(was) === restOf(line)))
160
170
  .filter((line) => placeOf(line) === undefined || !stillOld((was) => placeOf(was) === placeOf(line)));
161
171
  }
162
- async function execute(root, gate, args) {
172
+ /** Starts the command of a gate, found from the root of the repo, in the folder given: the root, or a project. */
173
+ async function execute(root, gate, args, cwd = root) {
163
174
  const started = performance.now();
164
175
  const [name = ""] = gate.run;
165
176
  // A gate that cannot start fails alone: the other gates of the turn still report.
@@ -178,14 +189,15 @@ async function execute(root, gate, args) {
178
189
  }
179
190
  return new Promise((resolve) => {
180
191
  execFile(command.file, [...command.args, ...args], {
181
- cwd: root,
182
- timeout: gate.timeoutSeconds * 1000,
192
+ cwd,
193
+ // In whole milliseconds, as Node wants them: what is left of a shared time is not.
194
+ timeout: Math.ceil(gate.timeoutSeconds * 1000),
183
195
  maxBuffer: MAX_OUTPUT_MB * 1024 * 1024,
184
196
  env: { ...toolEnv(root), ...(gate.prompt?.replace ? { [PROMPT_REPLACED]: "1" } : {}) },
185
197
  }, (error, stdout, stderr) => {
186
198
  resolve({
187
199
  ok: !error,
188
- output: outputOf(root, gate, command, error, `${stdout}${stderr}`),
200
+ output: outputOf(root, gate, command, error, `${stdout}${stderr}`, cwd),
189
201
  ms: performance.now() - started,
190
202
  timedOut: error?.killed === true && error.code !== "ERR_CHILD_PROCESS_STDIO_MAXBUFFER",
191
203
  cannotStart: error?.code === "ENOENT",
@@ -194,21 +206,26 @@ async function execute(root, gate, args) {
194
206
  });
195
207
  });
196
208
  }
197
- function outputOf(root, gate, command, error, printed) {
209
+ function outputOf(root, gate, command, error, printed, cwd) {
198
210
  if (error?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER")
199
211
  return `Printed more than ${MAX_OUTPUT_MB} MB: too much for the end of a turn. Make it quieter, or move it to CI.`;
200
212
  if (error?.killed === true)
201
- return `Out of time after ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
213
+ return outOfTime(gate);
202
214
  if (error?.code === "ENOENT")
203
215
  return command.missing;
204
- const said = cleaned(root, printed);
216
+ const said = cleaned(root, printed, cwd);
205
217
  if (said || !error)
206
218
  return said;
207
219
  return `exit code ${String(error.code)}, no output`;
208
220
  }
209
- /** What a tool printed, for the agent: some tools colour despite NO_COLOR, and absolute paths only cost it tokens. */
210
- export function cleaned(root, printed) {
211
- return stripVTControlCharacters(printed).split(`${root}${sep}`).join("").trim();
221
+ /**
222
+ * What a tool printed, for the agent: some tools colour despite NO_COLOR, and absolute paths only cost it tokens. A
223
+ * tool that ran in a project loses the path of that folder first, so its files read as the relative paths it prints.
224
+ */
225
+ export function cleaned(root, printed, cwd = root) {
226
+ return [cwd, root]
227
+ .reduce((text, dir) => text.split(`${dir}${sep}`).join(""), stripVTControlCharacters(printed))
228
+ .trim();
212
229
  }
213
230
  /**
214
231
  * Runs a compared gate on the whole project, as the turn starts, in the time the gate has or less: nothing when it
@@ -232,19 +249,96 @@ export function namesFiles(gate) {
232
249
  * code but 0: the same crash at the start and at the end of a turn prints no new line. Another gate is broken on the
233
250
  * exit codes it names as such. A gate out of time is neither.
234
251
  */
235
- export async function check(root, gate, files, turn, baseline, elsewhere = false) {
236
- const executed = await execute(root, gate, argumentsOf(gate, files, turn));
252
+ export async function check(root, gate, files, turn, baseline, elsewhere = false, dirs = []) {
253
+ const outcome = await ranIn(root, gate, files, turn, dirs);
254
+ if (!outcome.ok || !isCompared(gate))
255
+ return outcome;
256
+ return { ...outcome, ...addedLines(gate, outcome.output, baseline, files, elsewhere) };
257
+ }
258
+ /** What the command of a gate says of the files given, run once in a folder: by its exit code alone. */
259
+ async function ranIn(root, gate, files, turn, dirs = [], cwd = root) {
260
+ const executed = await execute(root, gate, argumentsOf(gate, files, turn, dirs), cwd);
237
261
  const { ok, output, ms, timedOut, cannotStart, exitCode = 0 } = executed;
238
262
  const ran = { name: gate.name, ms, report: ok ? output : undefined };
239
263
  if (timedOut)
240
264
  return { ...ran, ok, output, timedOut };
241
265
  // A compared gate exits with 0 when it finds problems: any other code is its command that broke.
242
266
  const broke = cannotStart || isCompared(gate) || gate.brokenExitCodes?.includes(exitCode);
243
- if (!ok && broke)
244
- return { ...ran, ok, output, broken: true };
245
- if (!isCompared(gate) || !ok)
246
- return { ...ran, ok, output };
247
- return { ...ran, ...addedLines(gate, output, baseline, files, elsewhere) };
267
+ return { ...ran, ok, output, ...(!ok && broke ? { broken: true } : {}) };
268
+ }
269
+ const ROOT = ".";
270
+ /** What a project said, under its folder: a tool prints its paths from where it runs. The root needs no telling. */
271
+ export function underFolder({ dir, output }) {
272
+ return dir === ROOT ? output : `in ${dir}, paths relative to it:\n${output}`;
273
+ }
274
+ /** What a failed gate says last of the projects it ran out of time for. */
275
+ export function notJudged(dirs) {
276
+ return `out of time, so not judged: ${dirs.join(", ")}`;
277
+ }
278
+ function outOfTime(gate) {
279
+ return `Out of time after ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
280
+ }
281
+ // Runs a task on each item, at most so many at once, and gives what they returned in the order of the items.
282
+ async function pooled(items, limit, run) {
283
+ const results = [];
284
+ let next = 0;
285
+ const worker = async () => {
286
+ for (let at = next++; at < items.length; at = next++)
287
+ results[at] = await run(items[at]);
288
+ };
289
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
290
+ return results;
291
+ }
292
+ /**
293
+ * Runs a gate once in each project given, from the folder of the project, and gives one outcome for them all: the
294
+ * gate stays one gate, with one name to report under and to waive. It is red when a project failed, with the report
295
+ * of each failed project under its folder, broken when one broke, and out of time when none failed and one ran out
296
+ * of it. As many projects run at once as the machine has cores: a build takes them all by itself. With a shared
297
+ * time, as at the stop, the time of the gate is for all its projects, and one whose turn comes too late is not
298
+ * started; otherwise each has it whole.
299
+ */
300
+ export async function checkEach(root, gate, projects, turn, sharedTime = false) {
301
+ const started = performance.now();
302
+ const ran = await pooled(projects, availableParallelism(), async ({ dir, files, dirs }) => {
303
+ const left = sharedTime ? gate.timeoutSeconds - (performance.now() - started) / 1000 : gate.timeoutSeconds;
304
+ if (left <= 0)
305
+ return { dir, name: gate.name, ok: false, ms: 0, output: "", report: undefined, timedOut: true };
306
+ return { dir, ...(await ranIn(root, { ...gate, timeoutSeconds: left }, files, turn, dirs, join(root, dir))) };
307
+ });
308
+ const merged = { name: gate.name, ms: performance.now() - started, report: undefined };
309
+ const named = (outcomes) => outcomes.map(({ dir }) => dir).filter((dir) => dir !== ROOT);
310
+ const red = ran.filter(failed);
311
+ const late = ran.filter(({ timedOut }) => timedOut);
312
+ if (red.length) {
313
+ const blocks = red.map(({ dir, output }) => ({ dir, output }));
314
+ // The root is named here, where nothing else would say a project was left.
315
+ const unjudged = late.map(({ dir }) => dir);
316
+ return {
317
+ ...merged,
318
+ ok: false,
319
+ output: [...blocks.map(underFolder), ...(unjudged.length ? [notJudged(unjudged)] : [])].join("\n\n"),
320
+ blocks,
321
+ ...(red.some(({ broken }) => broken) ? { broken: true } : {}),
322
+ ...(named(red).length ? { projects: named(red) } : {}),
323
+ ...(unjudged.length ? { unjudged } : {}),
324
+ };
325
+ }
326
+ if (late.length)
327
+ return {
328
+ ...merged,
329
+ ok: false,
330
+ output: outOfTime(gate),
331
+ timedOut: true,
332
+ ...(named(late).length ? { projects: named(late) } : {}),
333
+ };
334
+ return {
335
+ ...merged,
336
+ ok: true,
337
+ output: ran
338
+ .map(({ output }) => output)
339
+ .filter(Boolean)
340
+ .join("\n"),
341
+ };
248
342
  }
249
343
  /**
250
344
  * Judges the output of a compared gate that ran clean: it fails on the lines the turn added to the report of the turn
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tayomi/deterministic-gates",
3
- "version": "0.10.1",
3
+ "version": "0.12.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/cli.ts CHANGED
@@ -4,7 +4,6 @@ import { checkAll } from "./core/check.ts";
4
4
  import { configuredRoot } from "./core/config.ts";
5
5
  import { messageOf } from "./core/json.ts";
6
6
  import { broken, reports, results, summary } from "./core/report.ts";
7
- import { failed } from "./core/run.ts";
8
7
  import { HOOK_EVENTS, handleHook, isHookEvent } from "./hook/hook.ts";
9
8
 
10
9
  function readStdin(): string {
@@ -47,7 +46,8 @@ async function main([command, ...words]: string[]): Promise<void> {
47
46
  try {
48
47
  const all = await checkAll(root);
49
48
  console.log(json ? JSON.stringify(results(all), null, 2) : [summary(all), ...reports(all)].join("\n\n"));
50
- if (all.outcomes.some(failed)) process.exitCode = 1;
49
+ // A gate out of time judged nothing: a CI never passes on it.
50
+ if (!all.outcomes.every(({ ok }) => ok)) process.exitCode = 1;
51
51
  } catch (error) {
52
52
  console.error(`Could not run: ${messageOf(error)}`);
53
53
  process.exitCode = 2;
package/src/core/check.ts CHANGED
@@ -12,7 +12,18 @@ import {
12
12
  } from "./config.ts";
13
13
  import { headOf, movedSince, observed, thereOf } from "./head.ts";
14
14
  import { cachedReports, cacheReports } from "./report-cache.ts";
15
- import { check, filesOf, givenFiles, missingTool, namesFiles, type Outcome, wholeProject } from "./run.ts";
15
+ import { dirsOf, type Project, projectsOf } from "./projects.ts";
16
+ import {
17
+ check,
18
+ checkEach,
19
+ filesOf,
20
+ givenDirs,
21
+ givenFiles,
22
+ missingTool,
23
+ namesFiles,
24
+ type Outcome,
25
+ wholeProject,
26
+ } from "./run.ts";
16
27
  import { changedSince, emptyCommit, hasCommit, lastCommit, sharedDir, snapshot, workingTree } from "./snapshot.ts";
17
28
  import { readThere, readTurn, type TurnState, writeThere, writeTurn } from "./turn-state.ts";
18
29
  import { judgeWatch, keepWatch, startWatch, TURN_START_MS, watchReport } from "./watch.ts";
@@ -131,8 +142,10 @@ export async function startTurn(session: string, root: string): Promise<string[]
131
142
  /**
132
143
  * Runs, in parallel, each gate that looks at a changed file. A deleted file counts as changed, since a gate that
133
144
  * reads the whole project may break on it, but is never named: a gate given {files} looks at the files left, and
134
- * is skipped when none is. At the end of a turn of a session, a gate that keeps a watch is judged on it instead of
135
- * running. Elsewhere, the reports of the turn start are of code HEAD has left since.
145
+ * is skipped when none is. A gate given {dirs} looks at the folders of the changed files that are left, the folder
146
+ * of a deleted file among them, and is skipped when none is. At the end of a turn of a session, a gate that keeps a watch is judged on it instead of
147
+ * running. Elsewhere, the reports of the turn start are of code HEAD has left since. A gate that runs in each
148
+ * project looks at the files that have one, and is skipped when none has.
136
149
  */
137
150
  function runGates(
138
151
  root: string,
@@ -146,15 +159,34 @@ function runGates(
146
159
  return Promise.all(
147
160
  gates.map(async (gate) => {
148
161
  const matching = filesOf(gate, changed);
162
+ if (gate.each !== undefined) {
163
+ const projects = projectsIn(root, gate, gate.each, matching);
164
+ if (!projects.length) return { gate };
165
+ // At the stop, someone waits: the time of the gate is for all its projects together.
166
+ return { gate, outcome: await checkEach(root, gate, projects, turn, session !== undefined) };
167
+ }
149
168
  const files = givenFiles(gate) ? matching.filter((file) => existsSync(join(root, file))) : matching;
150
- if (!files.length) return { gate };
169
+ const dirs = givenDirs(gate) ? dirsOf(root, matching) : undefined;
170
+ if (!files.length || dirs?.length === 0) return { gate };
151
171
  if (session !== undefined && keepsWatch(gate))
152
172
  return { gate, outcome: await judgeWatch(session, root, gate, matching, baselines(gate), elsewhere) };
153
- return { gate, outcome: await check(root, gate, files, turn, baselines(gate), elsewhere) };
173
+ return { gate, outcome: await check(root, gate, files, turn, baselines(gate), elsewhere, dirs) };
154
174
  }),
155
175
  );
156
176
  }
157
177
 
178
+ // The projects a gate runs in: a gate given {files} looks at the files left, a gate given {dirs} at the folders
179
+ // left, and either leaves out a project with none.
180
+ function projectsIn(root: string, gate: Gate, marker: string, matching: string[]): Project[] {
181
+ return projectsOf(root, marker, matching)
182
+ .map(({ dir, files }) => ({
183
+ dir,
184
+ files: givenFiles(gate) ? files.filter((file) => existsSync(join(root, dir, file))) : files,
185
+ ...(givenDirs(gate) ? { dirs: dirsOf(join(root, dir), files) } : {}),
186
+ }))
187
+ .filter(({ files, dirs }) => files.length && dirs?.length !== 0);
188
+ }
189
+
158
190
  function checkedTurn(
159
191
  changed: string[],
160
192
  results: Result[],
@@ -27,12 +27,16 @@ const FIELDS = new Set([
27
27
  "maxReportChars",
28
28
  "omitLines",
29
29
  "brokenExitCodes",
30
+ "each",
30
31
  ]);
31
32
  const WATCH_FIELDS = new Set(["run", "cycleStart", "cycleEnd", "failed", "sync", "frozen"]);
32
33
 
33
34
  /** In the arguments of a gate: the changed files it looks at, and the commit of the turn start. */
34
35
  export const FILES = "{files}";
36
+ export const DIRS = "{dirs}";
35
37
  export const TURN = "{turn}";
38
+ /** Before the first word of a command: a script of this engine, where another word names one of the repo. */
39
+ export const ENGINE_PREFIX = "{engine}/";
36
40
 
37
41
  /**
38
42
  * A text of the repo for the agent, where the engine has one of its own: added after it, or in its place.
@@ -76,6 +80,11 @@ export interface Gate {
76
80
  prompt?: Prompt;
77
81
  /** The exit codes of its command that mean it broke, where any other than 0 means it found a problem. */
78
82
  brokenExitCodes?: number[];
83
+ /**
84
+ * The file that marks a project, such as go.mod: the gate then runs once per project the turn touched, from the
85
+ * folder of that project, where another gate runs once from the root of the repo.
86
+ */
87
+ each?: string;
79
88
  }
80
89
 
81
90
  /**
@@ -241,8 +250,8 @@ function toWatch(watch: unknown, compared: boolean): Watch {
241
250
  if (unknown !== undefined) refuse(`unknown field watch.${unknown}`);
242
251
  const { run, cycleStart, cycleEnd, failed, sync, frozen } = watch;
243
252
  if (!isStringArray(run) || !run.length) refuse("watch.run is a non-empty list of strings");
244
- if (run.some((argument) => argument.includes(FILES) || argument.includes(TURN)))
245
- refuse(`a watch outlives the turn: its run takes neither ${FILES} nor ${TURN}`);
253
+ if (run.some((argument) => [FILES, DIRS, TURN].some((token) => argument.includes(token))))
254
+ refuse(`a watch outlives the turn: its run takes none of ${FILES}, ${DIRS} and ${TURN}`);
246
255
  const pattern = (field: string, value: unknown): string =>
247
256
  isPattern(value) ? value : refuse(`watch.${field} is a regular expression on a line of its output`);
248
257
  if (compared && failed !== undefined) refuse("a compared watch fails on the lines its cycle added: no watch.failed");
@@ -273,6 +282,7 @@ function toGate(entry: Entry, maxTimeoutSeconds: number, reportChars: number | u
273
282
  prompt,
274
283
  omitLines,
275
284
  brokenExitCodes,
285
+ each,
276
286
  timeoutSeconds = maxTimeoutSeconds,
277
287
  maxReportChars = reportChars,
278
288
  } = entry;
@@ -284,8 +294,9 @@ function toGate(entry: Entry, maxTimeoutSeconds: number, reportChars: number | u
284
294
  if (!isPattern(files)) refuse("files is a regular expression on the repo-relative paths");
285
295
  if (!isStringArray(run) || !run.length) refuse("run is a non-empty list of strings");
286
296
  if (compare !== undefined && compare !== "turn-start") refuse('compare is "turn-start"');
287
- if (compare !== undefined && run.includes(FILES))
288
- refuse(`a compared gate reads the whole project: it takes no ${FILES}`);
297
+ const narrowed = [FILES, DIRS].find((token) => run.includes(token));
298
+ if (compare !== undefined && narrowed !== undefined)
299
+ refuse(`a compared gate reads the whole project: it takes no ${narrowed}`);
289
300
  if (ignoreLines !== undefined && !isPattern(ignoreLines)) refuse("ignoreLines is a regular expression");
290
301
  if (lineKey !== undefined && !isPattern(lineKey)) refuse("lineKey is a regular expression");
291
302
  if (lineKey !== undefined && compare === undefined)
@@ -295,6 +306,18 @@ function toGate(entry: Entry, maxTimeoutSeconds: number, reportChars: number | u
295
306
  if (omitLines !== undefined && !isPattern(omitLines)) refuse("omitLines is a regular expression");
296
307
  if (brokenExitCodes !== undefined && !isExitCodes(brokenExitCodes))
297
308
  refuse("brokenExitCodes is a list of exit codes, each a whole number from 1 to 255");
309
+ if (each !== undefined) {
310
+ if (typeof each !== "string" || !each || each === "." || each === ".." || /[\\/]/.test(each))
311
+ refuse("each is the name of the file that marks a project, such as go.mod: a name, not a path");
312
+ if (compare !== undefined)
313
+ refuse(
314
+ "a compared gate reports on the whole repo as the turn starts, before its projects are known: it takes no each",
315
+ );
316
+ if (watch !== undefined) refuse("a watch is kept for the whole repo, not for each project: it takes no each");
317
+ // Such a script takes the folder it runs in for the root of the repo: in a project, it would read nothing.
318
+ if (run[0]?.startsWith(ENGINE_PREFIX))
319
+ refuse("a script of the engine reads the repo from its root: it takes no each");
320
+ }
298
321
  const told = prompt === undefined ? undefined : (toPrompt(prompt) ?? refuse(`prompt is ${PROMPT_SHAPE}`));
299
322
  return {
300
323
  name,
@@ -311,6 +334,7 @@ function toGate(entry: Entry, maxTimeoutSeconds: number, reportChars: number | u
311
334
  ...(maxReportChars === undefined ? {} : { maxReportChars }),
312
335
  ...(omitLines === undefined ? {} : { omitLines }),
313
336
  ...(brokenExitCodes === undefined ? {} : { brokenExitCodes }),
337
+ ...(each === undefined ? {} : { each }),
314
338
  };
315
339
  }
316
340
 
@@ -0,0 +1,54 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ /** A folder of the repo that holds the marker of a gate, with the changed files it is the nearest such folder of. */
5
+ export interface Project {
6
+ /** Relative to the root of the repo, a dot for the root itself. */
7
+ dir: string;
8
+ /** Relative to the folder of the project. */
9
+ files: string[];
10
+ /** The folders of those files, for a gate given {dirs}. */
11
+ dirs?: string[];
12
+ }
13
+
14
+ const ROOT = ".";
15
+
16
+ /**
17
+ * Groups the repo-relative files a gate looks at by project: the nearest folder above each, up to the root of the
18
+ * repo and never past it, that holds the marker now. A file with no marker above it is of no project, which is what
19
+ * leaves out the folders a gate has nothing to do in. A deleted file is looked up from the folder it was in.
20
+ */
21
+ export function projectsOf(root: string, marker: string, files: string[]): Project[] {
22
+ const holds = new Map<string, boolean>();
23
+ const holdsMarker = (dir: string) => {
24
+ if (!holds.has(dir)) holds.set(dir, existsSync(join(root, dir, marker)));
25
+ return holds.get(dir) === true;
26
+ };
27
+ const projects = new Map<string, string[]>();
28
+ for (const file of files) {
29
+ const folders = file.split("/").slice(0, -1);
30
+ // From the folder of the file up to the root, which no folder names.
31
+ const above = folders.map((_, depth) => folders.slice(0, folders.length - depth).join("/"));
32
+ const dir = [...above, ROOT].find(holdsMarker);
33
+ if (dir === undefined) continue;
34
+ const inProject = dir === ROOT ? file : file.slice(dir.length + 1);
35
+ projects.set(dir, [...(projects.get(dir) ?? []), inProject]);
36
+ }
37
+ return [...projects]
38
+ .map(([dir, inProject]) => ({ dir, files: inProject }))
39
+ .sort((a, b) => (a.dir < b.dir ? -1 : a.dir > b.dir ? 1 : 0));
40
+ }
41
+
42
+ /**
43
+ * The folders of the files, each once and sorted, as a tool that runs in `base` is to be given them: with ./ in
44
+ * front, which a tool such as go needs to read a folder and not an import path, and a dot for `base` itself. A
45
+ * deleted file counts for its folder, since what is left there may break on it, but a folder that is gone is left
46
+ * out. A folder inside another stands next to it: what joins the two is for the tool to know.
47
+ */
48
+ export function dirsOf(base: string, files: string[]): string[] {
49
+ const dirs = new Set(files.map((file) => file.split("/").slice(0, -1).join("/")));
50
+ return [...dirs]
51
+ .filter((dir) => existsSync(join(base, dir)))
52
+ .sort()
53
+ .map((dir) => (dir ? `./${dir}` : ROOT));
54
+ }
@@ -1,6 +1,6 @@
1
1
  import type { CheckedTurn } from "./check.ts";
2
2
  import type { Prompt } from "./config.ts";
3
- import { failed, type Outcome } from "./run.ts";
3
+ import { failed, notJudged, type Outcome, underFolder } from "./run.ts";
4
4
  import { WAIVE_TAG } from "./waive-line.ts";
5
5
 
6
6
  const LABEL = "● gates";
@@ -49,8 +49,13 @@ export function duration(ms: number): string {
49
49
  return ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`;
50
50
  }
51
51
 
52
+ // The gate, with the projects it concerns when it runs in each: one line whatever their number.
53
+ function named({ name, projects = [] }: Outcome): string {
54
+ return projects.length ? `${name} [${projects.join(", ")}]` : name;
55
+ }
56
+
52
57
  function gateLine(mark: string, outcome: Outcome): string {
53
- return `${mark} ${outcome.name} ${paint("dim", duration(outcome.ms))}`;
58
+ return `${mark} ${named(outcome)} ${paint("dim", duration(outcome.ms))}`;
54
59
  }
55
60
 
56
61
  function skippedLine(skipped: string[]): string {
@@ -69,7 +74,7 @@ function nothingChecked({ changed, skipped }: CheckedTurn, after: string): strin
69
74
  // The gate in orange, then the reason the agent gave, under a star.
70
75
  function waivedLines(outcome: Outcome, reason: string): string[] {
71
76
  return [
72
- `${paint("warn", `${WARNING} ${outcome.name}`)} ${paint("dim", duration(outcome.ms))}`,
77
+ `${paint("warn", `${WARNING} ${named(outcome)}`)} ${paint("dim", duration(outcome.ms))}`,
73
78
  ` ${paint("warn", "*")} ${reason}`,
74
79
  ];
75
80
  }
@@ -225,23 +230,38 @@ export function toolsToInstall(missing: string[], prompt?: Prompt): string {
225
230
  /**
226
231
  * The report of each failed gate, under its name, how to act on one the turn broke, and the prompt of the repo for it:
227
232
  * less the lines the gate omits, each line a helper counts apart said once, in the characters it has, and in its share of a total when the reports have one.
233
+ * A gate that failed in several projects shares its characters between their blocks the same way, each under its
234
+ * folder, then names the projects it ran out of time for.
228
235
  */
229
236
  export function reports({ outcomes, wording = {} }: Pick<CheckedTurn, "outcomes" | "wording">): string[] {
230
237
  const { gates = [], prompts, maxTotalReportChars = Infinity } = wording;
231
- const red = outcomes.filter(failed).map(({ name, output, broken }) => {
238
+ const all = outcomes.filter(failed);
239
+ const red = all.map(({ name, output, broken, blocks = [{ dir: ".", output }] }) => {
232
240
  const gate = gates.find((known) => known.name === name);
233
- const report = saidOnce(sent(output, gate?.omitLines));
241
+ const said = blocks.map((block) => ({ ...block, output: saidOnce(sent(block.output, gate?.omitLines)) }));
234
242
  const told = [
235
243
  ...(broken ? [worded(BROKEN_GATE, prompts?.brokenGate, "\n")] : []),
236
244
  ...(gate?.prompt ? [gate.prompt.text] : []),
237
245
  ];
238
- return { name, told, report, needs: Math.min(report.length, gate?.maxReportChars ?? REPORT_CHARS) };
246
+ const length = said.reduce((sum, block) => sum + block.output.length, 0);
247
+ return { name, told, said, needs: Math.min(length, gate?.maxReportChars ?? REPORT_CHARS) };
239
248
  });
240
249
  const given = shares(
241
250
  red.map(({ needs }) => needs),
242
251
  maxTotalReportChars,
243
252
  );
244
- return red.map(({ name, told, report }, at) => [`## ${name}`, ...told, excerpt(report, given[at])].join("\n"));
253
+ return red.map(({ name, told, said }, at) => {
254
+ const each = shares(
255
+ said.map((block) => block.output.length),
256
+ given[at] ?? 0,
257
+ );
258
+ const { unjudged = [] } = all[at] ?? {};
259
+ const report = [
260
+ ...said.map((block, of) => underFolder({ ...block, output: excerpt(block.output, each[of]) })),
261
+ ...(unjudged.length ? [notJudged(unjudged)] : []),
262
+ ];
263
+ return [`## ${name}`, ...told, report.join("\n\n")].join("\n");
264
+ });
245
265
  }
246
266
 
247
267
  /**
@@ -273,12 +293,13 @@ function gateResult({ name, ok, ms, output, timedOut, broken }: Outcome): GateRe
273
293
 
274
294
  /**
275
295
  * A check for a tool to read, such as a CI or a script, where the summary is for its owner and the send-back for the
276
- * agent: whether it passed, each gate with its status and its whole report, and the notes of the check.
296
+ * agent: whether it passed, which a gate out of time keeps it from, each gate with its status and its whole report, and
297
+ * the notes of the check.
277
298
  */
278
299
  export function results({ outcomes, skipped, ms, note }: CheckedTurn) {
279
300
  const gates: GateResult[] = [
280
301
  ...outcomes.map(gateResult),
281
302
  ...skipped.map((name) => ({ name, status: "skipped" as const })),
282
303
  ];
283
- return { ok: !outcomes.some(failed), durationMs: Math.round(ms), gates, notes: note ? note.split("\n") : [] };
304
+ return { ok: outcomes.every(({ ok }) => ok), durationMs: Math.round(ms), gates, notes: note ? note.split("\n") : [] };
284
305
  }
package/src/core/run.ts CHANGED
@@ -1,9 +1,11 @@
1
1
  import { execFile, type ExecFileException } from "node:child_process";
2
2
  import { accessSync, constants, existsSync } from "node:fs";
3
+ import { availableParallelism } from "node:os";
3
4
  import { delimiter, isAbsolute, join, resolve, sep } from "node:path";
4
5
  import { stripVTControlCharacters } from "node:util";
5
- import { FILES, type Gate, isCompared, TURN } from "./config.ts";
6
+ import { DIRS, ENGINE_PREFIX, FILES, type Gate, isCompared, TURN } from "./config.ts";
6
7
  import { isRecord, messageOf, readJsonFile } from "./json.ts";
8
+ import type { Project } from "./projects.ts";
7
9
 
8
10
  export interface Outcome {
9
11
  name: string;
@@ -18,6 +20,18 @@ export interface Outcome {
18
20
  * nothing tells a gate the turn broke from one that broke before it, but the agent is told to repair it.
19
21
  */
20
22
  broken?: boolean;
23
+ /** For a gate that runs in each project: the folders of the ones it failed in, the root of the repo left out. */
24
+ projects?: string[];
25
+ /** For a gate that runs in each project: what each of the ones it failed in said, which its output holds too. */
26
+ blocks?: Block[];
27
+ /** For such a gate that failed: the folders of the projects it ran out of time for, so did not judge. */
28
+ unjudged?: string[];
29
+ }
30
+
31
+ /** What a gate said in one project, by the folder of the project: a dot for the root of the repo. */
32
+ export interface Block {
33
+ dir: string;
34
+ output: string;
21
35
  }
22
36
 
23
37
  /** A gate that judged the turn and found a problem, or that broke: the only kinds that send the agent back. */
@@ -52,7 +66,6 @@ export function headed(own: string, lines: string[], env = process.env): string
52
66
  }
53
67
 
54
68
  const MAX_OUTPUT_MB = 16;
55
- const ENGINE_PREFIX = "{engine}/";
56
69
 
57
70
  /** A script of this engine: its .ts source, or the .js it is built to when the engine runs from its npm package. */
58
71
  function engineScript(name: string): string {
@@ -143,8 +156,12 @@ export function missingTool(root: string, gate: Gate): string | undefined {
143
156
  return missingProgram(root, gate.run[0] ?? "") ?? (gate.watch && missingProgram(root, gate.watch.run[0] ?? ""));
144
157
  }
145
158
 
146
- export function argumentsOf(gate: Gate, files: string[], turn: string): string[] {
147
- return gate.run.slice(1).flatMap((argument) => (argument === FILES ? files : [argument.replaceAll(TURN, turn)]));
159
+ export function argumentsOf(gate: Gate, files: string[], turn: string, dirs: string[] = []): string[] {
160
+ return gate.run.slice(1).flatMap((argument) => {
161
+ if (argument === FILES) return files;
162
+ if (argument === DIRS) return dirs;
163
+ return [argument.replaceAll(TURN, turn)];
164
+ });
148
165
  }
149
166
 
150
167
  /** Whether the gate is given the changed files, where another reads the whole project. */
@@ -152,6 +169,11 @@ export function givenFiles(gate: Gate): boolean {
152
169
  return gate.run.includes(FILES);
153
170
  }
154
171
 
172
+ /** Whether the gate is given the folders of the changed files. */
173
+ export function givenDirs(gate: Gate): boolean {
174
+ return gate.run.includes(DIRS);
175
+ }
176
+
155
177
  export function filesOf(gate: Gate, changed: string[]): string[] {
156
178
  const pattern = new RegExp(gate.files);
157
179
  return changed.filter((file) => pattern.test(file));
@@ -209,7 +231,8 @@ interface Executed {
209
231
  exitCode?: number;
210
232
  }
211
233
 
212
- async function execute(root: string, gate: Gate, args: string[]): Promise<Executed> {
234
+ /** Starts the command of a gate, found from the root of the repo, in the folder given: the root, or a project. */
235
+ async function execute(root: string, gate: Gate, args: string[], cwd = root): Promise<Executed> {
213
236
  const started = performance.now();
214
237
  const [name = ""] = gate.run;
215
238
  // A gate that cannot start fails alone: the other gates of the turn still report.
@@ -230,15 +253,16 @@ async function execute(root: string, gate: Gate, args: string[]): Promise<Execut
230
253
  command.file,
231
254
  [...command.args, ...args],
232
255
  {
233
- cwd: root,
234
- timeout: gate.timeoutSeconds * 1000,
256
+ cwd,
257
+ // In whole milliseconds, as Node wants them: what is left of a shared time is not.
258
+ timeout: Math.ceil(gate.timeoutSeconds * 1000),
235
259
  maxBuffer: MAX_OUTPUT_MB * 1024 * 1024,
236
260
  env: { ...toolEnv(root), ...(gate.prompt?.replace ? { [PROMPT_REPLACED]: "1" } : {}) },
237
261
  },
238
262
  (error, stdout, stderr) => {
239
263
  resolve({
240
264
  ok: !error,
241
- output: outputOf(root, gate, command, error, `${stdout}${stderr}`),
265
+ output: outputOf(root, gate, command, error, `${stdout}${stderr}`, cwd),
242
266
  ms: performance.now() - started,
243
267
  timedOut: error?.killed === true && error.code !== "ERR_CHILD_PROCESS_STDIO_MAXBUFFER",
244
268
  cannotStart: error?.code === "ENOENT",
@@ -255,20 +279,25 @@ function outputOf(
255
279
  command: Command,
256
280
  error: ExecFileException | null,
257
281
  printed: string,
282
+ cwd: string,
258
283
  ): string {
259
284
  if (error?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER")
260
285
  return `Printed more than ${MAX_OUTPUT_MB} MB: too much for the end of a turn. Make it quieter, or move it to CI.`;
261
- if (error?.killed === true)
262
- return `Out of time after ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
286
+ if (error?.killed === true) return outOfTime(gate);
263
287
  if (error?.code === "ENOENT") return command.missing;
264
- const said = cleaned(root, printed);
288
+ const said = cleaned(root, printed, cwd);
265
289
  if (said || !error) return said;
266
290
  return `exit code ${String(error.code)}, no output`;
267
291
  }
268
292
 
269
- /** What a tool printed, for the agent: some tools colour despite NO_COLOR, and absolute paths only cost it tokens. */
270
- export function cleaned(root: string, printed: string): string {
271
- return stripVTControlCharacters(printed).split(`${root}${sep}`).join("").trim();
293
+ /**
294
+ * What a tool printed, for the agent: some tools colour despite NO_COLOR, and absolute paths only cost it tokens. A
295
+ * tool that ran in a project loses the path of that folder first, so its files read as the relative paths it prints.
296
+ */
297
+ export function cleaned(root: string, printed: string, cwd = root): string {
298
+ return [cwd, root]
299
+ .reduce((text, dir) => text.split(`${dir}${sep}`).join(""), stripVTControlCharacters(printed))
300
+ .trim();
272
301
  }
273
302
 
274
303
  /**
@@ -307,16 +336,113 @@ export async function check(
307
336
  turn: string,
308
337
  baseline: string | undefined,
309
338
  elsewhere = false,
339
+ dirs: string[] = [],
340
+ ): Promise<Outcome> {
341
+ const outcome = await ranIn(root, gate, files, turn, dirs);
342
+ if (!outcome.ok || !isCompared(gate)) return outcome;
343
+ return { ...outcome, ...addedLines(gate, outcome.output, baseline, files, elsewhere) };
344
+ }
345
+
346
+ /** What the command of a gate says of the files given, run once in a folder: by its exit code alone. */
347
+ async function ranIn(
348
+ root: string,
349
+ gate: Gate,
350
+ files: string[],
351
+ turn: string,
352
+ dirs: string[] = [],
353
+ cwd = root,
310
354
  ): Promise<Outcome> {
311
- const executed = await execute(root, gate, argumentsOf(gate, files, turn));
355
+ const executed = await execute(root, gate, argumentsOf(gate, files, turn, dirs), cwd);
312
356
  const { ok, output, ms, timedOut, cannotStart, exitCode = 0 } = executed;
313
357
  const ran = { name: gate.name, ms, report: ok ? output : undefined };
314
358
  if (timedOut) return { ...ran, ok, output, timedOut };
315
359
  // A compared gate exits with 0 when it finds problems: any other code is its command that broke.
316
360
  const broke = cannotStart || isCompared(gate) || gate.brokenExitCodes?.includes(exitCode);
317
- if (!ok && broke) return { ...ran, ok, output, broken: true };
318
- if (!isCompared(gate) || !ok) return { ...ran, ok, output };
319
- return { ...ran, ...addedLines(gate, output, baseline, files, elsewhere) };
361
+ return { ...ran, ok, output, ...(!ok && broke ? { broken: true } : {}) };
362
+ }
363
+
364
+ const ROOT = ".";
365
+
366
+ /** What a project said, under its folder: a tool prints its paths from where it runs. The root needs no telling. */
367
+ export function underFolder({ dir, output }: Block): string {
368
+ return dir === ROOT ? output : `in ${dir}, paths relative to it:\n${output}`;
369
+ }
370
+
371
+ /** What a failed gate says last of the projects it ran out of time for. */
372
+ export function notJudged(dirs: string[]): string {
373
+ return `out of time, so not judged: ${dirs.join(", ")}`;
374
+ }
375
+
376
+ function outOfTime(gate: Gate): string {
377
+ return `Out of time after ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
378
+ }
379
+
380
+ // Runs a task on each item, at most so many at once, and gives what they returned in the order of the items.
381
+ async function pooled<Item, Result>(items: Item[], limit: number, run: (item: Item) => Promise<Result>) {
382
+ const results: Result[] = [];
383
+ let next = 0;
384
+ const worker = async () => {
385
+ for (let at = next++; at < items.length; at = next++) results[at] = await run(items[at] as Item);
386
+ };
387
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
388
+ return results;
389
+ }
390
+
391
+ /**
392
+ * Runs a gate once in each project given, from the folder of the project, and gives one outcome for them all: the
393
+ * gate stays one gate, with one name to report under and to waive. It is red when a project failed, with the report
394
+ * of each failed project under its folder, broken when one broke, and out of time when none failed and one ran out
395
+ * of it. As many projects run at once as the machine has cores: a build takes them all by itself. With a shared
396
+ * time, as at the stop, the time of the gate is for all its projects, and one whose turn comes too late is not
397
+ * started; otherwise each has it whole.
398
+ */
399
+ export async function checkEach(
400
+ root: string,
401
+ gate: Gate,
402
+ projects: Project[],
403
+ turn: string,
404
+ sharedTime = false,
405
+ ): Promise<Outcome> {
406
+ const started = performance.now();
407
+ const ran = await pooled(projects, availableParallelism(), async ({ dir, files, dirs }) => {
408
+ const left = sharedTime ? gate.timeoutSeconds - (performance.now() - started) / 1000 : gate.timeoutSeconds;
409
+ if (left <= 0) return { dir, name: gate.name, ok: false, ms: 0, output: "", report: undefined, timedOut: true };
410
+ return { dir, ...(await ranIn(root, { ...gate, timeoutSeconds: left }, files, turn, dirs, join(root, dir))) };
411
+ });
412
+ const merged = { name: gate.name, ms: performance.now() - started, report: undefined };
413
+ const named = (outcomes: { dir: string }[]) => outcomes.map(({ dir }) => dir).filter((dir) => dir !== ROOT);
414
+ const red = ran.filter(failed);
415
+ const late = ran.filter(({ timedOut }) => timedOut);
416
+ if (red.length) {
417
+ const blocks = red.map(({ dir, output }) => ({ dir, output }));
418
+ // The root is named here, where nothing else would say a project was left.
419
+ const unjudged = late.map(({ dir }) => dir);
420
+ return {
421
+ ...merged,
422
+ ok: false,
423
+ output: [...blocks.map(underFolder), ...(unjudged.length ? [notJudged(unjudged)] : [])].join("\n\n"),
424
+ blocks,
425
+ ...(red.some(({ broken }) => broken) ? { broken: true } : {}),
426
+ ...(named(red).length ? { projects: named(red) } : {}),
427
+ ...(unjudged.length ? { unjudged } : {}),
428
+ };
429
+ }
430
+ if (late.length)
431
+ return {
432
+ ...merged,
433
+ ok: false,
434
+ output: outOfTime(gate),
435
+ timedOut: true,
436
+ ...(named(late).length ? { projects: named(late) } : {}),
437
+ };
438
+ return {
439
+ ...merged,
440
+ ok: true,
441
+ output: ran
442
+ .map(({ output }) => output)
443
+ .filter(Boolean)
444
+ .join("\n"),
445
+ };
320
446
  }
321
447
 
322
448
  /**