@tayomi/deterministic-gates 0.0.0-stage → 0.4.1
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.
- package/.claude-plugin/marketplace.json +15 -0
- package/.claude-plugin/plugin.json +14 -0
- package/.codex-plugin/plugin.json +20 -0
- package/LICENSE +21 -0
- package/README.md +111 -2
- package/catalog/go.json +92 -0
- package/catalog/index.html +398 -0
- package/catalog/python.json +46 -0
- package/catalog/typescript.json +125 -0
- package/dist/src/cli.js +65 -0
- package/dist/src/core/check.js +157 -0
- package/dist/src/core/config.js +180 -0
- package/dist/src/core/json.js +32 -0
- package/dist/src/core/report-cache.js +35 -0
- package/dist/src/core/report.js +127 -0
- package/dist/src/core/run.js +172 -0
- package/dist/src/core/send-back.js +53 -0
- package/dist/src/core/snapshot.js +94 -0
- package/dist/src/core/turn-state.js +93 -0
- package/dist/src/core/waive-line.js +15 -0
- package/dist/src/helpers/new-clones.js +57 -0
- package/dist/src/helpers/new-suppressions.js +31 -0
- package/dist/src/helpers/related-tests.js +109 -0
- package/dist/src/helpers/test-reporter.js +57 -0
- package/dist/src/hook/display.js +22 -0
- package/dist/src/hook/hook.js +119 -0
- package/hooks/claude.json +17 -0
- package/hooks/hooks.json +38 -0
- package/hooks/register.ts +12 -0
- package/package.json +51 -4
- package/src/catalog/catalog.ts +168 -0
- package/src/cli.ts +61 -0
- package/src/core/check.ts +209 -0
- package/src/core/config.ts +225 -0
- package/src/core/json.ts +36 -0
- package/src/core/report-cache.ts +51 -0
- package/src/core/report.ts +159 -0
- package/src/core/run.ts +217 -0
- package/src/core/send-back.ts +87 -0
- package/src/core/snapshot.ts +105 -0
- package/src/core/turn-state.ts +153 -0
- package/src/core/waive-line.ts +19 -0
- package/src/helpers/new-clones.ts +58 -0
- package/src/helpers/new-suppressions.ts +44 -0
- package/src/helpers/related-tests.ts +119 -0
- package/src/helpers/test-reporter.ts +71 -0
- package/src/hook/display.ts +21 -0
- package/src/hook/hook.ts +144 -0
- package/src/testing.ts +39 -0
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { changedGatesFiles, gatesOf, isCompared, readGatesFiles } from "./config.js";
|
|
4
|
+
import { cachedReports, cacheReports } from "./report-cache.js";
|
|
5
|
+
import { check, filesOf, givenFiles, missingTool, wholeProject } from "./run.js";
|
|
6
|
+
import { changedSince, emptyCommit, hasCommit, lastCommit, snapshot, workingTree } from "./snapshot.js";
|
|
7
|
+
import { readTurn, writeTurn } from "./turn-state.js";
|
|
8
|
+
function missingTools(root, gates) {
|
|
9
|
+
return gates.flatMap((gate) => {
|
|
10
|
+
const why = missingTool(root, gate);
|
|
11
|
+
return why === undefined ? [] : [{ gate, why }];
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
function runnable(gates, missing) {
|
|
15
|
+
return gates.filter((gate) => !missing.some((tool) => tool.gate === gate));
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Records the commit a turn starts from, and the reports its compared gates will compare with. After an interrupted
|
|
19
|
+
* turn, the next one of the repo starts where it did, so its check also covers what the interrupted one changed.
|
|
20
|
+
* Gives, gate by gate, the tools this machine misses to run the gates of the repo.
|
|
21
|
+
*/
|
|
22
|
+
export async function startTurn(session, root) {
|
|
23
|
+
const config = readGatesFiles(root);
|
|
24
|
+
const { gates } = gatesOf(config);
|
|
25
|
+
const missing = missingTools(root, gates);
|
|
26
|
+
const told = missing.map(({ gate, why }) => `${gate.name}: ${why}`);
|
|
27
|
+
const compared = runnable(gates, missing).filter(isCompared);
|
|
28
|
+
const interrupted = readTurn(session, root);
|
|
29
|
+
if (interrupted?.checked === false) {
|
|
30
|
+
writeTurn(session, root, interrupted);
|
|
31
|
+
return told;
|
|
32
|
+
}
|
|
33
|
+
const { commit: start, tree } = snapshot(root);
|
|
34
|
+
const cached = cachedReports(root, tree);
|
|
35
|
+
const baselines = await Promise.all(compared.map(async (gate) => {
|
|
36
|
+
const cachedReport = cached(gate);
|
|
37
|
+
return {
|
|
38
|
+
gate,
|
|
39
|
+
...(cachedReport === undefined ? await wholeProject(root, gate) : { ok: true, output: cachedReport }),
|
|
40
|
+
};
|
|
41
|
+
}));
|
|
42
|
+
// A report from a command that broke still serves this turn, since checking too much beats leaving a hole, but it
|
|
43
|
+
// is never kept for the next one.
|
|
44
|
+
cacheReports(root, tree, baselines.filter(({ ok }) => ok).map(({ gate, output }) => [gate, output]));
|
|
45
|
+
writeTurn(session, root, {
|
|
46
|
+
start,
|
|
47
|
+
baselines: Object.fromEntries(baselines.map(({ gate, output }) => [gate.name, output])),
|
|
48
|
+
config,
|
|
49
|
+
checked: false,
|
|
50
|
+
});
|
|
51
|
+
return told;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Runs, in parallel, each gate that looks at a changed file. A deleted file counts as changed, since a gate that
|
|
55
|
+
* reads the whole project may break on it, but is never named: a gate given {files} looks at the files left, and
|
|
56
|
+
* is skipped when none is.
|
|
57
|
+
*/
|
|
58
|
+
function runGates(root, gates, changed, turn, baselines) {
|
|
59
|
+
return Promise.all(gates.map(async (gate) => {
|
|
60
|
+
const matching = filesOf(gate, changed);
|
|
61
|
+
const files = givenFiles(gate) ? matching.filter((file) => existsSync(join(root, file))) : matching;
|
|
62
|
+
if (!files.length)
|
|
63
|
+
return { gate };
|
|
64
|
+
return { gate, outcome: await check(root, gate, files, turn, baselines(gate)) };
|
|
65
|
+
}));
|
|
66
|
+
}
|
|
67
|
+
function checkedTurn(changed, results, started, notes, showAllPasses) {
|
|
68
|
+
return {
|
|
69
|
+
changed,
|
|
70
|
+
outcomes: results.flatMap(({ outcome }) => (outcome ? [outcome] : [])),
|
|
71
|
+
skipped: results.filter(({ outcome }) => !outcome).map(({ gate }) => gate.name),
|
|
72
|
+
ms: performance.now() - started,
|
|
73
|
+
note: notes.join("\n") || undefined,
|
|
74
|
+
...(showAllPasses ? { showAllPasses } : {}),
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Runs each gate on every file of the repo, as if one turn had written it all: a compared gate counts every line
|
|
79
|
+
* of its report, and a gate given the turn gets the empty tree. The state of the repo, for the owner or an agent
|
|
80
|
+
* asked to clean it up, where the hook only ever judges a turn.
|
|
81
|
+
*/
|
|
82
|
+
export async function checkAll(root) {
|
|
83
|
+
const started = performance.now();
|
|
84
|
+
const empty = emptyCommit(root);
|
|
85
|
+
const files = changedSince(root, empty);
|
|
86
|
+
const { gates, refused, showAllPasses } = gatesOf(readGatesFiles(root));
|
|
87
|
+
const results = await runGates(root, gates, files, empty, () => "");
|
|
88
|
+
return checkedTurn(files, results, started, refusedNotes(refused), showAllPasses);
|
|
89
|
+
}
|
|
90
|
+
// A report holds for the tree a turn ends on only if the gate ran clean on the whole project. A gate that failed
|
|
91
|
+
// keeps the report it started from, so what the turn added stays new until it is fixed, and a gate that did not run
|
|
92
|
+
// keeps none: it may still read a changed file its pattern misses, as knip reads tsconfig.json.
|
|
93
|
+
function endReports(results, baselines) {
|
|
94
|
+
return results.flatMap(({ gate, outcome }) => {
|
|
95
|
+
if (!isCompared(gate) || !outcome)
|
|
96
|
+
return [];
|
|
97
|
+
const report = outcome.ok ? outcome.report : baselines(gate);
|
|
98
|
+
return report === undefined ? [] : [[gate, report]];
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Runs each gate that looks at a file the turn changed, with the gates as the turn started: an agent that weakens
|
|
103
|
+
* them mid-turn changes the next turn, never its own. Without a recorded start, the turn runs from the last commit
|
|
104
|
+
* with the gates of now; with a start git no longer has, from the last commit with the gates and the reports it
|
|
105
|
+
* started with: checking too much beats leaving a hole.
|
|
106
|
+
*/
|
|
107
|
+
export async function checkTurn(session, root) {
|
|
108
|
+
const recorded = readTurn(session, root);
|
|
109
|
+
const kept = recorded !== undefined && hasCommit(root, recorded.start) ? recorded : undefined;
|
|
110
|
+
const startNote = recorded === undefined
|
|
111
|
+
? "no turn start recorded: checked every change since the last commit"
|
|
112
|
+
: kept === undefined
|
|
113
|
+
? "turn start lost (history rewritten?): checked every change since the last commit"
|
|
114
|
+
: undefined;
|
|
115
|
+
const now = readGatesFiles(root);
|
|
116
|
+
const turn = {
|
|
117
|
+
start: kept?.start ?? lastCommit(root),
|
|
118
|
+
baselines: recorded?.baselines ?? {},
|
|
119
|
+
config: recorded?.config ?? now,
|
|
120
|
+
checked: false,
|
|
121
|
+
// What the earlier stops of the turn told the agent goes on, so its send-backs and waivers add up.
|
|
122
|
+
...(recorded?.sendBacks ? { sendBacks: recorded.sendBacks } : {}),
|
|
123
|
+
};
|
|
124
|
+
const baselines = (gate) => turn.baselines[gate.name];
|
|
125
|
+
const started = performance.now();
|
|
126
|
+
const end = workingTree(root);
|
|
127
|
+
const changed = changedSince(root, turn.start, end);
|
|
128
|
+
const { gates, refused, showAllPasses } = gatesOf(turn.config);
|
|
129
|
+
const missing = missingTools(root, gates);
|
|
130
|
+
const results = await runGates(root, runnable(gates, missing), changed, turn.start, baselines);
|
|
131
|
+
cacheReports(root, end, endReports(results, baselines));
|
|
132
|
+
writeTurn(session, root, { ...turn, checked: true });
|
|
133
|
+
// A compared gate with no report from the turn start can only count its exit code: a green it did not earn is said.
|
|
134
|
+
const uncompared = results
|
|
135
|
+
.filter(({ gate, outcome }) => outcome && isCompared(gate) && baselines(gate) === undefined)
|
|
136
|
+
.map(({ gate }) => `${gate.name} not compared: no report from the turn start, only its exit code counted`);
|
|
137
|
+
// Only a gate the turn concerned is named: one that would not have run anyway costs nothing to miss.
|
|
138
|
+
const notRun = missing
|
|
139
|
+
.filter(({ gate }) => filesOf(gate, changed).length)
|
|
140
|
+
.map(({ gate, why }) => `${gate.name} not run: ${why}`);
|
|
141
|
+
const notes = [
|
|
142
|
+
...(startNote ? [startNote] : []),
|
|
143
|
+
...configNote(changedGatesFiles(turn.config, now)),
|
|
144
|
+
...uncompared,
|
|
145
|
+
...refusedNotes(refused),
|
|
146
|
+
...notRun,
|
|
147
|
+
];
|
|
148
|
+
return checkedTurn(changed, results, started, notes, showAllPasses);
|
|
149
|
+
}
|
|
150
|
+
function refusedNotes(refused) {
|
|
151
|
+
return refused.map(({ name, why }) => `${name} not run, its entry is wrong: ${why}`);
|
|
152
|
+
}
|
|
153
|
+
function configNote(changedFiles) {
|
|
154
|
+
if (!changedFiles.length)
|
|
155
|
+
return [];
|
|
156
|
+
return [`the turn changed ${changedFiles.join(" and ")}: checked with the gates as the turn started`];
|
|
157
|
+
}
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { isRecord, isStringArray, messageOf } from "./json.js";
|
|
4
|
+
import { repoRoot } from "./snapshot.js";
|
|
5
|
+
const GATES_FILE = ".gates.json";
|
|
6
|
+
const LOCAL_GATES_FILE = ".gates.local.json";
|
|
7
|
+
// The time the gates of a check have, all together: they start at once, so each one stops at the latest when it ends.
|
|
8
|
+
const DEFAULT_MAX_TIMEOUT_SECONDS = 45;
|
|
9
|
+
// The times a turn sends the agent back: enough for a fix that breaks another gate, never a loop.
|
|
10
|
+
const DEFAULT_MAX_SEND_BACKS = 5;
|
|
11
|
+
const FIELDS = new Set(["name", "severity", "files", "run", "compare", "ignoreLines", "timeoutSeconds"]);
|
|
12
|
+
/** In the arguments of a gate: the changed files it looks at, and the commit of the turn start. */
|
|
13
|
+
export const FILES = "{files}";
|
|
14
|
+
export const TURN = "{turn}";
|
|
15
|
+
/** A gate that fails on the lines of output the turn added, with the report of the turn start to compare with. */
|
|
16
|
+
export function isCompared(gate) {
|
|
17
|
+
return gate.compare === "turn-start";
|
|
18
|
+
}
|
|
19
|
+
// The problem of one gate: the gate is left out, never the others.
|
|
20
|
+
function refuse(problem) {
|
|
21
|
+
throw new Error(problem);
|
|
22
|
+
}
|
|
23
|
+
function fileOf(text, file) {
|
|
24
|
+
if (text === undefined)
|
|
25
|
+
return { entries: [] };
|
|
26
|
+
let parsed;
|
|
27
|
+
try {
|
|
28
|
+
parsed = JSON.parse(text);
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
throw new Error(`${file} is not valid JSON: ${messageOf(error)}.`);
|
|
32
|
+
}
|
|
33
|
+
const { gates = [], maxTimeoutSeconds, showAllPasses, maxSendBacks, ...others } = isRecord(parsed) ? parsed : { others: true };
|
|
34
|
+
if (!Array.isArray(gates) || Object.keys(others).length)
|
|
35
|
+
throw new Error(`${file} holds "gates", a list of gates, "maxTimeoutSeconds", the most seconds a gate may take, ` +
|
|
36
|
+
`"showAllPasses", to name every green gate, and "maxSendBacks", the most times a turn sends the agent back.`);
|
|
37
|
+
const entries = gates.map((entry) => {
|
|
38
|
+
if (!isRecord(entry) || typeof entry.name !== "string")
|
|
39
|
+
throw new Error(`${file}: every gate has a name.`);
|
|
40
|
+
return { ...entry, name: entry.name };
|
|
41
|
+
});
|
|
42
|
+
return {
|
|
43
|
+
entries,
|
|
44
|
+
...(maxTimeoutSeconds === undefined ? {} : { maxTimeoutSeconds }),
|
|
45
|
+
...(showAllPasses === undefined ? {} : { showAllPasses }),
|
|
46
|
+
...(maxSendBacks === undefined ? {} : { maxSendBacks }),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
// The local file's own value wins, as for the fields of a gate.
|
|
50
|
+
function maxTimeoutOf(shared, local) {
|
|
51
|
+
const max = local.maxTimeoutSeconds ?? shared.maxTimeoutSeconds ?? DEFAULT_MAX_TIMEOUT_SECONDS;
|
|
52
|
+
if (typeof max !== "number" || max <= 0)
|
|
53
|
+
throw new Error("maxTimeoutSeconds is a positive number.");
|
|
54
|
+
return max;
|
|
55
|
+
}
|
|
56
|
+
// Off by default: the summary names the slowest passes and counts the rest.
|
|
57
|
+
function showAllPassesOf(shared, local) {
|
|
58
|
+
const show = local.showAllPasses ?? shared.showAllPasses ?? false;
|
|
59
|
+
if (typeof show !== "boolean")
|
|
60
|
+
throw new Error("showAllPasses is true or false.");
|
|
61
|
+
return show;
|
|
62
|
+
}
|
|
63
|
+
// 0 never sends the agent back: the owner only sees the summary.
|
|
64
|
+
function maxSendBacksOf(shared, local) {
|
|
65
|
+
const max = local.maxSendBacks ?? shared.maxSendBacks ?? DEFAULT_MAX_SEND_BACKS;
|
|
66
|
+
if (typeof max !== "number" || !Number.isInteger(max) || max < 0)
|
|
67
|
+
throw new Error("maxSendBacks is a whole number, 0 or more.");
|
|
68
|
+
return max;
|
|
69
|
+
}
|
|
70
|
+
function isPattern(value) {
|
|
71
|
+
if (typeof value !== "string")
|
|
72
|
+
return false;
|
|
73
|
+
try {
|
|
74
|
+
new RegExp(value);
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function toGate(entry, maxTimeoutSeconds) {
|
|
82
|
+
const { name, severity, files, run, compare, ignoreLines, timeoutSeconds = maxTimeoutSeconds } = entry;
|
|
83
|
+
const unknown = Object.keys(entry).find((key) => !FIELDS.has(key));
|
|
84
|
+
if (unknown !== undefined)
|
|
85
|
+
refuse(`unknown field ${unknown}`);
|
|
86
|
+
if (!/^[a-z][a-z0-9-]*$/.test(name))
|
|
87
|
+
refuse("a name is lowercase words joined by hyphens");
|
|
88
|
+
if (severity !== "error" && severity !== "off")
|
|
89
|
+
refuse('severity is "error" or "off": a warning sends nobody back to fix it');
|
|
90
|
+
if (!isPattern(files))
|
|
91
|
+
refuse("files is a regular expression on the repo-relative paths");
|
|
92
|
+
if (!isStringArray(run) || !run.length)
|
|
93
|
+
refuse("run is a non-empty list of strings");
|
|
94
|
+
if (compare !== undefined && compare !== "turn-start")
|
|
95
|
+
refuse('compare is "turn-start"');
|
|
96
|
+
if (compare !== undefined && run.includes(FILES))
|
|
97
|
+
refuse(`a compared gate reads the whole project: it takes no ${FILES}`);
|
|
98
|
+
if (ignoreLines !== undefined && !isPattern(ignoreLines))
|
|
99
|
+
refuse("ignoreLines is a regular expression");
|
|
100
|
+
if (typeof timeoutSeconds !== "number" || timeoutSeconds <= 0)
|
|
101
|
+
refuse("timeoutSeconds is a positive number");
|
|
102
|
+
return {
|
|
103
|
+
name,
|
|
104
|
+
severity,
|
|
105
|
+
files,
|
|
106
|
+
run,
|
|
107
|
+
// A gate may stop sooner than the others, never later.
|
|
108
|
+
timeoutSeconds: Math.min(timeoutSeconds, maxTimeoutSeconds),
|
|
109
|
+
...(compare === undefined ? {} : { compare }),
|
|
110
|
+
...(ignoreLines === undefined ? {} : { ignoreLines }),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Reads the shared gates and the developer's own. A local entry named like a shared one changes only the fields it
|
|
115
|
+
* gives, such as {"name": "lint", "severity": "off"}. Any other local entry adds a gate. A gate with a problem of its
|
|
116
|
+
* own is left out, and the others still run: only a file that cannot be read stops them all.
|
|
117
|
+
*/
|
|
118
|
+
export function readGates(shared, local) {
|
|
119
|
+
const sharedFile = fileOf(shared, GATES_FILE);
|
|
120
|
+
const localFile = fileOf(local, LOCAL_GATES_FILE);
|
|
121
|
+
const max = maxTimeoutOf(sharedFile, localFile);
|
|
122
|
+
const merged = new Map(sharedFile.entries.map((entry) => [entry.name, entry]));
|
|
123
|
+
for (const entry of localFile.entries)
|
|
124
|
+
merged.set(entry.name, { ...merged.get(entry.name), ...entry });
|
|
125
|
+
const read = {
|
|
126
|
+
gates: [],
|
|
127
|
+
refused: [],
|
|
128
|
+
showAllPasses: showAllPassesOf(sharedFile, localFile),
|
|
129
|
+
maxSendBacks: maxSendBacksOf(sharedFile, localFile),
|
|
130
|
+
};
|
|
131
|
+
for (const entry of merged.values()) {
|
|
132
|
+
if (entry.severity === "off")
|
|
133
|
+
continue;
|
|
134
|
+
try {
|
|
135
|
+
read.gates.push(toGate(entry, max));
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
read.refused.push({ name: entry.name, why: messageOf(error) });
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
return read;
|
|
142
|
+
}
|
|
143
|
+
/** The gates of the two files, refusing the first gate with a problem, as a catalog does. */
|
|
144
|
+
export function parseGates(shared, local) {
|
|
145
|
+
const { gates, refused } = readGates(shared, local);
|
|
146
|
+
const [first] = refused;
|
|
147
|
+
if (first !== undefined)
|
|
148
|
+
throw new Error(`Gate ${first.name}: ${first.why}.`);
|
|
149
|
+
return gates;
|
|
150
|
+
}
|
|
151
|
+
function readIfPresent(path) {
|
|
152
|
+
try {
|
|
153
|
+
return readFileSync(path, "utf8");
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
if (error.code === "ENOENT")
|
|
157
|
+
return undefined;
|
|
158
|
+
throw error;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
export function readGatesFiles(root) {
|
|
162
|
+
return { shared: readIfPresent(join(root, GATES_FILE)), local: readIfPresent(join(root, LOCAL_GATES_FILE)) };
|
|
163
|
+
}
|
|
164
|
+
export function gatesOf({ shared, local }) {
|
|
165
|
+
return readGates(shared, local);
|
|
166
|
+
}
|
|
167
|
+
/** The gates files a turn changed, by name: a turn is checked with the gates it started with, whatever it did to them. */
|
|
168
|
+
export function changedGatesFiles(before, after) {
|
|
169
|
+
return [
|
|
170
|
+
...(before.shared === after.shared ? [] : [GATES_FILE]),
|
|
171
|
+
...(before.local === after.local ? [] : [LOCAL_GATES_FILE]),
|
|
172
|
+
];
|
|
173
|
+
}
|
|
174
|
+
/** The repo to check from a working directory, or nothing outside git or in a repo with no gates file. */
|
|
175
|
+
export function configuredRoot(cwd) {
|
|
176
|
+
const root = repoRoot(cwd);
|
|
177
|
+
if (root === undefined)
|
|
178
|
+
return undefined;
|
|
179
|
+
return [GATES_FILE, LOCAL_GATES_FILE].some((file) => existsSync(join(root, file))) ? root : undefined;
|
|
180
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
export function isRecord(value) {
|
|
3
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
4
|
+
}
|
|
5
|
+
export function isStringRecord(value) {
|
|
6
|
+
return isRecord(value) && Object.values(value).every((entry) => typeof entry === "string");
|
|
7
|
+
}
|
|
8
|
+
export function isStringArray(value) {
|
|
9
|
+
return Array.isArray(value) && value.every((entry) => typeof entry === "string");
|
|
10
|
+
}
|
|
11
|
+
/** The message of whatever was thrown. */
|
|
12
|
+
export function messageOf(error) {
|
|
13
|
+
return error instanceof Error ? error.message : String(error);
|
|
14
|
+
}
|
|
15
|
+
/** What the text holds as JSON, or nothing when it is not JSON. */
|
|
16
|
+
export function parseJson(text) {
|
|
17
|
+
try {
|
|
18
|
+
return JSON.parse(text);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/** What the file holds as JSON, or nothing when it cannot be read or is not JSON. */
|
|
25
|
+
export function readJsonFile(path) {
|
|
26
|
+
try {
|
|
27
|
+
return parseJson(readFileSync(path, "utf8"));
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { isRecord, isStringRecord, readJsonFile } from "./json.js";
|
|
6
|
+
function isCache(value) {
|
|
7
|
+
return isRecord(value) && typeof value.tree === "string" && isStringRecord(value.reports);
|
|
8
|
+
}
|
|
9
|
+
function cacheFile(root) {
|
|
10
|
+
const repo = createHash("sha256").update(root).digest("hex").slice(0, 16);
|
|
11
|
+
return join(tmpdir(), `gates-reports-${repo}.json`);
|
|
12
|
+
}
|
|
13
|
+
function commandOf(gate) {
|
|
14
|
+
return JSON.stringify(gate.run);
|
|
15
|
+
}
|
|
16
|
+
function readCache(root) {
|
|
17
|
+
const cache = readJsonFile(cacheFile(root));
|
|
18
|
+
return isCache(cache) ? cache : undefined;
|
|
19
|
+
}
|
|
20
|
+
export function cachedReports(root, tree) {
|
|
21
|
+
const cache = readCache(root);
|
|
22
|
+
return (gate) => (cache?.tree === tree ? cache.reports[commandOf(gate)] : undefined);
|
|
23
|
+
}
|
|
24
|
+
/** Keeps reports for a tree, with the ones already kept for that tree, and in place of the ones of another tree. */
|
|
25
|
+
export function cacheReports(root, tree, reports) {
|
|
26
|
+
const kept = readCache(root);
|
|
27
|
+
const cache = {
|
|
28
|
+
tree,
|
|
29
|
+
reports: {
|
|
30
|
+
...(kept?.tree === tree ? kept.reports : {}),
|
|
31
|
+
...Object.fromEntries(reports.map(([gate, report]) => [commandOf(gate), report])),
|
|
32
|
+
},
|
|
33
|
+
};
|
|
34
|
+
writeFileSync(cacheFile(root), JSON.stringify(cache));
|
|
35
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { failed } from "./run.js";
|
|
2
|
+
import { WAIVE_TAG } from "./waive-line.js";
|
|
3
|
+
const LABEL = "● gates";
|
|
4
|
+
const SHOWN_PASSES = 6;
|
|
5
|
+
const REPORT_CHARS = 4000;
|
|
6
|
+
const HEAD_CHARS = 1000;
|
|
7
|
+
const TONES = { pass: "1;32", fail: "1;31", late: "1;33", warn: "1;38;5;208", dim: "2" };
|
|
8
|
+
// The warning sign as text, never as the emoji some terminals draw without the variation selector.
|
|
9
|
+
const WARNING = "\u26A0\uFE0E";
|
|
10
|
+
function paint(tone, text) {
|
|
11
|
+
return `\x1b[${TONES[tone]}m${text}\x1b[0m`;
|
|
12
|
+
}
|
|
13
|
+
/** Keeps the start and the end of a long report: tools put the problem at one or the other. */
|
|
14
|
+
export function excerpt(report) {
|
|
15
|
+
if (report.length <= REPORT_CHARS)
|
|
16
|
+
return report;
|
|
17
|
+
const cut = report.length - REPORT_CHARS;
|
|
18
|
+
return `${report.slice(0, HEAD_CHARS)}\n[... ${cut} characters cut ...]\n${report.slice(-(REPORT_CHARS - HEAD_CHARS))}`;
|
|
19
|
+
}
|
|
20
|
+
export function duration(ms) {
|
|
21
|
+
return ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`;
|
|
22
|
+
}
|
|
23
|
+
function gateLine(mark, outcome) {
|
|
24
|
+
return `${mark} ${outcome.name} ${paint("dim", duration(outcome.ms))}`;
|
|
25
|
+
}
|
|
26
|
+
function skippedLine(skipped) {
|
|
27
|
+
return paint("dim", `${skipped.map((name) => `- ${name}`).join(" ")} · no matching file changed`);
|
|
28
|
+
}
|
|
29
|
+
function nothingChecked({ changed, skipped }, after) {
|
|
30
|
+
if (!changed.length)
|
|
31
|
+
return [`${paint("pass", LABEL)}${after}`, `${paint("pass", "✓")} no file changed`];
|
|
32
|
+
const files = changed.length === 1 ? "1 changed file" : `${changed.length} changed files`;
|
|
33
|
+
return [
|
|
34
|
+
`${paint("pass", LABEL)} no gate looks at the ${files}${after}`,
|
|
35
|
+
...(skipped.length ? [skippedLine(skipped)] : []),
|
|
36
|
+
];
|
|
37
|
+
}
|
|
38
|
+
// The gate in orange, then the reason the agent gave, under a star.
|
|
39
|
+
function waivedLines(outcome, reason) {
|
|
40
|
+
return [
|
|
41
|
+
`${paint("warn", `${WARNING} ${outcome.name}`)} ${paint("dim", duration(outcome.ms))}`,
|
|
42
|
+
` ${paint("warn", "*")} ${reason}`,
|
|
43
|
+
];
|
|
44
|
+
}
|
|
45
|
+
// Every pass, as many to a line as the summary shows by default; or the slowest of them, with a count of the rest.
|
|
46
|
+
function passLines(passed, showAll) {
|
|
47
|
+
const marked = passed.map((outcome) => gateLine(paint("pass", "✓"), outcome));
|
|
48
|
+
if (showAll)
|
|
49
|
+
return Array.from({ length: Math.ceil(marked.length / SHOWN_PASSES) }, (_, line) => marked.slice(line * SHOWN_PASSES, (line + 1) * SHOWN_PASSES).join(" "));
|
|
50
|
+
const rest = marked.length - SHOWN_PASSES;
|
|
51
|
+
return marked.length
|
|
52
|
+
? [[...marked.slice(0, SHOWN_PASSES), ...(rest > 0 ? [paint("dim", `... +${rest}`)] : [])].join(" ")]
|
|
53
|
+
: [];
|
|
54
|
+
}
|
|
55
|
+
function resultLines({ outcomes, skipped, ms, showAllPasses = false }, after, waived) {
|
|
56
|
+
const slowest = (a, b) => b.ms - a.ms;
|
|
57
|
+
const reasons = new Map(waived.map(({ name, reason }) => [name, reason]));
|
|
58
|
+
const failing = outcomes.filter(failed).sort(slowest);
|
|
59
|
+
const red = failing.filter(({ name }) => !reasons.has(name));
|
|
60
|
+
const left = failing.filter(({ name }) => reasons.has(name));
|
|
61
|
+
const late = outcomes.filter((outcome) => outcome.timedOut).sort(slowest);
|
|
62
|
+
const passed = outcomes.filter((outcome) => outcome.ok).sort(slowest);
|
|
63
|
+
const leftOut = left.length ? ` · ${left.length} waived` : "";
|
|
64
|
+
const outOfTime = late.length ? ` · ${late.length} out of time` : "";
|
|
65
|
+
const notRun = skipped.length ? ` · ${skipped.length} skipped` : "";
|
|
66
|
+
const tone = red.length ? "fail" : left.length ? "warn" : late.length ? "late" : "pass";
|
|
67
|
+
const totals = `${passed.length}/${outcomes.length} gates green in ${duration(ms)}`;
|
|
68
|
+
return [
|
|
69
|
+
`${paint(tone, LABEL)} ${totals}${leftOut}${outOfTime}${notRun}${after}`,
|
|
70
|
+
...red.map((outcome) => gateLine(paint("fail", "✗"), outcome)),
|
|
71
|
+
...left.flatMap((outcome) => waivedLines(outcome, reasons.get(outcome.name) ?? "")),
|
|
72
|
+
...late.map((outcome) => gateLine(paint("late", "⏱"), outcome)),
|
|
73
|
+
...passLines(passed, showAllPasses),
|
|
74
|
+
...(skipped.length ? [skippedLine(skipped)] : []),
|
|
75
|
+
];
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* What the owner sees after every check, even when no gate ran, so a silent check never looks dead: one line of
|
|
79
|
+
* totals, with how the stop ends, each failure, each gate the agent waived with its reason, the passes slowest
|
|
80
|
+
* first, then the gates the turn did not concern.
|
|
81
|
+
*/
|
|
82
|
+
export function summary(turn, ending = "", waived = []) {
|
|
83
|
+
const after = ending ? ` · ${ending}` : "";
|
|
84
|
+
const lines = turn.outcomes.length ? resultLines(turn, after, waived) : nothingChecked(turn, after);
|
|
85
|
+
return [...lines, ...(turn.note ? [paint("dim", turn.note)] : [])].join("\n");
|
|
86
|
+
}
|
|
87
|
+
/** What the owner sees when the gates cannot run at all, such as with a gates file that does not parse. */
|
|
88
|
+
export function broken(reason) {
|
|
89
|
+
return `${paint("fail", LABEL)} could not run: ${reason}`;
|
|
90
|
+
}
|
|
91
|
+
// The cheapest green is to silence the rule, and nothing in the engine judges a report. So the agent is told the one
|
|
92
|
+
// way out that is not a cheat: waive the gate, with a reason the owner reads and judges.
|
|
93
|
+
const CONDUCT = [
|
|
94
|
+
"Fix the code, never the check: a silenced rule (noqa, eslint-disable, nolint), a weakened gate or an edited",
|
|
95
|
+
".gates.json does not pass this turn. If you can fix a problem, fix it. Leave a gate red only when it cannot be",
|
|
96
|
+
"fixed (the report is wrong, or fixing it would loop until the last send-back), when fixing it goes against what",
|
|
97
|
+
"the owner asked, or when the owner has to settle a question first. Then waive it in your final message, after a",
|
|
98
|
+
"blank line, one line per gate, its reason in one line:",
|
|
99
|
+
].join(" ");
|
|
100
|
+
const WAIVE_SYNTAX = `[${WAIVE_TAG}:<gate>]: waive "<reason>"`;
|
|
101
|
+
/** What the owner sees when the gates of the repo miss tools on this machine, as the agent is asked to install them. */
|
|
102
|
+
export function toolsMissing(missing) {
|
|
103
|
+
const gates = missing.length === 1 ? "1 gate is off" : `${missing.length} gates are off`;
|
|
104
|
+
const lines = missing.map((tool) => paint("dim", `- ${tool}`));
|
|
105
|
+
return [`${paint("fail", LABEL)} ${gates}, a tool is missing: the agent is asked to install it`, ...lines].join("\n");
|
|
106
|
+
}
|
|
107
|
+
/** What the agent is told when the gates of the repo miss tools: install them, or the gates that need them stay off. */
|
|
108
|
+
export function toolsToInstall(missing) {
|
|
109
|
+
return [
|
|
110
|
+
"Some gates of this repo cannot run on this machine, for a missing tool:",
|
|
111
|
+
...missing.map((tool) => `- ${tool}`),
|
|
112
|
+
"Install these tools first. If they cannot be installed, or the developer refuses, say so and go on with the",
|
|
113
|
+
"prompt: the gates that need them stay off until they are installed, and every other gate still runs.",
|
|
114
|
+
].join("\n");
|
|
115
|
+
}
|
|
116
|
+
/** The report of each failed gate, under its name. */
|
|
117
|
+
export function reports(outcomes) {
|
|
118
|
+
return outcomes.filter(failed).map(({ name, output }) => `## ${name}\n${excerpt(output)}`);
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* What the agent gets when it is sent back: how to act on a failure, what the stop has to tell it, the note of the
|
|
122
|
+
* check, each failed report.
|
|
123
|
+
*/
|
|
124
|
+
export function failures({ outcomes, note }, told = []) {
|
|
125
|
+
const head = ["Gates fail on what this turn changed. Fix every problem before you hand back.", CONDUCT, WAIVE_SYNTAX];
|
|
126
|
+
return [...head, ...told, ...(note ? [note] : []), ...reports(outcomes)].join("\n\n");
|
|
127
|
+
}
|