@tayomi/deterministic-gates 0.9.0 → 0.10.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.9.0"
12
+ "version": "0.10.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.9.0",
4
+ "version": "0.10.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.9.0",
3
+ "version": "0.10.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",
@@ -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,8 +1,9 @@
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 } from "./head.js";
4
5
  import { cachedReports, cacheReports } from "./report-cache.js";
5
- import { check, filesOf, givenFiles, missingTool, wholeProject } from "./run.js";
6
+ import { check, filesOf, givenFiles, missingTool, namesFiles, wholeProject } from "./run.js";
6
7
  import { changedSince, emptyCommit, hasCommit, lastCommit, snapshot, workingTree } from "./snapshot.js";
7
8
  import { readTurn, writeTurn } from "./turn-state.js";
8
9
  import { judgeWatch, keepWatch, startWatch, TURN_START_MS, watchReport } from "./watch.js";
@@ -42,9 +43,10 @@ export async function startTurn(session, root) {
42
43
  writeTurn(session, root, interrupted);
43
44
  return told;
44
45
  }
46
+ const head = headOf(root);
45
47
  const { commit: start, tree } = snapshot(root);
46
48
  // 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 });
49
+ writeTurn(session, root, { start, ...head, baselines: {}, config, checked: false });
48
50
  const cached = cachedReports(root, tree);
