@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.
@@ -1,30 +1,43 @@
1
- import { execFileSync } from "node:child_process";
2
1
  import { readFileSync } from "node:fs";
2
+ import { headed } from "../core/run.js";
3
+ import { fileAt } from "../core/snapshot.js";
3
4
  // The cheapest green is to silence the rule. This prints the rule suppressions the turn added to the changed files,
4
5
  // one per line, compared with the file as the turn started: the ones already there are the owner's business.
5
6
  /** The ways to silence a rule in the languages of the catalog: linters, type checkers, formatters, scanners. */
6
- const SUPPRESSIONS = /eslint-disable|@ts-(ignore|expect-error|nocheck)|prettier-ignore|biome-ignore|\bnoqa\b|type:\s*ignore|pylint:\s*disable|fmt:\s*(off|skip)|\bnosec\b|\bnolint\b|go:nolint|coverage:\s*ignore|pragma:\s*no cover/;
7
- /** The suppressions in the lines the file holds now and did not hold as the turn started. */
7
+ const SUPPRESSIONS = /eslint-disable|stylelint-disable|@ts-(ignore|expect-error|nocheck)|prettier-ignore|biome-ignore|\bnoqa\b|type:\s*ignore|pylint:\s*disable|fmt:\s*(off|skip)|\bnosec\b|\bnolint\b|go:nolint|coverage:\s*ignore|pragma:\s*no cover/;
8
+ // A suppression from where it starts to the end of its line, without the code before it: a change of that code does
9
+ // not make it new.
10
+ function suppressionOf(line) {
11
+ const found = SUPPRESSIONS.exec(line);
12
+ return found ? line.slice(found.index).trim() : undefined;
13
+ }
14
+ /**
15
+ * The suppressions the file holds now and did not hold as the turn started. Each one of the turn start stands for one
16
+ * of now that says the same, so a second one beside it is new.
17
+ */
8
18
  export function newSuppressions(before, after) {
9
- const seen = new Set((before ?? "").split("\n").map((line) => line.trim()));
19
+ const held = new Map();
20
+ for (const line of (before ?? "").split("\n")) {
21
+ const suppression = suppressionOf(line);
22
+ if (suppression !== undefined)
23
+ held.set(suppression, (held.get(suppression) ?? 0) + 1);
24
+ }
10
25
  return after.split("\n").flatMap((text, index) => {
11
- const line = text.trim();
12
- return line && !seen.has(line) && SUPPRESSIONS.test(line) ? [{ line: index + 1, text: line }] : [];
26
+ const suppression = suppressionOf(text);
27
+ if (suppression === undefined)
28
+ return [];
29
+ const left = held.get(suppression) ?? 0;
30
+ if (left === 0)
31
+ return [{ line: index + 1, text: text.trim() }];
32
+ held.set(suppression, left - 1);
33
+ return [];
13
34
  });
14
35
  }
15
- function atTurnStart(root, turn, file) {
16
- try {
17
- return execFileSync("git", ["show", `${turn}:${file}`], { cwd: root, encoding: "utf8", stdio: "pipe" });
18
- }
19
- catch {
20
- return undefined;
21
- }
22
- }
23
36
  function main(root, turn, files) {
24
- const found = files.flatMap((file) => newSuppressions(atTurnStart(root, turn, file), readFileSync(file, "utf8")).map(({ line, text }) => `${file}:${line}: ${text}`));
37
+ const found = files.flatMap((file) => newSuppressions(fileAt(root, turn, file), readFileSync(file, "utf8")).map(({ line, text }) => `${file}:${line}: ${text}`));
25
38
  if (!found.length)
26
39
  return;
27
- console.log(`New rule suppressions: fix the code, never the check.\n${found.join("\n")}`);
40
+ console.log(headed("New rule suppressions: fix the code, never the check.", found));
28
41
  process.exitCode = 1;
29
42
  }
30
43
  if (import.meta.main)
@@ -1,10 +1,10 @@
1
1
  import { checkTurn, startSession, startTurn } from "../core/check.js";
