@tayomi/deterministic-gates 0.10.0 → 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.
package/src/core/check.ts CHANGED
@@ -10,11 +10,22 @@ import {
10
10
  type Prompts,
11
11
  readGatesFiles,
12
12
  } from "./config.ts";
13
- import { headOf, movedSince } from "./head.ts";
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";
16
- import { changedSince, emptyCommit, hasCommit, lastCommit, snapshot, workingTree } from "./snapshot.ts";
17
- import { readTurn, type TurnState, writeTurn } from "./turn-state.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";
27
+ import { changedSince, emptyCommit, hasCommit, lastCommit, sharedDir, snapshot, workingTree } from "./snapshot.ts";
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";
19
30
 
20
31
  /** What the repo says of what the agent is sent: the prompts of the whole check, and its gates, for their own. */
@@ -85,10 +96,16 @@ export async function startTurn(session: string, root: string): Promise<string[]
85
96
  const compared = runnable(gates, missing).filter(isCompared);
86
97
  startWatches(session, root, runnable(gates, missing));
87
98
  const interrupted = readTurn(session, root);
99
+ // The worktrees of a repo share its commits: what the session knows of them is of the repo, not of the folder.
100
+ const shared = sharedDir(root);
101
+ const there = readThere(session, shared);
88
102
  if (interrupted?.checked === false) {
89
- writeTurn(session, root, interrupted);
103
+ // What it committed so far stays the session's, and a commit older than this prompt is one a fetch may bring.
104
+ if (there) writeThere(session, shared, observed(root, there, interrupted.at ?? Date.now()));
105
+ writeTurn(session, root, { ...interrupted, at: Date.now() });
90
106
  return told;
91
107
  }
108
+ writeThere(session, shared, thereOf(root, there));
92
109
  const head = headOf(root);
93
110
  const { commit: start, tree } = snapshot(root);
94
111
  // The turn starts before its reports are ready: a hook stopped for lack of time leaves it, never the turn before.
@@ -125,8 +142,10 @@ export async function startTurn(session: string, root: string): Promise<string[]
125
142
  /**
126
143
  * Runs, in parallel, each gate that looks at a changed file. A deleted file counts as changed, since a gate that
127
144
  * reads the whole project may break on it, but is never named: a gate given {files} looks at the files left, and
128
- * 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
129
- * 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.
130
149
  */
131
150
  function runGates(
132
151
  root: string,
@@ -140,15 +159,34 @@ function runGates(
140
159
  return Promise.all(
141
160
  gates.map(async (gate) => {
142
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
+ }
143
168
  const files = givenFiles(gate) ? matching.filter((file) => existsSync(join(root, file))) : matching;
144
- if (!files.length) return { gate };
169
+ const dirs = givenDirs(gate) ? dirsOf(root, matching) : undefined;
170
+ if (!files.length || dirs?.length === 0) return { gate };
145
171
  if (session !== undefined && keepsWatch(gate))
146
172
  return { gate, outcome: await judgeWatch(session, root, gate, matching, baselines(gate), elsewhere) };
147
- 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) };
148
174
  }),
149
175
  );
150
176
  }