49
51
  const baselines = await Promise.all(compared.map(async (gate) => {
50
52
  const cachedReport = cached(gate);
@@ -60,6 +62,7 @@ export async function startTurn(session, root) {
60
62
  cacheReports(root, tree, baselines.flatMap(({ gate, ok, output }) => (ok && output !== undefined ? [[gate, output]] : [])));
61
63
  writeTurn(session, root, {
62
64
  start,
65
+ ...head,
63
66
  baselines: Object.fromEntries(baselines.flatMap(({ gate, output }) => (output === undefined ? [] : [[gate.name, output]]))),
64
67
  config,
65
68
  checked: false,
@@ -70,17 +73,17 @@ export async function startTurn(session, root) {
70
73
  * Runs, in parallel, each gate that looks at a changed file. A deleted file counts as changed, since a gate that
71
74
  * reads the whole project may break on it, but is never named: a gate given {files} looks at the files left, and
72
75
  * 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.
76
+ * running. Elsewhere, the reports of the turn start are of code HEAD has left since.
74
77
  */
75
- function runGates(root, gates, changed, turn, baselines, session) {
78
+ function runGates(root, gates, changed, turn, baselines, session, elsewhere = false) {
76
79
  return Promise.all(gates.map(async (gate) => {
77
80
  const matching = filesOf(gate, changed);
78
81
  const files = givenFiles(gate) ? matching.filter((file) => existsSync(join(root, file))) : matching;
79
82
  if (!files.length)
80
83
  return { gate };
81
84
  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)) };
85
+ return { gate, outcome: await judgeWatch(session, root, gate, matching, baselines(gate), elsewhere) };
86
+ return { gate, outcome: await check(root, gate, files, turn, baselines(gate), elsewhere) };
84
87
  }));
85
88
  }
86
89
  function checkedTurn(changed, results, started, notes, { gates, prompts, maxTotalReportChars, showAllPasses }) {
@@ -109,13 +112,14 @@ export async function checkAll(root) {
109
112
  }
110
113
  // 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
114
  // 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) {
115
+ // keeps none: it may still read a changed file its pattern misses, as knip reads tsconfig.json. Elsewhere, the report
116
+ // a failed gate started from is of code HEAD has left, and is not kept either.
117
+ function endReports(results, baselines, elsewhere) {
114
118
  return results.flatMap(({ gate, outcome }) => {
115
119
  // A gate that could not run says nothing of the tree: the report it started from was a crash, or may be stale.
116
120
  if (!isCompared(gate) || !outcome || outcome.broken)
117
121
  return [];
118
- const report = outcome.ok ? outcome.report : baselines(gate);
122
+ const report = outcome.ok ? outcome.report : elsewhere ? undefined : baselines(gate);
119
123
  return report === undefined ? [] : [[gate, report]];
120
124
  });
121
125
  }
@@ -123,7 +127,9 @@ function endReports(results, baselines) {
123
127
  * Runs each gate that looks at a file the turn changed, with the gates as the turn started: an agent that weakens
124
128
  * them mid-turn changes the next turn, never its own. Without a recorded start, the turn runs from the last commit
125
129
  * 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.
130
+ * started with: checking too much beats leaving a hole. When HEAD moved during the turn to code it did not write, as
131
+ * a checkout or a pull does, the turn is only what the tree differs by from the commit HEAD reached, with what the
132
+ * turn committed before: the rest came with that commit.
127
133
  */
128
134
  export async function checkTurn(session, root) {
129
135
  const recorded = readTurn(session, root);
@@ -139,35 +145,44 @@ export async function checkTurn(session, root) {
139
145
  baselines: recorded?.baselines ?? {},
140
146
  config: recorded?.config ?? now,
141
147
  checked: false,
148
+ ...(kept ? { head: kept.head, moves: kept.moves } : {}),
142
149
  // What the earlier stops of the turn told the agent goes on, so its send-backs and waivers add up.
143
150
  ...(recorded?.sendBacks ? { sendBacks: recorded.sendBacks } : {}),
144
151
  };
145
- const baselines = (gate) => turn.baselines[gate.name];
152
+ const moved = kept && movedSince(root, kept);
153
+ // A report of code HEAD has left serves a gate whose lines name their file, to count the ones of the turn's files.
154
+ const baselines = (gate) => (moved && !namesFiles(gate) ? undefined : turn.baselines[gate.name]);
146
155
  const started = performance.now();
147
156
  const end = workingTree(root);
148
- const changed = changedSince(root, turn.start, end);
157
+ const since = changedSince(root, turn.start, end);
158
+ const own = moved && new Set([...changedSince(root, moved.to, end), ...moved.committed]);
159
+ const changed = own ? since.filter((file) => own.has(file)) : since;
149
160
  const config = gatesOf(turn.config);
150
161
  const { gates, refused } = config;
151
162
  const missing = missingTools(root, gates);
152
163
  for (const gate of gates)
153
164
  if (keepsWatch(gate))
154
165
  keepWatch(root, gate);
155
- const results = await runGates(root, runnable(gates, missing), changed, turn.start, baselines, session);
156
- cacheReports(root, end, endReports(results, baselines));
166
+ const from = moved?.to ?? turn.start;
167
+ const results = await runGates(root, runnable(gates, missing), changed, from, baselines, session, moved !== undefined);
168
+ cacheReports(root, end, endReports(results, baselines, moved !== undefined));
157
169
  writeTurn(session, root, { ...turn, checked: true });
158
170
  // 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
171
  // did not earn is said.
160
172
  const uncompared = results
161
173
  .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`);
174
+ .map(({ gate }) => turn.baselines[gate.name] !== undefined
175
+ ? `${gate.name} not compared: its report of the turn start is of the code HEAD left, and its lines name no file`
176
+ : keepsWatch(gate)
177
+ ? `${gate.name} not judged: no report from the turn start to compare its cycle with`
178
+ : `${gate.name} not compared: no report from the turn start, only its exit code counted`);
165
179
  // Only a gate the turn concerned is named: one that would not have run anyway costs nothing to miss.
166
180
  const notRun = missing
167
181
  .filter(({ gate }) => filesOf(gate, changed).length)
168
182
  .map(({ gate, why }) => `${gate.name} not run: ${why}`);
169
183
  const notes = [
170
184
  ...(startNote ? [startNote] : []),
185
+ ...(moved ? [`HEAD moved during the turn (${moved.how}): only what the turn changed since is checked`] : []),
171
186
  ...configNote(changedGatesFiles(turn.config, now)),
172
187
  ...uncompared,
173
188
  ...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,30 @@
1
+ import { commitFiles, headMoves } from "./snapshot.js";
2
+ // 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,
3
+ // as an amend or a cherry-pick: checking too much beats leaving a hole.
4
+ const NOT_ITS_COMMIT = /^(checkout|pull|merge|rebase|reset)\b/;
5
+ // A merge the turn commits brings the code of a branch too: of its files, the turn wrote the conflicts it resolved.
6
+ const ELSEWHERE = new RegExp(`${NOT_ITS_COMMIT.source}|^commit \\(merge\\)`);
7
+ export function headOf(root) {
8
+ const moves = headMoves(root);
9
+ const head = moves.at(-1)?.to;
10
+ return { moves: moves.length, ...(head === undefined ? {} : { head }) };
11
+ }
12
+ /**
13
+ * Whether HEAD moved, since the turn started, to code the turn did not write: a checkout, a pull, a merge, a rebase or
14
+ * a reset. Nothing when it did not, or when the reflog no longer tells: all the turn changed is then checked.
15
+ */
16
+ export function movedSince(root, { head, moves }) {
17
+ if (moves === undefined)
18
+ return undefined;
19
+ const all = headMoves(root);
20
+ if (all[moves - 1]?.to !== head)
21
+ return undefined;
22
+ // A move that reaches the commit it left brings no code, as a new branch or a stash does.
23
+ const since = all.slice(moves).filter(({ from, to }) => from !== to);
24
+ const last = since.findLastIndex(({ how }) => ELSEWHERE.test(how));
25
+ const move = since[last];
26
+ if (move === undefined)
27
+ return undefined;
28
+ const own = since.filter(({ how }) => !NOT_ITS_COMMIT.test(how));
29
+ return { to: move.to, how: move.how, committed: own.flatMap(({ to }) => commitFiles(root, to)) };
30
+ }
@@ -135,6 +135,19 @@ 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)` before the tab that ends their key,
139
+ // so that one more of them is new. The agent reads each of them once, with how many times it stands.
140
+ function saidOnce(report) {
141
+ const lines = report.split("\n").map((line) => line.replace(/ \(\d+\)\t/, "\t"));
142
+ const times = new Map();
143
+ for (const line of lines)
144
+ if (line.includes("\t"))
145
+ times.set(line, (times.get(line) ?? 0) + 1);
146
+ return lines
147
+ .filter((line, at) => !times.has(line) || lines.indexOf(line) === at)
148
+ .map((line) => ((times.get(line) ?? 1) > 1 ? `${line} (×${times.get(line)})` : line))
149
+ .join("\n");
150
+ }
138
151
  // The characters each report gets of a total: what it needs when all fit, else the short ones whole and the rest of
139
152
  // the total in equal shares for the long ones.
140
153
  function shares(needs, total) {
@@ -167,13 +180,13 @@ export function toolsToInstall(missing, prompt) {
167
180
  }
168
181
  /**
169
182
  * 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.
183
+ * 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.
171
184
  */
172
185
  export function reports({ outcomes, wording = {} }) {
173
186
  const { gates = [], prompts, maxTotalReportChars = Infinity } = wording;
174
187
  const red = outcomes.filter(failed).map(({ name, output, broken }) => {
175
188
  const gate = gates.find((known) => known.name === name);
176
- const report = sent(output, gate?.omitLines);
189
+ const report = sent(saidOnce(output), gate?.omitLines);
177
190
  const told = [
178
191
  ...(broken ? [worded(BROKEN_GATE, prompts?.brokenGate, "\n")] : []),
179
192
  ...(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
  }
@@ -107,3 +107,22 @@ export function fileAt(root, commit, file) {
107
107
  export function changedSince(root, start, end = workingTree(root)) {
108
108
  return paths(git(root, ["diff", "-z", "--name-only", start, end])).sort();
109
109
  }
110
+ /** The moves of HEAD its reflog holds, oldest first: none in a repo with no commit, or that keeps no reflog. */
111
+ export function headMoves(root) {
112
+ try {
113
+ const entries = git(root, ["reflog", "show", "--format=%H %gs", "HEAD"]).split("\n").filter(Boolean).reverse();
114
+ const reached = entries.map((entry) => entry.slice(0, entry.indexOf(" ")));
115
+ return entries.map((entry, at) => ({
116
+ from: reached[at - 1],
117
+ to: reached[at] ?? "",
118
+ how: entry.slice(entry.indexOf(" ") + 1),
119
+ }));
120
+ }
121
+ catch {
122
+ return [];
123
+ }
124
+ }
125
+ /** The files a commit changed. For a merge, the ones it leaves unlike each of its parents: its resolved conflicts. */
126
+ export function commitFiles(root, commit) {
127
+ return paths(git(root, ["diff-tree", "--no-commit-id", "--name-only", "-r", "-c", "--root", "-z", commit]));
128
+ }
@@ -24,6 +24,8 @@ 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.moves === undefined || typeof value.moves === "number") &&
27
29
  isStringRecord(value.baselines) &&
28
30
  isGatesFiles(value.config) &&
29
31
  typeof value.checked === "boolean" &&
@@ -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
  /**
@@ -44,18 +44,19 @@ export function newBulkSuppressions(before, after, moved = () => false) {
44
44
  return cameWithIt ? [] : [`${source}: ${rule} ${old} -> ${count}`];
45
45
  }));
46
46
  }
47
- function main(root, turn, files) {
48
- const found = files.flatMap((file) => {
47
+ /** The counts the turn raised in the suppressions files given, each under the name of its file. */
48
+ export function bulkSuppressions(root, turn, files) {
49
+ return files.flatMap((file) => {
49
50
  const before = fileAt(root, turn, file);
50
- // ESLint names a source from the folder it runs in, which holds its suppressions file unless the repo moved it:
51
- // a source not found there is never taken for a moved one.
52
- const moved = (source) => {
53
- const path = join(dirname(file), source);
54
- return existsSync(join(root, path)) && fileAt(root, turn, path) === undefined;
55
- };
56
- const rose = newBulkSuppressions(before === undefined ? undefined : parseJson(before), parseJson(readFileSync(file, "utf8")), moved);
51
+ // ESLint names a source from the folder it runs in: the one of its suppressions file, or the root of the repo
52
+ // when the repo keeps that file in a folder of its own. A source found in neither is never taken for a moved one.
53
+ const moved = (source) => [join(dirname(file), source), source].some((path) => existsSync(join(root, path)) && fileAt(root, turn, path) === undefined);
54
+ const rose = newBulkSuppressions(before === undefined ? undefined : parseJson(before), parseJson(readFileSync(join(root, file), "utf8")), moved);
57
55
  return rose.map((line) => `${file}: ${line}`);
58
56
  });
57
+ }
58
+ function main(root, turn, files) {
59
+ const found = bulkSuppressions(root, turn, files);
59
60
  if (!found.length)
60
61
  return;
61
62
  console.log(headed("New bulk suppressions: fix the violations, never the file that hides them.", found));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tayomi/deterministic-gates",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Deterministic backpressure for coding agents: gates that run on what each turn changed and send the agent back until they pass.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/core/check.ts CHANGED
@@ -10,8 +10,9 @@ import {
10
10
  type Prompts,
11
11
  readGatesFiles,
12
12
  } from "./config.ts";
13
+ import { headOf, movedSince } from "./head.ts";
13
14
  import { cachedReports, cacheReports } from "./report-cache.ts";
14
- import { check, filesOf, givenFiles, missingTool, type Outcome, wholeProject } from "./run.ts";
15
+ import { check, filesOf, givenFiles, missingTool, namesFiles, type Outcome, wholeProject } from "./run.ts";
15
16
  import { changedSince, emptyCommit, hasCommit, lastCommit, snapshot, workingTree } from "./snapshot.ts";
16
17
  import { readTurn, type TurnState, writeTurn } from "./turn-state.ts";
17
18
  import { judgeWatch, keepWatch, startWatch, TURN_START_MS, watchReport } from "./watch.ts";
@@ -88,9 +89,10 @@ export async function startTurn(session: string, root: string): Promise<string[]
88
89
  writeTurn(session, root, interrupted);
89
90
  return told;
90
91
  }
92
+ const head = headOf(root);
91
93
  const { commit: start, tree } = snapshot(root);
92
94
  // The turn starts before its reports are ready: a hook stopped for lack of time leaves it, never the turn before.
93
- writeTurn(session, root, { start, baselines: {}, config, checked: false });
95
+ writeTurn(session, root, { start, ...head, baselines: {}, config, checked: false });
94
96
  const cached = cachedReports(root, tree);
95
97
  const baselines = await Promise.all(
96
98
  compared.map(async (gate): Promise<{ gate: Gate; ok: boolean; output?: string }> => {
@@ -110,6 +112,7 @@ export async function startTurn(session: string, root: string): Promise<string[]
110
112
  );
111
113
  writeTurn(session, root, {
112
114
  start,
115
+ ...head,
113
116
  baselines: Object.fromEntries(
114
117
  baselines.flatMap(({ gate, output }) => (output === undefined ? [] : [[gate.name, output]])),
115
118
  ),
@@ -123,7 +126,7 @@ export async function startTurn(session: string, root: string): Promise<string[]
123
126
  * Runs, in parallel, each gate that looks at a changed file. A deleted file counts as changed, since a gate that
124
127
  * reads the whole project may break on it, but is never named: a gate given {files} looks at the files left, and
125
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
126
- * running.
129
+ * running. Elsewhere, the reports of the turn start are of code HEAD has left since.
127
130
  */
128
131
  function runGates(
129
132
  root: string,
@@ -132,6 +135,7 @@ function runGates(
132
135
  turn: string,
133
136
  baselines: Baselines,
134
137
  session?: string,
138
+ elsewhere = false,
135
139
  ): Promise<Result[]> {
136
140
  return Promise.all(
137
141
  gates.map(async (gate) => {
@@ -139,8 +143,8 @@ function runGates(
139
143
  const files = givenFiles(gate) ? matching.filter((file) => existsSync(join(root, file))) : matching;
140
144
  if (!files.length) return { gate };
141
145
  if (session !== undefined && keepsWatch(gate))
142
- return { gate, outcome: await judgeWatch(session, root, gate, matching, baselines(gate)) };
143
- return { gate, outcome: await check(root, gate, files, turn, baselines(gate)) };
146
+ 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) };
144
148
  }),
145
149
  );
146
150
  }
@@ -179,12 +183,13 @@ export async function checkAll(root: string): Promise<CheckedTurn> {
179
183
 
180
184
  // A report holds for the tree a turn ends on only if the gate ran clean on the whole project. A gate that failed
181
185
  // keeps the report it started from, so what the turn added stays new until it is fixed, and a gate that did not run
182
- // keeps none: it may still read a changed file its pattern misses, as knip reads tsconfig.json.
183
- function endReports(results: Result[], baselines: Baselines) {
186
+ // keeps none: it may still read a changed file its pattern misses, as knip reads tsconfig.json. Elsewhere, the report
187
+ // a failed gate started from is of code HEAD has left, and is not kept either.
188
+ function endReports(results: Result[], baselines: Baselines, elsewhere: boolean) {
184
189
  return results.flatMap(({ gate, outcome }) => {
185
190
  // A gate that could not run says nothing of the tree: the report it started from was a crash, or may be stale.
186
191
  if (!isCompared(gate) || !outcome || outcome.broken) return [];
187
- const report = outcome.ok ? outcome.report : baselines(gate);
192
+ const report = outcome.ok ? outcome.report : elsewhere ? undefined : baselines(gate);
188
193
  return report === undefined ? [] : [[gate, report] as const];
189
194
  });
190
195
  }
@@ -193,7 +198,9 @@ function endReports(results: Result[], baselines: Baselines) {
193
198
  * Runs each gate that looks at a file the turn changed, with the gates as the turn started: an agent that weakens
194
199
  * them mid-turn changes the next turn, never its own. Without a recorded start, the turn runs from the last commit
195
200
  * with the gates of now; with a start git no longer has, from the last commit with the gates and the reports it
196
- * started with: checking too much beats leaving a hole.
201
+ * 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.
197
204
  */
198
205
  export async function checkTurn(session: string, root: string): Promise<CheckedTurn> {
199
206
  const recorded = readTurn(session, root);
@@ -210,28 +217,44 @@ export async function checkTurn(session: string, root: string): Promise<CheckedT
210
217
  baselines: recorded?.baselines ?? {},
211
218
  config: recorded?.config ?? now,
212
219
  checked: false,
220
+ ...(kept ? { head: kept.head, moves: kept.moves } : {}),
213
221
  // What the earlier stops of the turn told the agent goes on, so its send-backs and waivers add up.
214
222
  ...(recorded?.sendBacks ? { sendBacks: recorded.sendBacks } : {}),
215
223
  };
216
- const baselines: Baselines = (gate) => turn.baselines[gate.name];
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]);
217
227
  const started = performance.now();
218
228
  const end = workingTree(root);
219
- const changed = changedSince(root, turn.start, end);
229
+ 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;
220
232
  const config = gatesOf(turn.config);
221
233
  const { gates, refused } = config;
222
234
  const missing = missingTools(root, gates);
223
235
  for (const gate of gates) if (keepsWatch(gate)) keepWatch(root, gate);
224
- const results = await runGates(root, runnable(gates, missing), changed, turn.start, baselines, session);
225
- cacheReports(root, end, endReports(results, baselines));
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));
226
247
  writeTurn(session, root, { ...turn, checked: true });
227
248
  // A compared gate with no report from the turn start can only count its exit code, and a watch has none: a green it
228
249
  // did not earn is said.
229
250
  const uncompared = results
230
251
  .filter(({ gate, outcome }) => outcome && isCompared(gate) && baselines(gate) === undefined)
231
252
  .map(({ gate }) =>
232
- keepsWatch(gate)
233
- ? `${gate.name} not judged: no report from the turn start to compare its cycle with`
234
- : `${gate.name} not compared: no report from the turn start, only its exit code counted`,
253
+ turn.baselines[gate.name] !== undefined
254
+ ? `${gate.name} not compared: its report of the turn start is of the code HEAD left, and its lines name no file`
255
+ : keepsWatch(gate)
256
+ ? `${gate.name} not judged: no report from the turn start to compare its cycle with`
257
+ : `${gate.name} not compared: no report from the turn start, only its exit code counted`,
235
258
  );
236
259
  // Only a gate the turn concerned is named: one that would not have run anyway costs nothing to miss.
237
260
  const notRun = missing
@@ -239,6 +262,7 @@ export async function checkTurn(session: string, root: string): Promise<CheckedT
239
262
  .map(({ gate, why }) => `${gate.name} not run: ${why}`);
240
263
  const notes = [
241
264
  ...(startNote ? [startNote] : []),
265
+ ...(moved ? [`HEAD moved during the turn (${moved.how}): only what the turn changed since is checked`] : []),
242
266
  ...configNote(changedGatesFiles(turn.config, now)),
243
267
  ...uncompared,
244
268
  ...refusedNotes(refused),
@@ -26,6 +26,7 @@ const FIELDS = new Set([
26
26
  "prompt",
27
27
  "maxReportChars",
28
28
  "omitLines",
29
+ "brokenExitCodes",
29
30
  ]);
30
31
  const WATCH_FIELDS = new Set(["run", "cycleStart", "cycleEnd", "failed", "sync", "frozen"]);
31
32
 
@@ -73,6 +74,8 @@ export interface Gate {
73
74
  omitLines?: string;
74
75
  /** What the agent is told with the report of the gate. Replaced, an engine helper leaves its own line out. */
75
76
  prompt?: Prompt;
77
+ /** The exit codes of its command that mean it broke, where any other than 0 means it found a problem. */
78
+ brokenExitCodes?: number[];
76
79
  }
77
80
 
78
81
  /**
@@ -176,6 +179,10 @@ function isReportChars(value: unknown): value is number {
176
179
  return typeof value === "number" && Number.isInteger(value) && value > 0;
177
180
  }
178
181
 
182
+ function isExitCodes(value: unknown): value is number[] {
183
+ return Array.isArray(value) && value.every((code) => Number.isInteger(code) && code >= 1 && code <= 255);
184
+ }
185
+
179
186
  // Nothing unless a file says: the report then keeps the characters the engine gives every gate.
180
187
  function maxReportCharsOf(shared: GatesFile, local: GatesFile): number | undefined {
181
188
  const max = local.maxReportChars ?? shared.maxReportChars;
@@ -265,6 +272,7 @@ function toGate(entry: Entry, maxTimeoutSeconds: number, reportChars: number | u
265
272
  watch,
266
273
  prompt,
267
274
  omitLines,
275
+ brokenExitCodes,
268
276
  timeoutSeconds = maxTimeoutSeconds,
269
277
  maxReportChars = reportChars,
270
278
  } = entry;
@@ -285,6 +293,8 @@ function toGate(entry: Entry, maxTimeoutSeconds: number, reportChars: number | u
285
293
  if (typeof timeoutSeconds !== "number" || timeoutSeconds <= 0) refuse("timeoutSeconds is a positive number");
286
294
  if (maxReportChars !== undefined && !isReportChars(maxReportChars)) refuse(REPORT_CHARS_SHAPE);
287
295
  if (omitLines !== undefined && !isPattern(omitLines)) refuse("omitLines is a regular expression");
296
+ if (brokenExitCodes !== undefined && !isExitCodes(brokenExitCodes))
297
+ refuse("brokenExitCodes is a list of exit codes, each a whole number from 1 to 255");
288
298
  const told = prompt === undefined ? undefined : (toPrompt(prompt) ?? refuse(`prompt is ${PROMPT_SHAPE}`));
289
299
  return {
290
300
  name,
@@ -300,6 +310,7 @@ function toGate(entry: Entry, maxTimeoutSeconds: number, reportChars: number | u
300
310
  ...(told === undefined ? {} : { prompt: told }),
301
311
  ...(maxReportChars === undefined ? {} : { maxReportChars }),
302
312
  ...(omitLines === undefined ? {} : { omitLines }),
313
+ ...(brokenExitCodes === undefined ? {} : { brokenExitCodes }),
303
314
  };
304
315
  }
305
316
 
@@ -0,0 +1,45 @@
1
+ import { commitFiles, headMoves } from "./snapshot.ts";
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\\)`);
8
+
9
+ /** HEAD as a turn starts: its commit, and how many moves its reflog holds. */
10
+ export interface Head {
11
+ head?: string;
12
+ moves?: number;
13
+ }
14
+
15
+ /** The last move of a turn that took HEAD to code the turn did not write. */
16
+ 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[];
22
+ }
23
+
24
+ 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 }) };
28
+ }
29
+
30
+ /**
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.
33
+ */
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)) };
45
+ }
@@ -168,6 +168,18 @@ function sent(report: string, omitLines: string | undefined): string {
168
168
  return kept.some((line) => line.trim()) ? kept.join("\n") : report;
169
169
  }
170
170
 
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.
173
+ function saidOnce(report: string): string {
174
+ const lines = report.split("\n").map((line) => line.replace(/ \(\d+\)\t/, "\t"));
175
+ 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)
179
+ .map((line) => ((times.get(line) ?? 1) > 1 ? `${line} (×${times.get(line)})` : line))
180
+ .join("\n");
181
+ }
182
+
171
183
  // The characters each report gets of a total: what it needs when all fit, else the short ones whole and the rest of
172
184
  // the total in equal shares for the long ones.
173
185
  function shares(needs: number[], total: number): number[] {
@@ -205,13 +217,13 @@ export function toolsToInstall(missing: string[], prompt?: Prompt): string {
205
217
 
206
218
  /**
207
219
  * 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:
208
- * less the lines the gate omits, in the characters it has, and in its share of a total when the reports have one.
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.
209
221
  */
210
222
  export function reports({ outcomes, wording = {} }: Pick<CheckedTurn, "outcomes" | "wording">): string[] {
211
223
  const { gates = [], prompts, maxTotalReportChars = Infinity } = wording;
212
224
  const red = outcomes.filter(failed).map(({ name, output, broken }) => {
213
225
  const gate = gates.find((known) => known.name === name);
214
- const report = sent(output, gate?.omitLines);
226
+ const report = sent(saidOnce(output), gate?.omitLines);
215
227
  const told = [
216
228
  ...(broken ? [worded(BROKEN_GATE, prompts?.brokenGate, "\n")] : []),
217
229
  ...(gate?.prompt ? [gate.prompt.text] : []),
package/src/core/run.ts CHANGED
@@ -205,6 +205,8 @@ interface Executed {
205
205
  timedOut: boolean;
206
206
  /** The command was never started: it is missing, or the engine cannot resolve it. */
207
207
  cannotStart: boolean;
208
+ /** The code the command exited with, when it ran to its end. */
209
+ exitCode?: number;
208
210
  }
209
211
 
210
212
  async function execute(root: string, gate: Gate, args: string[]): Promise<Executed> {
@@ -240,6 +242,7 @@ async function execute(root: string, gate: Gate, args: string[]): Promise<Execut
240
242
  ms: performance.now() - started,
241
243
  timedOut: error?.killed === true && error.code !== "ERR_CHILD_PROCESS_STDIO_MAXBUFFER",
242
244
  cannotStart: error?.code === "ENOENT",
245
+ ...(typeof error?.code === "number" ? { exitCode: error.code } : {}),
243
246
  });
244
247
  },
245
248
  );
@@ -282,9 +285,20 @@ export async function wholeProject(
282
285
  return timedOut ? { ok: false } : { ok, output };
283
286
  }
284
287
 
288
+ /** The file a line of a compared gate names, by the group of its key named file. */
289
+ function fileOf(gate: Gate, line: string): string | undefined {
290
+ return gate.lineKey === undefined ? undefined : new RegExp(gate.lineKey).exec(line)?.groups?.file;
291
+ }
292
+
293
+ /** Whether the lines of a compared gate name their file, so that they can be told from the ones of other files. */
294
+ export function namesFiles(gate: Gate): boolean {
295
+ return /\(\?<file>/.test(gate.lineKey ?? "");
296
+ }
297
+
285
298
  /**
286
299
  * Runs a gate on the turn. A compared gate fails on the lines of output the turn added, and is broken on any exit
287
- * 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.
300
+ * 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
301
+ * exit codes it names as such. A gate out of time is neither.
288
302
  */
289
303
  export async function check(
290
304
  root: string,
@@ -292,27 +306,34 @@ export async function check(
292
306
  files: string[],
293
307
  turn: string,
294
308
  baseline: string | undefined,
309
+ elsewhere = false,
295
310
  ): Promise<Outcome> {
296
- const { ok, output, ms, timedOut, cannotStart } = await execute(root, gate, argumentsOf(gate, files, turn));
311
+ const executed = await execute(root, gate, argumentsOf(gate, files, turn));
312
+ const { ok, output, ms, timedOut, cannotStart, exitCode = 0 } = executed;
297
313
  const ran = { name: gate.name, ms, report: ok ? output : undefined };
298
314
  if (timedOut) return { ...ran, ok, output, timedOut };
299
315
  // A compared gate exits with 0 when it finds problems: any other code is its command that broke.
300
- if (!ok && (cannotStart || isCompared(gate))) return { ...ran, ok, output, broken: true };
316
+ const broke = cannotStart || isCompared(gate) || gate.brokenExitCodes?.includes(exitCode);
317
+ if (!ok && broke) return { ...ran, ok, output, broken: true };
301
318
  if (!isCompared(gate) || !ok) return { ...ran, ok, output };
302
- return { ...ran, ...addedLines(gate, output, baseline, files) };
319
+ return { ...ran, ...addedLines(gate, output, baseline, files, elsewhere) };
303
320
  }
304
321
 
305
322
  /**
306
323
  * Judges the output of a compared gate that ran clean: it fails on the lines the turn added to the report of the turn
307
- * start. Without that report, nothing counts but the exit code.
324
+ * start. Without that report, nothing counts but the exit code. With a report of code HEAD has left since, elsewhere,
325
+ * only the lines that name a file the turn changed count: the others came with the code HEAD moved to.
308
326
  */
309
327
  export function addedLines(
310
328
  gate: Gate,
311
329
  output: string,
312
330
  baseline: string | undefined,
313
331
  changed: string[],
332
+ elsewhere = false,
314
333
  ): { ok: boolean; output: string } {
315
334
  if (baseline === undefined) return { ok: true, output: "" };
316
- const added = newLines(baseline, output, gate.ignoreLines, gate.lineKey, changed);
335
+ const added = newLines(baseline, output, gate.ignoreLines, gate.lineKey, changed).filter(
336
+ (line) => !elsewhere || changed.includes(fileOf(gate, line) ?? ""),
337
+ );
317
338
  return { ok: added.length === 0, output: added.join("\n") };
318
339
  }
@@ -118,3 +118,30 @@ export function fileAt(root: string, commit: string, file: string): string | und
118
118
  export function changedSince(root: string, start: string, end = workingTree(root)): string[] {
119
119
  return paths(git(root, ["diff", "-z", "--name-only", start, end])).sort();
120
120
  }
121
+
122
+ /** A move of HEAD, as its reflog tells it: the commit it left, the one it reached, and how. */
123
+ export interface HeadMove {
124
+ from: string | undefined;
125
+ to: string;
126
+ how: string;
127
+ }
128
+
129
+ /** The moves of HEAD its reflog holds, oldest first: none in a repo with no commit, or that keeps no reflog. */
130
+ export function headMoves(root: string): HeadMove[] {
131
+ try {
132
+ const entries = git(root, ["reflog", "show", "--format=%H %gs", "HEAD"]).split("\n").filter(Boolean).reverse();
133
+ const reached = entries.map((entry) => entry.slice(0, entry.indexOf(" ")));
134
+ return entries.map((entry, at) => ({
135
+ from: reached[at - 1],
136
+ to: reached[at] ?? "",
137
+ how: entry.slice(entry.indexOf(" ") + 1),
138
+ }));
139
+ } catch {
140
+ return [];
141
+ }
142
+ }
143
+
144
+ /** The files a commit changed. For a merge, the ones it leaves unlike each of its parents: its resolved conflicts. */
145
+ export function commitFiles(root: string, commit: string): string[] {
146
+ return paths(git(root, ["diff-tree", "--no-commit-id", "--name-only", "-r", "-c", "--root", "-z", commit]));
147
+ }
@@ -2,6 +2,7 @@ import { writeFileSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import type { GatesFiles } from "./config.ts";
5
+ import type { Head } from "./head.ts";
5
6
  import { isRecord, isStringArray, isStringRecord, readJsonFile } from "./json.ts";
6
7
 
7
8
  /** A red gate the agent chose to leave, with why, bound to the fingerprint of the report it saw. */
@@ -21,11 +22,11 @@ export interface SendBacks {
21
22
  }
22
23
 
23
24
  /**
24
- * What a turn started from: the commit, the reports of its compared gates, and the gates files themselves, since a
25
- * turn is checked with the gates it started with. A turn the owner interrupts never reaches its check: it stays
26
- * unchecked until the next turn of its repo. Once checked, what its stops told the agent.
25
+ * What a turn started from: the commit, where HEAD was, the reports of its compared gates, and the gates files
26
+ * themselves, since a turn is checked with the gates it started with. A turn the owner interrupts never reaches its
27
+ * check: it stays unchecked until the next turn of its repo. Once checked, what its stops told the agent.
27
28
  */
28
- export interface TurnState {
29
+ export interface TurnState extends Head {
29
30
  start: string;
30
31
  baselines: Record<string, string>;
31
32
  config: GatesFiles;
@@ -78,6 +79,8 @@ function isTurnState(value: unknown): value is TurnState {
78
79
  return (
79
80
  isRecord(value) &&
80
81
  typeof value.start === "string" &&
82
+ (value.head === undefined || typeof value.head === "string") &&
83
+ (value.moves === undefined || typeof value.moves === "number") &&
81
84
  isStringRecord(value.baselines) &&
82
85
  isGatesFiles(value.config) &&
83
86
  typeof value.checked === "boolean" &&
package/src/core/watch.ts CHANGED
@@ -398,6 +398,7 @@ export async function judgeWatch(
398
398
  gate: WatchedGate,
399
399
  files: string[],
400
400
  baseline: string | undefined,
401
+ elsewhere = false,
401
402
  ): Promise<Outcome> {
402
403
  const folder = folderOf(root, gate);
403
404
  const owed = owedFiles(folder);
@@ -413,7 +414,7 @@ export async function judgeWatch(
413
414
  }
414
415
  // Paid, less what a stop out of time meanwhile added: only the lists this stop asked for.
415
416
  for (const list of owed.lists) rmSync(list, { force: true });
416
- const judged = judgeCycle(gate, settled.cycle, baseline, asked);
417
+ const judged = judgeCycle(gate, settled.cycle, baseline, asked, elsewhere);
417
418
  return { name, ms, ...judged, report: judged.ok ? settled.cycle : undefined };
418
419
  }
419
420
 
@@ -423,10 +424,11 @@ function judgeCycle(
423
424
  cycle: string,
424
425
  baseline: string | undefined,
425
426
  files: string[],
427
+ elsewhere: boolean,
426
428
  ): { ok: boolean; output: string } {
427
429
  const fails = new RegExp(gate.watch.failed ?? "(?!)");
428
430
  return isCompared(gate)
429
- ? addedLines(gate, cycle, baseline, files)
431
+ ? addedLines(gate, cycle, baseline, files, elsewhere)
430
432
  : { ok: !cycle.split("\n").some((line) => fails.test(line)), output: cycle };
431
433
  }
432
434
 
@@ -58,22 +58,27 @@ export function newBulkSuppressions(
58
58
  );
59
59
  }
60
60
 
61
- function main(root: string, turn: string, files: string[]): void {
62
- const found = files.flatMap((file) => {
61
+ /** The counts the turn raised in the suppressions files given, each under the name of its file. */
62
+ export function bulkSuppressions(root: string, turn: string, files: string[]): string[] {
63
+ return files.flatMap((file) => {
63
64
  const before = fileAt(root, turn, file);
64
- // ESLint names a source from the folder it runs in, which holds its suppressions file unless the repo moved it:
65
- // a source not found there is never taken for a moved one.
66
- const moved = (source: string) => {
67
- const path = join(dirname(file), source);
68
- return existsSync(join(root, path)) && fileAt(root, turn, path) === undefined;
69
- };
65
+ // ESLint names a source from the folder it runs in: the one of its suppressions file, or the root of the repo
66
+ // when the repo keeps that file in a folder of its own. A source found in neither is never taken for a moved one.
67
+ const moved = (source: string) =>
68
+ [join(dirname(file), source), source].some(
69
+ (path) => existsSync(join(root, path)) && fileAt(root, turn, path) === undefined,
70
+ );
70
71
  const rose = newBulkSuppressions(
71
72
  before === undefined ? undefined : parseJson(before),
72
- parseJson(readFileSync(file, "utf8")),
73
+ parseJson(readFileSync(join(root, file), "utf8")),
73
74
  moved,
74
75
  );
75
76
  return rose.map((line) => `${file}: ${line}`);
76
77
  });
78
+ }
79
+
80
+ function main(root: string, turn: string, files: string[]): void {
81
+ const found = bulkSuppressions(root, turn, files);
77
82
  if (!found.length) return;
78
83
  console.log(headed("New bulk suppressions: fix the violations, never the file that hides them.", found));
79
84
  process.exitCode = 1;