@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,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,67 @@ 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
+ // A helper of the engine counts apart the errors of one source line, with `(2)` before the tab that ends their key,
172
+ // so that one more of them is new. The agent reads each of them once, with how many times it stands.
173
+ function saidOnce(report: string): string {
174
+ const lines = report.split("\n").map((line) => line.replace(/ \(\d+\)\t/, "\t"));
175
+ const times = new Map<string, number>();
176
+ for (const line of lines) if (line.includes("\t")) times.set(line, (times.get(line) ?? 0) + 1);
177
+ return lines
178
+ .filter((line, at) => !times.has(line) || lines.indexOf(line) === at)
179
+ .map((line) => ((times.get(line) ?? 1) > 1 ? `${line} (×${times.get(line)})` : line))
180
+ .join("\n");
181
+ }
182
+
183
+ // The characters each report gets of a total: what it needs when all fit, else the short ones whole and the rest of
184
+ // the total in equal shares for the long ones.
185
+ function shares(needs: number[], total: number): number[] {
186
+ const given = [...needs];
187
+ let left = total;
188
+ const shortestFirst = needs.map((_, at) => at).sort((a, b) => (needs[a] ?? 0) - (needs[b] ?? 0));
189
+ shortestFirst.forEach((at, done) => {
190
+ given[at] = Math.min(needs[at] ?? 0, Math.floor(left / (needs.length - done)));
191
+ left -= given[at];
192
+ });
193
+ return given;
194
+ }
195
+
128
196
  /** What the owner sees when the gates of the repo miss tools on this machine, as the agent is asked to install them. */
129
197
  export function toolsMissing(missing: string[]): string {
130
198
  const gates = missing.length === 1 ? "1 gate is off" : `${missing.length} gates are off`;
@@ -135,25 +203,75 @@ export function toolsMissing(missing: string[]): string {
135
203
  }
136
204
 
137
205
  /** 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 {
206
+ export function toolsToInstall(missing: string[], prompt?: Prompt): string {
207
+ const install = [
208
+ "Install these tools first. If they cannot be installed, or the developer refuses, say so and go on with the",
209
+ "prompt: the gates that need them stay off until they are installed, and every other gate still runs.",
210
+ ].join("\n");
139
211
  return [
140
212
  "Some gates of this repo cannot run on this machine, for a missing tool:",
141
213
  ...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.",
214
+ worded(install, prompt, "\n"),
144
215
  ].join("\n");
145
216
  }
146
217
 
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)}`);
218
+ /**
219
+ * The report of each failed gate, under its name, how to act on one the turn broke, and the prompt of the repo for it:
220
+ * each line a helper counts apart said once, less the lines the gate omits, in the characters it has, and in its share of a total when the reports have one.
221
+ */
222
+ export function reports({ outcomes, wording = {} }: Pick<CheckedTurn, "outcomes" | "wording">): string[] {
223
+ const { gates = [], prompts, maxTotalReportChars = Infinity } = wording;
224
+ const red = outcomes.filter(failed).map(({ name, output, broken }) => {
225
+ const gate = gates.find((known) => known.name === name);
226
+ const report = sent(saidOnce(output), gate?.omitLines);
227
+ const told = [
228
+ ...(broken ? [worded(BROKEN_GATE, prompts?.brokenGate, "\n")] : []),
229
+ ...(gate?.prompt ? [gate.prompt.text] : []),
230
+ ];
231
+ return { name, told, report, needs: Math.min(report.length, gate?.maxReportChars ?? REPORT_CHARS) };
232
+ });
233
+ const given = shares(
234
+ red.map(({ needs }) => needs),
235
+ maxTotalReportChars,
236
+ );
237
+ return red.map(({ name, told, report }, at) => [`## ${name}`, ...told, excerpt(report, given[at])].join("\n"));
238
+ }
239
+
240
+ /**
241
+ * 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
242
+ * 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.
243
+ */
244
+ export function failures(turn: CheckedTurn, told: string[] = [], brief = false): string {
245
+ const head = brief ? [BRIEF] : [worded(SEND_BACK, turn.wording?.prompts?.sendBack, "\n\n"), WAIVE];
246
+ return [...head, ...told, ...(turn.note ? [turn.note] : []), ...reports(turn)].join("\n\n");
247
+ }
248
+
249
+ /** A gate of a check, as a tool reads it: its status says what else it holds. */
250
+ type GateResult =
251
+ | { name: string; status: "passed"; durationMs: number }
252
+ | { name: string; status: "failed"; durationMs: number; report: string }
253
+ /** The gate could not run: its report says what stopped it, never what the code does wrong. */
254
+ | { name: string; status: "broken"; durationMs: number; report: string }
255
+ /** Stopped for lack of time, so neither green nor red. */
256
+ | { name: string; status: "timed-out"; durationMs: number }
257
+ /** No file it looks at changed. */
258
+ | { name: string; status: "skipped" };
259
+
260
+ function gateResult({ name, ok, ms, output, timedOut, broken }: Outcome): GateResult {
261
+ const durationMs = Math.round(ms);
262
+ if (ok) return { name, status: "passed", durationMs };
263
+ if (timedOut) return { name, status: "timed-out", durationMs };
264
+ return { name, status: broken ? "broken" : "failed", durationMs, report: output };
150
265
  }
151
266
 
152
267
  /**
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.
268
+ * 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
269
+ * agent: whether it passed, each gate with its status and its whole report, and the notes of the check.
155
270
  */
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");
271
+ export function results({ outcomes, skipped, ms, note }: CheckedTurn) {
272
+ const gates: GateResult[] = [
273
+ ...outcomes.map(gateResult),
274
+ ...skipped.map((name) => ({ name, status: "skipped" as const })),
275
+ ];
276
+ return { ok: !outcomes.some(failed), durationMs: Math.round(ms), gates, notes: note ? note.split("\n") : [] };
159
277
  }
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,10 @@ 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;
208
+ /** The code the command exited with, when it ran to its end. */
209
+ exitCode?: number;
193
210
  }
