@tayomi/deterministic-gates 0.8.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -34,7 +34,8 @@ function isSessionState(value) {
34
34
  (value.current === undefined || typeof value.current === "string") &&
35
35
  isRecord(value.turns) &&
36
36
  Object.values(value.turns).every(isTurnState) &&
37
- (value.told === undefined || (isRecord(value.told) && Object.values(value.told).every(isStringArray))));
37
+ (value.told === undefined || (isRecord(value.told) && Object.values(value.told).every(isStringArray))) &&
38
+ (value.conductTold === undefined || isStringArray(value.conductTold)));
38
39
  }
39
40
  function readSession(session) {
40
41
  const state = readJsonFile(stateFile(session));
@@ -52,14 +53,17 @@ export function readTurn(session, root) {
52
53
  * progress is read again, by its retry.
53
54
  */
54
55
  export function writeTurn(session, root, turn) {
55
- const { turns, told } = readSession(session);
56
+ const { turns, ...state } = readSession(session);
56
57
  const unchecked = Object.entries(turns).filter(([, kept]) => !kept.checked);
57
- writeSession(session, { told, current: root, turns: { ...Object.fromEntries(unchecked), [root]: turn } });
58
+ writeSession(session, { ...state, current: root, turns: { ...Object.fromEntries(unchecked), [root]: turn } });
58
59
  }
59
60
  /** Ends the turn in progress without a check, as a prompt from a folder with no gates, or a failed start, does. */
60
61
  export function forgetTurn(session) {
61
- const { current, ...state } = readSession(session);
62
- if (current !== undefined)
62
+ forget(session, "current");
63
+ }
64
+ function forget(session, key) {
65
+ const { [key]: had, ...state } = readSession(session);
66
+ if (had !== undefined)
63
67
  writeSession(session, state);
64
68
  }
65
69
  /**
@@ -74,11 +78,25 @@ export function tellOnce(session, root, missing) {
74
78
  writeSession(session, { ...state, told: { ...state.told, [root]: missing } });
75
79
  return missing.length > 0;
76
80
  }
81
+ /**
82
+ * 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
83
+ * its context, and saying it again at every send-back only costs it tokens. Each repo has its own words for it.
84
+ */
85
+ export function tellConductOnce(session, root) {
86
+ const state = readSession(session);
87
+ const told = state.conductTold ?? [];
88
+ if (told.includes(root))
89
+ return false;
90
+ writeSession(session, { ...state, conductTold: [...told, root] });
91
+ return true;
92
+ }
93
+ /** Forgets that the agent was told how to act: a session that starts again, or compacts, may have lost it. */
94
+ export function forgetConduct(session) {
95
+ forget(session, "conductTold");
96
+ }
77
97
  /** Forgets what the agent was told of missing tools, so a session that starts again, or resumes, is told again. */
78
98
  export function forgetTold(session) {
79
- const { told, ...state } = readSession(session);
80
- if (told !== undefined)
81
- writeSession(session, state);
99
+ forget(session, "told");
82
100
  }
83
101
  /**
84
102
  * The repo of the turn a check is about, whatever folder the agent stops in. A check that follows its own turn start
@@ -43,21 +43,30 @@ export function keepWatch(root, gate) {
43
43
  if (existsSync(folder))
44
44
  touch(folder);
45
45
  }
46
+ // What the folders of the watches of a gate of a repo start with, whatever version of the engine started them.
47
+ function watchesOf(root, gate) {
48
+ const key = createHash("sha256").update(`${root}\0${gate.name}`).digest("hex").slice(0, 16);
49
+ return `${PREFIX}${key}-`;
50
+ }
46
51
  /**
47
52
  * Where a watch keeps its process, its output and the sessions that use it, outside the repo: one per repo, gate and
48
53
  * engine version, since a helper of the engine may print its cycles otherwise from one version to the next.
49
54
  */
50
55
  function folderOf(root, gate) {
51
- const key = createHash("sha256").update(`${root}\0${gate.name}\0${ENGINE_VERSION}`).digest("hex").slice(0, 16);
52
- return join(tmpdir(), `${PREFIX}${key}`);
56
+ return join(tmpdir(), `${watchesOf(root, gate)}${ENGINE_VERSION}`);
53
57
  }
54
58
  // A file per session that uses the watch: two hooks at once each write their own, and neither loses the other's.
55
59
  function sessionFile(folder, session) {
56
60
  return join(folder, "sessions", session.replace(/[^\w-]/g, ""));
57
61
  }
62
+ /** Records that the session uses the watch, and says whether it is the first time it does. */
58
63
  function register(folder, session) {
64
+ const file = sessionFile(folder, session);
65
+ if (existsSync(file))
66
+ return false;
59
67
  mkdirSync(join(folder, "sessions"), { recursive: true });
60
- writeFileSync(sessionFile(folder, session), "");
68
+ writeFileSync(file, "");
69
+ return true;
61
70
  }
62
71
  /** The process of the watch, as the engine recorded it when it started it, or nothing when it never did. */
63
72
  function processOf(folder) {
@@ -111,7 +120,8 @@ export function startWatch(session, root, gate) {
111
120
  mkdirSync(folder, { recursive: true });
112
121
  touch(folder);
113
122
  // The sessions of a watch that starts again still use it.
114
- register(folder, session);
123
+ if (register(folder, session))
124
+ leaveOtherVersions(session, root, gate);
115
125
  if (stateOf(folder) === "running" || !lockStart(folder))
116
126
  return;
117
127
  try {
@@ -123,6 +133,25 @@ export function startWatch(session, root, gate) {
123
133
  unlockStart(folder);
124
134
  }
125
135
  }
136
+ /**
137
+ * The session leaves the watches other versions of the engine started for this gate of this repo, now that it uses
138
+ * the one of this version: after an update of the engine, the watch of the version before would otherwise run beside
139
+ * the new one, until the session ends or it stops for idleness. A session still on that version keeps its watch, and
140
+ * the watch of another repo, such as another worktree, is not one of them.
141
+ */
142
+ function leaveOtherVersions(session, root, gate) {
143
+ const tmp = tmpdir();
144
+ const prefix = watchesOf(root, gate);
145
+ for (const entry of readDir(tmp))
146
+ if (entry.startsWith(prefix) && entry !== `${prefix}${ENGINE_VERSION}`)
147
+ leave(join(tmp, entry), session);
148
+ }
149
+ /** The session no longer uses the watch, which stops once no session does: the watch and every process it started. */
150
+ function leave(folder, session) {
151
+ rmSync(sessionFile(folder, session), { force: true });
152
+ if (!readDir(join(folder, "sessions")).length)
153
+ stop(folder);
154
+ }
126
155
  /** The files of the repo the watch lists only as it starts, one per line. */
127
156
  function frozenFiles(root, watch) {
128
157
  if (watch.frozen === undefined)
@@ -332,7 +361,7 @@ function readDir(folder) {
332
361
  * the gate: out of time, neither green nor red, never judged on an older cycle. The watch then owes a cycle for these
333
362
  * files, which the next stop it answers asks for with its own: a change it missed would otherwise stay unseen until
334
363
  * the file changes again. Only a stop pays that debt, never the report of a turn start, which would make old a
335
- * failure no turn was judged on. A watch that stopped fails, with the last lines it printed.
364
+ * failure no turn was judged on. A watch that stopped is a broken gate, with the last lines it printed.
336
365
  */
337
366
  export async function judgeWatch(session, root, gate, files, baseline) {
338
367
  const folder = folderOf(root, gate);
@@ -342,7 +371,7 @@ export async function judgeWatch(session, root, gate, files, baseline) {
342
371
  const { name } = gate;
343
372
  const { ms } = settled;
344
373
  if ("stopped" in settled)
345
- return { name, ok: false, ms, output: settled.stopped, report: undefined };
374
+ return { name, ok: false, ms, output: settled.stopped, report: undefined, broken: true };
346
375
  if (!("cycle" in settled)) {
347
376
  owe(folder, files);
348
377
  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.`;
@@ -375,12 +404,8 @@ export function endSession(session) {
375
404
  if (!entry.startsWith(PREFIX))
376
405
  continue;
377
406
  const folder = join(tmpdir(), entry);
378
- const file = sessionFile(folder, session);
379
- if (!existsSync(file))
380
- continue;
381
- rmSync(file, { force: true });
382
- if (!readdirSync(join(folder, "sessions")).length)
383
- stop(folder);
407
+ if (existsSync(sessionFile(folder, session)))
408
+ leave(folder, session);
384
409
  }
385
410
  }
386
411
  function stop(folder) {
@@ -87,6 +87,16 @@ export async function compilerOf(root, args) {
87
87
  const sources = new Map();
88
88
  const resources = new Map();
89
89
  let last;
90
+ // No file the check before this one read has another date: it would say the same.
91
+ const unchanged = () => {
92
+ for (const [file, { at }] of sources)
93
+ if (changedAt(file) !== at)
94
+ return false;
95
+ for (const [file, at] of resources)
96
+ if (changedAt(file) !== at)
97
+ return false;
98
+ return true;
99
+ };
90
100
  return {
91
101
  compiler: {
92
102
  async diagnostics() {
@@ -98,10 +108,19 @@ export async function compilerOf(root, args) {
98
108
  sources.clear();
99
109
  resources.clear();
100
110
  }
111
+ // The check before this one stands when nothing it read has changed, which saves checking every file again.
112
+ // Never the first check of a compiler: TypeScript reports some errors once per type, in the first file it
113
+ // checks, and that order is another in a program that reuses one, so a first check served again would be
114
+ // compared with the checks after it, and an error would look new for having moved.
115
+ const roots = JSON.stringify(config.rootNames);
116
+ if (last?.reused && last.roots === roots && unchanged())
117
+ return [...config.errors, ...last.checked];
101
118
  const base = ng.createCompilerHost({ options });
119
+ const asked = new Set();
102
120
  const host = {
103
121
  ...base,
104
122
  getSourceFile(file, ...rest) {
123
+ asked.add(file);
105
124
  const at = changedAt(file);
106
125
  const kept = sources.get(file);
107
126
  if (kept?.at === at)
@@ -131,15 +150,21 @@ export async function compilerOf(root, args) {
131
150
  return modified;
132
151
  },
133
152
  };
153
+ const reused = last !== undefined;
134
154
  const program = new ng.NgtscProgram(config.rootNames, options, host, last?.program);
135
155
  await program.loadNgStructureAsync();
136
- last = { program, options: JSON.stringify(options) };
137
- return [
138
- ...config.errors,
156
+ const checked = [
139
157
  ...program.getTsSyntacticDiagnostics(),
140
158
  ...program.getTsSemanticDiagnostics(),
141
159
  ...program.getNgSemanticDiagnostics(),
142
160
  ];
161
+ // A file the program no longer reads is forgotten once it changes: kept with its old date, it would make
162
+ // every check to come a whole one.
163
+ for (const [file, { at }] of sources)
164
+ if (!asked.has(file) && changedAt(file) !== at)
165
+ sources.delete(file);
166
+ last = { program, options: JSON.stringify(options), roots, reused, checked };
167
+ return [...config.errors, ...checked];
143
168
  },
144
169
  },
145
170
  };
@@ -0,0 +1,73 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { isRecord, messageOf, parseJson } from "../core/json.js";
4
+ import { headed } from "../core/run.js";
5
+ import { fileAt } from "../core/snapshot.js";
6
+ function countsOf(file) {
7
+ const refuse = () => {
8
+ throw new Error("Not an ESLint suppressions file.");
9
+ };
10
+ if (!isRecord(file))
11
+ return refuse();
12
+ return new Map(Object.entries(file).map(([source, rules]) => {
13
+ if (!isRecord(rules))
14
+ return refuse();
15
+ const counted = Object.entries(rules).map(([rule, entry]) => {
16
+ if (!isRecord(entry) || typeof entry.count !== "number")
17
+ return refuse();
18
+ return [rule, entry.count];
19
+ });
20
+ return [source, new Map(counted)];
21
+ }));
22
+ }
23
+ function totals(counts) {
24
+ const total = new Map();
25
+ for (const rules of counts.values())
26
+ for (const [rule, count] of rules)
27
+ total.set(rule, (total.get(rule) ?? 0) + count);
28
+ return total;
29
+ }
30
+ /**
31
+ * The counts that rose, one line per file and rule. A file the turn moved takes its counts to another path: there, a
32
+ * count that rose is new only when the suppressions file holds more of its rule than as the turn started.
33
+ */
34
+ export function newBulkSuppressions(before, after, moved = () => false) {
35
+ const was = countsOf(before ?? {});
36
+ const now = countsOf(after);
37
+ const [wasTotal, nowTotal] = [totals(was), totals(now)];
38
+ return [...now].flatMap(([source, rules]) => [...rules].flatMap(([rule, count]) => {
39
+ const old = was.get(source)?.get(rule) ?? 0;
40
+ if (count <= old)
41
+ return [];
42
+ // Asked last: it costs a look at the turn start.
43
+ const cameWithIt = (nowTotal.get(rule) ?? 0) <= (wasTotal.get(rule) ?? 0) && moved(source);
44
+ return cameWithIt ? [] : [`${source}: ${rule} ${old} -> ${count}`];
45
+ }));
46
+ }
47
+ function main(root, turn, files) {
48
+ const found = files.flatMap((file) => {
49
+ const before = fileAt(root, turn, file);
50
+ // ESLint names a source from the folder it runs in, which holds its suppressions file unless the repo moved it:
51
+ // a source not found there is never taken for a moved one.
52
+ const moved = (source) => {
53
+ const path = join(dirname(file), source);
54
+ return existsSync(join(root, path)) && fileAt(root, turn, path) === undefined;
55
+ };
56
+ const rose = newBulkSuppressions(before === undefined ? undefined : parseJson(before), parseJson(readFileSync(file, "utf8")), moved);
57
+ return rose.map((line) => `${file}: ${line}`);
58
+ });
59
+ if (!found.length)
60
+ return;
61
+ console.log(headed("New bulk suppressions: fix the violations, never the file that hides them.", found));
62
+ process.exitCode = 1;
63
+ }
64
+ if (import.meta.main) {
65
+ try {
66
+ main(process.cwd(), process.argv[2] ?? "HEAD", process.argv.slice(3));
67
+ }
68
+ catch (error) {
69
+ // What is wrong with the file, without the stack of this script around it.
70
+ console.log(messageOf(error));
71
+ process.exitCode = 1;
72
+ }
73
+ }
@@ -3,7 +3,7 @@ import { mkdtempSync, rmSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { isRecord, readJsonFile } from "../core/json.js";
6
- import { packageScript } from "../core/run.js";
6
+ import { headed, packageScript } from "../core/run.js";
7
7
  // jscpd compared with the tree the turn started from. Its own console report lists every clone of the repo, the old
8
8
  // ones included, so this prints only the clones the turn added, one per line.
9
9
  function refuse() {
@@ -46,7 +46,7 @@ function main(root, turn) {
46
46
  const clones = newClones(readJsonFile(join(output, "jscpd-report.json")));
47
47
  if (!clones.length)
48
48
  return;
49
- console.log(`New clones: factor each one out.\n${clones.join("\n")}`);
49
+ console.log(headed("New clones: reuse the code already there, or factor it out.", clones));
50
50
  process.exitCode = 1;
51
51
  }
52
52
  finally {
@@ -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.1",
3
+ "version": "0.9.0",
4
4
  "description": "Deterministic backpressure for coding agents: gates that run on what each turn changed and send the agent back until they pass.",
5
5
  "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,29 @@
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";
4
13
  import { cachedReports, cacheReports } from "./report-cache.ts";
5
14
  import { check, filesOf, givenFiles, missingTool, type Outcome, wholeProject } from "./run.ts";
6
15
  import { changedSince, emptyCommit, hasCommit, lastCommit, snapshot, workingTree } from "./snapshot.ts";
7
16
  import { readTurn, type TurnState, writeTurn } from "./turn-state.ts";
8
17
  import { judgeWatch, keepWatch, startWatch, TURN_START_MS, watchReport } from "./watch.ts";
9
18
 
19
+ /** What the repo says of what the agent is sent: the prompts of the whole check, and its gates, for their own. */
20
+ interface Wording {
21
+ prompts?: Prompts;
22
+ gates?: Pick<Gate, "name" | "omitLines" | "maxReportChars" | "prompt">[];
23
+ /** The most characters the reports of a send-back hold, all together. */
24
+ maxTotalReportChars?: number;
25
+ }
26
+
10
27
  export interface CheckedTurn {
11
28
  changed: string[];
12
29
  outcomes: Outcome[];
@@ -14,6 +31,8 @@ export interface CheckedTurn {
14
31
  ms: number;
15
32
  note?: string;
16
33
  showAllPasses?: boolean;
34
+ /** As the gates the check ran with word it. */
35
+ wording?: Wording;
17
36
  }
18
37
 
19
38
  /** A gate of the turn, with its outcome when it ran. */
@@ -131,7 +150,7 @@ function checkedTurn(
131
150
  results: Result[],
132
151
  started: number,
133
152
  notes: string[],
134
- showAllPasses: boolean,
153
+ { gates, prompts, maxTotalReportChars, showAllPasses }: Gates,
135
154
  ): CheckedTurn {
136
155
  return {
137
156
  changed,
@@ -140,6 +159,7 @@ function checkedTurn(
140
159
  ms: performance.now() - started,
141
160
  note: notes.join("\n") || undefined,
142
161
  ...(showAllPasses ? { showAllPasses } : {}),
162
+ wording: { gates, prompts, maxTotalReportChars },
143
163
  };
144
164
  }
145
165
 
@@ -152,9 +172,9 @@ export async function checkAll(root: string): Promise<CheckedTurn> {
152
172
  const started = performance.now();
153
173
  const empty = emptyCommit(root);
154
174
  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);
175
+ const config = gatesOf(readGatesFiles(root));
176
+ const results = await runGates(root, config.gates, files, empty, () => "");
177
+ return checkedTurn(files, results, started, refusedNotes(config.refused), config);
158
178
  }
159
179
 
160
180
  // A report holds for the tree a turn ends on only if the gate ran clean on the whole project. A gate that failed
@@ -162,7 +182,8 @@ export async function checkAll(root: string): Promise<CheckedTurn> {
162
182
  // keeps none: it may still read a changed file its pattern misses, as knip reads tsconfig.json.
163
183
  function endReports(results: Result[], baselines: Baselines) {
164
184
  return results.flatMap(({ gate, outcome }) => {
165
- if (!isCompared(gate) || !outcome) return [];
185
+ // A gate that could not run says nothing of the tree: the report it started from was a crash, or may be stale.
186
+ if (!isCompared(gate) || !outcome || outcome.broken) return [];
166
187
  const report = outcome.ok ? outcome.report : baselines(gate);
167
188
  return report === undefined ? [] : [[gate, report] as const];
168
189
  });
@@ -196,7 +217,8 @@ export async function checkTurn(session: string, root: string): Promise<CheckedT
196
217
  const started = performance.now();
197
218
  const end = workingTree(root);
198
219
  const changed = changedSince(root, turn.start, end);
199
- const { gates, refused, showAllPasses } = gatesOf(turn.config);
220
+ const config = gatesOf(turn.config);
221
+ const { gates, refused } = config;
200
222
  const missing = missingTools(root, gates);
201
223
  for (const gate of gates) if (keepsWatch(gate)) keepWatch(root, gate);
202
224
  const results = await runGates(root, runnable(gates, missing), changed, turn.start, baselines, session);
@@ -222,7 +244,7 @@ export async function checkTurn(session: string, root: string): Promise<CheckedT
222
244
  ...refusedNotes(refused),
223
245
  ...notRun,
224
246
  ];
225
- return checkedTurn(changed, results, started, notes, showAllPasses);
247
+ return checkedTurn(changed, results, started, notes, config);
226
248
  }
227
249
 
228
250
  function refusedNotes(refused: Gates["refused"]): string[] {