@tayomi/deterministic-gates 0.9.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,7 +9,7 @@
9
9
  "name": "deterministic-gates",
10
10
  "source": "./",
11
11
  "description": "Gates that run on what each turn changed and send the agent back until they pass.",
12
- "version": "0.9.0"
12
+ "version": "0.10.1"
13
13
  }
14
14
  ]
15
15
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/claude-code-plugin-manifest.json",
3
3
  "name": "deterministic-gates",
4
- "version": "0.9.0",
4
+ "version": "0.10.1",
5
5
  "description": "Deterministic backpressure for coding agents: gates that run on what each turn changed and send the agent back until they pass.",
6
6
  "author": {
7
7
  "name": "Pierre Moati",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "deterministic-gates",
3
- "version": "0.9.0",
3
+ "version": "0.10.1",
4
4
  "description": "Deterministic backpressure for coding agents: gates that run on what each turn changed and send the agent back until they pass.",
5
5
  "author": {
6
6
  "name": "Pierre Moati",
@@ -81,7 +81,8 @@
81
81
  "name": "template-lint",
82
82
  "severity": "error",
83
83
  "files": "\\.html$",
84
- "run": ["eslint", "--max-warnings", "0", "--no-warn-ignored", "{files}"]
84
+ "run": ["eslint", "--max-warnings", "0", "--no-warn-ignored", "{files}"],
85
+ "brokenExitCodes": [2]
85
86
  }
86
87
  },
87
88
  {
@@ -125,6 +125,9 @@ summary { cursor: pointer; color: var(--muted); }
125
125
  "0",
126
126
  "--no-warn-ignored",
127
127
  "{files}"
128
+ ],
129
+ "brokenExitCodes": [
130
+ 2
128
131
  ]
129
132
  }</code></pre></details>
130
133
  </article>
@@ -368,6 +371,9 @@ summary { cursor: pointer; color: var(--muted); }
368
371
  &quot;0&quot;,
369
372
  &quot;--no-warn-ignored&quot;,
370
373
  &quot;{files}&quot;
374
+ ],
375
+ &quot;brokenExitCodes&quot;: [
376
+ 2
371
377
  ]
372
378
  }</code></pre></details>
373
379
  </article>
@@ -14,7 +14,8 @@
14
14
  "name": "lint",
15
15
  "severity": "error",
16
16
  "files": "\\.(ts|tsx|js|mjs)$",
17
- "run": ["eslint", "--max-warnings", "0", "--no-warn-ignored", "{files}"]
17
+ "run": ["eslint", "--max-warnings", "0", "--no-warn-ignored", "{files}"],
18
+ "brokenExitCodes": [2]
18
19
  }
19
20
  },
