@tayomi/deterministic-gates 0.8.2 → 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.8.2"
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.8.2",
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.8.2",
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",
package/README.md CHANGED
@@ -91,7 +91,7 @@ To check the whole repo, as before adopting the gates, in a pre-push hook or in
91
91
  npx @tayomi/deterministic-gates check
92
92
  ```
93
93
 
94
- Every gate runs on every file that matches, and the command exits with 1 when a gate fails.
94
+ Every gate runs on every file that matches, and the command exits with 1 when a gate fails. With `--format json`, it prints each gate and its status for a tool to read: see [the whole check](docs/turn.md#the-whole-check).
95
95
 
96
96
  ## Develop
97
97
 
@@ -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
  {
@@ -40,7 +40,7 @@ summary { cursor: pointer; color: var(--muted); }
40
40
  <h1>Gate catalog</h1>
41
41
  <p>The gates worth copying into a repo. Nothing here runs by itself: the engine reads only the repo's <code>.gates.json</code>. Copy the definition of a gate there, install what it requires, and adapt its <code>files</code> to the layout of the repo.</p>
42
42
  <p>Generated from <code>catalog/*.json</code> by <code>pnpm catalog</code>: edit those files, never this page.</p>
43
- <nav><a href="#angular">Angular (4)</a><a href="#go">Go (6)</a><a href="#python">Python (3)</a><a href="#typescript">TypeScript (9)</a></nav>
43
+ <nav><a href="#angular">Angular (4)</a><a href="#go">Go (6)</a><a href="#python">Python (3)</a><a href="#typescript">TypeScript (10)</a></nav>
44
44
  </header>
45
45
  <section id="angular">
46
46
  <h2>Angular</h2>
@@ -125,6 +125,9 @@ summary { cursor: pointer; color: var(--muted); }
125
125
  &quot;0&quot;,
126
126
  &quot;--no-warn-ignored&quot;,
127
127
  &quot;{files}&quot;
128
+ ],
129
+ &quot;brokenExitCodes&quot;: [
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>
@@ -531,16 +537,16 @@ summary { cursor: pointer; color: var(--muted); }
531
537
  </article>
532
538
  <article id="typescript/no-new-suppressions">
533
539
  <h3><code>typescript/no-new-suppressions</code></h3>
534
- <p>Fails on the rule suppressions the turn added, never on the ones already there: eslint-disable, @ts-ignore, @ts-expect-error, @ts-nocheck, prettier-ignore, biome-ignore. The cheapest green is to silence the rule, and this is the gate that refuses it.</p>
540
+ <p>Fails on the rule suppressions the turn added, never on the ones already there: eslint-disable, @ts-ignore, @ts-expect-error, @ts-nocheck, prettier-ignore, biome-ignore, stylelint-disable. The cheapest green is to silence the rule, and this is the gate that refuses it.</p>
535
541
  <dl>
536
542
  <dt>Runs</dt><dd><code>{engine}/src/helpers/new-suppressions.ts {turn} {files}</code></dd>
537
- <dt>When the turn changes</dt><dd><code>\.(ts|tsx|js|jsx|mjs|cjs)$</code></dd>
543
+ <dt>When the turn changes</dt><dd><code>\.(ts|tsx|js|jsx|mjs|cjs|css|scss)$</code></dd>
538
544
  <dt>Requires</dt><dd><ul></ul></dd>
539
545
  </dl>
540
546
  <details><summary>Definition to copy into .gates.json</summary><pre><code>{
541
547
  &quot;name&quot;: &quot;no-new-suppressions&quot;,
542
548
  &quot;severity&quot;: &quot;error&quot;,
543
- &quot;files&quot;: &quot;\\.(ts|tsx|js|jsx|mjs|cjs)$&quot;,
549
+ &quot;files&quot;: &quot;\\.(ts|tsx|js|jsx|mjs|cjs|css|scss)$&quot;,
544
550
  &quot;run&quot;: [
545
551
  &quot;{engine}/src/helpers/new-suppressions.ts&quot;,
546
552
  &quot;{turn}&quot;,
@@ -548,6 +554,25 @@ summary { cursor: pointer; color: var(--muted); }
548
554
  ]
549
555
  }</code></pre></details>
550
556
  </article>
557
+ <article id="typescript/no-new-bulk-suppressions">
558
+ <h3><code>typescript/no-new-bulk-suppressions</code></h3>
559
+ <p>Fails when the turn raised a count of an ESLint suppressions file, the one eslint --suppress-all writes: every violation of now goes into it, and the lint turns green with no comment in the code. A file the turn created or moved may take over the counts that left another, as long as the file holds no more of the rule than before: any other count that rises fails. Give its files the suppressions file of the repo, wherever --suppressions-location puts it.</p>
560
+ <dl>
561
+ <dt>Runs</dt><dd><code>{engine}/src/helpers/bulk-suppressions.ts {turn} {files}</code></dd>
562
+ <dt>When the turn changes</dt><dd><code>(^|/)eslint-suppressions\.json$</code></dd>
563
+ <dt>Requires</dt><dd><ul></ul></dd>
564
+ </dl>
565
+ <details><summary>Definition to copy into .gates.json</summary><pre><code>{
566
+ &quot;name&quot;: &quot;no-new-bulk-suppressions&quot;,
567
+ &quot;severity&quot;: &quot;error&quot;,
568
+ &quot;files&quot;: &quot;(^|/)eslint-suppressions\\.json$&quot;,
569
+ &quot;run&quot;: [
570
+ &quot;{engine}/src/helpers/bulk-suppressions.ts&quot;,
571
+ &quot;{turn}&quot;,
572
+ &quot;{files}&quot;
573
+ ]
574
+ }</code></pre></details>
575
+ </article>
551
576
  </section>
552
577
  </main>
553
578
  </body>
@@ -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
  {
@@ -141,14 +142,24 @@
141
142
  }
142
143
  },
143
144
  {
144
- "description": "Fails on the rule suppressions the turn added, never on the ones already there: eslint-disable, @ts-ignore, @ts-expect-error, @ts-nocheck, prettier-ignore, biome-ignore. The cheapest green is to silence the rule, and this is the gate that refuses it.",
145
+ "description": "Fails on the rule suppressions the turn added, never on the ones already there: eslint-disable, @ts-ignore, @ts-expect-error, @ts-nocheck, prettier-ignore, biome-ignore, stylelint-disable. The cheapest green is to silence the rule, and this is the gate that refuses it.",
145
146
  "requires": [],
146
147
  "gate": {
147
148
  "name": "no-new-suppressions",
148
149
  "severity": "error",
149
- "files": "\\.(ts|tsx|js|jsx|mjs|cjs)$",
150
+ "files": "\\.(ts|tsx|js|jsx|mjs|cjs|css|scss)$",
150
151
  "run": ["{engine}/src/helpers/new-suppressions.ts", "{turn}", "{files}"]
151
152
  }
153
+ },
154
+ {
155
+ "description": "Fails when the turn raised a count of an ESLint suppressions file, the one eslint --suppress-all writes: every violation of now goes into it, and the lint turns green with no comment in the code. A file the turn created or moved may take over the counts that left another, as long as the file holds no more of the rule than before: any other count that rises fails. Give its files the suppressions file of the repo, wherever --suppressions-location puts it.",
156
+ "requires": [],
157
+ "gate": {
158
+ "name": "no-new-bulk-suppressions",
159
+ "severity": "error",
160
+ "files": "(^|/)eslint-suppressions\\.json$",
161
+ "run": ["{engine}/src/helpers/bulk-suppressions.ts", "{turn}", "{files}"]
162
+ }
152
163
  }
153
164
  ]
154
165
  }
package/dist/src/cli.js CHANGED
@@ -3,7 +3,7 @@ import { readFileSync } from "node:fs";
3
3
  import { checkAll } from "./core/check.js";
4
4
  import { configuredRoot } from "./core/config.js";
5
5
  import { messageOf } from "./core/json.js";
6
- import { broken, reports, summary } from "./core/report.js";
6
+ import { broken, reports, results, summary } from "./core/report.js";
7
7
  import { failed } from "./core/run.js";
8
8
  import { HOOK_EVENTS, handleHook, isHookEvent } from "./hook/hook.js";
9
9
  function readStdin() {
@@ -15,13 +15,16 @@ function readStdin() {
15
15
  }
16
16
  }
17
17
  /** What the command prints when it is called with words it does not know, named by the bin of the npm package. */
18
- export const USAGE = `Usage: deterministic-gates check, or deterministic-gates hook <${HOOK_EVENTS.join("|")}>`;
18
+ export const USAGE = `Usage: deterministic-gates check [--format json], or deterministic-gates hook <${HOOK_EVENTS.join("|")}>`;
19
19
  // The helpers of the engine run only on import.meta.main, which came with Node 24.2: below, they are a silent green.
20
20
  const [major = 0, minor = 0] = process.versions.node.split(".").map(Number);
21
21
  const oldNode = major < 24 || (major === 24 && minor < 2)
22
22
  ? `Node 24.2 or later is needed, this is ${process.versions.node}.`
23
23
  : undefined;
24
- async function main([command, event]) {
24
+ async function main([command, ...words]) {
25
+ const [event] = words;
26
+ // For a tool, such as a CI or a script, where the text is for the one who reads the terminal.
27
+ const json = words.join(" ") === "--format json";
25
28
  if (oldNode !== undefined) {
26
29
  if (command === "hook")
27
30
  console.log(JSON.stringify({ systemMessage: broken(oldNode) }));
@@ -35,7 +38,7 @@ async function main([command, event]) {
35
38
  if (output)
36
39
  console.log(JSON.stringify(output));
37
40
  }
38
- else if (command === "check" && event === undefined) {
41
+ else if (command === "check" && (json || event === undefined)) {
39
42
  const root = configuredRoot(process.cwd());
40
43
  if (root === undefined) {
41
44
  console.error("Not in a git repository, or no .gates.json in it.");
@@ -44,7 +47,7 @@ async function main([command, event]) {
44
47
  else {
45
48
  try {
46
49
  const all = await checkAll(root);
47
- console.log([summary(all), ...reports(all.outcomes)].join("\n\n"));
50
+ console.log(json ? JSON.stringify(results(all), null, 2) : [summary(all), ...reports(all)].join("\n\n"));
48
51
  if (all.outcomes.some(failed))
49
52
  process.exitCode = 1;
50
53
  }
@@ -1,8 +1,9 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { changedGatesFiles, gatesOf, isCompared, keepsWatch, readGatesFiles } from "./config.js";
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,20 +73,20 @@ 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
- function checkedTurn(changed, results, started, notes, showAllPasses) {
89
+ function checkedTurn(changed, results, started, notes, { gates, prompts, maxTotalReportChars, showAllPasses }) {
87
90
  return {
88
91
  changed,
89
92
  outcomes: results.flatMap(({ outcome }) => (outcome ? [outcome] : [])),
@@ -91,6 +94,7 @@ function checkedTurn(changed, results, started, notes, showAllPasses) {
91
94
  ms: performance.now() - started,
92
95
  note: notes.join("\n") || undefined,
93
96
  ...(showAllPasses ? { showAllPasses } : {}),
97
+ wording: { gates, prompts, maxTotalReportChars },
94
98
  };
95
99
  }
96
100
  /**
@@ -102,18 +106,20 @@ export async function checkAll(root) {
102
106
  const started = performance.now();
103
107
  const empty = emptyCommit(root);
104
108
  const files = changedSince(root, empty);
105
- const { gates, refused, showAllPasses } = gatesOf(readGatesFiles(root));
106
- const results = await runGates(root, gates, files, empty, () => "");
107
- return checkedTurn(files, results, started, refusedNotes(refused), showAllPasses);
109
+ const config = gatesOf(readGatesFiles(root));
110
+ const results = await runGates(root, config.gates, files, empty, () => "");
111
+ return checkedTurn(files, results, started, refusedNotes(config.refused), config);
108
112
  }
109
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
110
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
111
- // keeps none: it may still read a changed file its pattern misses, as knip reads tsconfig.json.
112
- 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) {
113
118
  return results.flatMap(({ gate, outcome }) => {
114
- if (!isCompared(gate) || !outcome)
119
+ // A gate that could not run says nothing of the tree: the report it started from was a crash, or may be stale.
120
+ if (!isCompared(gate) || !outcome || outcome.broken)
115
121
  return [];
116
- const report = outcome.ok ? outcome.report : baselines(gate);
122
+ const report = outcome.ok ? outcome.report : elsewhere ? undefined : baselines(gate);
117
123
  return report === undefined ? [] : [[gate, report]];
118
124
  });
119
125
  }
@@ -121,7 +127,9 @@ function endReports(results, baselines) {
121
127
  * Runs each gate that looks at a file the turn changed, with the gates as the turn started: an agent that weakens
122
128
  * them mid-turn changes the next turn, never its own. Without a recorded start, the turn runs from the last commit
123
129
  * with the gates of now; with a start git no longer has, from the last commit with the gates and the reports it
124
- * 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.
125
133
  */
126
134
  export async function checkTurn(session, root) {
127
135
  const recorded = readTurn(session, root);
@@ -137,40 +145,50 @@ export async function checkTurn(session, root) {
137
145
  baselines: recorded?.baselines ?? {},
138
146
  config: recorded?.config ?? now,
139
147
  checked: false,
148
+ ...(kept ? { head: kept.head, moves: kept.moves } : {}),
140
149
  // What the earlier stops of the turn told the agent goes on, so its send-backs and waivers add up.
141
150
  ...(recorded?.sendBacks ? { sendBacks: recorded.sendBacks } : {}),
142
151
  };
143
- 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]);
144
155
  const started = performance.now();
145
156
  const end = workingTree(root);
146
- const changed = changedSince(root, turn.start, end);
147
- const { gates, refused, showAllPasses } = gatesOf(turn.config);
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;
160
+ const config = gatesOf(turn.config);
161
+ const { gates, refused } = config;
148
162
  const missing = missingTools(root, gates);
149
163
  for (const gate of gates)
150
164
  if (keepsWatch(gate))
151
165
  keepWatch(root, gate);
152
- const results = await runGates(root, runnable(gates, missing), changed, turn.start, baselines, session);
153
- 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));
154
169
  writeTurn(session, root, { ...turn, checked: true });
155
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
156
171
  // did not earn is said.
157
172
  const uncompared = results
158
173
  .filter(({ gate, outcome }) => outcome && isCompared(gate) && baselines(gate) === undefined)
159
- .map(({ gate }) => keepsWatch(gate)
160
- ? `${gate.name} not judged: no report from the turn start to compare its cycle with`
161
- : `${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`);
162
179
  // Only a gate the turn concerned is named: one that would not have run anyway costs nothing to miss.
163
180
  const notRun = missing
164
181
  .filter(({ gate }) => filesOf(gate, changed).length)
165
182
  .map(({ gate, why }) => `${gate.name} not run: ${why}`);
166
183
  const notes = [
167
184
  ...(startNote ? [startNote] : []),
185
+ ...(moved ? [`HEAD moved during the turn (${moved.how}): only what the turn changed since is checked`] : []),
168
186
  ...configNote(changedGatesFiles(turn.config, now)),
169
187
  ...uncompared,
170
188
  ...refusedNotes(refused),
171
189
  ...notRun,
172
190
  ];
173
- return checkedTurn(changed, results, started, notes, showAllPasses);
191
+ return checkedTurn(changed, results, started, notes, config);
174
192
  }
175
193
  function refusedNotes(refused) {
176
194
  return refused.map(({ name, why }) => `${name} not run, its entry is wrong: ${why}`);
@@ -8,6 +8,9 @@ const LOCAL_GATES_FILE = ".gates.local.json";
8
8
  const DEFAULT_MAX_TIMEOUT_SECONDS = 45;
9
9
  // The times a turn sends the agent back: enough for a fix that breaks another gate, never a loop.
10
10
  const DEFAULT_MAX_SEND_BACKS = 5;
11
+ // The characters of reports a send-back holds, all gates together: what one gate may send alone. The agent fixes
12
+ // the first problems, and the next check shows it what is left.
13
+ const DEFAULT_MAX_TOTAL_REPORT_CHARS = 4000;
11
14
  const FIELDS = new Set([
12
15
  "name",
13
16
  "severity",
@@ -18,11 +21,28 @@ const FIELDS = new Set([
18
21
  "lineKey",
19
22
  "timeoutSeconds",
20
23
  "watch",
24
+ "prompt",
25
+ "maxReportChars",
26
+ "omitLines",
27
+ "brokenExitCodes",
21
28
  ]);
22
29
  const WATCH_FIELDS = new Set(["run", "cycleStart", "cycleEnd", "failed", "sync", "frozen"]);
23
30
  /** In the arguments of a gate: the changed files it looks at, and the commit of the turn start. */
24
31
  export const FILES = "{files}";
25
32
  export const TURN = "{turn}";
33
+ /**
34
+ * What the engine tells the agent that a repo may word again: as it sends it back, as it asks for missing tools, and
35
+ * with the report of a gate the turn broke.
36
+ */
37
+ const PROMPTS = ["sendBack", "missingTools", "brokenGate"];
38
+ function toPrompt(value) {
39
+ if (typeof value === "string" && value)
40
+ return { text: value, replace: false };
41
+ if (!isRecord(value) || Object.keys(value).join() !== "replace")
42
+ return undefined;
43
+ return typeof value.replace === "string" && value.replace ? { text: value.replace, replace: true } : undefined;
44
+ }
45
+ const PROMPT_SHAPE = 'a text to add to what the agent is told, or {"replace": "a text"} to say it instead';
26
46
  export function keepsWatch(gate) {
27
47
  return gate.watch !== undefined;
28
48
  }
@@ -44,10 +64,12 @@ function fileOf(text, file) {
44
64
  catch (error) {
45
65
  throw new Error(`${file} is not valid JSON: ${messageOf(error)}.`);
46
66
  }
47
- const { gates = [], maxTimeoutSeconds, showAllPasses, maxSendBacks, ...others } = isRecord(parsed) ? parsed : { others: true };
67
+ const { gates = [], maxTimeoutSeconds, showAllPasses, maxSendBacks, maxReportChars, maxTotalReportChars, prompts, ...others } = isRecord(parsed) ? parsed : { others: true };
48
68
  if (!Array.isArray(gates) || Object.keys(others).length)
49
69
  throw new Error(`${file} holds "gates", a list of gates, "maxTimeoutSeconds", the most seconds a gate may take, ` +
50
- `"showAllPasses", to name every green gate, and "maxSendBacks", the most times a turn sends the agent back.`);
70
+ `"showAllPasses", to name every green gate, "maxSendBacks", the most times a turn sends the agent back, ` +
71
+ `"maxReportChars", the most characters of a report the agent is sent, "maxTotalReportChars", the most of ` +
72
+ `all its reports together, and "prompts", what the agent is told.`);
51
73
  const entries = gates.map((entry) => {
52
74
  if (!isRecord(entry) || typeof entry.name !== "string")
53
75
  throw new Error(`${file}: every gate has a name.`);
@@ -58,8 +80,42 @@ function fileOf(text, file) {
58
80
  ...(maxTimeoutSeconds === undefined ? {} : { maxTimeoutSeconds }),
59
81
  ...(showAllPasses === undefined ? {} : { showAllPasses }),
60
82
  ...(maxSendBacks === undefined ? {} : { maxSendBacks }),
83
+ ...(maxReportChars === undefined ? {} : { maxReportChars }),
84
+ ...(maxTotalReportChars === undefined ? {} : { maxTotalReportChars }),
85
+ ...(prompts === undefined ? {} : { prompts }),
61
86
  };
62
87
  }
88
+ function maxTotalReportCharsOf(shared, local) {
89
+ const max = local.maxTotalReportChars ?? shared.maxTotalReportChars ?? DEFAULT_MAX_TOTAL_REPORT_CHARS;
90
+ if (!isReportChars(max))
91
+ throw new Error("maxTotalReportChars is a whole number, 1 or more.");
92
+ return max;
93
+ }
94
+ const REPORT_CHARS_SHAPE = "maxReportChars is a whole number, 1 or more";
95
+ function isReportChars(value) {
96
+ return typeof value === "number" && Number.isInteger(value) && value > 0;
97
+ }
98
+ function isExitCodes(value) {
99
+ return Array.isArray(value) && value.every((code) => Number.isInteger(code) && code >= 1 && code <= 255);
100
+ }
101
+ // Nothing unless a file says: the report then keeps the characters the engine gives every gate.
102
+ function maxReportCharsOf(shared, local) {
103
+ const max = local.maxReportChars ?? shared.maxReportChars;
104
+ if (max !== undefined && !isReportChars(max))
105
+ throw new Error(`${REPORT_CHARS_SHAPE}.`);
106
+ return max;
107
+ }
108
+ function promptsOf({ prompts = {} }) {
109
+ const known = PROMPTS.map((key) => `"${key}"`).join(", ");
110
+ if (!isRecord(prompts) || Object.keys(prompts).some((key) => !PROMPTS.some((prompt) => prompt === key)))
111
+ throw new Error(`prompts holds ${known}.`);
112
+ return Object.fromEntries(Object.entries(prompts).map(([key, value]) => {
113
+ const prompt = toPrompt(value);
114
+ if (prompt === undefined)
115
+ throw new Error(`prompts.${key} is ${PROMPT_SHAPE}.`);
116
+ return [key, prompt];
117
+ }));
118
+ }
63
119
  // The local file's own value wins, as for the fields of a gate.
64
120
  function maxTimeoutOf(shared, local) {
65
121
  const max = local.maxTimeoutSeconds ?? shared.maxTimeoutSeconds ?? DEFAULT_MAX_TIMEOUT_SECONDS;
@@ -119,8 +175,8 @@ function toWatch(watch, compared) {
119
175
  ...(compared ? {} : { failed: pattern("failed", failed) }),
120
176
  };
121
177
  }
122
- function toGate(entry, maxTimeoutSeconds) {
123
- const { name, severity, files, run, compare, ignoreLines, lineKey, watch, timeoutSeconds = maxTimeoutSeconds, } = entry;
178
+ function toGate(entry, maxTimeoutSeconds, reportChars) {
179
+ const { name, severity, files, run, compare, ignoreLines, lineKey, watch, prompt, omitLines, brokenExitCodes, timeoutSeconds = maxTimeoutSeconds, maxReportChars = reportChars, } = entry;
124
180
  const unknown = Object.keys(entry).find((key) => !FIELDS.has(key));
125
181
  if (unknown !== undefined)
126
182
  refuse(`unknown field ${unknown}`);
@@ -144,6 +200,13 @@ function toGate(entry, maxTimeoutSeconds) {
144
200
  refuse("lineKey tells apart the lines of a compared gate: it takes compare");
145
201
  if (typeof timeoutSeconds !== "number" || timeoutSeconds <= 0)
146
202
  refuse("timeoutSeconds is a positive number");
203
+ if (maxReportChars !== undefined && !isReportChars(maxReportChars))
204
+ refuse(REPORT_CHARS_SHAPE);
205
+ if (omitLines !== undefined && !isPattern(omitLines))
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");
209
+ const told = prompt === undefined ? undefined : (toPrompt(prompt) ?? refuse(`prompt is ${PROMPT_SHAPE}`));
147
210
  return {
148
211
  name,
149
212
  severity,
@@ -155,6 +218,10 @@ function toGate(entry, maxTimeoutSeconds) {
155
218
  ...(ignoreLines === undefined ? {} : { ignoreLines }),
156
219
  ...(lineKey === undefined ? {} : { lineKey }),
157
220
  ...(watch === undefined ? {} : { watch: toWatch(watch, compare !== undefined) }),
221
+ ...(told === undefined ? {} : { prompt: told }),
222
+ ...(maxReportChars === undefined ? {} : { maxReportChars }),
223
+ ...(omitLines === undefined ? {} : { omitLines }),
224
+ ...(brokenExitCodes === undefined ? {} : { brokenExitCodes }),
158
225
  };
159
226
  }
160
227
  /**
@@ -166,6 +233,7 @@ export function readGates(shared, local) {
166
233
  const sharedFile = fileOf(shared, GATES_FILE);
167
234
  const localFile = fileOf(local, LOCAL_GATES_FILE);
168
235
  const max = maxTimeoutOf(sharedFile, localFile);
236
+ const reportChars = maxReportCharsOf(sharedFile, localFile);
169
237
  const merged = new Map(sharedFile.entries.map((entry) => [entry.name, entry]));
170
238
  for (const entry of localFile.entries)
171
239
  merged.set(entry.name, { ...merged.get(entry.name), ...entry });
@@ -174,12 +242,15 @@ export function readGates(shared, local) {
174
242
  refused: [],
175
243
  showAllPasses: showAllPassesOf(sharedFile, localFile),
176
244
  maxSendBacks: maxSendBacksOf(sharedFile, localFile),
245
+ maxTotalReportChars: maxTotalReportCharsOf(sharedFile, localFile),
246
+ // The local file's own prompt wins, key by key.
247
+ prompts: { ...promptsOf(sharedFile), ...promptsOf(localFile) },
177
248
  };
178
249
  for (const entry of merged.values()) {
179
250
  if (entry.severity === "off")
180
251
  continue;
181
252
  try {
182
- read.gates.push(toGate(entry, max));
253
+ read.gates.push(toGate(entry, max, reportChars));
183
254
  }
184
255
  catch (error) {
185
256
  read.refused.push({ name: entry.name, why: messageOf(error) });
@@ -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
+ }