194
211
 
195
212
  async function execute(root: string, gate: Gate, args: string[]): Promise<Executed> {
@@ -200,7 +217,13 @@ async function execute(root: string, gate: Gate, args: string[]): Promise<Execut
200
217
  try {
201
218
  command = commandOf(root, name);
202
219
  } catch (error) {
203
- return { ok: false, output: messageOf(error), ms: performance.now() - started, timedOut: false };
220
+ return {
221
+ ok: false,
222
+ output: messageOf(error),
223
+ ms: performance.now() - started,
224
+ timedOut: false,
225
+ cannotStart: true,
226
+ };
204
227
  }
205
228
  return new Promise((resolve) => {
206
229
  execFile(
@@ -210,7 +233,7 @@ async function execute(root: string, gate: Gate, args: string[]): Promise<Execut
210
233
  cwd: root,
211
234
  timeout: gate.timeoutSeconds * 1000,
212
235
  maxBuffer: MAX_OUTPUT_MB * 1024 * 1024,
213
- env: toolEnv(root),
236
+ env: { ...toolEnv(root), ...(gate.prompt?.replace ? { [PROMPT_REPLACED]: "1" } : {}) },
214
237
  },
215
238
  (error, stdout, stderr) => {
216
239
  resolve({
@@ -218,6 +241,8 @@ async function execute(root: string, gate: Gate, args: string[]): Promise<Execut
218
241
  output: outputOf(root, gate, command, error, `${stdout}${stderr}`),
219
242
  ms: performance.now() - started,
220
243
  timedOut: error?.killed === true && error.code !== "ERR_CHILD_PROCESS_STDIO_MAXBUFFER",
244
+ cannotStart: error?.code === "ENOENT",
245
+ ...(typeof error?.code === "number" ? { exitCode: error.code } : {}),
221
246
  });
222
247
  },
223
248
  );
@@ -260,9 +285,20 @@ export async function wholeProject(
260
285
  return timedOut ? { ok: false } : { ok, output };
261
286
  }
262
287
 
288
+ /** The file a line of a compared gate names, by the group of its key named file. */
289
+ function fileOf(gate: Gate, line: string): string | undefined {
290
+ return gate.lineKey === undefined ? undefined : new RegExp(gate.lineKey).exec(line)?.groups?.file;
291
+ }
292
+
293
+ /** Whether the lines of a compared gate name their file, so that they can be told from the ones of other files. */
294
+ export function namesFiles(gate: Gate): boolean {
295
+ return /\(\?<file>/.test(gate.lineKey ?? "");
296
+ }
297
+
263
298
  /**
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.
299
+ * Runs a gate on the turn. A compared gate fails on the lines of output the turn added, and is broken on any exit
300
+ * code but 0: the same crash at the start and at the end of a turn prints no new line. Another gate is broken on the
301
+ * exit codes it names as such. A gate out of time is neither.
266
302
  */
267
303
  export async function check(
268
304
  root: string,
@@ -270,25 +306,34 @@ export async function check(
270
306
  files: string[],
271
307
  turn: string,
272
308
  baseline: string | undefined,
309
+ elsewhere = false,
273
310
  ): Promise<Outcome> {
274
- const { ok, output, ms, timedOut } = await execute(root, gate, argumentsOf(gate, files, turn));
311
+ const executed = await execute(root, gate, argumentsOf(gate, files, turn));
312
+ const { ok, output, ms, timedOut, cannotStart, exitCode = 0 } = executed;
275
313
  const ran = { name: gate.name, ms, report: ok ? output : undefined };
276
314
  if (timedOut) return { ...ran, ok, output, timedOut };
315
+ // A compared gate exits with 0 when it finds problems: any other code is its command that broke.
316
+ const broke = cannotStart || isCompared(gate) || gate.brokenExitCodes?.includes(exitCode);
317
+ if (!ok && broke) return { ...ran, ok, output, broken: true };
277
318
  if (!isCompared(gate) || !ok) return { ...ran, ok, output };
278
- return { ...ran, ...addedLines(gate, output, baseline, files) };
319
+ return { ...ran, ...addedLines(gate, output, baseline, files, elsewhere) };
279
320
  }
280
321
 
281
322
  /**
282
323
  * Judges the output of a compared gate that ran clean: it fails on the lines the turn added to the report of the turn
283
- * start. Without that report, nothing counts but the exit code.
324
+ * start. Without that report, nothing counts but the exit code. With a report of code HEAD has left since, elsewhere,
325
+ * only the lines that name a file the turn changed count: the others came with the code HEAD moved to.
284
326
  */
285
327
  export function addedLines(
286
328
  gate: Gate,
287
329
  output: string,
288
330
  baseline: string | undefined,
289
331
  changed: string[],
332
+ elsewhere = false,
290
333
  ): { ok: boolean; output: string } {
291
334
  if (baseline === undefined) return { ok: true, output: "" };
292
- const added = newLines(baseline, output, gate.ignoreLines, gate.lineKey, changed);
335
+ const added = newLines(baseline, output, gate.ignoreLines, gate.lineKey, changed).filter(
336
+ (line) => !elsewhere || changed.includes(fileOf(gate, line) ?? ""),
337
+ );
293
338
  return { ok: added.length === 0, output: added.join("\n") };
294
339
  }
@@ -99,7 +99,49 @@ 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();
105
120
  }
121
+
122
+ /** A move of HEAD, as its reflog tells it: the commit it left, the one it reached, and how. */
123
+ export interface HeadMove {
124
+ from: string | undefined;
125
+ to: string;
126
+ how: string;
127
+ }
128
+
129
+ /** The moves of HEAD its reflog holds, oldest first: none in a repo with no commit, or that keeps no reflog. */
130
+ export function headMoves(root: string): HeadMove[] {
131
+ try {
132
+ const entries = git(root, ["reflog", "show", "--format=%H %gs", "HEAD"]).split("\n").filter(Boolean).reverse();
133
+ const reached = entries.map((entry) => entry.slice(0, entry.indexOf(" ")));
134
+ return entries.map((entry, at) => ({
135
+ from: reached[at - 1],
136
+ to: reached[at] ?? "",
137
+ how: entry.slice(entry.indexOf(" ") + 1),
138
+ }));
139
+ } catch {
140
+ return [];
141
+ }
142
+ }
143
+
144
+ /** The files a commit changed. For a merge, the ones it leaves unlike each of its parents: its resolved conflicts. */
145
+ export function commitFiles(root: string, commit: string): string[] {
146
+ return paths(git(root, ["diff-tree", "--no-commit-id", "--name-only", "-r", "-c", "--root", "-z", commit]));
147
+ }
@@ -2,6 +2,7 @@ import { writeFileSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import type { GatesFiles } from "./config.ts";
5
+ import type { Head } from "./head.ts";
5
6
  import { isRecord, isStringArray, isStringRecord, readJsonFile } from "./json.ts";
6
7
 
7
8
  /** A red gate the agent chose to leave, with why, bound to the fingerprint of the report it saw. */
@@ -21,11 +22,11 @@ export interface SendBacks {
21
22
  }
22
23
 
23
24
  /**
24
- * What a turn started from: the commit, the reports of its compared gates, and the gates files themselves, since a
25
- * turn is checked with the gates it started with. A turn the owner interrupts never reaches its check: it stays
26
- * unchecked until the next turn of its repo. Once checked, what its stops told the agent.
25
+ * What a turn started from: the commit, where HEAD was, the reports of its compared gates, and the gates files
26
+ * themselves, since a turn is checked with the gates it started with. A turn the owner interrupts never reaches its
27
+ * check: it stays unchecked until the next turn of its repo. Once checked, what its stops told the agent.
27
28
  */
28
- export interface TurnState {
29
+ export interface TurnState extends Head {
29
30
  start: string;
30
31
  baselines: Record<string, string>;
31
32
  config: GatesFiles;
@@ -50,6 +51,8 @@ interface SessionState {
50
51
  current?: string;
51
52
  turns: Record<string, TurnState>;
52
53
  told?: Record<string, string[]>;
54
+ /** The repos a send-back of the session told the agent how to act in: the next ones there say it in one line. */
55
+ conductTold?: string[];
53
56
  }
54
57
 
55
58
  const EMPTY: SessionState = { turns: {} };
@@ -76,6 +79,8 @@ function isTurnState(value: unknown): value is TurnState {
76
79
  return (
77
80
  isRecord(value) &&
78
81
  typeof value.start === "string" &&
82
+ (value.head === undefined || typeof value.head === "string") &&
83
+ (value.moves === undefined || typeof value.moves === "number") &&
79
84
  isStringRecord(value.baselines) &&
80
85
  isGatesFiles(value.config) &&
81
86
  typeof value.checked === "boolean" &&
@@ -89,7 +94,8 @@ function isSessionState(value: unknown): value is SessionState {
89
94
  (value.current === undefined || typeof value.current === "string") &&
90
95
  isRecord(value.turns) &&
91
96
  Object.values(value.turns).every(isTurnState) &&
92
- (value.told === undefined || (isRecord(value.told) && Object.values(value.told).every(isStringArray)))
97
+ (value.told === undefined || (isRecord(value.told) && Object.values(value.told).every(isStringArray))) &&
98
+ (value.conductTold === undefined || isStringArray(value.conductTold))
93
99
  );
94
100
  }
95
101
 
@@ -112,15 +118,19 @@ export function readTurn(session: string, root: string): TurnState | undefined {
112
118
  * progress is read again, by its retry.
113
119
  */
114
120
  export function writeTurn(session: string, root: string, turn: TurnState): void {
115
- const { turns, told } = readSession(session);
121
+ const { turns, ...state } = readSession(session);
116
122
  const unchecked = Object.entries(turns).filter(([, kept]) => !kept.checked);
117
- writeSession(session, { told, current: root, turns: { ...Object.fromEntries(unchecked), [root]: turn } });
123
+ writeSession(session, { ...state, current: root, turns: { ...Object.fromEntries(unchecked), [root]: turn } });
118
124
  }
119
125
 
120
126
  /** Ends the turn in progress without a check, as a prompt from a folder with no gates, or a failed start, does. */
121
127
  export function forgetTurn(session: string): void {
122
- const { current, ...state } = readSession(session);
123
- if (current !== undefined) writeSession(session, state);
128
+ forget(session, "current");
129
+ }
130
+
131
+ function forget(session: string, key: "current" | "told" | "conductTold"): void {
132
+ const { [key]: had, ...state } = readSession(session);
133
+ if (had !== undefined) writeSession(session, state);
124
134
  }
125
135
 
126
136
  /**
@@ -135,10 +145,26 @@ export function tellOnce(session: string, root: string, missing: string[]): bool
135
145
  return missing.length > 0;
136
146
  }
137
147
 
148
+ /**
149
+ * 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
150
+ * its context, and saying it again at every send-back only costs it tokens. Each repo has its own words for it.
151
+ */
152
+ export function tellConductOnce(session: string, root: string): boolean {
153
+ const state = readSession(session);
154
+ const told = state.conductTold ?? [];
155
+ if (told.includes(root)) return false;
156
+ writeSession(session, { ...state, conductTold: [...told, root] });
157
+ return true;
158
+ }
159
+
160
+ /** Forgets that the agent was told how to act: a session that starts again, or compacts, may have lost it. */
161
+ export function forgetConduct(session: string): void {
162
+ forget(session, "conductTold");
163
+ }
164
+
138
165
  /** Forgets what the agent was told of missing tools, so a session that starts again, or resumes, is told again. */
139
166
  export function forgetTold(session: string): void {
140
- const { told, ...state } = readSession(session);
141
- if (told !== undefined) writeSession(session, state);
167
+ forget(session, "told");
142
168
  }
143
169
 
144
170
  /**
package/src/core/watch.ts CHANGED
@@ -61,13 +61,18 @@ export function keepWatch(root: string, gate: Gate): void {
61
61
  if (existsSync(folder)) touch(folder);
62
62
  }
63
63
 
64
+ // What the folders of the watches of a gate of a repo start with, whatever version of the engine started them.
65
+ function watchesOf(root: string, gate: Gate): string {
66
+ const key = createHash("sha256").update(`${root}\0${gate.name}`).digest("hex").slice(0, 16);
67
+ return `${PREFIX}${key}-`;
68
+ }
69
+
64
70
  /**
65
71
  * Where a watch keeps its process, its output and the sessions that use it, outside the repo: one per repo, gate and
66
72
  * engine version, since a helper of the engine may print its cycles otherwise from one version to the next.
67
73
  */
68
74
  function folderOf(root: string, gate: Gate): string {
69
- const key = createHash("sha256").update(`${root}\0${gate.name}\0${ENGINE_VERSION}`).digest("hex").slice(0, 16);
70
- return join(tmpdir(), `${PREFIX}${key}`);
75
+ return join(tmpdir(), `${watchesOf(root, gate)}${ENGINE_VERSION}`);
71
76
  }
72
77
 
73
78
  // A file per session that uses the watch: two hooks at once each write their own, and neither loses the other's.
@@ -75,9 +80,13 @@ function sessionFile(folder: string, session: string): string {
75
80
  return join(folder, "sessions", session.replace(/[^\w-]/g, ""));
76
81
  }
77
82
 
78
- function register(folder: string, session: string): void {
83
+ /** Records that the session uses the watch, and says whether it is the first time it does. */
84
+ function register(folder: string, session: string): boolean {
85
+ const file = sessionFile(folder, session);
86
+ if (existsSync(file)) return false;
79
87
  mkdirSync(join(folder, "sessions"), { recursive: true });
80
- writeFileSync(sessionFile(folder, session), "");
88
+ writeFileSync(file, "");
89
+ return true;
81
90
  }
82
91
 
83
92
  /** The process of the watch, as the engine recorded it when it started it, or nothing when it never did. */
@@ -130,7 +139,7 @@ export function startWatch(session: string, root: string, gate: WatchedGate): vo
130
139
  mkdirSync(folder, { recursive: true });
131
140
  touch(folder);
132
141
  // The sessions of a watch that starts again still use it.
133
- register(folder, session);
142
+ if (register(folder, session)) leaveOtherVersions(session, root, gate);
134
143
  if (stateOf(folder) === "running" || !lockStart(folder)) return;
135
144
  try {
136
145
  // Another hook may have started it between the look above and the lock.
@@ -140,6 +149,25 @@ export function startWatch(session: string, root: string, gate: WatchedGate): vo
140
149
  }
141
150
  }
142
151
 
152
+ /**
153
+ * The session leaves the watches other versions of the engine started for this gate of this repo, now that it uses
154
+ * the one of this version: after an update of the engine, the watch of the version before would otherwise run beside
155
+ * the new one, until the session ends or it stops for idleness. A session still on that version keeps its watch, and
156
+ * the watch of another repo, such as another worktree, is not one of them.
157
+ */
158
+ function leaveOtherVersions(session: string, root: string, gate: Gate): void {
159
+ const tmp = tmpdir();
160
+ const prefix = watchesOf(root, gate);
161
+ for (const entry of readDir(tmp))
162
+ if (entry.startsWith(prefix) && entry !== `${prefix}${ENGINE_VERSION}`) leave(join(tmp, entry), session);
163
+ }
164
+
165
+ /** The session no longer uses the watch, which stops once no session does: the watch and every process it started. */
166
+ function leave(folder: string, session: string): void {
167
+ rmSync(sessionFile(folder, session), { force: true });
168
+ if (!readDir(join(folder, "sessions")).length) stop(folder);
169
+ }
170
+
143
171
  /** The files of the repo the watch lists only as it starts, one per line. */
144
172
  function frozenFiles(root: string, watch: Watch): string {
145
173
  if (watch.frozen === undefined) return "";
@@ -362,7 +390,7 @@ function readDir(folder: string): string[] {
362
390
  * the gate: out of time, neither green nor red, never judged on an older cycle. The watch then owes a cycle for these
363
391
  * files, which the next stop it answers asks for with its own: a change it missed would otherwise stay unseen until
364
392
  * the file changes again. Only a stop pays that debt, never the report of a turn start, which would make old a
365
- * failure no turn was judged on. A watch that stopped fails, with the last lines it printed.
393
+ * failure no turn was judged on. A watch that stopped is a broken gate, with the last lines it printed.
366
394
  */
367
395
  export async function judgeWatch(
368
396
  session: string,
@@ -370,6 +398,7 @@ export async function judgeWatch(
370
398
  gate: WatchedGate,
371
399
  files: string[],
372
400
  baseline: string | undefined,
401
+ elsewhere = false,
373
402
  ): Promise<Outcome> {
374
403
  const folder = folderOf(root, gate);
375
404
  const owed = owedFiles(folder);
@@ -377,7 +406,7 @@ export async function judgeWatch(
377
406
  const settled = await settle(session, root, gate, asked, gate.timeoutSeconds * 1000);
378
407
  const { name } = gate;
379
408
  const { ms } = settled;
380
- if ("stopped" in settled) return { name, ok: false, ms, output: settled.stopped, report: undefined };
409
+ if ("stopped" in settled) return { name, ok: false, ms, output: settled.stopped, report: undefined, broken: true };
381
410
  if (!("cycle" in settled)) {
382
411
  owe(folder, files);
383
412
  const output = `The watch opened no cycle for the turn within ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
@@ -385,7 +414,7 @@ export async function judgeWatch(
385
414
  }
386
415
  // Paid, less what a stop out of time meanwhile added: only the lists this stop asked for.
387
416
  for (const list of owed.lists) rmSync(list, { force: true });
388
- const judged = judgeCycle(gate, settled.cycle, baseline, asked);
417
+ const judged = judgeCycle(gate, settled.cycle, baseline, asked, elsewhere);
389
418
  return { name, ms, ...judged, report: judged.ok ? settled.cycle : undefined };
390
419
  }
391
420
 
@@ -395,10 +424,11 @@ function judgeCycle(
395
424
  cycle: string,
396
425
  baseline: string | undefined,
397
426
  files: string[],
427
+ elsewhere: boolean,
398
428
  ): { ok: boolean; output: string } {
399
429
  const fails = new RegExp(gate.watch.failed ?? "(?!)");
400
430
  return isCompared(gate)
401
- ? addedLines(gate, cycle, baseline, files)
431
+ ? addedLines(gate, cycle, baseline, files, elsewhere)
402
432
  : { ok: !cycle.split("\n").some((line) => fails.test(line)), output: cycle };
403
433
  }
404
434
 
@@ -416,10 +446,7 @@ export function endSession(session: string): void {
416
446
  for (const entry of readdirSync(tmpdir())) {
417
447
  if (!entry.startsWith(PREFIX)) continue;
418
448
  const folder = join(tmpdir(), entry);
419
- const file = sessionFile(folder, session);
420
- if (!existsSync(file)) continue;
421
- rmSync(file, { force: true });
422
- if (!readdirSync(join(folder, "sessions")).length) stop(folder);
449
+ if (existsSync(sessionFile(folder, session))) leave(folder, session);
423
450
  }
424
451
  }
425
452