20
21
  {
@@ -1,10 +1,11 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { changedGatesFiles, gatesOf, isCompared, keepsWatch, readGatesFiles, } from "./config.js";
4
+ import { headOf, movedSince, observed, thereOf } from "./head.js";
4
5
  import { cachedReports, cacheReports } from "./report-cache.js";
5
- import { check, filesOf, givenFiles, missingTool, wholeProject } from "./run.js";
6
- import { changedSince, emptyCommit, hasCommit, lastCommit, snapshot, workingTree } from "./snapshot.js";
7
- import { readTurn, writeTurn } from "./turn-state.js";
6
+ import { check, filesOf, givenFiles, missingTool, namesFiles, wholeProject } from "./run.js";
7
+ import { changedSince, emptyCommit, hasCommit, lastCommit, sharedDir, snapshot, workingTree } from "./snapshot.js";
8
+ import { readThere, readTurn, writeThere, writeTurn } from "./turn-state.js";
8
9
  import { judgeWatch, keepWatch, startWatch, TURN_START_MS, watchReport } from "./watch.js";
9
10
  function missingTools(root, gates) {
10
11
  return gates.flatMap((gate) => {
@@ -38,13 +39,21 @@ export async function startTurn(session, root) {
38
39
  const compared = runnable(gates, missing).filter(isCompared);
39
40
  startWatches(session, root, runnable(gates, missing));
40
41
  const interrupted = readTurn(session, root);
42
+ // The worktrees of a repo share its commits: what the session knows of them is of the repo, not of the folder.
43
+ const shared = sharedDir(root);
44
+ const there = readThere(session, shared);
41
45
  if (interrupted?.checked === false) {
42
- writeTurn(session, root, interrupted);
46
+ // What it committed so far stays the session's, and a commit older than this prompt is one a fetch may bring.
47
+ if (there)
48
+ writeThere(session, shared, observed(root, there, interrupted.at ?? Date.now()));
49
+ writeTurn(session, root, { ...interrupted, at: Date.now() });
43
50
  return told;
44
51
  }
52
+ writeThere(session, shared, thereOf(root, there));
53
+ const head = headOf(root);
45
54
  const { commit: start, tree } = snapshot(root);
46
55
  // The turn starts before its reports are ready: a hook stopped for lack of time leaves it, never the turn before.
47
- writeTurn(session, root, { start, baselines: {}, config, checked: false });
56
+ writeTurn(session, root, { start, ...head, baselines: {}, config, checked: false });
48
57
  const cached = cachedReports(root, tree);
49
58
  const baselines = await Promise.all(compared.map(async (gate) => {
50
59
  const cachedReport = cached(gate);
@@ -60,6 +69,7 @@ export async function startTurn(session, root) {
60
69
  cacheReports(root, tree, baselines.flatMap(({ gate, ok, output }) => (ok && output !== undefined ? [[gate, output]] : [])));
61
70
  writeTurn(session, root, {
62
71
  start,
72
+ ...head,
63
73
  baselines: Object.fromEntries(baselines.flatMap(({ gate, output }) => (output === undefined ? [] : [[gate.name, output]]))),
64
74
  config,
65
75
  checked: false,
@@ -70,17 +80,17 @@ export async function startTurn(session, root) {
70
80
  * Runs, in parallel, each gate that looks at a changed file. A deleted file counts as changed, since a gate that
71
81
  * reads the whole project may break on it, but is never named: a gate given {files} looks at the files left, and
72
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
73
- * running.
83
+ * running. Elsewhere, the reports of the turn start are of code HEAD has left since.
74
84
  */
75
- function runGates(root, gates, changed, turn, baselines, session) {
85
+ function runGates(root, gates, changed, turn, baselines, session, elsewhere = false) {
76
86
  return Promise.all(gates.map(async (gate) => {
77
87
  const matching = filesOf(gate, changed);
78
88
  const files = givenFiles(gate) ? matching.filter((file) => existsSync(join(root, file))) : matching;
79
89
  if (!files.length)
80
90
  return { gate };
81
91
  if (session !== undefined && keepsWatch(gate))
82
- return { gate, outcome: await judgeWatch(session, root, gate, matching, baselines(gate)) };
83
- return { gate, outcome: await check(root, gate, files, turn, baselines(gate)) };
92
+ 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) };
84
94
  }));
85
95
  }
86
96
  function checkedTurn(changed, results, started, notes, { gates, prompts, maxTotalReportChars, showAllPasses }) {
@@ -109,13 +119,14 @@ export async function checkAll(root) {
109
119
  }
110
120
  // A report holds for the tree a turn ends on only if the gate ran clean on the whole project. A gate that failed
111
121
  // keeps the report it started from, so what the turn added stays new until it is fixed, and a gate that did not run
112
- // keeps none: it may still read a changed file its pattern misses, as knip reads tsconfig.json.
113
- function endReports(results, baselines) {
122
+ // keeps none: it may still read a changed file its pattern misses, as knip reads tsconfig.json. Elsewhere, the report
123
+ // a failed gate started from is of code HEAD has left, and is not kept either.
124
+ function endReports(results, baselines, elsewhere) {
114
125
  return results.flatMap(({ gate, outcome }) => {
115
126
  // A gate that could not run says nothing of the tree: the report it started from was a crash, or may be stale.
116
127
  if (!isCompared(gate) || !outcome || outcome.broken)
117
128
  return [];
118
- const report = outcome.ok ? outcome.report : baselines(gate);
129
+ const report = outcome.ok ? outcome.report : elsewhere ? undefined : baselines(gate);
119
130
  return report === undefined ? [] : [[gate, report]];
120
131
  });
121
132
  }
@@ -123,7 +134,8 @@ function endReports(results, baselines) {
123
134
  * Runs each gate that looks at a file the turn changed, with the gates as the turn started: an agent that weakens
124
135
  * them mid-turn changes the next turn, never its own. Without a recorded start, the turn runs from the last commit
125
136
  * with the gates of now; with a start git no longer has, from the last commit with the gates and the reports it
126
- * started with: checking too much beats leaving a hole.
137
+ * started with: checking too much beats leaving a hole. When HEAD moved during the turn to code it did not write, as
138
+ * a checkout or a pull does, the turn is only the files unlike the ones that code holds: the rest came with it.
127
139
  */
128
140
  export async function checkTurn(session, root) {
129
141
  const recorded = readTurn(session, root);
@@ -139,35 +151,54 @@ export async function checkTurn(session, root) {
139
151
  baselines: recorded?.baselines ?? {},
140
152
  config: recorded?.config ?? now,
141
153
  checked: false,
154
+ ...(kept ? { head: kept.head, at: kept.at } : {}),
142
155
  // What the earlier stops of the turn told the agent goes on, so its send-backs and waivers add up.
143
156
  ...(recorded?.sendBacks ? { sendBacks: recorded.sendBacks } : {}),
144
157
  };
145
- const baselines = (gate) => turn.baselines[gate.name];
158
+ const shared = sharedDir(root);
159
+ const there = readThere(session, shared);
160
+ const moved = kept && there && movedSince(root, kept, there);
146
161
  const started = performance.now();
147
162
  const end = workingTree(root);
148
- const changed = changedSince(root, turn.start, end);
163
+ const since = changedSince(root, turn.start, end);
164
+ // A file like the one a commit under HEAD holds came with that commit: the turn did not write it.
165
+ const changed = (moved?.under ?? []).reduce((files, commit) => {
166
+ const unlike = new Set(changedSince(root, commit, end));
167
+ return files.filter((file) => unlike.has(file));
168
+ }, since);
169
+ // Code came with a commit, or left with one: the tree the turn started on no longer tells what the turn wrote.
170
+ const elsewhere = moved !== undefined && (moved.arrived || changed.length < since.length);
171
+ // Where a gate given the turn starts from: then, the commit that brought the code.
172
+ const from = (elsewhere ? moved?.to : undefined) ?? turn.start;
173
+ // A report of code HEAD has left serves a gate whose lines name their file, to count the ones of the turn's files.
174
+ const baselines = (gate) => (elsewhere && !namesFiles(gate) ? undefined : turn.baselines[gate.name]);
149
175
  const config = gatesOf(turn.config);
150
176
  const { gates, refused } = config;
151
177
  const missing = missingTools(root, gates);
152
178
  for (const gate of gates)
153
179
  if (keepsWatch(gate))
154
180
  keepWatch(root, gate);
155
- const results = await runGates(root, runnable(gates, missing), changed, turn.start, baselines, session);
156
- cacheReports(root, end, endReports(results, baselines));
181
+ const results = await runGates(root, runnable(gates, missing), changed, from, baselines, session, elsewhere);
182
+ cacheReports(root, end, endReports(results, baselines, elsewhere));
157
183
  writeTurn(session, root, { ...turn, checked: true });
184
+ if (there)
185
+ writeThere(session, shared, observed(root, there, kept?.at ?? Date.now()));
158
186
  // A compared gate with no report from the turn start can only count its exit code, and a watch has none: a green it
159
187
  // did not earn is said.
160
188
  const uncompared = results
161
189
  .filter(({ gate, outcome }) => outcome && isCompared(gate) && baselines(gate) === undefined)
162
- .map(({ gate }) => keepsWatch(gate)
163
- ? `${gate.name} not judged: no report from the turn start to compare its cycle with`
164
- : `${gate.name} not compared: no report from the turn start, only its exit code counted`);
190
+ .map(({ gate }) => turn.baselines[gate.name] !== undefined
191
+ ? `${gate.name} not compared: its report of the turn start is of the code HEAD left, and its lines name no file`
192
+ : keepsWatch(gate)
193
+ ? `${gate.name} not judged: no report from the turn start to compare its cycle with`
194
+ : `${gate.name} not compared: no report from the turn start, only its exit code counted`);
165
195
  // Only a gate the turn concerned is named: one that would not have run anyway costs nothing to miss.
166
196
  const notRun = missing
167
197
  .filter(({ gate }) => filesOf(gate, changed).length)
168
198
  .map(({ gate, why }) => `${gate.name} not run: ${why}`);
169
199
  const notes = [
170
200
  ...(startNote ? [startNote] : []),
201
+ ...(elsewhere ? ["HEAD moved during the turn to code it did not write: only what the turn wrote is checked"] : []),
171
202
  ...configNote(changedGatesFiles(turn.config, now)),
172
203
  ...uncompared,
173
204
  ...refusedNotes(refused),
@@ -24,6 +24,7 @@ const FIELDS = new Set([
24
24
  "prompt",
25
25
  "maxReportChars",
26
26
  "omitLines",
27
+ "brokenExitCodes",
27
28
  ]);
28
29
  const WATCH_FIELDS = new Set(["run", "cycleStart", "cycleEnd", "failed", "sync", "frozen"]);
29
30
  /** In the arguments of a gate: the changed files it looks at, and the commit of the turn start. */
@@ -94,6 +95,9 @@ const REPORT_CHARS_SHAPE = "maxReportChars is a whole number, 1 or more";
94
95
  function isReportChars(value) {
95
96
  return typeof value === "number" && Number.isInteger(value) && value > 0;
96
97
  }
98
+ function isExitCodes(value) {
99
+ return Array.isArray(value) && value.every((code) => Number.isInteger(code) && code >= 1 && code <= 255);
100
+ }
97
101
  // Nothing unless a file says: the report then keeps the characters the engine gives every gate.
98
102
  function maxReportCharsOf(shared, local) {
99
103
  const max = local.maxReportChars ?? shared.maxReportChars;
@@ -172,7 +176,7 @@ function toWatch(watch, compared) {
172
176
  };
173
177
  }
174
178
  function toGate(entry, maxTimeoutSeconds, reportChars) {
175
- const { name, severity, files, run, compare, ignoreLines, lineKey, watch, prompt, omitLines, timeoutSeconds = maxTimeoutSeconds, maxReportChars = reportChars, } = entry;
179
+ const { name, severity, files, run, compare, ignoreLines, lineKey, watch, prompt, omitLines, brokenExitCodes, timeoutSeconds = maxTimeoutSeconds, maxReportChars = reportChars, } = entry;
176
180
  const unknown = Object.keys(entry).find((key) => !FIELDS.has(key));
177
181
  if (unknown !== undefined)
178
182
  refuse(`unknown field ${unknown}`);
@@ -200,6 +204,8 @@ function toGate(entry, maxTimeoutSeconds, reportChars) {
200
204
  refuse(REPORT_CHARS_SHAPE);
201
205
  if (omitLines !== undefined && !isPattern(omitLines))
202
206
  refuse("omitLines is a regular expression");
207
+ if (brokenExitCodes !== undefined && !isExitCodes(brokenExitCodes))
208
+ refuse("brokenExitCodes is a list of exit codes, each a whole number from 1 to 255");
203
209
  const told = prompt === undefined ? undefined : (toPrompt(prompt) ?? refuse(`prompt is ${PROMPT_SHAPE}`));
204
210
  return {
205
211
  name,
@@ -215,6 +221,7 @@ function toGate(entry, maxTimeoutSeconds, reportChars) {
215
221
  ...(told === undefined ? {} : { prompt: told }),
216
222
  ...(maxReportChars === undefined ? {} : { maxReportChars }),
217
223
  ...(omitLines === undefined ? {} : { omitLines }),
224
+ ...(brokenExitCodes === undefined ? {} : { brokenExitCodes }),
218
225
  };
219
226
  }
220
227
  /**
@@ -0,0 +1,84 @@
1
+ import { branchTips, commitsPast, hasCommit, isIn } from "./snapshot.js";
2
+ export function headOf(root) {
3
+ const { head } = branchTips(root);
4
+ return { ...(head === undefined ? {} : { head }), at: Date.now() };
5
+ }
6
+ /**
7
+ * What a session knows of a repo as a turn starts there, from what it knew: the commit HEAD is on was there, since
8
+ * a turn that made it has been judged on it. Before its first turn, the tips of the branches were.
9
+ */
10
+ export function thereOf(root, before) {
11
+ const { head, tips } = branchTips(root);
12
+ if (before === undefined)
13
+ return { known: tips, made: [] };
14
+ return { known: [...new Set([...before.known, ...(head === undefined ? [] : [head])])], made: before.made };
15
+ }
16
+ /** 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. */
17
+ function madeOf(past, { made }, at) {
18
+ const seen = new Set(made);
19
+ const started = Math.floor(at / 1000);
20
+ return past.filter((commit) => seen.has(commit.hash) || commit.at >= started);
21
+ }
22
+ /**
23
+ * What the session knows once a turn that started then stops: with the commits the turn made, on whatever branch, so
24
+ * that they stay its own in the turns after. Less the known commits git no longer has, as after a deleted branch.
25
+ */
26
+ export function observed(root, there, at) {
27
+ const seen = (known) => {
28
+ const mine = madeOf(commitsPast(root, branchTips(root).tips, known), there, at);
29
+ return { known, made: [...new Set([...there.made, ...mine.map(({ hash }) => hash)])] };
30
+ };
31
+ try {
32
+ return seen(there.known);
33
+ }
34
+ catch {
35
+ const kept = there.known.filter((commit) => hasCommit(root, commit));
36
+ try {
37
+ return seen(kept);
38
+ }
39
+ catch {
40
+ return { known: kept, made: there.made };
41
+ }
42
+ }
43
+ }
44
+ /** The commits that were there, nearest under a commit: itself, or the ones under the commits the session made. */
45
+ function under(tip, made) {
46
+ const there = new Set();
47
+ const seen = new Set();
48
+ const left = [tip];
49
+ for (let commit = left.pop(); commit !== undefined; commit = left.pop()) {
50
+ if (seen.has(commit))
51
+ continue;
52
+ seen.add(commit);
53
+ const parents = made.get(commit);
54
+ if (parents === undefined)
55
+ there.add(commit);
56
+ else
57
+ left.push(...parents);
58
+ }
59
+ return [...there];
60
+ }
61
+ /**
62
+ * Whether the code under HEAD that the session did not write changed since the turn started, as after a checkout, a
63
+ * 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
64
+ * came back to; nor when nothing tells any more, where all the turn changed is checked.
65
+ */
66
+ export function movedSince(root, { head, at }, there) {
67
+ const now = branchTips(root).head;
68
+ if (head === undefined || at === undefined || now === undefined || now === head)
69
+ return undefined;
70
+ let past;
71
+ try {
72
+ past = commitsPast(root, [now, head], there.known);
73
+ }
74
+ catch {
75
+ return undefined;
76
+ }
77
+ const made = new Map(madeOf(past, there, at).map(({ hash, parents }) => [hash, parents]));
78
+ const [before, after] = [under(head, made), under(now, made)];
79
+ if (after.length === before.length && after.every((commit) => before.includes(commit)))
80
+ return undefined;
81
+ const brought = after.find((commit) => !before.some((had) => isIn(root, commit, had)));
82
+ const to = brought ?? after.find((commit) => !before.includes(commit));
83
+ return { under: after, arrived: brought !== undefined, ...(to === undefined ? {} : { to }) };
84
+ }
@@ -135,6 +135,26 @@ function sent(report, omitLines) {
135
135
  const kept = report.split("\n").filter((line) => !omitted.test(line));
136
136
  return kept.some((line) => line.trim()) ? kept.join("\n") : report;
137
137
  }
138
+ // A helper of the engine counts apart the errors of one source line, with `(2)` after the source it quotes and before
139
+ // the tab that ends their key, so that one more of them is new. The agent reads each of them once, with how many
140
+ // times it stands. A line of another tool is left as it is.
141
+ const COUNTED_APART = /` \(\d+\)\t/;
142
+ function saidOnce(report) {
143
+ if (!COUNTED_APART.test(report))
144
+ return report;
145
+ const lines = report.split("\n");
146
+ const keyed = lines.map((line) => line.replace(COUNTED_APART, "`\t"));
147
+ const counted = new Set(keyed.filter((line, at) => line !== lines[at]));
148
+ const times = new Map();
149
+ for (const line of keyed)
150
+ if (counted.has(line))
151
+ times.set(line, (times.get(line) ?? 0) + 1);
152
+ const said = new Set();
153
+ return keyed
154
+ .filter((line) => !times.has(line) || (!said.has(line) && said.add(line)))
155
+ .map((line) => ((times.get(line) ?? 1) > 1 ? `${line} (×${times.get(line)})` : line))
156
+ .join("\n");
157
+ }
138
158
  // The characters each report gets of a total: what it needs when all fit, else the short ones whole and the rest of
139
159
  // the total in equal shares for the long ones.
140
160
  function shares(needs, total) {
@@ -167,13 +187,13 @@ export function toolsToInstall(missing, prompt) {
167
187
  }
168
188
  /**
169
189
  * 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:
170
- * less the lines the gate omits, in the characters it has, and in its share of a total when the reports have one.
190
+ * 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.
171
191
  */
172
192
  export function reports({ outcomes, wording = {} }) {
173
193
  const { gates = [], prompts, maxTotalReportChars = Infinity } = wording;
174
194
  const red = outcomes.filter(failed).map(({ name, output, broken }) => {
175
195
  const gate = gates.find((known) => known.name === name);
176
- const report = sent(output, gate?.omitLines);
196
+ const report = saidOnce(sent(output, gate?.omitLines));
177
197
  const told = [
178
198
  ...(broken ? [worded(BROKEN_GATE, prompts?.brokenGate, "\n")] : []),
179
199
  ...(gate?.prompt ? [gate.prompt.text] : []),
@@ -189,6 +189,7 @@ async function execute(root, gate, args) {
189
189
  ms: performance.now() - started,
190
190
  timedOut: error?.killed === true && error.code !== "ERR_CHILD_PROCESS_STDIO_MAXBUFFER",
191
191
  cannotStart: error?.code === "ENOENT",
192
+ ...(typeof error?.code === "number" ? { exitCode: error.code } : {}),
192
193
  });
193
194
  });
194
195
  });
@@ -218,29 +219,41 @@ export async function wholeProject(root, gate, ms = gate.timeoutSeconds * 1000)
218
219
  const { ok, output, timedOut } = await execute(root, { ...gate, timeoutSeconds }, gate.run.slice(1));
219
220
  return timedOut ? { ok: false } : { ok, output };
220
221
  }
222
+ /** The file a line of a compared gate names, by the group of its key named file. */
223
+ function fileOf(gate, line) {
224
+ return gate.lineKey === undefined ? undefined : new RegExp(gate.lineKey).exec(line)?.groups?.file;
225
+ }
226
+ /** Whether the lines of a compared gate name their file, so that they can be told from the ones of other files. */
227
+ export function namesFiles(gate) {
228
+ return /\(\?<file>/.test(gate.lineKey ?? "");
229
+ }
221
230
  /**
222
231
  * Runs a gate on the turn. A compared gate fails on the lines of output the turn added, and is broken on any exit
223
- * code but 0: the same crash at the start and at the end of a turn prints no new line. A gate out of time is neither.
232
+ * 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
+ * exit codes it names as such. A gate out of time is neither.
224
234
  */
225
- export async function check(root, gate, files, turn, baseline) {
226
- const { ok, output, ms, timedOut, cannotStart } = await execute(root, gate, argumentsOf(gate, files, turn));
235
+ export async function check(root, gate, files, turn, baseline, elsewhere = false) {
236
+ const executed = await execute(root, gate, argumentsOf(gate, files, turn));
237
+ const { ok, output, ms, timedOut, cannotStart, exitCode = 0 } = executed;
227
238
  const ran = { name: gate.name, ms, report: ok ? output : undefined };
228
239
  if (timedOut)
229
240
  return { ...ran, ok, output, timedOut };
230
241
  // A compared gate exits with 0 when it finds problems: any other code is its command that broke.
231
- if (!ok && (cannotStart || isCompared(gate)))
242
+ const broke = cannotStart || isCompared(gate) || gate.brokenExitCodes?.includes(exitCode);
243
+ if (!ok && broke)
232
244
  return { ...ran, ok, output, broken: true };
233
245
  if (!isCompared(gate) || !ok)
234
246
  return { ...ran, ok, output };
235
- return { ...ran, ...addedLines(gate, output, baseline, files) };
247
+ return { ...ran, ...addedLines(gate, output, baseline, files, elsewhere) };
236
248
  }
237
249
  /**
238
250
  * Judges the output of a compared gate that ran clean: it fails on the lines the turn added to the report of the turn
239
- * start. Without that report, nothing counts but the exit code.
251
+ * start. Without that report, nothing counts but the exit code. With a report of code HEAD has left since, elsewhere,
252
+ * only the lines that name a file the turn changed count: the others came with the code HEAD moved to.
240
253
  */
241
- export function addedLines(gate, output, baseline, changed) {
254
+ export function addedLines(gate, output, baseline, changed, elsewhere = false) {
242
255
  if (baseline === undefined)
243
256
  return { ok: true, output: "" };
244
- const added = newLines(baseline, output, gate.ignoreLines, gate.lineKey, changed);
257
+ const added = newLines(baseline, output, gate.ignoreLines, gate.lineKey, changed).filter((line) => !elsewhere || changed.includes(fileOf(gate, line) ?? ""));
245
258
  return { ok: added.length === 0, output: added.join("\n") };
246
259
  }
@@ -2,9 +2,20 @@ import { execFileSync } from "node:child_process";
2
2
  import { cpSync, existsSync, mkdtempSync, rmSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join, resolve } from "node:path";
5
- /** Runs git in the repo, and gives what it printed, trimmed. */
5
+ /**
6
+ * Runs git in the repo, and gives what it printed, without the line break that ends it, however long. Nothing else is
7
+ * trimmed: the name of a file may start with a space.
8
+ */
6
9
  function git(root, args, { env = process.env, input } = {}) {
7
- return execFileSync("git", args, { cwd: root, encoding: "utf8", env, input, stdio: "pipe" }).trim();
10
+ const printed = execFileSync("git", args, {
11
+ cwd: root,
12
+ encoding: "utf8",
13
+ env,
14
+ input,
15
+ stdio: "pipe",
16
+ maxBuffer: Infinity,
17
+ });
18
+ return printed.replace(/\n$/, "");
8
19
  }
9
20
  // One NUL after each path, which git otherwise quotes and escapes when it holds an accent.
10
21
  function paths(printed) {
@@ -107,3 +118,68 @@ export function fileAt(root, commit, file) {
107
118
  export function changedSince(root, start, end = workingTree(root)) {
108
119
  return paths(git(root, ["diff", "-z", "--name-only", start, end])).sort();
109
120
  }
121
+ /** The commit HEAD is on, and the tips of the branches: nothing in a repo with no commit. */
122
+ export function branchTips(root) {
123
+ try {
124
+ const head = git(root, ["rev-parse", "--verify", "--quiet", "HEAD"]);
125
+ const tips = git(root, ["for-each-ref", "--format=%(objectname)", "refs/heads"]).split("\n");
126
+ return { head, tips: [...new Set([head, ...tips.filter(Boolean)])] };
127
+ }
128
+ catch {
129
+ return { tips: [] };
130
+ }
131
+ }
132
+ /** The folder of git that the worktrees of a repo share: what tells that two of them are of the same repo. */
133
+ export function sharedDir(root) {
134
+ try {
135
+ return git(root, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
136
+ }
137
+ catch {
138
+ return root;
139
+ }
140
+ }
141
+ /** Whether a commit is another one, or one it holds. */
142
+ export function isIn(root, commit, other) {
143
+ try {
144
+ git(root, ["merge-base", "--is-ancestor", commit, other]);
145
+ return true;
146
+ }
147
+ catch {
148
+ return false;
149
+ }
150
+ }
151
+ /** The commits these tips hold that none of the known commits does. It throws when git no longer has one of them. */
152
+ export function commitsPast(root, tips, known) {
153
+ const input = known.map((commit) => `^${commit}\n`).join("");
154
+ // Two lines a commit: "commit", its hash and its parents, then its time.
155
+ const lines = git(root, ["rev-list", "--parents", "--format=%ct", "--stdin", ...tips], { input }).split("\n");
156
+ return lines.filter(Boolean).flatMap((line, at, all) => {
157
+ if (at % 2)
158
+ return [];
159
+ const [, hash = "", ...parents] = line.split(" ");
160
+ return [{ hash, parents, at: Number(all[at + 1]) }];
161
+ });
162
+ }
163
+ /**
164
+ * The lines of a file the working tree wrote since a commit that has the file. The file is compared with the one of
165
+ * the commit, not through the index, which does not know a file nobody added; and with the diff of git itself, plain,
166
+ * whatever colours or program the owner set for it.
167
+ */
168
+ export function writtenSince(root, commit, file) {
169
+ const plain = ["--no-color", "--no-ext-diff", "--no-textconv", "--unified=0", "--inter-hunk-context=0"];
170
+ // The name as it is: git would otherwise read the brackets of a file such as [slug].ts as a pattern.
171
+ const diff = git(root, ["--literal-pathspecs", "diff", ...plain, `${commit}:${file}`, "--", file]);
172
+ const hunks = diff.matchAll(/^@@ -\S+ \+(\d+)(?:,(\d+))? @@/gm);
173
+ return [...hunks].map(([, at, lines = "1"]) => ({ at: Number(at), lines: Number(lines) }));
174
+ }
175
+ // Fewer names at once than a command line holds.
176
+ const NAMES_AT_ONCE = 500;
177
+ /** The ones of these files a commit has. */
178
+ export function filesAt(root, commit, files) {
179
+ const found = [];
180
+ for (let at = 0; at < files.length; at += NAMES_AT_ONCE) {
181
+ const names = files.slice(at, at + NAMES_AT_ONCE);
182
+ found.push(...paths(git(root, ["--literal-pathspecs", "ls-tree", "-r", "--name-only", "-z", commit, "--", ...names])));
183
+ }
184
+ return found;
185
+ }
@@ -24,18 +24,24 @@ function isSendBacks(value) {
24
24
  function isTurnState(value) {
25
25
  return (isRecord(value) &&
26
26
  typeof value.start === "string" &&
27
+ (value.head === undefined || typeof value.head === "string") &&
28
+ (value.at === undefined || typeof value.at === "number") &&
27
29
  isStringRecord(value.baselines) &&
28
30
  isGatesFiles(value.config) &&
29
31
  typeof value.checked === "boolean" &&
30
32
  (value.sendBacks === undefined || isSendBacks(value.sendBacks)));
31
33
  }
34
+ function isThere(value) {
35
+ return isRecord(value) && isStringArray(value.known) && isStringArray(value.made);
36
+ }
32
37
  function isSessionState(value) {
33
38
  return (isRecord(value) &&
34
39
  (value.current === undefined || typeof value.current === "string") &&
35
40
  isRecord(value.turns) &&
36
41
  Object.values(value.turns).every(isTurnState) &&
37
42
  (value.told === undefined || (isRecord(value.told) && Object.values(value.told).every(isStringArray))) &&
38
- (value.conductTold === undefined || isStringArray(value.conductTold)));
43
+ (value.conductTold === undefined || isStringArray(value.conductTold)) &&
44
+ (value.there === undefined || (isRecord(value.there) && Object.values(value.there).every(isThere))));
39
45
  }
40
46
  function readSession(session) {
41
47
  const state = readJsonFile(stateFile(session));
@@ -57,6 +63,14 @@ export function writeTurn(session, root, turn) {
57
63
  const unchecked = Object.entries(turns).filter(([, kept]) => !kept.checked);
58
64
  writeSession(session, { ...state, current: root, turns: { ...Object.fromEntries(unchecked), [root]: turn } });
59
65
  }
66
+ /** What the session knows of the commits of a repo, or nothing before its first turn there. */
67
+ export function readThere(session, root) {
68
+ return readSession(session).there?.[root];
69
+ }
70
+ export function writeThere(session, root, there) {
71
+ const state = readSession(session);
72
+ writeSession(session, { ...state, there: { ...state.there, [root]: there } });
73
+ }
60
74
  /** Ends the turn in progress without a check, as a prompt from a folder with no gates, or a failed start, does. */
61
75
  export function forgetTurn(session) {
62
76
  forget(session, "current");
@@ -363,7 +363,7 @@ function readDir(folder) {
363
363
  * the file changes again. Only a stop pays that debt, never the report of a turn start, which would make old a
364
364
  * failure no turn was judged on. A watch that stopped is a broken gate, with the last lines it printed.
365
365
  */
366
- export async function judgeWatch(session, root, gate, files, baseline) {
366
+ export async function judgeWatch(session, root, gate, files, baseline, elsewhere = false) {
367
367
  const folder = folderOf(root, gate);
368
368
  const owed = owedFiles(folder);
369
369
  const asked = [...new Set([...files, ...owed.files])];
@@ -380,14 +380,14 @@ export async function judgeWatch(session, root, gate, files, baseline) {
380
380
  // Paid, less what a stop out of time meanwhile added: only the lists this stop asked for.
381
381
  for (const list of owed.lists)
382
382
  rmSync(list, { force: true });
383
- const judged = judgeCycle(gate, settled.cycle, baseline, asked);
383
+ const judged = judgeCycle(gate, settled.cycle, baseline, asked, elsewhere);
384
384
  return { name, ms, ...judged, report: judged.ok ? settled.cycle : undefined };
385
385
  }
386
386
  /** The verdict of a cycle: its failed lines, or for a compared gate, the lines it added to the report of the turn start. */
387
- function judgeCycle(gate, cycle, baseline, files) {
387
+ function judgeCycle(gate, cycle, baseline, files, elsewhere) {
388
388
  const fails = new RegExp(gate.watch.failed ?? "(?!)");
389
389
  return isCompared(gate)
390
- ? addedLines(gate, cycle, baseline, files)
390
+ ? addedLines(gate, cycle, baseline, files, elsewhere)
391
391
  : { ok: !cycle.split("\n").some((line) => fails.test(line)), output: cycle };
392
392
  }
393
393
  /**