151
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
+
152
190
  function checkedTurn(
153
191
  changed: string[],
154
192
  results: Result[],
@@ -199,8 +237,7 @@ function endReports(results: Result[], baselines: Baselines, elsewhere: boolean)
199
237
  * them mid-turn changes the next turn, never its own. Without a recorded start, the turn runs from the last commit
200
238
  * with the gates of now; with a start git no longer has, from the last commit with the gates and the reports it
201
239
  * started with: checking too much beats leaving a hole. When HEAD moved during the turn to code it did not write, as
202
- * a checkout or a pull does, the turn is only what the tree differs by from the commit HEAD reached, with what the
203
- * turn committed before: the rest came with that commit.
240
+ * a checkout or a pull does, the turn is only the files unlike the ones that code holds: the rest came with it.
204
241
  */
205
242
  export async function checkTurn(session: string, root: string): Promise<CheckedTurn> {
206
243
  const recorded = readTurn(session, root);
@@ -217,34 +254,35 @@ export async function checkTurn(session: string, root: string): Promise<CheckedT
217
254
  baselines: recorded?.baselines ?? {},
218
255
  config: recorded?.config ?? now,
219
256
  checked: false,
220
- ...(kept ? { head: kept.head, moves: kept.moves } : {}),
257
+ ...(kept ? { head: kept.head, at: kept.at } : {}),
221
258
  // What the earlier stops of the turn told the agent goes on, so its send-backs and waivers add up.
222
259
  ...(recorded?.sendBacks ? { sendBacks: recorded.sendBacks } : {}),
223
260
  };
224
- const moved = kept && movedSince(root, kept);
225
- // A report of code HEAD has left serves a gate whose lines name their file, to count the ones of the turn's files.
226
- const baselines: Baselines = (gate) => (moved && !namesFiles(gate) ? undefined : turn.baselines[gate.name]);
261
+ const shared = sharedDir(root);
262
+ const there = readThere(session, shared);
263
+ const moved = kept && there && movedSince(root, kept, there);
227
264
  const started = performance.now();
228
265
  const end = workingTree(root);
229
266
  const since = changedSince(root, turn.start, end);
230
- const own = moved && new Set([...changedSince(root, moved.to, end), ...moved.committed]);
231
- const changed = own ? since.filter((file) => own.has(file)) : since;
267
+ // A file like the one a commit under HEAD holds came with that commit: the turn did not write it.
268
+ const changed = (moved?.under ?? []).reduce((files, commit) => {
269
+ const unlike = new Set(changedSince(root, commit, end));
270
+ return files.filter((file) => unlike.has(file));
271
+ }, since);
272
+ // Code came with a commit, or left with one: the tree the turn started on no longer tells what the turn wrote.
273
+ const elsewhere = moved !== undefined && (moved.arrived || changed.length < since.length);
274
+ // Where a gate given the turn starts from: then, the commit that brought the code.
275
+ const from = (elsewhere ? moved?.to : undefined) ?? turn.start;
276
+ // A report of code HEAD has left serves a gate whose lines name their file, to count the ones of the turn's files.
277
+ const baselines: Baselines = (gate) => (elsewhere && !namesFiles(gate) ? undefined : turn.baselines[gate.name]);
232
278
  const config = gatesOf(turn.config);
233
279
  const { gates, refused } = config;
234
280
  const missing = missingTools(root, gates);
235
281
  for (const gate of gates) if (keepsWatch(gate)) keepWatch(root, gate);
236
- const from = moved?.to ?? turn.start;
237
- const results = await runGates(
238
- root,
239
- runnable(gates, missing),
240
- changed,
241
- from,
242
- baselines,
243
- session,
244
- moved !== undefined,
245
- );
246
- cacheReports(root, end, endReports(results, baselines, moved !== undefined));
282
+ const results = await runGates(root, runnable(gates, missing), changed, from, baselines, session, elsewhere);
283
+ cacheReports(root, end, endReports(results, baselines, elsewhere));
247
284
  writeTurn(session, root, { ...turn, checked: true });
285
+ if (there) writeThere(session, shared, observed(root, there, kept?.at ?? Date.now()));
248
286
  // A compared gate with no report from the turn start can only count its exit code, and a watch has none: a green it
249
287
  // did not earn is said.
250
288
  const uncompared = results
@@ -262,7 +300,7 @@ export async function checkTurn(session: string, root: string): Promise<CheckedT
262
300
  .map(({ gate, why }) => `${gate.name} not run: ${why}`);
263
301
  const notes = [
264
302
  ...(startNote ? [startNote] : []),
265
- ...(moved ? [`HEAD moved during the turn (${moved.how}): only what the turn changed since is checked`] : []),
303
+ ...(elsewhere ? ["HEAD moved during the turn to code it did not write: only what the turn wrote is checked"] : []),
266
304
  ...configNote(changedGatesFiles(turn.config, now)),
267
305
  ...uncompared,
268
306
  ...refusedNotes(refused),
@@ -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
 
package/src/core/head.ts CHANGED
@@ -1,45 +1,114 @@
1
- import { commitFiles, headMoves } from "./snapshot.ts";
1
+ import { branchTips, type Commit, commitsPast, hasCommit, isIn } from "./snapshot.ts";
2
2
 
3
- // What takes HEAD to a commit the turn did not write, as the reflog names it. Any other move is a commit of the turn,
4
- // as an amend or a cherry-pick: checking too much beats leaving a hole.
5
- const NOT_ITS_COMMIT = /^(checkout|pull|merge|rebase|reset)\b/;
6
- // A merge the turn commits brings the code of a branch too: of its files, the turn wrote the conflicts it resolved.
7
- const ELSEWHERE = new RegExp(`${NOT_ITS_COMMIT.source}|^commit \\(merge\\)`);
3
+ // What tells the code a turn wrote from the code that came with a branch it checked out, pulled, merged or rebased on.
4
+ // Nothing here reads how HEAD moved, which git tells in too many ways: only which commits were there before.
5
+ //
6
+ // A commit was there when a branch held it as the session first started a turn in the repo, when HEAD was on it as a
7
+ // turn of the session started, since the turns before have judged it, or when it was committed before the turn, as
8
+ // one a fetch brought, unless a stop of the session saw it as its own already. Any other commit is one the session
9
+ // made, by whatever command, in whatever worktree: checking too much beats leaving a hole.
8
10
 
9
- /** HEAD as a turn starts: its commit, and how many moves its reflog holds. */
11
+ /** What a turn records of HEAD as it starts: its commit, when the repo has one, and when, in milliseconds. */
10
12
  export interface Head {
11
13
  head?: string;
12
- moves?: number;
14
+ at?: number;
13
15
  }
14
16
 
15
- /** The last move of a turn that took HEAD to code the turn did not write. */
17
+ /**
18
+ * What a session knows of the commits of a repo: the tips of its branches as its first turn there started, with the
19
+ * commit each of its turns started on, and the commits it made since, as its stops saw them.
20
+ */
21
+ export interface There {
22
+ known: string[];
23
+ made: string[];
24
+ }
25
+
26
+ /** The code under HEAD that the session did not write, when it is not the one the turn started on. */
16
27
  export interface Moved {
17
- /** The commit HEAD reached: what the tree differs from since is the turn's. */
18
- to: string;
19
- how: string;
20
- /** The files of the commits the turn made, which the commit reached may hold already, as after a rebase. */
21
- committed: string[];
28
+ /** The commits that were there, nearest under HEAD: a file like the one any of them holds is not the turn's. */
29
+ under: string[];
30
+ /** The one of them the turn did not start on, when there is one: where a gate given the turn starts from. */
31
+ to?: string;
32
+ /** Whether one of them holds code the turn did not start on, where the others only hold less of it. */
33
+ arrived: boolean;
22
34
  }
23
35
 
24
36
  export function headOf(root: string): Head {
25
- const moves = headMoves(root);
26
- const head = moves.at(-1)?.to;
27
- return { moves: moves.length, ...(head === undefined ? {} : { head }) };
37
+ const { head } = branchTips(root);
38
+ return { ...(head === undefined ? {} : { head }), at: Date.now() };
39
+ }
40
+
41
+ /**
42
+ * What a session knows of a repo as a turn starts there, from what it knew: the commit HEAD is on was there, since
43
+ * a turn that made it has been judged on it. Before its first turn, the tips of the branches were.
44
+ */
45
+ export function thereOf(root: string, before?: There): There {
46
+ const { head, tips } = branchTips(root);
47
+ if (before === undefined) return { known: tips, made: [] };
48
+ return { known: [...new Set([...before.known, ...(head === undefined ? [] : [head])])], made: before.made };
49
+ }
50
+
51
+ /** The commits the session made, among the ones past what it knew: the ones it saw as its own, and the ones of the turn. */
52
+ function madeOf(past: Commit[], { made }: There, at: number): Commit[] {
53
+ const seen = new Set(made);
54
+ const started = Math.floor(at / 1000);
55
+ return past.filter((commit) => seen.has(commit.hash) || commit.at >= started);
56
+ }
57
+
58
+ /**
59
+ * What the session knows once a turn that started then stops: with the commits the turn made, on whatever branch, so
60
+ * that they stay its own in the turns after. Less the known commits git no longer has, as after a deleted branch.
61
+ */
62
+ export function observed(root: string, there: There, at: number): There {
63
+ const seen = (known: string[]): There => {
64
+ const mine = madeOf(commitsPast(root, branchTips(root).tips, known), there, at);
65
+ return { known, made: [...new Set([...there.made, ...mine.map(({ hash }) => hash)])] };
66
+ };
67
+ try {
68
+ return seen(there.known);
69
+ } catch {
70
+ const kept = there.known.filter((commit) => hasCommit(root, commit));
71
+ try {
72
+ return seen(kept);
73
+ } catch {
74
+ return { known: kept, made: there.made };
75
+ }
76
+ }
77
+ }
78
+
79
+ /** The commits that were there, nearest under a commit: itself, or the ones under the commits the session made. */
80
+ function under(tip: string, made: Map<string, string[]>): string[] {
81
+ const there = new Set<string>();
82
+ const seen = new Set<string>();
83
+ const left = [tip];
84
+ for (let commit = left.pop(); commit !== undefined; commit = left.pop()) {
85
+ if (seen.has(commit)) continue;
86
+ seen.add(commit);
87
+ const parents = made.get(commit);
88
+ if (parents === undefined) there.add(commit);
89
+ else left.push(...parents);
90
+ }
91
+ return [...there];
28
92
  }
29
93
 
30
94
  /**
31
- * Whether HEAD moved, since the turn started, to code the turn did not write: a checkout, a pull, a merge, a rebase or
32
- * a reset. Nothing when it did not, or when the reflog no longer tells: all the turn changed is then checked.
95
+ * Whether the code under HEAD that the session did not write changed since the turn started, as after a checkout, a
96
+ * pull, a merge, a rebase or a reset. Nothing when it did not, as after a commit of the turn, or a branch it left and
97
+ * came back to; nor when nothing tells any more, where all the turn changed is checked.
33
98
  */
34
- export function movedSince(root: string, { head, moves }: Head): Moved | undefined {
35
- if (moves === undefined) return undefined;
36
- const all = headMoves(root);
37
- if (all[moves - 1]?.to !== head) return undefined;
38
- // A move that reaches the commit it left brings no code, as a new branch or a stash does.
39
- const since = all.slice(moves).filter(({ from, to }) => from !== to);
40
- const last = since.findLastIndex(({ how }) => ELSEWHERE.test(how));
41
- const move = since[last];
42
- if (move === undefined) return undefined;
43
- const own = since.filter(({ how }) => !NOT_ITS_COMMIT.test(how));
44
- return { to: move.to, how: move.how, committed: own.flatMap(({ to }) => commitFiles(root, to)) };
99
+ export function movedSince(root: string, { head, at }: Head, there: There): Moved | undefined {
100
+ const now = branchTips(root).head;
101
+ if (head === undefined || at === undefined || now === undefined || now === head) return undefined;
102
+ let past: Commit[];
103
+ try {
104
+ past = commitsPast(root, [now, head], there.known);
105
+ } catch {
106
+ return undefined;
107
+ }
108
+ const made = new Map(madeOf(past, there, at).map(({ hash, parents }) => [hash, parents]));
109
+ const [before, after] = [under(head, made), under(now, made)];
110
+ if (after.length === before.length && after.every((commit) => before.includes(commit))) return undefined;
111
+ const brought = after.find((commit) => !before.some((had) => isIn(root, commit, had)));
112
+ const to = brought ?? after.find((commit) => !before.includes(commit));
113
+ return { under: after, arrived: brought !== undefined, ...(to === undefined ? {} : { to }) };
45
114
  }
@@ -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
  }
@@ -168,14 +173,21 @@ function sent(report: string, omitLines: string | undefined): string {
168
173
  return kept.some((line) => line.trim()) ? kept.join("\n") : report;
169
174
  }
170
175
 
171
- // A helper of the engine counts apart the errors of one source line, with `(2)` before the tab that ends their key,
172
- // so that one more of them is new. The agent reads each of them once, with how many times it stands.
176
+ // A helper of the engine counts apart the errors of one source line, with `(2)` after the source it quotes and before
177
+ // the tab that ends their key, so that one more of them is new. The agent reads each of them once, with how many
178
+ // times it stands. A line of another tool is left as it is.
179
+ const COUNTED_APART = /` \(\d+\)\t/;
180
+
173
181
  function saidOnce(report: string): string {
174
- const lines = report.split("\n").map((line) => line.replace(/ \(\d+\)\t/, "\t"));
182
+ if (!COUNTED_APART.test(report)) return report;
183
+ const lines = report.split("\n");
184
+ const keyed = lines.map((line) => line.replace(COUNTED_APART, "`\t"));
185
+ const counted = new Set(keyed.filter((line, at) => line !== lines[at]));
175
186
  const times = new Map<string, number>();
176
- for (const line of lines) if (line.includes("\t")) times.set(line, (times.get(line) ?? 0) + 1);
177
- return lines
178
- .filter((line, at) => !times.has(line) || lines.indexOf(line) === at)
187
+ for (const line of keyed) if (counted.has(line)) times.set(line, (times.get(line) ?? 0) + 1);
188
+ const said = new Set<string>();
189
+ return keyed
190
+ .filter((line) => !times.has(line) || (!said.has(line) && said.add(line)))
179
191
  .map((line) => ((times.get(line) ?? 1) > 1 ? `${line} (×${times.get(line)})` : line))
180
192
  .join("\n");
181
193
  }
@@ -217,24 +229,39 @@ export function toolsToInstall(missing: string[], prompt?: Prompt): string {
217
229
 
218
230
  /**
219
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:
220
- * each line a helper counts apart said once, less the lines the gate omits, in the characters it has, and in its share of a total when the reports have one.
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.
221
235
  */
222
236
  export function reports({ outcomes, wording = {} }: Pick<CheckedTurn, "outcomes" | "wording">): string[] {
223
237
  const { gates = [], prompts, maxTotalReportChars = Infinity } = wording;
224
- 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 }] }) => {
225
240
  const gate = gates.find((known) => known.name === name);
226
- const report = sent(saidOnce(output), gate?.omitLines);
241
+ const said = blocks.map((block) => ({ ...block, output: saidOnce(sent(block.output, gate?.omitLines)) }));
227
242
  const told = [
228
243
  ...(broken ? [worded(BROKEN_GATE, prompts?.brokenGate, "\n")] : []),
229
244
  ...(gate?.prompt ? [gate.prompt.text] : []),
230
245
  ];
231
- 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) };
232
248
  });
233
249
  const given = shares(
234
250
  red.map(({ needs }) => needs),
235
251
  maxTotalReportChars,
236
252
  );
237
- 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
+ });
238
265
  }
239
266
 
240
267
  /**
@@ -266,12 +293,13 @@ function gateResult({ name, ok, ms, output, timedOut, broken }: Outcome): GateRe
266
293
 
267
294
  /**
268
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
269
- * 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.
270
298
  */
271
299
  export function results({ outcomes, skipped, ms, note }: CheckedTurn) {
272
300
  const gates: GateResult[] = [
273
301
  ...outcomes.map(gateResult),
274
302
  ...skipped.map((name) => ({ name, status: "skipped" as const })),
275
303
  ];
276
- 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") : [] };
277
305
  }