@tayomi/deterministic-gates 0.8.1 → 0.9.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.1"
12
+ "version": "0.9.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.1",
4
+ "version": "0.9.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.1",
3
+ "version": "0.9.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
 
@@ -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>
@@ -531,16 +531,16 @@ summary { cursor: pointer; color: var(--muted); }
531
531
  </article>
532
532
  <article id="typescript/no-new-suppressions">
533
533
  <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>
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, stylelint-disable. The cheapest green is to silence the rule, and this is the gate that refuses it.</p>
535
535
  <dl>
536
536
  <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>
537
+ <dt>When the turn changes</dt><dd><code>\.(ts|tsx|js|jsx|mjs|cjs|css|scss)$</code></dd>
538
538
  <dt>Requires</dt><dd><ul></ul></dd>
539
539
  </dl>
540
540
  <details><summary>Definition to copy into .gates.json</summary><pre><code>{
541
541
  &quot;name&quot;: &quot;no-new-suppressions&quot;,
542
542
  &quot;severity&quot;: &quot;error&quot;,
543
- &quot;files&quot;: &quot;\\.(ts|tsx|js|jsx|mjs|cjs)$&quot;,
543
+ &quot;files&quot;: &quot;\\.(ts|tsx|js|jsx|mjs|cjs|css|scss)$&quot;,
544
544
  &quot;run&quot;: [
545
545
  &quot;{engine}/src/helpers/new-suppressions.ts&quot;,
546
546
  &quot;{turn}&quot;,
@@ -548,6 +548,25 @@ summary { cursor: pointer; color: var(--muted); }
548
548
  ]
549
549
  }</code></pre></details>
550
550
  </article>
551
+ <article id="typescript/no-new-bulk-suppressions">
552
+ <h3><code>typescript/no-new-bulk-suppressions</code></h3>
553
+ <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>
554
+ <dl>
555
+ <dt>Runs</dt><dd><code>{engine}/src/helpers/bulk-suppressions.ts {turn} {files}</code></dd>
556
+ <dt>When the turn changes</dt><dd><code>(^|/)eslint-suppressions\.json$</code></dd>
557
+ <dt>Requires</dt><dd><ul></ul></dd>
558
+ </dl>
559
+ <details><summary>Definition to copy into .gates.json</summary><pre><code>{
560
+ &quot;name&quot;: &quot;no-new-bulk-suppressions&quot;,
561
+ &quot;severity&quot;: &quot;error&quot;,
562
+ &quot;files&quot;: &quot;(^|/)eslint-suppressions\\.json$&quot;,
563
+ &quot;run&quot;: [
564
+ &quot;{engine}/src/helpers/bulk-suppressions.ts&quot;,
565
+ &quot;{turn}&quot;,
566
+ &quot;{files}&quot;
567
+ ]
568
+ }</code></pre></details>
569
+ </article>
551
570
  </section>
552
571
  </main>
553
572
  </body>
@@ -141,14 +141,24 @@
141
141
  }
142
142
  },
143
143
  {
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.",
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, stylelint-disable. The cheapest green is to silence the rule, and this is the gate that refuses it.",
145
145
  "requires": [],
146
146
  "gate": {
147
147
  "name": "no-new-suppressions",
148
148
  "severity": "error",
149
- "files": "\\.(ts|tsx|js|jsx|mjs|cjs)$",
149
+ "files": "\\.(ts|tsx|js|jsx|mjs|cjs|css|scss)$",
150
150
  "run": ["{engine}/src/helpers/new-suppressions.ts", "{turn}", "{files}"]
151
151
  }
152
+ },
153
+ {
154
+ "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.",
155
+ "requires": [],
156
+ "gate": {
157
+ "name": "no-new-bulk-suppressions",
158
+ "severity": "error",
159
+ "files": "(^|/)eslint-suppressions\\.json$",
160
+ "run": ["{engine}/src/helpers/bulk-suppressions.ts", "{turn}", "{files}"]
161
+ }
152
162
  }
153
163
  ]
