@tayomi/deterministic-gates 0.8.2 → 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.
@@ -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,9 @@ const FIELDS = new Set([
20
23
  "lineKey",
21
24
  "timeoutSeconds",
22
25
  "watch",
26
+ "prompt",
27
+ "maxReportChars",
28
+ "omitLines",
23
29
  ]);
24
30
  const WATCH_FIELDS = new Set(["run", "cycleStart", "cycleEnd", "failed", "sync", "frozen"]);
25
31
 
@@ -27,6 +33,29 @@ const WATCH_FIELDS = new Set(["run", "cycleStart", "cycleEnd", "failed", "sync",
27
33
  export const FILES = "{files}";
28
34
  export const TURN = "{turn}";
29
35
 
36
+ /**
37
+ * A text of the repo for the agent, where the engine has one of its own: added after it, or in its place.
38
+ */
39
+ export interface Prompt {
40
+ text: string;
41
+ replace: boolean;
42
+ }
43
+
44
+ /**
45
+ * What the engine tells the agent that a repo may word again: as it sends it back, as it asks for missing tools, and
46
+ * with the report of a gate the turn broke.
47
+ */
48
+ const PROMPTS = ["sendBack", "missingTools", "brokenGate"] as const;
49
+ export type Prompts = Partial<Record<(typeof PROMPTS)[number], Prompt>>;
50
+
51
+ function toPrompt(value: unknown): Prompt | undefined {
52
+ if (typeof value === "string" && value) return { text: value, replace: false };
53
+ if (!isRecord(value) || Object.keys(value).join() !== "replace") return undefined;
54
+ return typeof value.replace === "string" && value.replace ? { text: value.replace, replace: true } : undefined;
55
+ }
56
+
57
+ const PROMPT_SHAPE = 'a text to add to what the agent is told, or {"replace": "a text"} to say it instead';
58
+
30
59
  export interface Gate {
31
60
  name: string;
32
61
  severity: "error" | "off";
@@ -38,6 +67,12 @@ export interface Gate {
38
67
  lineKey?: string;
39
68
  timeoutSeconds: number;
40
69
  watch?: Watch;
70
+ /** The most characters of its report the agent is sent, when the repo or the gate says: 4000 otherwise. */
71
+ maxReportChars?: number;
72
+ /** The lines of its report the agent is never sent, such as the frames of a stack. They change no verdict. */
73
+ omitLines?: string;
74
+ /** What the agent is told with the report of the gate. Replaced, an engine helper leaves its own line out. */
75
+ prompt?: Prompt;
41
76
  }
42
77
 
43
78
  /**
@@ -84,6 +119,9 @@ interface GatesFile {
84
119
  maxTimeoutSeconds?: unknown;
85
120
  showAllPasses?: unknown;
86
121
  maxSendBacks?: unknown;
122
+ maxReportChars?: unknown;
123
+ maxTotalReportChars?: unknown;
124
+ prompts?: unknown;
87
125
  }
88
126
 
89
127
  function fileOf(text: string | undefined, file: string): GatesFile {
@@ -99,12 +137,17 @@ function fileOf(text: string | undefined, file: string): GatesFile {
99
137
  maxTimeoutSeconds,
100
138
  showAllPasses,
101
139
  maxSendBacks,
140
+ maxReportChars,
141
+ maxTotalReportChars,
142
+ prompts,
102
143
  ...others
103
144
  } = isRecord(parsed) ? parsed : { others: true };
104
145
  if (!Array.isArray(gates) || Object.keys(others).length)
105
146
  throw new Error(
106
147
  `${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.`,
148
+ `"showAllPasses", to name every green gate, "maxSendBacks", the most times a turn sends the agent back, ` +
149
+ `"maxReportChars", the most characters of a report the agent is sent, "maxTotalReportChars", the most of ` +
150
+ `all its reports together, and "prompts", what the agent is told.`,
108
151
  );
109
152
  const entries = gates.map((entry: unknown) => {
110
153
  if (!isRecord(entry) || typeof entry.name !== "string") throw new Error(`${file}: every gate has a name.`);
@@ -115,9 +158,44 @@ function fileOf(text: string | undefined, file: string): GatesFile {
115
158
  ...(maxTimeoutSeconds === undefined ? {} : { maxTimeoutSeconds }),
116
159
  ...(showAllPasses === undefined ? {} : { showAllPasses }),
117
160
  ...(maxSendBacks === undefined ? {} : { maxSendBacks }),
161
+ ...(maxReportChars === undefined ? {} : { maxReportChars }),
162
+ ...(maxTotalReportChars === undefined ? {} : { maxTotalReportChars }),
163
+ ...(prompts === undefined ? {} : { prompts }),
118
164
  };
119
165
  }
120
166
 
167
+ function maxTotalReportCharsOf(shared: GatesFile, local: GatesFile): number {
168
+ const max = local.maxTotalReportChars ?? shared.maxTotalReportChars ?? DEFAULT_MAX_TOTAL_REPORT_CHARS;
169
+ if (!isReportChars(max)) throw new Error("maxTotalReportChars is a whole number, 1 or more.");
170
+ return max;
171
+ }
172
+
173
+ const REPORT_CHARS_SHAPE = "maxReportChars is a whole number, 1 or more";
174
+
175
+ function isReportChars(value: unknown): value is number {
176
+ return typeof value === "number" && Number.isInteger(value) && value > 0;
177
+ }
178
+
179
+ // Nothing unless a file says: the report then keeps the characters the engine gives every gate.
180
+ function maxReportCharsOf(shared: GatesFile, local: GatesFile): number | undefined {
181
+ const max = local.maxReportChars ?? shared.maxReportChars;
182
+ if (max !== undefined && !isReportChars(max)) throw new Error(`${REPORT_CHARS_SHAPE}.`);
183
+ return max;
184
+ }
185
+
186
+ function promptsOf({ prompts = {} }: GatesFile): Prompts {
187
+ const known = PROMPTS.map((key) => `"${key}"`).join(", ");
188
+ if (!isRecord(prompts) || Object.keys(prompts).some((key) => !PROMPTS.some((prompt) => prompt === key)))
189
+ throw new Error(`prompts holds ${known}.`);
190
+ return Object.fromEntries(
191
+ Object.entries(prompts).map(([key, value]) => {
192
+ const prompt = toPrompt(value);
193
+ if (prompt === undefined) throw new Error(`prompts.${key} is ${PROMPT_SHAPE}.`);
194
+ return [key, prompt];
195
+ }),
196
+ );
197
+ }
198
+
121
199
  // The local file's own value wins, as for the fields of a gate.
122
200
  function maxTimeoutOf(shared: GatesFile, local: GatesFile): number {
123
201
  const max = local.maxTimeoutSeconds ?? shared.maxTimeoutSeconds ?? DEFAULT_MAX_TIMEOUT_SECONDS;
@@ -175,7 +253,7 @@ function toWatch(watch: unknown, compared: boolean): Watch {
175
253
  };
176
254
  }
177
255
 
178
- function toGate(entry: Entry, maxTimeoutSeconds: number): Gate {
256
+ function toGate(entry: Entry, maxTimeoutSeconds: number, reportChars: number | undefined): Gate {
179
257
  const {
180
258
  name,
181
259
  severity,
@@ -185,7 +263,10 @@ function toGate(entry: Entry, maxTimeoutSeconds: number): Gate {
185
263
  ignoreLines,
186
264
  lineKey,
187
265
  watch,
266
+ prompt,
267
+ omitLines,
188
268
  timeoutSeconds = maxTimeoutSeconds,
269
+ maxReportChars = reportChars,
189
270
  } = entry;
190
271
  const unknown = Object.keys(entry).find((key) => !FIELDS.has(key));
191
272
  if (unknown !== undefined) refuse(`unknown field ${unknown}`);
@@ -202,6 +283,9 @@ function toGate(entry: Entry, maxTimeoutSeconds: number): Gate {
202
283
  if (lineKey !== undefined && compare === undefined)
203
284
  refuse("lineKey tells apart the lines of a compared gate: it takes compare");
204
285
  if (typeof timeoutSeconds !== "number" || timeoutSeconds <= 0) refuse("timeoutSeconds is a positive number");
286
+ if (maxReportChars !== undefined && !isReportChars(maxReportChars)) refuse(REPORT_CHARS_SHAPE);
287
+ if (omitLines !== undefined && !isPattern(omitLines)) refuse("omitLines is a regular expression");
288
+ const told = prompt === undefined ? undefined : (toPrompt(prompt) ?? refuse(`prompt is ${PROMPT_SHAPE}`));
205
289
  return {
206
290
  name,
207
291
  severity,
@@ -213,6 +297,9 @@ function toGate(entry: Entry, maxTimeoutSeconds: number): Gate {
213
297
  ...(ignoreLines === undefined ? {} : { ignoreLines }),
214
298
  ...(lineKey === undefined ? {} : { lineKey }),
215
299
  ...(watch === undefined ? {} : { watch: toWatch(watch, compare !== undefined) }),
300
+ ...(told === undefined ? {} : { prompt: told }),
301
+ ...(maxReportChars === undefined ? {} : { maxReportChars }),
302
+ ...(omitLines === undefined ? {} : { omitLines }),
216
303
  };
217
304
  }
218
305
 
@@ -225,6 +312,8 @@ export interface Gates {
225
312
  refused: { name: string; why: string }[];
226
313
  showAllPasses: boolean;
227
314
  maxSendBacks: number;
315
+ maxTotalReportChars: number;
316
+ prompts: Prompts;
228
317
  }
229
318
 
230
319
  /**
@@ -236,6 +325,7 @@ export function readGates(shared: string | undefined, local?: string): Gates {
236
325
  const sharedFile = fileOf(shared, GATES_FILE);
237
326
  const localFile = fileOf(local, LOCAL_GATES_FILE);
238
327
  const max = maxTimeoutOf(sharedFile, localFile);
328
+ const reportChars = maxReportCharsOf(sharedFile, localFile);
239
329
  const merged = new Map(sharedFile.entries.map((entry) => [entry.name, entry]));
240
330
  for (const entry of localFile.entries) merged.set(entry.name, { ...merged.get(entry.name), ...entry });
241
331
  const read: Gates = {
@@ -243,11 +333,14 @@ export function readGates(shared: string | undefined, local?: string): Gates {
243
333
  refused: [],
244
334
  showAllPasses: showAllPassesOf(sharedFile, localFile),
245
335
  maxSendBacks: maxSendBacksOf(sharedFile, localFile),
336
+ maxTotalReportChars: maxTotalReportCharsOf(sharedFile, localFile),
337
+ // The local file's own prompt wins, key by key.
338
+ prompts: { ...promptsOf(sharedFile), ...promptsOf(localFile) },
246
339
  };
247
340
  for (const entry of merged.values()) {
248
341
  if (entry.severity === "off") continue;
249
342
  try {
250
- read.gates.push(toGate(entry, max));
343
+ read.gates.push(toGate(entry, max, reportChars));
251
344
  } catch (error) {
252
345
  read.refused.push({ name: entry.name, why: messageOf(error) });
253
346
  }
@@ -1,11 +1,13 @@
1
1
  import type { CheckedTurn } from "./check.ts";
2
+ import type { Prompt } from "./config.ts";
2
3
  import { failed, type Outcome } from "./run.ts";
3
4
  import { WAIVE_TAG } from "./waive-line.ts";
4
5
 
5
6
  const LABEL = "● gates";
6
7
  const SHOWN_PASSES = 6;
7
8
  const REPORT_CHARS = 4000;
8
- const HEAD_CHARS = 1000;
9
+ // The share of a cut report kept from its start.
10
+ const HEAD_SHARE = 0.25;
9
11
 
10
12
  const TONES = { pass: "1;32", fail: "1;31", late: "1;33", warn: "1;38;5;208", dim: "2" } as const;
11
13
  // The warning sign as text, never as the emoji some terminals draw without the variation selector.
@@ -21,11 +23,26 @@ function paint(tone: keyof typeof TONES, text: string): string {
21
23
  return `\x1b[${TONES[tone]}m${text}\x1b[0m`;
22
24
  }
23
25
 
24
- /** Keeps the start and the end of a long report: tools put the problem at one or the other. */
25
- export function excerpt(report: string): string {
26
- if (report.length <= REPORT_CHARS) return report;
27
- const cut = report.length - REPORT_CHARS;
28
- return `${report.slice(0, HEAD_CHARS)}\n[... ${cut} characters cut ...]\n${report.slice(-(REPORT_CHARS - HEAD_CHARS))}`;
26
+ /**
27
+ * Keeps the start and the end of a long report, in the characters given: tools put the problem at one or the other.
28
+ * 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
29
+ * stays inside a line longer than that, which would otherwise go whole.
30
+ */
31
+ export function excerpt(report: string, max = REPORT_CHARS): string {
32
+ if (report.length <= max) return report;
33
+ const head = Math.floor(max * HEAD_SHARE);
34
+ const tail = max - head;
35
+ const before = report.lastIndexOf("\n", head - 1);
36
+ const after = report.indexOf("\n", report.length - tail);
37
+ const wholeHead = before >= head / 2;
38
+ const wholeTail = after !== -1 && after - (report.length - tail) <= tail / 2;
39
+ const end = wholeHead ? before : head;
40
+ const start = wholeTail ? after + 1 : report.length - tail;
41
+ const cut =
42
+ wholeHead && wholeTail
43
+ ? `${report.slice(end + 1, start - 1).split("\n").length} lines`
44
+ : `${start - end} characters`;
45
+ return `${report.slice(0, end)}\n[... ${cut} cut ...]\n${report.slice(start)}`;
29
46
  }
30
47
 
31
48
  export function duration(ms: number): string {
@@ -115,16 +132,55 @@ export function broken(reason: string): string {
115
132
 
116
133
  // The cheapest green is to silence the rule, and nothing in the engine judges a report. So the agent is told the one
117
134
  // way out that is not a cheat: waive the gate, with a reason the owner reads and judges.
118
- const CONDUCT = [
119
- "Fix the code, never the check: a silenced rule (noqa, eslint-disable, nolint), a weakened gate or an edited",
135
+ const SEND_BACK = [
136
+ "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",
120
137
  ".gates.json does not pass this turn. If you can fix a problem, fix it. Leave a gate red only when it cannot be",
121
138
  "fixed (the report is wrong, or fixing it would loop until the last send-back), when fixing it goes against what",
122
- "the owner asked, or when the owner has to settle a question first. Then waive it in your final message, after a",
123
- "blank line, one line per gate, its reason in one line:",
139
+ "the owner asked, or when the owner has to settle a question first.",
124
140
  ].join(" ");
125
141
 
126
142
  const WAIVE_SYNTAX = `[${WAIVE_TAG}:<gate>]: waive "<reason>"`;
127
143
 
144
+ // Said whatever the repo says in place of the rest: without it, an agent could only loop on a gate it cannot fix.
145
+ const WAIVE = [
146
+ "To leave a gate red, waive it in your final message, after a blank line, one line per gate, its reason in one line:",
147
+ WAIVE_SYNTAX,
148
+ ].join("\n");
149
+
150
+ // A gate that broke found no problem to fix: the agent looks for what stops it from running, in the code or around it.
151
+ const BROKEN_GATE =
152
+ "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.";
153
+
154
+ // What a session already told how to act reads at its next send-backs: what it has in its context is not said again.
155
+ const BRIEF = `Gates fail again: act as the first send-back of this session told you, or waive with ${WAIVE_SYNTAX}`;
156
+
157
+ /** What the engine tells the agent, with the prompt of the repo after it, or in its place. */
158
+ function worded(own: string, prompt: Prompt | undefined, between: string): string {
159
+ if (prompt === undefined) return own;
160
+ return prompt.replace ? prompt.text : `${own}${between}${prompt.text}`;
161
+ }
162
+
163
+ // The report less the lines the gate omits, or whole when it would omit them all: a red gate always says something.
164
+ function sent(report: string, omitLines: string | undefined): string {
165
+ if (omitLines === undefined) return report;
166
+ const omitted = new RegExp(omitLines);
167
+ const kept = report.split("\n").filter((line) => !omitted.test(line));
168
+ return kept.some((line) => line.trim()) ? kept.join("\n") : report;
169
+ }
170
+
171
+ // The characters each report gets of a total: what it needs when all fit, else the short ones whole and the rest of
172
+ // the total in equal shares for the long ones.
173
+ function shares(needs: number[], total: number): number[] {
174
+ const given = [...needs];
175
+ let left = total;
176
+ const shortestFirst = needs.map((_, at) => at).sort((a, b) => (needs[a] ?? 0) - (needs[b] ?? 0));
177
+ shortestFirst.forEach((at, done) => {
178
+ given[at] = Math.min(needs[at] ?? 0, Math.floor(left / (needs.length - done)));
179
+ left -= given[at];
180
+ });
181
+ return given;
182
+ }
183
+
128
184
  /** What the owner sees when the gates of the repo miss tools on this machine, as the agent is asked to install them. */
129
185
  export function toolsMissing(missing: string[]): string {
130
186
  const gates = missing.length === 1 ? "1 gate is off" : `${missing.length} gates are off`;
@@ -135,25 +191,75 @@ export function toolsMissing(missing: string[]): string {
135
191
  }
136
192
 
137
193
  /** What the agent is told when the gates of the repo miss tools: install them, or the gates that need them stay off. */
138
- export function toolsToInstall(missing: string[]): string {
194
+ export function toolsToInstall(missing: string[], prompt?: Prompt): string {
195
+ const install = [
196
+ "Install these tools first. If they cannot be installed, or the developer refuses, say so and go on with the",
197
+ "prompt: the gates that need them stay off until they are installed, and every other gate still runs.",
198
+ ].join("\n");
139
199
  return [
140
200
  "Some gates of this repo cannot run on this machine, for a missing tool:",
141
201
  ...missing.map((tool) => `- ${tool}`),
142
- "Install these tools first. If they cannot be installed, or the developer refuses, say so and go on with the",
143
- "prompt: the gates that need them stay off until they are installed, and every other gate still runs.",
202
+ worded(install, prompt, "\n"),
144
203
  ].join("\n");
145
204
  }
146
205
 
147
- /** The report of each failed gate, under its name. */
148
- export function reports(outcomes: Outcome[]): string[] {
149
- return outcomes.filter(failed).map(({ name, output }) => `## ${name}\n${excerpt(output)}`);
206
+ /**
207
+ * The report of each failed gate, under its name, how to act on one the turn broke, and the prompt of the repo for it:
208
+ * less the lines the gate omits, in the characters it has, and in its share of a total when the reports have one.
209
+ */
210
+ export function reports({ outcomes, wording = {} }: Pick<CheckedTurn, "outcomes" | "wording">): string[] {
211
+ const { gates = [], prompts, maxTotalReportChars = Infinity } = wording;
212
+ const red = outcomes.filter(failed).map(({ name, output, broken }) => {
213
+ const gate = gates.find((known) => known.name === name);
214
+ const report = sent(output, gate?.omitLines);
215
+ const told = [
216
+ ...(broken ? [worded(BROKEN_GATE, prompts?.brokenGate, "\n")] : []),
217
+ ...(gate?.prompt ? [gate.prompt.text] : []),
218
+ ];
219
+ return { name, told, report, needs: Math.min(report.length, gate?.maxReportChars ?? REPORT_CHARS) };
220
+ });
221
+ const given = shares(
222
+ red.map(({ needs }) => needs),
223
+ maxTotalReportChars,
224
+ );
225
+ return red.map(({ name, told, report }, at) => [`## ${name}`, ...told, excerpt(report, given[at])].join("\n"));
150
226
  }
151
227
 
152
228
  /**
153
- * 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
154
- * check, each failed report.
229
+ * 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
230
+ * 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.
155
231
  */
156
- export function failures({ outcomes, note }: CheckedTurn, told: string[] = []): string {
157
- const head = ["Gates fail on what this turn changed. Fix every problem before you hand back.", CONDUCT, WAIVE_SYNTAX];
158
- return [...head, ...told, ...(note ? [note] : []), ...reports(outcomes)].join("\n\n");
232
+ export function failures(turn: CheckedTurn, told: string[] = [], brief = false): string {
233
+ const head = brief ? [BRIEF] : [worded(SEND_BACK, turn.wording?.prompts?.sendBack, "\n\n"), WAIVE];
234
+ return [...head, ...told, ...(turn.note ? [turn.note] : []), ...reports(turn)].join("\n\n");
235
+ }
236
+
237
+ /** A gate of a check, as a tool reads it: its status says what else it holds. */
238
+ type GateResult =
239
+ | { name: string; status: "passed"; durationMs: number }
240
+ | { name: string; status: "failed"; durationMs: number; report: string }
241
+ /** The gate could not run: its report says what stopped it, never what the code does wrong. */
242
+ | { name: string; status: "broken"; durationMs: number; report: string }
243
+ /** Stopped for lack of time, so neither green nor red. */
244
+ | { name: string; status: "timed-out"; durationMs: number }
245
+ /** No file it looks at changed. */
246
+ | { name: string; status: "skipped" };
247
+
248
+ function gateResult({ name, ok, ms, output, timedOut, broken }: Outcome): GateResult {
249
+ const durationMs = Math.round(ms);
250
+ if (ok) return { name, status: "passed", durationMs };
251
+ if (timedOut) return { name, status: "timed-out", durationMs };
252
+ return { name, status: broken ? "broken" : "failed", durationMs, report: output };
253
+ }
254
+
255
+ /**
256
+ * 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
257
+ * agent: whether it passed, each gate with its status and its whole report, and the notes of the check.
258
+ */
259
+ export function results({ outcomes, skipped, ms, note }: CheckedTurn) {
260
+ const gates: GateResult[] = [
261
+ ...outcomes.map(gateResult),
262
+ ...skipped.map((name) => ({ name, status: "skipped" as const })),
263
+ ];
264
+ return { ok: !outcomes.some(failed), durationMs: Math.round(ms), gates, notes: note ? note.split("\n") : [] };
159
265
  }
package/src/core/run.ts CHANGED
@@ -13,9 +13,14 @@ export interface Outcome {
13
13
  report: string | undefined;
14
14
  /** Stopped for lack of time: neither green nor red, since nobody knows what it would have said. */
15
15
  timedOut?: boolean;
16
+ /**
17
+ * The gate did not report: its command is missing or broke, its watch stopped. It still fails the turn, since
18
+ * nothing tells a gate the turn broke from one that broke before it, but the agent is told to repair it.
19
+ */
20
+ broken?: boolean;
16
21
  }
17
22
 
18
- /** A gate that judged the turn and found a problem: the only kind that sends the agent back. */
23
+ /** A gate that judged the turn and found a problem, or that broke: the only kinds that send the agent back. */
19
24
  export function failed(outcome: Outcome): boolean {
20
25
  return !outcome.ok && !outcome.timedOut;
21
26
  }
@@ -38,6 +43,14 @@ function repoNode(root: string): string {
38
43
  const pinned = join(root, "node_modules", ".bin", "node");
39
44
  return executable(pinned) ? pinned : process.execPath;
40
45
  }
46
+ /** Set for a gate whose prompt the repo replaces: its command leaves out the line it would tell the agent itself. */
47
+ const PROMPT_REPLACED = "GATES_PROMPT_REPLACED";
48
+
49
+ /** The report of an engine helper: its own line for the agent, unless the repo says another instead, then its list. */
50
+ export function headed(own: string, lines: string[], env = process.env): string {
51
+ return [...(env[PROMPT_REPLACED] ? [] : [own]), ...lines].join("\n");
52
+ }
53
+
41
54
  const MAX_OUTPUT_MB = 16;
42
55
  const ENGINE_PREFIX = "{engine}/";
43
56
 
@@ -190,6 +203,8 @@ interface Executed {
190
203
  output: string;
191
204
  ms: number;
192
205
  timedOut: boolean;
206
+ /** The command was never started: it is missing, or the engine cannot resolve it. */
207
+ cannotStart: boolean;
193
208
  }
194
209
 
195
210
  async function execute(root: string, gate: Gate, args: string[]): Promise<Executed> {
@@ -200,7 +215,13 @@ async function execute(root: string, gate: Gate, args: string[]): Promise<Execut
200
215
  try {
201
216
  command = commandOf(root, name);
202
217
  } catch (error) {
203
- return { ok: false, output: messageOf(error), ms: performance.now() - started, timedOut: false };
218
+ return {
219
+ ok: false,
220
+ output: messageOf(error),
221
+ ms: performance.now() - started,
222
+ timedOut: false,
223
+ cannotStart: true,
224
+ };
204
225
  }
205
226
  return new Promise((resolve) => {
206
227
  execFile(
@@ -210,7 +231,7 @@ async function execute(root: string, gate: Gate, args: string[]): Promise<Execut
210
231
  cwd: root,
211
232
  timeout: gate.timeoutSeconds * 1000,
212
233
  maxBuffer: MAX_OUTPUT_MB * 1024 * 1024,
213
- env: toolEnv(root),
234
+ env: { ...toolEnv(root), ...(gate.prompt?.replace ? { [PROMPT_REPLACED]: "1" } : {}) },
214
235
  },
215
236
  (error, stdout, stderr) => {
216
237
  resolve({
@@ -218,6 +239,7 @@ async function execute(root: string, gate: Gate, args: string[]): Promise<Execut
218
239
  output: outputOf(root, gate, command, error, `${stdout}${stderr}`),
219
240
  ms: performance.now() - started,
220
241
  timedOut: error?.killed === true && error.code !== "ERR_CHILD_PROCESS_STDIO_MAXBUFFER",
242
+ cannotStart: error?.code === "ENOENT",
221
243
  });
222
244
  },
223
245
  );
@@ -261,8 +283,8 @@ export async function wholeProject(
261
283
  }
262
284
 
263
285
  /**
264
- * 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:
265
- * the same crash at the start and at the end of a turn prints no new line. A gate out of time is neither.
286
+ * Runs a gate on the turn. A compared gate fails on the lines of output the turn added, and is broken on any exit
287
+ * code but 0: the same crash at the start and at the end of a turn prints no new line. A gate out of time is neither.
266
288
  */
267
289
  export async function check(
268
290
  root: string,
@@ -271,9 +293,11 @@ export async function check(
271
293
  turn: string,
272
294
  baseline: string | undefined,
273
295
  ): Promise<Outcome> {
274
- const { ok, output, ms, timedOut } = await execute(root, gate, argumentsOf(gate, files, turn));
296
+ const { ok, output, ms, timedOut, cannotStart } = await execute(root, gate, argumentsOf(gate, files, turn));
275
297
  const ran = { name: gate.name, ms, report: ok ? output : undefined };
276
298
  if (timedOut) return { ...ran, ok, output, timedOut };
299
+ // A compared gate exits with 0 when it finds problems: any other code is its command that broke.
300
+ if (!ok && (cannotStart || isCompared(gate))) return { ...ran, ok, output, broken: true };
277
301
  if (!isCompared(gate) || !ok) return { ...ran, ok, output };
278
302
  return { ...ran, ...addedLines(gate, output, baseline, files) };
279
303
  }
@@ -99,6 +99,21 @@ export function hasCommit(root: string, commit: string): boolean {
99
99
  }
100
100
  }
101
101
 
102
+ /** A file as a commit holds it, or nothing when the commit does not have it. */
103
+ export function fileAt(root: string, commit: string, file: string): string | undefined {
104
+ try {
105
+ // However long: past the default megabyte, git would read as a commit that does not have the file.
106
+ return execFileSync("git", ["show", `${commit}:${file}`], {
107
+ cwd: root,
108
+ encoding: "utf8",
109
+ stdio: "pipe",
110
+ maxBuffer: Infinity,
111
+ });
112
+ } catch {
113
+ return undefined;
114
+ }
115
+ }
116
+
102
117
  /** The files that differ between two commits or trees, the deleted ones included. */
103
118
  export function changedSince(root: string, start: string, end = workingTree(root)): string[] {
104
119
  return paths(git(root, ["diff", "-z", "--name-only", start, end])).sort();
@@ -50,6 +50,8 @@ interface SessionState {
50
50
  current?: string;
51
51
  turns: Record<string, TurnState>;
52
52
  told?: Record<string, string[]>;
53
+ /** The repos a send-back of the session told the agent how to act in: the next ones there say it in one line. */
54
+ conductTold?: string[];
53
55
  }
54
56
 
55
57
  const EMPTY: SessionState = { turns: {} };
@@ -89,7 +91,8 @@ function isSessionState(value: unknown): value is SessionState {
89
91
  (value.current === undefined || typeof value.current === "string") &&
90
92
  isRecord(value.turns) &&
91
93
  Object.values(value.turns).every(isTurnState) &&
92
- (value.told === undefined || (isRecord(value.told) && Object.values(value.told).every(isStringArray)))
94
+ (value.told === undefined || (isRecord(value.told) && Object.values(value.told).every(isStringArray))) &&
95
+ (value.conductTold === undefined || isStringArray(value.conductTold))
93
96
  );
94
97
  }
95
98
 
@@ -112,15 +115,19 @@ export function readTurn(session: string, root: string): TurnState | undefined {
112
115
  * progress is read again, by its retry.
113
116
  */
114
117
  export function writeTurn(session: string, root: string, turn: TurnState): void {
115
- const { turns, told } = readSession(session);
118
+ const { turns, ...state } = readSession(session);
116
119
  const unchecked = Object.entries(turns).filter(([, kept]) => !kept.checked);
117
- writeSession(session, { told, current: root, turns: { ...Object.fromEntries(unchecked), [root]: turn } });
120
+ writeSession(session, { ...state, current: root, turns: { ...Object.fromEntries(unchecked), [root]: turn } });
118
121
  }
119
122
 
120
123
  /** Ends the turn in progress without a check, as a prompt from a folder with no gates, or a failed start, does. */
121
124
  export function forgetTurn(session: string): void {
122
- const { current, ...state } = readSession(session);
123
- if (current !== undefined) writeSession(session, state);
125
+ forget(session, "current");
126
+ }
127
+
128
+ function forget(session: string, key: "current" | "told" | "conductTold"): void {
129
+ const { [key]: had, ...state } = readSession(session);
130
+ if (had !== undefined) writeSession(session, state);
124
131
  }
125
132
 
126
133
  /**
@@ -135,10 +142,26 @@ export function tellOnce(session: string, root: string, missing: string[]): bool
135
142
  return missing.length > 0;
136
143
  }
137
144
 
145
+ /**
146
+ * Whether the agent is yet to be told how to act on a send-back of this repo, in this session: said once, it stays in
147
+ * its context, and saying it again at every send-back only costs it tokens. Each repo has its own words for it.
148
+ */
149
+ export function tellConductOnce(session: string, root: string): boolean {
150
+ const state = readSession(session);
151
+ const told = state.conductTold ?? [];
152
+ if (told.includes(root)) return false;
153
+ writeSession(session, { ...state, conductTold: [...told, root] });
154
+ return true;
155
+ }
156
+
157
+ /** Forgets that the agent was told how to act: a session that starts again, or compacts, may have lost it. */
158
+ export function forgetConduct(session: string): void {
159
+ forget(session, "conductTold");
160
+ }
161
+
138
162
  /** Forgets what the agent was told of missing tools, so a session that starts again, or resumes, is told again. */
139
163
  export function forgetTold(session: string): void {
140
- const { told, ...state } = readSession(session);
141
- if (told !== undefined) writeSession(session, state);
164
+ forget(session, "told");
142
165
  }
143
166
 
144
167
  /**