2
- import { configuredRoot, gatesOf } from "../core/config.js";
2
+ import { configuredRoot, gatesOf, readGatesFiles } from "../core/config.js";
3
3
  import { isRecord, messageOf, parseJson } from "../core/json.js";
4
4
  import { broken, failures, summary, toolsMissing, toolsToInstall } from "../core/report.js";
5
5
  import { judge, waivesOf } from "../core/send-back.js";
6
6
  import { endSession } from "../core/watch.js";
7
- import { forgetTold, forgetTurn, readTurn, tellOnce, turnRoot, writeTurn } from "../core/turn-state.js";
7
+ import { forgetConduct, forgetTold, forgetTurn, readTurn, tellConductOnce, tellOnce, turnRoot, writeTurn, } from "../core/turn-state.js";
8
8
  /** The events the plugin hooks, each named as the CLI takes it. */
9
9
  export const HOOK_EVENTS = ["session-start", "turn-start", "check", "session-end"];
10
10
  export function isHookEvent(word) {
@@ -51,11 +51,12 @@ function told({ count, max, waived, fallen, unknown, gates }) {
51
51
  * breaks another gate is caught, and a gate the agent cannot satisfy never loops. The owner sees each stop, the
52
52
  * waived gates with their reasons, and why the turn ended.
53
53
  */
54
- export function stopOutput(turn, judged) {
54
+ export function stopOutput(turn, judged, brief = false) {
55
55
  const systemMessage = summary(turn, ending(judged), judged.waived);
56
56
  if (!judged.sendBack)
57
57
  return { systemMessage };
58
- return { decision: "block", reason: failures({ ...turn, outcomes: judged.open }, told(judged)), systemMessage };
58
+ const reason = failures({ ...turn, outcomes: judged.open }, told(judged), brief);
59
+ return { decision: "block", reason, systemMessage };
59
60
  }
60
61
  // When the gates cannot run, such as with a gates file that does not parse, only the owner is told: a crash would
61
62
  // show them a stack trace at best, and the agent is not to blame.
@@ -87,9 +88,13 @@ async function promptHook(session, cwd) {
87
88
  const missing = await startTurn(session, root);
88
89
  if (!tellOnce(session, root, missing))
89
90
  return undefined;
91
+ const { prompts } = gatesOf(readGatesFiles(root));
90
92
  return {
91
93
  systemMessage: toolsMissing(missing),
92
- hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: toolsToInstall(missing) },
94
+ hookSpecificOutput: {
95
+ hookEventName: "UserPromptSubmit",
96
+ additionalContext: toolsToInstall(missing, prompts.missingTools),
97
+ },
93
98
  };
94
99
  }
95
100
  catch (error) {
@@ -113,7 +118,8 @@ async function stopHook(session, cwd, retry, message) {
113
118
  const names = [...gates.map(({ name }) => name), ...refused.map(({ name }) => name)];
114
119
  const judged = judge(checked, waivesOf(message), names, maxSendBacks, turn.sendBacks);
115
120
  writeTurn(session, root, { ...turn, sendBacks: judged.state });
116
- return stopOutput(checked, judged);
121
+ const brief = judged.sendBack && !tellConductOnce(session, root);
122
+ return stopOutput(checked, judged, brief);
117
123
  }
118
124
  catch (error) {
119
125
  return cannotRun(error);
@@ -131,6 +137,8 @@ export async function handleHook(event, text) {
131
137
  if (event === "session-start") {
132
138
  if (source !== "compact")
133
139
  forgetTold(session);
140
+ // A compaction may have summed up how to act on a send-back: the next one says it whole again.
141
+ forgetConduct(session);
134
142
  sessionHook(session, cwd);
135
143
  return undefined;
136
144
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tayomi/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
  "type": "module",
6
6
  "license": "MIT",
package/src/cli.ts CHANGED
@@ -3,7 +3,7 @@ import { readFileSync } from "node:fs";
3
3
  import { checkAll } from "./core/check.ts";
4
4
  import { configuredRoot } from "./core/config.ts";
5
5
  import { messageOf } from "./core/json.ts";
6
- import { broken, reports, summary } from "./core/report.ts";
6
+ import { broken, reports, results, summary } from "./core/report.ts";
7
7
  import { failed } from "./core/run.ts";
8
8
  import { HOOK_EVENTS, handleHook, isHookEvent } from "./hook/hook.ts";
9
9
 
@@ -16,7 +16,7 @@ function readStdin(): string {
16
16
  }
17
17
 
18
18
  /** What the command prints when it is called with words it does not know, named by the bin of the npm package. */
19
- export const USAGE = `Usage: deterministic-gates check, or deterministic-gates hook <${HOOK_EVENTS.join("|")}>`;
19
+ export const USAGE = `Usage: deterministic-gates check [--format json], or deterministic-gates hook <${HOOK_EVENTS.join("|")}>`;
20
20
 
21
21
  // The helpers of the engine run only on import.meta.main, which came with Node 24.2: below, they are a silent green.
22
22
  const [major = 0, minor = 0] = process.versions.node.split(".").map(Number);
@@ -25,7 +25,10 @@ const oldNode =
25
25
  ? `Node 24.2 or later is needed, this is ${process.versions.node}.`
26
26
  : undefined;
27
27
 
28
- async function main([command, event]: string[]): Promise<void> {
28
+ async function main([command, ...words]: string[]): Promise<void> {
29
+ const [event] = words;
30
+ // For a tool, such as a CI or a script, where the text is for the one who reads the terminal.
31
+ const json = words.join(" ") === "--format json";
29
32
  if (oldNode !== undefined) {
30
33
  if (command === "hook") console.log(JSON.stringify({ systemMessage: broken(oldNode) }));
31
34
  else {
@@ -35,7 +38,7 @@ async function main([command, event]: string[]): Promise<void> {
35
38
  } else if (command === "hook" && isHookEvent(event)) {
36
39
  const output = await handleHook(event, readStdin());
37
40
  if (output) console.log(JSON.stringify(output));
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.");
@@ -43,7 +46,7 @@ async function main([command, event]: string[]): Promise<void> {
43
46
  } else {
44
47
  try {
45
48
  const all = await checkAll(root);
46
- console.log([summary(all), ...reports(all.outcomes)].join("\n\n"));
49
+ console.log(json ? JSON.stringify(results(all), null, 2) : [summary(all), ...reports(all)].join("\n\n"));
47
50
  if (all.outcomes.some(failed)) process.exitCode = 1;
48
51
  } catch (error) {
49
52
  console.error(`Could not run: ${messageOf(error)}`);
package/src/core/check.ts CHANGED
@@ -1,12 +1,30 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { changedGatesFiles, type Gate, type Gates, gatesOf, isCompared, keepsWatch, readGatesFiles } from "./config.ts";
3
+ import {
4
+ changedGatesFiles,
5
+ type Gate,
6
+ type Gates,
7
+ gatesOf,
8
+ isCompared,
9
+ keepsWatch,
10
+ type Prompts,
11
+ readGatesFiles,
12
+ } from "./config.ts";
13
+ import { headOf, movedSince } from "./head.ts";
4
14
  import { cachedReports, cacheReports } from "./report-cache.ts";
5
- import { check, filesOf, givenFiles, missingTool, type Outcome, wholeProject } from "./run.ts";
15
+ import { check, filesOf, givenFiles, missingTool, namesFiles, type Outcome, wholeProject } from "./run.ts";
6
16
  import { changedSince, emptyCommit, hasCommit, lastCommit, snapshot, workingTree } from "./snapshot.ts";
7
17
  import { readTurn, type TurnState, writeTurn } from "./turn-state.ts";
8
18
  import { judgeWatch, keepWatch, startWatch, TURN_START_MS, watchReport } from "./watch.ts";
9
19
 
20
+ /** What the repo says of what the agent is sent: the prompts of the whole check, and its gates, for their own. */
21
+ interface Wording {
22
+ prompts?: Prompts;
23
+ gates?: Pick<Gate, "name" | "omitLines" | "maxReportChars" | "prompt">[];
24
+ /** The most characters the reports of a send-back hold, all together. */
25
+ maxTotalReportChars?: number;
26
+ }
27
+
10
28
  export interface CheckedTurn {
11
29
  changed: string[];
12
30
  outcomes: Outcome[];
@@ -14,6 +32,8 @@ export interface CheckedTurn {
14
32
  ms: number;
15
33
  note?: string;
16
34
  showAllPasses?: boolean;
35
+ /** As the gates the check ran with word it. */
36
+ wording?: Wording;
17
37
  }
18
38
 
19
39
  /** A gate of the turn, with its outcome when it ran. */
@@ -69,9 +89,10 @@ export async function startTurn(session: string, root: string): Promise<string[]
69
89
  writeTurn(session, root, interrupted);
70
90
  return told;
71
91
  }
92
+ const head = headOf(root);
72
93
  const { commit: start, tree } = snapshot(root);
73
94
  // The turn starts before its reports are ready: a hook stopped for lack of time leaves it, never the turn before.
74
- writeTurn(session, root, { start, baselines: {}, config, checked: false });
95
+ writeTurn(session, root, { start, ...head, baselines: {}, config, checked: false });
75
96
  const cached = cachedReports(root, tree);
76
97
  const baselines = await Promise.all(
77
98
  compared.map(async (gate): Promise<{ gate: Gate; ok: boolean; output?: string }> => {
@@ -91,6 +112,7 @@ export async function startTurn(session: string, root: string): Promise<string[]
91
112
  );
92
113
  writeTurn(session, root, {
93
114
  start,
115
+ ...head,
94
116
  baselines: Object.fromEntries(
95
117
  baselines.flatMap(({ gate, output }) => (output === undefined ? [] : [[gate.name, output]])),
96
118
  ),
@@ -104,7 +126,7 @@ export async function startTurn(session: string, root: string): Promise<string[]
104
126
  * Runs, in parallel, each gate that looks at a changed file. A deleted file counts as changed, since a gate that
105
127
  * reads the whole project may break on it, but is never named: a gate given {files} looks at the files left, and
106
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
107
- * running.
129
+ * running. Elsewhere, the reports of the turn start are of code HEAD has left since.
108
130
  */
109
131
  function runGates(
110
132
  root: string,
@@ -113,6 +135,7 @@ function runGates(
113
135
  turn: string,
114
136
  baselines: Baselines,
115
137
  session?: string,
138
+ elsewhere = false,
116
139
  ): Promise<Result[]> {
117
140
  return Promise.all(
118
141
  gates.map(async (gate) => {
@@ -120,8 +143,8 @@ function runGates(
120
143
  const files = givenFiles(gate) ? matching.filter((file) => existsSync(join(root, file))) : matching;
121
144
  if (!files.length) return { gate };
122
145
  if (session !== undefined && keepsWatch(gate))
123
- return { gate, outcome: await judgeWatch(session, root, gate, matching, baselines(gate)) };
124
- 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) };
125
148
  }),
126
149
  );
127
150
  }
@@ -131,7 +154,7 @@ function checkedTurn(
131
154
  results: Result[],
132
155
  started: number,
133
156
  notes: string[],
134
- showAllPasses: boolean,
157
+ { gates, prompts, maxTotalReportChars, showAllPasses }: Gates,
135
158
  ): CheckedTurn {
136
159
  return {
137
160
  changed,
@@ -140,6 +163,7 @@ function checkedTurn(
140
163
  ms: performance.now() - started,
141
164
  note: notes.join("\n") || undefined,
142
165
  ...(showAllPasses ? { showAllPasses } : {}),
166
+ wording: { gates, prompts, maxTotalReportChars },
143
167
  };
144
168
  }
145
169
 
@@ -152,18 +176,20 @@ export async function checkAll(root: string): Promise<CheckedTurn> {
152
176
  const started = performance.now();
153
177
  const empty = emptyCommit(root);
154
178
  const files = changedSince(root, empty);
155
- const { gates, refused, showAllPasses } = gatesOf(readGatesFiles(root));
156
- const results = await runGates(root, gates, files, empty, () => "");
157
- return checkedTurn(files, results, started, refusedNotes(refused), showAllPasses);
179
+ const config = gatesOf(readGatesFiles(root));
180
+ const results = await runGates(root, config.gates, files, empty, () => "");
181
+ return checkedTurn(files, results, started, refusedNotes(config.refused), config);
158
182
  }
159
183
 
160
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
161
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
162
- // keeps none: it may still read a changed file its pattern misses, as knip reads tsconfig.json.
163
- 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) {
164
189
  return results.flatMap(({ gate, outcome }) => {
165
- if (!isCompared(gate) || !outcome) return [];
166
- const report = outcome.ok ? outcome.report : baselines(gate);
190
+ // A gate that could not run says nothing of the tree: the report it started from was a crash, or may be stale.
191
+ if (!isCompared(gate) || !outcome || outcome.broken) return [];
192
+ const report = outcome.ok ? outcome.report : elsewhere ? undefined : baselines(gate);
167
193
  return report === undefined ? [] : [[gate, report] as const];
168
194
  });
169
195
  }
@@ -172,7 +198,9 @@ function endReports(results: Result[], baselines: Baselines) {
172
198
  * Runs each gate that looks at a file the turn changed, with the gates as the turn started: an agent that weakens
173
199
  * them mid-turn changes the next turn, never its own. Without a recorded start, the turn runs from the last commit
174
200
  * with the gates of now; with a start git no longer has, from the last commit with the gates and the reports it
175
- * 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.
176
204
  */
177
205
  export async function checkTurn(session: string, root: string): Promise<CheckedTurn> {
178
206
  const recorded = readTurn(session, root);
@@ -189,27 +217,44 @@ export async function checkTurn(session: string, root: string): Promise<CheckedT
189
217
  baselines: recorded?.baselines ?? {},
190
218
  config: recorded?.config ?? now,
191
219
  checked: false,
220
+ ...(kept ? { head: kept.head, moves: kept.moves } : {}),
192
221
  // What the earlier stops of the turn told the agent goes on, so its send-backs and waivers add up.
193
222
  ...(recorded?.sendBacks ? { sendBacks: recorded.sendBacks } : {}),
194
223
  };
195
- 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]);
196
227
  const started = performance.now();
197
228
  const end = workingTree(root);
198
- const changed = changedSince(root, turn.start, end);
199
- const { gates, refused, showAllPasses } = gatesOf(turn.config);
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;
232
+ const config = gatesOf(turn.config);
233
+ const { gates, refused } = config;
200
234
  const missing = missingTools(root, gates);
201
235
  for (const gate of gates) if (keepsWatch(gate)) keepWatch(root, gate);
202
- const results = await runGates(root, runnable(gates, missing), changed, turn.start, baselines, session);
203
- 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));
204
247
  writeTurn(session, root, { ...turn, checked: true });
205
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
206
249
  // did not earn is said.
207
250
  const uncompared = results
208
251
  .filter(({ gate, outcome }) => outcome && isCompared(gate) && baselines(gate) === undefined)
209
252
  .map(({ gate }) =>
210
- keepsWatch(gate)
211
- ? `${gate.name} not judged: no report from the turn start to compare its cycle with`
212
- : `${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`,
213
258
  );
214
259
  // Only a gate the turn concerned is named: one that would not have run anyway costs nothing to miss.
215
260
  const notRun = missing
@@ -217,12 +262,13 @@ export async function checkTurn(session: string, root: string): Promise<CheckedT
217
262
  .map(({ gate, why }) => `${gate.name} not run: ${why}`);
218
263
  const notes = [
219
264
  ...(startNote ? [startNote] : []),
265
+ ...(moved ? [`HEAD moved during the turn (${moved.how}): only what the turn changed since is checked`] : []),
220
266
  ...configNote(changedGatesFiles(turn.config, now)),
221
267
  ...uncompared,
222
268
  ...refusedNotes(refused),
223
269
  ...notRun,
224
270
  ];
225
- return checkedTurn(changed, results, started, notes, showAllPasses);
271
+ return checkedTurn(changed, results, started, notes, config);
226
272
  }
227
273
 
228
274
  function refusedNotes(refused: Gates["refused"]): string[] {
@@ -10,6 +10,9 @@ const LOCAL_GATES_FILE = ".gates.local.json";
10
10
  const DEFAULT_MAX_TIMEOUT_SECONDS = 45;
11
11
  // The times a turn sends the agent back: enough for a fix that breaks another gate, never a loop.
12
12
  const DEFAULT_MAX_SEND_BACKS = 5;
13
+ // The characters of reports a send-back holds, all gates together: what one gate may send alone. The agent fixes
14
+ // the first problems, and the next check shows it what is left.
15
+ const DEFAULT_MAX_TOTAL_REPORT_CHARS = 4000;
13
16
  const FIELDS = new Set([
14
17
  "name",
15
18
  "severity",
@@ -20,6 +23,10 @@ const FIELDS = new Set([
20
23
  "lineKey",
21
24
  "timeoutSeconds",
22
25
  "watch",
26
+ "prompt",
27
+ "maxReportChars",
28
+ "omitLines",
29
+ "brokenExitCodes",
23
30
  ]);
24
31
  const WATCH_FIELDS = new Set(["run", "cycleStart", "cycleEnd", "failed", "sync", "frozen"]);
25
32
 
@@ -27,6 +34,29 @@ const WATCH_FIELDS = new Set(["run", "cycleStart", "cycleEnd", "failed", "sync",
27
34
  export const FILES = "{files}";
28
35
  export const TURN = "{turn}";
29
36
 
37
+ /**
38
+ * A text of the repo for the agent, where the engine has one of its own: added after it, or in its place.
39
+ */
40
+ export interface Prompt {
41
+ text: string;
42
+ replace: boolean;
43
+ }
44
+
45
+ /**
46
+ * What the engine tells the agent that a repo may word again: as it sends it back, as it asks for missing tools, and
47
+ * with the report of a gate the turn broke.
48
+ */
49
+ const PROMPTS = ["sendBack", "missingTools", "brokenGate"] as const;
50
+ export type Prompts = Partial<Record<(typeof PROMPTS)[number], Prompt>>;
51
+
52
+ function toPrompt(value: unknown): Prompt | undefined {
53
+ if (typeof value === "string" && value) return { text: value, replace: false };
54
+ if (!isRecord(value) || Object.keys(value).join() !== "replace") return undefined;
55
+ return typeof value.replace === "string" && value.replace ? { text: value.replace, replace: true } : undefined;
56
+ }
57
+
58
+ const PROMPT_SHAPE = 'a text to add to what the agent is told, or {"replace": "a text"} to say it instead';
59
+
30
60
  export interface Gate {
31
61
  name: string;
32
62
  severity: "error" | "off";
@@ -38,6 +68,14 @@ export interface Gate {
38
68
  lineKey?: string;
39
69
  timeoutSeconds: number;
40
70
  watch?: Watch;
71
+ /** The most characters of its report the agent is sent, when the repo or the gate says: 4000 otherwise. */
72
+ maxReportChars?: number;
73
+ /** The lines of its report the agent is never sent, such as the frames of a stack. They change no verdict. */
74
+ omitLines?: string;
75
+ /** What the agent is told with the report of the gate. Replaced, an engine helper leaves its own line out. */
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[];
41
79
  }
42
80
 
43
81
  /**
@@ -84,6 +122,9 @@ interface GatesFile {
84
122
  maxTimeoutSeconds?: unknown;
85
123
  showAllPasses?: unknown;
86
124
  maxSendBacks?: unknown;
125
+ maxReportChars?: unknown;
126
+ maxTotalReportChars?: unknown;
127
+ prompts?: unknown;
87
128
  }
88
129
 
89
130
  function fileOf(text: string | undefined, file: string): GatesFile {
@@ -99,12 +140,17 @@ function fileOf(text: string | undefined, file: string): GatesFile {
99
140
  maxTimeoutSeconds,
100
141
  showAllPasses,
101
142
  maxSendBacks,
143
+ maxReportChars,
144
+ maxTotalReportChars,
145
+ prompts,
102
146
  ...others
103
147
  } = isRecord(parsed) ? parsed : { others: true };
104
148
  if (!Array.isArray(gates) || Object.keys(others).length)
105
149
  throw new Error(
106
150
  `${file} holds "gates", a list of gates, "maxTimeoutSeconds", the most seconds a gate may take, ` +
107
- `"showAllPasses", to name every green gate, and "maxSendBacks", the most times a turn sends the agent back.`,
151
+ `"showAllPasses", to name every green gate, "maxSendBacks", the most times a turn sends the agent back, ` +
152
+ `"maxReportChars", the most characters of a report the agent is sent, "maxTotalReportChars", the most of ` +
153
+ `all its reports together, and "prompts", what the agent is told.`,
108
154
  );
109
155
  const entries = gates.map((entry: unknown) => {
110
156
  if (!isRecord(entry) || typeof entry.name !== "string") throw new Error(`${file}: every gate has a name.`);
@@ -115,9 +161,48 @@ function fileOf(text: string | undefined, file: string): GatesFile {
115
161
  ...(maxTimeoutSeconds === undefined ? {} : { maxTimeoutSeconds }),
116
162
  ...(showAllPasses === undefined ? {} : { showAllPasses }),
117
163
  ...(maxSendBacks === undefined ? {} : { maxSendBacks }),
164
+ ...(maxReportChars === undefined ? {} : { maxReportChars }),
165
+ ...(maxTotalReportChars === undefined ? {} : { maxTotalReportChars }),
166
+ ...(prompts === undefined ? {} : { prompts }),
118
167
  };
119
168
  }
120
169
 
170
+ function maxTotalReportCharsOf(shared: GatesFile, local: GatesFile): number {
171
+ const max = local.maxTotalReportChars ?? shared.maxTotalReportChars ?? DEFAULT_MAX_TOTAL_REPORT_CHARS;
172
+ if (!isReportChars(max)) throw new Error("maxTotalReportChars is a whole number, 1 or more.");
173
+ return max;
174
+ }
175
+
176
+ const REPORT_CHARS_SHAPE = "maxReportChars is a whole number, 1 or more";
177
+
178
+ function isReportChars(value: unknown): value is number {
179
+ return typeof value === "number" && Number.isInteger(value) && value > 0;
180
+ }
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
+
186
+ // Nothing unless a file says: the report then keeps the characters the engine gives every gate.
187
+ function maxReportCharsOf(shared: GatesFile, local: GatesFile): number | undefined {
188
+ const max = local.maxReportChars ?? shared.maxReportChars;
189
+ if (max !== undefined && !isReportChars(max)) throw new Error(`${REPORT_CHARS_SHAPE}.`);
190
+ return max;
191
+ }
192
+
193
+ function promptsOf({ prompts = {} }: GatesFile): Prompts {
194
+ const known = PROMPTS.map((key) => `"${key}"`).join(", ");
195
+ if (!isRecord(prompts) || Object.keys(prompts).some((key) => !PROMPTS.some((prompt) => prompt === key)))
196
+ throw new Error(`prompts holds ${known}.`);
197
+ return Object.fromEntries(
198
+ Object.entries(prompts).map(([key, value]) => {
199
+ const prompt = toPrompt(value);
200
+ if (prompt === undefined) throw new Error(`prompts.${key} is ${PROMPT_SHAPE}.`);
201
+ return [key, prompt];
202
+ }),
203
+ );
204
+ }
205
+
121
206
  // The local file's own value wins, as for the fields of a gate.
122
207
  function maxTimeoutOf(shared: GatesFile, local: GatesFile): number {
123
208
  const max = local.maxTimeoutSeconds ?? shared.maxTimeoutSeconds ?? DEFAULT_MAX_TIMEOUT_SECONDS;
@@ -175,7 +260,7 @@ function toWatch(watch: unknown, compared: boolean): Watch {
175
260
  };
176
261
  }
177
262
 
178
- function toGate(entry: Entry, maxTimeoutSeconds: number): Gate {
263
+ function toGate(entry: Entry, maxTimeoutSeconds: number, reportChars: number | undefined): Gate {
179
264
  const {
180
265
  name,
181
266
  severity,
@@ -185,7 +270,11 @@ function toGate(entry: Entry, maxTimeoutSeconds: number): Gate {
185
270
  ignoreLines,
186
271
  lineKey,
187
272
  watch,
273
+ prompt,
274
+ omitLines,
275
+ brokenExitCodes,
188
276
  timeoutSeconds = maxTimeoutSeconds,
277
+ maxReportChars = reportChars,
189
278
  } = entry;
190
279
  const unknown = Object.keys(entry).find((key) => !FIELDS.has(key));
191
280
  if (unknown !== undefined) refuse(`unknown field ${unknown}`);
@@ -202,6 +291,11 @@ function toGate(entry: Entry, maxTimeoutSeconds: number): Gate {
202
291
  if (lineKey !== undefined && compare === undefined)
203
292
  refuse("lineKey tells apart the lines of a compared gate: it takes compare");
204
293
  if (typeof timeoutSeconds !== "number" || timeoutSeconds <= 0) refuse("timeoutSeconds is a positive number");
294
+ if (maxReportChars !== undefined && !isReportChars(maxReportChars)) refuse(REPORT_CHARS_SHAPE);
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");
298
+ const told = prompt === undefined ? undefined : (toPrompt(prompt) ?? refuse(`prompt is ${PROMPT_SHAPE}`));
205
299
  return {
206
300
  name,
207
301
  severity,
@@ -213,6 +307,10 @@ function toGate(entry: Entry, maxTimeoutSeconds: number): Gate {
213
307
  ...(ignoreLines === undefined ? {} : { ignoreLines }),
214
308
  ...(lineKey === undefined ? {} : { lineKey }),
215
309
  ...(watch === undefined ? {} : { watch: toWatch(watch, compare !== undefined) }),
310
+ ...(told === undefined ? {} : { prompt: told }),
311
+ ...(maxReportChars === undefined ? {} : { maxReportChars }),
312
+ ...(omitLines === undefined ? {} : { omitLines }),
313
+ ...(brokenExitCodes === undefined ? {} : { brokenExitCodes }),
216
314
  };
217
315
  }
218
316
 
@@ -225,6 +323,8 @@ export interface Gates {
225
323
  refused: { name: string; why: string }[];
226
324
  showAllPasses: boolean;
227
325
  maxSendBacks: number;
326
+ maxTotalReportChars: number;
327
+ prompts: Prompts;
228
328
  }
229
329
 
230
330
  /**
@@ -236,6 +336,7 @@ export function readGates(shared: string | undefined, local?: string): Gates {
236
336
  const sharedFile = fileOf(shared, GATES_FILE);
237
337
  const localFile = fileOf(local, LOCAL_GATES_FILE);
238
338
  const max = maxTimeoutOf(sharedFile, localFile);
339
+ const reportChars = maxReportCharsOf(sharedFile, localFile);
239
340
  const merged = new Map(sharedFile.entries.map((entry) => [entry.name, entry]));
240
341
  for (const entry of localFile.entries) merged.set(entry.name, { ...merged.get(entry.name), ...entry });
241
342
  const read: Gates = {
@@ -243,11 +344,14 @@ export function readGates(shared: string | undefined, local?: string): Gates {
243
344
  refused: [],
244
345
  showAllPasses: showAllPassesOf(sharedFile, localFile),
245
346
  maxSendBacks: maxSendBacksOf(sharedFile, localFile),
347
+ maxTotalReportChars: maxTotalReportCharsOf(sharedFile, localFile),
348
+ // The local file's own prompt wins, key by key.
349
+ prompts: { ...promptsOf(sharedFile), ...promptsOf(localFile) },
246
350
  };
247
351
  for (const entry of merged.values()) {
248
352
  if (entry.severity === "off") continue;
249
353
  try {
250
- read.gates.push(toGate(entry, max));
354
+ read.gates.push(toGate(entry, max, reportChars));
251
355
  } catch (error) {
252
356
  read.refused.push({ name: entry.name, why: messageOf(error) });
253
357
  }
@@ -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
+ }