154
164
  }
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,6 +1,6 @@
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
4
  import { cachedReports, cacheReports } from "./report-cache.js";
5
5
  import { check, filesOf, givenFiles, missingTool, wholeProject } from "./run.js";
6
6
  import { changedSince, emptyCommit, hasCommit, lastCommit, snapshot, workingTree } from "./snapshot.js";
@@ -83,7 +83,7 @@ function runGates(root, gates, changed, turn, baselines, session) {
83
83
  return { gate, outcome: await check(root, gate, files, turn, baselines(gate)) };
84
84
  }));
85
85
  }
86
- function checkedTurn(changed, results, started, notes, showAllPasses) {
86
+ function checkedTurn(changed, results, started, notes, { gates, prompts, maxTotalReportChars, showAllPasses }) {
87
87
  return {
88
88
  changed,
89
89
  outcomes: results.flatMap(({ outcome }) => (outcome ? [outcome] : [])),
@@ -91,6 +91,7 @@ function checkedTurn(changed, results, started, notes, showAllPasses) {
91
91
  ms: performance.now() - started,
92
92
  note: notes.join("\n") || undefined,
93
93
  ...(showAllPasses ? { showAllPasses } : {}),
94
+ wording: { gates, prompts, maxTotalReportChars },
94
95
  };
95
96
  }
96
97
  /**
@@ -102,16 +103,17 @@ export async function checkAll(root) {
102
103
  const started = performance.now();
103
104
  const empty = emptyCommit(root);
104
105
  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);
106
+ const config = gatesOf(readGatesFiles(root));
107
+ const results = await runGates(root, config.gates, files, empty, () => "");
108
+ return checkedTurn(files, results, started, refusedNotes(config.refused), config);
108
109
  }
109
110
  // 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
111
  // 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
112
  // keeps none: it may still read a changed file its pattern misses, as knip reads tsconfig.json.
112
113
  function endReports(results, baselines) {
113
114
  return results.flatMap(({ gate, outcome }) => {
114
- if (!isCompared(gate) || !outcome)
115
+ // A gate that could not run says nothing of the tree: the report it started from was a crash, or may be stale.
116
+ if (!isCompared(gate) || !outcome || outcome.broken)
115
117
  return [];
116
118
  const report = outcome.ok ? outcome.report : baselines(gate);
117
119
  return report === undefined ? [] : [[gate, report]];
@@ -144,7 +146,8 @@ export async function checkTurn(session, root) {
144
146
  const started = performance.now();
145
147
  const end = workingTree(root);
146
148
  const changed = changedSince(root, turn.start, end);
147
- const { gates, refused, showAllPasses } = gatesOf(turn.config);
149
+ const config = gatesOf(turn.config);
150
+ const { gates, refused } = config;
148
151
  const missing = missingTools(root, gates);
149
152
  for (const gate of gates)
150
153
  if (keepsWatch(gate))
@@ -170,7 +173,7 @@ export async function checkTurn(session, root) {
170
173
  ...refusedNotes(refused),
171
174
  ...notRun,
172
175
  ];
173
- return checkedTurn(changed, results, started, notes, showAllPasses);
176
+ return checkedTurn(changed, results, started, notes, config);
174
177
  }
175
178
  function refusedNotes(refused) {
176
179
  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,27 @@ const FIELDS = new Set([
18
21
  "lineKey",
19
22
  "timeoutSeconds",
20
23
  "watch",
24
+ "prompt",
25
+ "maxReportChars",
26
+ "omitLines",
21
27
  ]);
22
28
  const WATCH_FIELDS = new Set(["run", "cycleStart", "cycleEnd", "failed", "sync", "frozen"]);
23
29
  /** In the arguments of a gate: the changed files it looks at, and the commit of the turn start. */
24
30
  export const FILES = "{files}";
25
31
  export const TURN = "{turn}";
32
+ /**
33
+ * What the engine tells the agent that a repo may word again: as it sends it back, as it asks for missing tools, and
34
+ * with the report of a gate the turn broke.
35
+ */
36
+ const PROMPTS = ["sendBack", "missingTools", "brokenGate"];
37
+ function toPrompt(value) {
38
+ if (typeof value === "string" && value)
39
+ return { text: value, replace: false };
40
+ if (!isRecord(value) || Object.keys(value).join() !== "replace")
41
+ return undefined;
42
+ return typeof value.replace === "string" && value.replace ? { text: value.replace, replace: true } : undefined;
43
+ }
44
+ const PROMPT_SHAPE = 'a text to add to what the agent is told, or {"replace": "a text"} to say it instead';
26
45
  export function keepsWatch(gate) {
27
46
  return gate.watch !== undefined;
28
47
  }
@@ -44,10 +63,12 @@ function fileOf(text, file) {
44
63
  catch (error) {
45
64
  throw new Error(`${file} is not valid JSON: ${messageOf(error)}.`);
46
65
  }
47
- const { gates = [], maxTimeoutSeconds, showAllPasses, maxSendBacks, ...others } = isRecord(parsed) ? parsed : { others: true };
66
+ const { gates = [], maxTimeoutSeconds, showAllPasses, maxSendBacks, maxReportChars, maxTotalReportChars, prompts, ...others } = isRecord(parsed) ? parsed : { others: true };
48
67
  if (!Array.isArray(gates) || Object.keys(others).length)
49
68
  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.`);
69
+ `"showAllPasses", to name every green gate, "maxSendBacks", the most times a turn sends the agent back, ` +
70
+ `"maxReportChars", the most characters of a report the agent is sent, "maxTotalReportChars", the most of ` +
71
+ `all its reports together, and "prompts", what the agent is told.`);
51
72
  const entries = gates.map((entry) => {
52
73
  if (!isRecord(entry) || typeof entry.name !== "string")
53
74
  throw new Error(`${file}: every gate has a name.`);
@@ -58,8 +79,39 @@ function fileOf(text, file) {
58
79
  ...(maxTimeoutSeconds === undefined ? {} : { maxTimeoutSeconds }),
59
80
  ...(showAllPasses === undefined ? {} : { showAllPasses }),
60
81
  ...(maxSendBacks === undefined ? {} : { maxSendBacks }),
82
+ ...(maxReportChars === undefined ? {} : { maxReportChars }),
83
+ ...(maxTotalReportChars === undefined ? {} : { maxTotalReportChars }),
84
+ ...(prompts === undefined ? {} : { prompts }),
61
85
  };
62
86
  }
87
+ function maxTotalReportCharsOf(shared, local) {
88
+ const max = local.maxTotalReportChars ?? shared.maxTotalReportChars ?? DEFAULT_MAX_TOTAL_REPORT_CHARS;
89
+ if (!isReportChars(max))
90
+ throw new Error("maxTotalReportChars is a whole number, 1 or more.");
91
+ return max;
92
+ }
93
+ const REPORT_CHARS_SHAPE = "maxReportChars is a whole number, 1 or more";
94
+ function isReportChars(value) {
95
+ return typeof value === "number" && Number.isInteger(value) && value > 0;
96
+ }
97
+ // Nothing unless a file says: the report then keeps the characters the engine gives every gate.
98
+ function maxReportCharsOf(shared, local) {
99
+ const max = local.maxReportChars ?? shared.maxReportChars;
100
+ if (max !== undefined && !isReportChars(max))
101
+ throw new Error(`${REPORT_CHARS_SHAPE}.`);
102
+ return max;
103
+ }
104
+ function promptsOf({ prompts = {} }) {
105
+ const known = PROMPTS.map((key) => `"${key}"`).join(", ");
106
+ if (!isRecord(prompts) || Object.keys(prompts).some((key) => !PROMPTS.some((prompt) => prompt === key)))
107
+ throw new Error(`prompts holds ${known}.`);
108
+ return Object.fromEntries(Object.entries(prompts).map(([key, value]) => {
109
+ const prompt = toPrompt(value);
110
+ if (prompt === undefined)
111
+ throw new Error(`prompts.${key} is ${PROMPT_SHAPE}.`);
112
+ return [key, prompt];
113
+ }));
114
+ }
63
115
  // The local file's own value wins, as for the fields of a gate.
64
116
  function maxTimeoutOf(shared, local) {
65
117
  const max = local.maxTimeoutSeconds ?? shared.maxTimeoutSeconds ?? DEFAULT_MAX_TIMEOUT_SECONDS;
@@ -119,8 +171,8 @@ function toWatch(watch, compared) {
119
171
  ...(compared ? {} : { failed: pattern("failed", failed) }),
120
172
  };
121
173
  }
122
- function toGate(entry, maxTimeoutSeconds) {
123
- const { name, severity, files, run, compare, ignoreLines, lineKey, watch, timeoutSeconds = maxTimeoutSeconds, } = entry;
174
+ function toGate(entry, maxTimeoutSeconds, reportChars) {
175
+ const { name, severity, files, run, compare, ignoreLines, lineKey, watch, prompt, omitLines, timeoutSeconds = maxTimeoutSeconds, maxReportChars = reportChars, } = entry;
124
176
  const unknown = Object.keys(entry).find((key) => !FIELDS.has(key));
125
177
  if (unknown !== undefined)
126
178
  refuse(`unknown field ${unknown}`);
@@ -144,6 +196,11 @@ function toGate(entry, maxTimeoutSeconds) {
144
196
  refuse("lineKey tells apart the lines of a compared gate: it takes compare");
145
197
  if (typeof timeoutSeconds !== "number" || timeoutSeconds <= 0)
146
198
  refuse("timeoutSeconds is a positive number");
199
+ if (maxReportChars !== undefined && !isReportChars(maxReportChars))
200
+ refuse(REPORT_CHARS_SHAPE);
201
+ if (omitLines !== undefined && !isPattern(omitLines))
202
+ refuse("omitLines is a regular expression");
203
+ const told = prompt === undefined ? undefined : (toPrompt(prompt) ?? refuse(`prompt is ${PROMPT_SHAPE}`));
147
204
  return {
148
205
  name,
149
206
  severity,
@@ -155,6 +212,9 @@ function toGate(entry, maxTimeoutSeconds) {
155
212
  ...(ignoreLines === undefined ? {} : { ignoreLines }),
156
213
  ...(lineKey === undefined ? {} : { lineKey }),
157
214
  ...(watch === undefined ? {} : { watch: toWatch(watch, compare !== undefined) }),
215
+ ...(told === undefined ? {} : { prompt: told }),
216
+ ...(maxReportChars === undefined ? {} : { maxReportChars }),
217
+ ...(omitLines === undefined ? {} : { omitLines }),
158
218
  };
159
219
  }
160
220
  /**
@@ -166,6 +226,7 @@ export function readGates(shared, local) {
166
226
  const sharedFile = fileOf(shared, GATES_FILE);
167
227
  const localFile = fileOf(local, LOCAL_GATES_FILE);
168
228
  const max = maxTimeoutOf(sharedFile, localFile);
229
+ const reportChars = maxReportCharsOf(sharedFile, localFile);
169
230
  const merged = new Map(sharedFile.entries.map((entry) => [entry.name, entry]));
170
231
  for (const entry of localFile.entries)
171
232
  merged.set(entry.name, { ...merged.get(entry.name), ...entry });
@@ -174,12 +235,15 @@ export function readGates(shared, local) {
174
235
  refused: [],
175
236
  showAllPasses: showAllPassesOf(sharedFile, localFile),
176
237
  maxSendBacks: maxSendBacksOf(sharedFile, localFile),
238
+ maxTotalReportChars: maxTotalReportCharsOf(sharedFile, localFile),
239
+ // The local file's own prompt wins, key by key.
240
+ prompts: { ...promptsOf(sharedFile), ...promptsOf(localFile) },
177
241
  };
178
242
  for (const entry of merged.values()) {
179
243
  if (entry.severity === "off")
180
244
  continue;
181
245
  try {
182
- read.gates.push(toGate(entry, max));
246
+ read.gates.push(toGate(entry, max, reportChars));
183
247
  }
184
248
  catch (error) {
185
249
  read.refused.push({ name: entry.name, why: messageOf(error) });
@@ -3,19 +3,34 @@ import { WAIVE_TAG } from "./waive-line.js";
3
3
  const LABEL = "● gates";
4
4
  const SHOWN_PASSES = 6;
5
5
  const REPORT_CHARS = 4000;
6
- const HEAD_CHARS = 1000;
6
+ // The share of a cut report kept from its start.
7
+ const HEAD_SHARE = 0.25;
7
8
  const TONES = { pass: "1;32", fail: "1;31", late: "1;33", warn: "1;38;5;208", dim: "2" };
8
9
  // The warning sign as text, never as the emoji some terminals draw without the variation selector.
9
10
  const WARNING = "\u26A0\uFE0E";
10
11
  function paint(tone, text) {
11
12
  return `\x1b[${TONES[tone]}m${text}\x1b[0m`;
12
13
  }
13
- /** Keeps the start and the end of a long report: tools put the problem at one or the other. */
14
- export function excerpt(report) {
15
- if (report.length <= REPORT_CHARS)
14
+ /**
15
+ * Keeps the start and the end of a long report, in the characters given: tools put the problem at one or the other.
16
+ * Each cut moves to the end of a line when that keeps at least half of its side, so a list keeps whole entries, and
17
+ * stays inside a line longer than that, which would otherwise go whole.
18
+ */
19
+ export function excerpt(report, max = REPORT_CHARS) {
20
+ if (report.length <= max)
16
21
  return report;
17
- const cut = report.length - REPORT_CHARS;
18
- return `${report.slice(0, HEAD_CHARS)}\n[... ${cut} characters cut ...]\n${report.slice(-(REPORT_CHARS - HEAD_CHARS))}`;
22
+ const head = Math.floor(max * HEAD_SHARE);
23
+ const tail = max - head;
24
+ const before = report.lastIndexOf("\n", head - 1);
25
+ const after = report.indexOf("\n", report.length - tail);
26
+ const wholeHead = before >= head / 2;
27
+ const wholeTail = after !== -1 && after - (report.length - tail) <= tail / 2;
28
+ const end = wholeHead ? before : head;
29
+ const start = wholeTail ? after + 1 : report.length - tail;
30
+ const cut = wholeHead && wholeTail
31
+ ? `${report.slice(end + 1, start - 1).split("\n").length} lines`
32
+ : `${start - end} characters`;
33
+ return `${report.slice(0, end)}\n[... ${cut} cut ...]\n${report.slice(start)}`;
19
34
  }
20
35
  export function duration(ms) {
21
36
  return ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`;
@@ -90,14 +105,48 @@ export function broken(reason) {
90
105
  }
91
106
  // The cheapest green is to silence the rule, and nothing in the engine judges a report. So the agent is told the one
92
107
  // way out that is not a cheat: waive the gate, with a reason the owner reads and judges.
93
- const CONDUCT = [
94
- "Fix the code, never the check: a silenced rule (noqa, eslint-disable, nolint), a weakened gate or an edited",
108
+ const SEND_BACK = [
109
+ "Gates fail on what this turn changed. Fix every problem before you hand back.\n\nFix the code, never the check: a silenced rule (noqa, eslint-disable, nolint), a weakened gate or an edited",
95
110
  ".gates.json does not pass this turn. If you can fix a problem, fix it. Leave a gate red only when it cannot be",
96
111
  "fixed (the report is wrong, or fixing it would loop until the last send-back), when fixing it goes against what",
97
- "the owner asked, or when the owner has to settle a question first. Then waive it in your final message, after a",
98
- "blank line, one line per gate, its reason in one line:",
112
+ "the owner asked, or when the owner has to settle a question first.",
99
113
  ].join(" ");
100
114
  const WAIVE_SYNTAX = `[${WAIVE_TAG}:<gate>]: waive "<reason>"`;
115
+ // Said whatever the repo says in place of the rest: without it, an agent could only loop on a gate it cannot fix.
116
+ const WAIVE = [
117
+ "To leave a gate red, waive it in your final message, after a blank line, one line per gate, its reason in one line:",
118
+ WAIVE_SYNTAX,
119
+ ].join("\n");
120
+ // A gate that broke found no problem to fix: the agent looks for what stops it from running, in the code or around it.
121
+ const BROKEN_GATE = "This gate broke instead of reporting: repair what stops it from running (a missing dependency, a broken configuration, a file it cannot read), then fix what it reports.";
122
+ // What a session already told how to act reads at its next send-backs: what it has in its context is not said again.
123
+ const BRIEF = `Gates fail again: act as the first send-back of this session told you, or waive with ${WAIVE_SYNTAX}`;
124
+ /** What the engine tells the agent, with the prompt of the repo after it, or in its place. */
125
+ function worded(own, prompt, between) {
126
+ if (prompt === undefined)
127
+ return own;
128
+ return prompt.replace ? prompt.text : `${own}${between}${prompt.text}`;
129
+ }
130
+ // The report less the lines the gate omits, or whole when it would omit them all: a red gate always says something.
131
+ function sent(report, omitLines) {
132
+ if (omitLines === undefined)
133
+ return report;
134
+ const omitted = new RegExp(omitLines);
135
+ const kept = report.split("\n").filter((line) => !omitted.test(line));
136
+ return kept.some((line) => line.trim()) ? kept.join("\n") : report;
137
+ }
138
+ // The characters each report gets of a total: what it needs when all fit, else the short ones whole and the rest of
139
+ // the total in equal shares for the long ones.
140
+ function shares(needs, total) {
141
+ const given = [...needs];
142
+ let left = total;
143
+ const shortestFirst = needs.map((_, at) => at).sort((a, b) => (needs[a] ?? 0) - (needs[b] ?? 0));
144
+ shortestFirst.forEach((at, done) => {
145
+ given[at] = Math.min(needs[at] ?? 0, Math.floor(left / (needs.length - done)));
146
+ left -= given[at];
147
+ });
148
+ return given;
149
+ }
101
150
  /** What the owner sees when the gates of the repo miss tools on this machine, as the agent is asked to install them. */
102
151
  export function toolsMissing(missing) {
103
152
  const gates = missing.length === 1 ? "1 gate is off" : `${missing.length} gates are off`;
@@ -105,23 +154,59 @@ export function toolsMissing(missing) {
105
154
  return [`${paint("fail", LABEL)} ${gates}, a tool is missing: the agent is asked to install it`, ...lines].join("\n");
106
155
  }
107
156
  /** What the agent is told when the gates of the repo miss tools: install them, or the gates that need them stay off. */
108
- export function toolsToInstall(missing) {
157
+ export function toolsToInstall(missing, prompt) {
158
+ const install = [
159
+ "Install these tools first. If they cannot be installed, or the developer refuses, say so and go on with the",
160
+ "prompt: the gates that need them stay off until they are installed, and every other gate still runs.",
161
+ ].join("\n");
109
162
  return [
110
163
  "Some gates of this repo cannot run on this machine, for a missing tool:",
111
164
  ...missing.map((tool) => `- ${tool}`),
112
- "Install these tools first. If they cannot be installed, or the developer refuses, say so and go on with the",
113
- "prompt: the gates that need them stay off until they are installed, and every other gate still runs.",
165
+ worded(install, prompt, "\n"),
114
166
  ].join("\n");
115
167
  }
116
- /** The report of each failed gate, under its name. */
117
- export function reports(outcomes) {
118
- return outcomes.filter(failed).map(({ name, output }) => `## ${name}\n${excerpt(output)}`);
168
+ /**
169
+ * 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.
171
+ */
172
+ export function reports({ outcomes, wording = {} }) {
173
+ const { gates = [], prompts, maxTotalReportChars = Infinity } = wording;
174
+ const red = outcomes.filter(failed).map(({ name, output, broken }) => {
175
+ const gate = gates.find((known) => known.name === name);
176
+ const report = sent(output, gate?.omitLines);
177
+ const told = [
178
+ ...(broken ? [worded(BROKEN_GATE, prompts?.brokenGate, "\n")] : []),
179
+ ...(gate?.prompt ? [gate.prompt.text] : []),
180
+ ];
181
+ return { name, told, report, needs: Math.min(report.length, gate?.maxReportChars ?? REPORT_CHARS) };
182
+ });
183
+ const given = shares(red.map(({ needs }) => needs), maxTotalReportChars);
184
+ return red.map(({ name, told, report }, at) => [`## ${name}`, ...told, excerpt(report, given[at])].join("\n"));
119
185
  }
120
186
  /**
121
- * What the agent gets when it is sent back: how to act on a failure, what the stop has to tell it, the note of the
122
- * check, each failed report.
187
+ * What the agent gets when it is sent back: how to act on a failure, in the words of the engine or of the repo, how
188
+ * to waive a gate, or one line for both once the session was told, what the stop has to tell it, the note of the check, each failed report.
123
189
  */
124
- export function failures({ outcomes, note }, told = []) {
125
- const head = ["Gates fail on what this turn changed. Fix every problem before you hand back.", CONDUCT, WAIVE_SYNTAX];
126
- return [...head, ...told, ...(note ? [note] : []), ...reports(outcomes)].join("\n\n");
190
+ export function failures(turn, told = [], brief = false) {
191
+ const head = brief ? [BRIEF] : [worded(SEND_BACK, turn.wording?.prompts?.sendBack, "\n\n"), WAIVE];
192
+ return [...head, ...told, ...(turn.note ? [turn.note] : []), ...reports(turn)].join("\n\n");
193
+ }
194
+ function gateResult({ name, ok, ms, output, timedOut, broken }) {
195
+ const durationMs = Math.round(ms);
196
+ if (ok)
197
+ return { name, status: "passed", durationMs };
198
+ if (timedOut)
199
+ return { name, status: "timed-out", durationMs };
200
+ return { name, status: broken ? "broken" : "failed", durationMs, report: output };
201
+ }
202
+ /**
203
+ * A check for a tool to read, such as a CI or a script, where the summary is for its owner and the send-back for the
204
+ * agent: whether it passed, each gate with its status and its whole report, and the notes of the check.
205
+ */
206
+ export function results({ outcomes, skipped, ms, note }) {
207
+ const gates = [
208
+ ...outcomes.map(gateResult),
209
+ ...skipped.map((name) => ({ name, status: "skipped" })),
210
+ ];
211
+ return { ok: !outcomes.some(failed), durationMs: Math.round(ms), gates, notes: note ? note.split("\n") : [] };
127
212
  }
@@ -4,7 +4,7 @@ import { delimiter, isAbsolute, join, resolve, sep } from "node:path";
4
4
  import { stripVTControlCharacters } from "node:util";
5
5
  import { FILES, isCompared, TURN } from "./config.js";
6
6
  import { isRecord, messageOf, readJsonFile } from "./json.js";
7
- /** A gate that judged the turn and found a problem: the only kind that sends the agent back. */
7
+ /** A gate that judged the turn and found a problem, or that broke: the only kinds that send the agent back. */
8
8
  export function failed(outcome) {
9
9
  return !outcome.ok && !outcome.timedOut;
10
10
  }
@@ -25,6 +25,12 @@ function repoNode(root) {
25
25
  const pinned = join(root, "node_modules", ".bin", "node");
26
26
  return executable(pinned) ? pinned : process.execPath;
27
27
  }
28
+ /** Set for a gate whose prompt the repo replaces: its command leaves out the line it would tell the agent itself. */
29
+ const PROMPT_REPLACED = "GATES_PROMPT_REPLACED";
30
+ /** The report of an engine helper: its own line for the agent, unless the repo says another instead, then its list. */
31
+ export function headed(own, lines, env = process.env) {
32
+ return [...(env[PROMPT_REPLACED] ? [] : [own]), ...lines].join("\n");
33
+ }
28
34
  const MAX_OUTPUT_MB = 16;
29
35
  const ENGINE_PREFIX = "{engine}/";
30
36
  /** A script of this engine: its .ts source, or the .js it is built to when the engine runs from its npm package. */
@@ -162,20 +168,27 @@ async function execute(root, gate, args) {
162
168
  command = commandOf(root, name);
163
169
  }
164
170
  catch (error) {
165
- return { ok: false, output: messageOf(error), ms: performance.now() - started, timedOut: false };
171
+ return {
172
+ ok: false,
173
+ output: messageOf(error),
174
+ ms: performance.now() - started,
175
+ timedOut: false,
176
+ cannotStart: true,
177
+ };
166
178
  }
167
179
  return new Promise((resolve) => {
168
180
  execFile(command.file, [...command.args, ...args], {
169
181
  cwd: root,
170
182
  timeout: gate.timeoutSeconds * 1000,
171
183
  maxBuffer: MAX_OUTPUT_MB * 1024 * 1024,
172
- env: toolEnv(root),
184
+ env: { ...toolEnv(root), ...(gate.prompt?.replace ? { [PROMPT_REPLACED]: "1" } : {}) },
173
185
  }, (error, stdout, stderr) => {
174
186
  resolve({
175
187
  ok: !error,
176
188
  output: outputOf(root, gate, command, error, `${stdout}${stderr}`),
177
189
  ms: performance.now() - started,
178
190
  timedOut: error?.killed === true && error.code !== "ERR_CHILD_PROCESS_STDIO_MAXBUFFER",
191
+ cannotStart: error?.code === "ENOENT",
179
192
  });
180
193
  });
181
194
  });
@@ -206,14 +219,17 @@ export async function wholeProject(root, gate, ms = gate.timeoutSeconds * 1000)
206
219
  return timedOut ? { ok: false } : { ok, output };
207
220
  }
208
221
  /**
209
- * Runs a gate on the turn. A compared gate fails on the lines of output the turn added, and on any exit code but 0:
210
- * the same crash at the start and at the end of a turn prints no new line. A gate out of time is neither.
222
+ * 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.
211
224
  */
212
225
  export async function check(root, gate, files, turn, baseline) {
213
- const { ok, output, ms, timedOut } = await execute(root, gate, argumentsOf(gate, files, turn));
226
+ const { ok, output, ms, timedOut, cannotStart } = await execute(root, gate, argumentsOf(gate, files, turn));
214
227
  const ran = { name: gate.name, ms, report: ok ? output : undefined };
215
228
  if (timedOut)
216
229
  return { ...ran, ok, output, timedOut };
230
+ // A compared gate exits with 0 when it finds problems: any other code is its command that broke.
231
+ if (!ok && (cannotStart || isCompared(gate)))
232
+ return { ...ran, ok, output, broken: true };
217
233
  if (!isCompared(gate) || !ok)
218
234
  return { ...ran, ok, output };
219
235
  return { ...ran, ...addedLines(gate, output, baseline, files) };
@@ -88,6 +88,21 @@ export function hasCommit(root, commit) {
88
88
  return false;
89
89
  }
90
90
  }
91
+ /** A file as a commit holds it, or nothing when the commit does not have it. */
92
+ export function fileAt(root, commit, file) {
93
+ try {
94
+ // However long: past the default megabyte, git would read as a commit that does not have the file.
95
+ return execFileSync("git", ["show", `${commit}:${file}`], {
96
+ cwd: root,
97
+ encoding: "utf8",
98
+ stdio: "pipe",
99
+ maxBuffer: Infinity,
100
+ });
101
+ }
102
+ catch {
103
+ return undefined;
104
+ }
105
+ }
91
106
  /** The files that differ between two commits or trees, the deleted ones included. */
92
107
  export function changedSince(root, start, end = workingTree(root)) {
93
108
  return paths(git(root, ["diff", "-z", "--name-only", start, end])).sort();