@tayomi/deterministic-gates 0.4.2 → 0.5.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 +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +1 -1
- package/catalog/angular.json +85 -0
- package/catalog/index.html +119 -4
- package/catalog/typescript.json +29 -2
- package/dist/src/cli.js +3 -3
- package/dist/src/core/check.js +35 -12
- package/dist/src/core/config.js +28 -2
- package/dist/src/core/report-cache.js +7 -2
- package/dist/src/core/run.js +29 -11
- package/dist/src/core/watch.js +283 -0
- package/dist/src/helpers/angular-watch.js +47 -0
- package/dist/src/helpers/tsc.js +57 -0
- package/dist/src/helpers/type-errors.js +144 -0
- package/dist/src/helpers/vitest-state-reporter.js +26 -0
- package/dist/src/hook/hook.js +25 -1
- package/hooks/hooks.json +11 -0
- package/package.json +1 -1
- package/src/cli.ts +3 -3
- package/src/core/check.ts +36 -12
- package/src/core/config.ts +43 -2
- package/src/core/report-cache.ts +12 -3
- package/src/core/run.ts +32 -11
- package/src/core/watch.ts +313 -0
- package/src/helpers/angular-watch.ts +50 -0
- package/src/helpers/tsc.ts +60 -0
- package/src/helpers/type-errors.ts +142 -0
- package/src/helpers/vitest-state-reporter.ts +48 -0
- package/src/hook/hook.ts +27 -2
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync, } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { createInterface } from "node:readline";
|
|
7
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
8
|
+
import { isCompared } from "./config.js";
|
|
9
|
+
import { addedLines, cleaned, commandOf, ENGINE_VERSION, TOOL_ENV } from "./run.js";
|
|
10
|
+
// Once a cycle closes, the lines a watch prints after it, such as the errors of a failed build, come within this long.
|
|
11
|
+
const QUIET_MS = 1000;
|
|
12
|
+
// A change no cycle started after in this long is one the watch does not look at, such as a spec its build leaves out:
|
|
13
|
+
// it cannot change the last cycle, which then judges the turn.
|
|
14
|
+
const UNSEEN_MS = 5000;
|
|
15
|
+
const POLL_MS = 100;
|
|
16
|
+
// What a watch that stopped leaves the agent: enough to see the error, not the whole history of the session.
|
|
17
|
+
const LAST_LINES = 20;
|
|
18
|
+
// A prompt waits this long at most for a compared watch to settle, under the 60 s its hook has.
|
|
19
|
+
const TURN_START_MS = 45_000;
|
|
20
|
+
const PREFIX = "gates-watch-";
|
|
21
|
+
// A start that holds its lock longer than this died on the way: the next hook takes the lock over.
|
|
22
|
+
const STALE_START_MS = 10_000;
|
|
23
|
+
// A watch stops by itself after this long without a prompt nor a stop on its repo, as for a session left open. The
|
|
24
|
+
// tests of the engine shorten it.
|
|
25
|
+
const IDLE_MS = 30 * 60 * 1000;
|
|
26
|
+
function idleMs() {
|
|
27
|
+
return Number(process.env.GATES_WATCH_IDLE_MS) || IDLE_MS;
|
|
28
|
+
}
|
|
29
|
+
/** Records a prompt or a stop on the repo of a watch, which keeps it from stopping for idleness. */
|
|
30
|
+
function touch(folder) {
|
|
31
|
+
writeFileSync(join(folder, "activity"), "");
|
|
32
|
+
}
|
|
33
|
+
/** Records a stop on the repo of the watch of a gate, if it has one, whether the stop judges it or not. */
|
|
34
|
+
export function keepWatch(root, gate) {
|
|
35
|
+
const folder = folderOf(root, gate);
|
|
36
|
+
if (existsSync(folder))
|
|
37
|
+
touch(folder);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Where a watch keeps its process, its output and the sessions that use it, outside the repo: one per repo, gate and
|
|
41
|
+
* engine version, since a helper of the engine may print its cycles otherwise from one version to the next.
|
|
42
|
+
*/
|
|
43
|
+
function folderOf(root, gate) {
|
|
44
|
+
const key = createHash("sha256").update(`${root}\0${gate.name}\0${ENGINE_VERSION}`).digest("hex").slice(0, 16);
|
|
45
|
+
return join(tmpdir(), `${PREFIX}${key}`);
|
|
46
|
+
}
|
|
47
|
+
// A file per session that uses the watch: two hooks at once each write their own, and neither loses the other's.
|
|
48
|
+
function sessionFile(folder, session) {
|
|
49
|
+
return join(folder, "sessions", session.replace(/[^\w-]/g, ""));
|
|
50
|
+
}
|
|
51
|
+
function register(folder, session) {
|
|
52
|
+
mkdirSync(join(folder, "sessions"), { recursive: true });
|
|
53
|
+
writeFileSync(sessionFile(folder, session), "");
|
|
54
|
+
}
|
|
55
|
+
/** Whether the watch runs, has stopped on its own, was stopped for idleness, or was never started. */
|
|
56
|
+
function stateOf(folder) {
|
|
57
|
+
let pid;
|
|
58
|
+
try {
|
|
59
|
+
pid = Number(readFileSync(join(folder, "pid"), "utf8"));
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return "absent";
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
if (!pid)
|
|
66
|
+
return "stopped";
|
|
67
|
+
process.kill(pid, 0);
|
|
68
|
+
return "running";
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return existsSync(join(folder, "idle")) ? "idle" : "stopped";
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Starts the watch of a gate in the background, unless it already runs, and records that the session uses it: it
|
|
76
|
+
* outlives the hook that starts it, until no session uses it.
|
|
77
|
+
*/
|
|
78
|
+
export function startWatch(session, root, gate) {
|
|
79
|
+
const folder = folderOf(root, gate);
|
|
80
|
+
mkdirSync(folder, { recursive: true });
|
|
81
|
+
touch(folder);
|
|
82
|
+
// The sessions of a watch that starts again still use it.
|
|
83
|
+
register(folder, session);
|
|
84
|
+
if (stateOf(folder) === "running")
|
|
85
|
+
return;
|
|
86
|
+
// Two hooks at once, such as two sessions starting, start one watch: the other only registers its session.
|
|
87
|
+
const lock = join(folder, "starting");
|
|
88
|
+
if (Date.now() - changedAt(lock) >= STALE_START_MS)
|
|
89
|
+
rmSync(lock, { force: true });
|
|
90
|
+
try {
|
|
91
|
+
closeSync(openSync(lock, "wx"));
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
try {
|
|
97
|
+
// Another hook may have started it between the look above and the lock.
|
|
98
|
+
if (stateOf(folder) !== "running")
|
|
99
|
+
launch(folder, root, gate.watch);
|
|
100
|
+
}
|
|
101
|
+
finally {
|
|
102
|
+
rmSync(lock, { force: true });
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
function launch(folder, root, watch) {
|
|
106
|
+
rmSync(join(folder, "idle"), { force: true });
|
|
107
|
+
const [name = "", ...args] = watch.run;
|
|
108
|
+
const command = commandOf(root, name);
|
|
109
|
+
const supervisor = commandOf(root, "{engine}/src/core/watch.ts");
|
|
110
|
+
const watched = [
|
|
111
|
+
join(folder, "activity"),
|
|
112
|
+
String(idleMs()),
|
|
113
|
+
watch.cycleStart,
|
|
114
|
+
command.file,
|
|
115
|
+
...command.args,
|
|
116
|
+
...args,
|
|
117
|
+
];
|
|
118
|
+
const log = openSync(join(folder, "output.log"), "w");
|
|
119
|
+
const child = spawn(supervisor.file, [...supervisor.args, ...watched], {
|
|
120
|
+
cwd: root,
|
|
121
|
+
detached: true,
|
|
122
|
+
stdio: ["ignore", log, log],
|
|
123
|
+
env: TOOL_ENV,
|
|
124
|
+
});
|
|
125
|
+
closeSync(log);
|
|
126
|
+
child.on("error", () => { });
|
|
127
|
+
child.unref();
|
|
128
|
+
writeFileSync(join(folder, "pid"), String(child.pid ?? ""));
|
|
129
|
+
}
|
|
130
|
+
/** The last cycle of a watch: its lines since it opened, and whether it is still open. */
|
|
131
|
+
function lastCycle(printed, watch) {
|
|
132
|
+
const lines = printed.split("\n");
|
|
133
|
+
if (lines.at(-1) === "")
|
|
134
|
+
lines.pop();
|
|
135
|
+
const opens = new RegExp(watch.cycleStart);
|
|
136
|
+
const closes = new RegExp(watch.cycleEnd);
|
|
137
|
+
// The start of the watch opens the first cycle, and lines after the one that closes it still belong to it.
|
|
138
|
+
const cycle = lines.slice(lines.findLastIndex((line) => opens.test(line)) + 1);
|
|
139
|
+
return { open: !cycle.some((line) => closes.test(line)), lines: cycle };
|
|
140
|
+
}
|
|
141
|
+
function changedAt(path) {
|
|
142
|
+
try {
|
|
143
|
+
return statSync(path).mtimeMs;
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
return 0;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
function readLog(log) {
|
|
150
|
+
try {
|
|
151
|
+
return readFileSync(log, "utf8");
|
|
152
|
+
}
|
|
153
|
+
catch {
|
|
154
|
+
return "";
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Waits for the watch of a gate to settle: no cycle open, and for a quiet while neither new output nor a new change to
|
|
159
|
+
* one of the files. A watch no hook started, as when the hooks were installed mid-session, starts now, and so does one
|
|
160
|
+
* stopped for idleness, as during a turn longer than the idle delay: it is not to blame.
|
|
161
|
+
*/
|
|
162
|
+
async function settle(session, root, gate, files, limitMs) {
|
|
163
|
+
const started = performance.now();
|
|
164
|
+
const folder = folderOf(root, gate);
|
|
165
|
+
const log = join(folder, "output.log");
|
|
166
|
+
if (["absent", "idle"].includes(stateOf(folder)))
|
|
167
|
+
startWatch(session, root, gate);
|
|
168
|
+
touch(folder);
|
|
169
|
+
for (;;) {
|
|
170
|
+
// Read once the watch is known stopped, so its last lines are in.
|
|
171
|
+
const stopped = stateOf(folder) === "stopped";
|
|
172
|
+
const printed = readLog(log);
|
|
173
|
+
const ms = performance.now() - started;
|
|
174
|
+
if (stopped) {
|
|
175
|
+
const last = cleaned(root, printed
|
|
176
|
+
.split("\n")
|
|
177
|
+
.slice(-LAST_LINES - 1)
|
|
178
|
+
.join("\n"));
|
|
179
|
+
return {
|
|
180
|
+
ms,
|
|
181
|
+
stopped: last ? `The watch stopped. Its last lines:\n${last}` : "The watch stopped, with no output.",
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
// A cycle that started after the last change read it, however long the watch took to see it.
|
|
185
|
+
const changed = Math.max(0, ...files.map((file) => changedAt(join(root, file))));
|
|
186
|
+
const seen = changedAt(join(folder, "cycle")) >= changed || Date.now() - changed >= UNSEEN_MS;
|
|
187
|
+
const cycle = lastCycle(printed, gate.watch);
|
|
188
|
+
if (seen && !cycle.open && Date.now() - changedAt(log) >= QUIET_MS)
|
|
189
|
+
return { ms, cycle: cleaned(root, cycle.lines.join("\n")) };
|
|
190
|
+
if (ms >= limitMs)
|
|
191
|
+
return { ms, timedOut: true };
|
|
192
|
+
await sleep(POLL_MS);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Judges a turn on the last cycle of the watch of a gate, once the watch has settled with the files of the turn the
|
|
197
|
+
* gate looks at: on its failed lines, or for a compared gate, on the lines it added to the report of the turn start.
|
|
198
|
+
* Not settled in the time of the gate: out of time, neither green nor red. A watch that stopped fails, with the last
|
|
199
|
+
* lines it printed.
|
|
200
|
+
*/
|
|
201
|
+
export async function judgeWatch(session, root, gate, files, baseline) {
|
|
202
|
+
const settled = await settle(session, root, gate, files, gate.timeoutSeconds * 1000);
|
|
203
|
+
const { name } = gate;
|
|
204
|
+
const { ms } = settled;
|
|
205
|
+
if ("stopped" in settled)
|
|
206
|
+
return { name, ok: false, ms, output: settled.stopped, report: undefined };
|
|
207
|
+
if ("timedOut" in settled) {
|
|
208
|
+
const output = `The watch did not settle within ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
|
|
209
|
+
return { name, ok: false, ms, output, report: undefined, timedOut: true };
|
|
210
|
+
}
|
|
211
|
+
const { cycle } = settled;
|
|
212
|
+
const fails = new RegExp(gate.watch.failed ?? "(?!)");
|
|
213
|
+
const judged = isCompared(gate)
|
|
214
|
+
? addedLines(gate, cycle, baseline)
|
|
215
|
+
: { ok: !cycle.split("\n").some((line) => fails.test(line)), output: cycle };
|
|
216
|
+
return { name, ms, ...judged, report: judged.ok ? cycle : undefined };
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* The report a compared watch gives the turn start: its last cycle, once it settles in the time a prompt can wait.
|
|
220
|
+
* Nothing when it does not, and the turn then counts nothing as new.
|
|
221
|
+
*/
|
|
222
|
+
export async function watchReport(session, root, gate) {
|
|
223
|
+
const settled = await settle(session, root, gate, [], Math.min(gate.timeoutSeconds * 1000, TURN_START_MS));
|
|
224
|
+
return "cycle" in settled ? settled.cycle : undefined;
|
|
225
|
+
}
|
|
226
|
+
/** Stops each watch the session was the last to use, in any repo: the watch and every process it started. */
|
|
227
|
+
export function endSession(session) {
|
|
228
|
+
for (const entry of readdirSync(tmpdir())) {
|
|
229
|
+
if (!entry.startsWith(PREFIX))
|
|
230
|
+
continue;
|
|
231
|
+
const folder = join(tmpdir(), entry);
|
|
232
|
+
const file = sessionFile(folder, session);
|
|
233
|
+
if (!existsSync(file))
|
|
234
|
+
continue;
|
|
235
|
+
rmSync(file, { force: true });
|
|
236
|
+
if (!readdirSync(join(folder, "sessions")).length)
|
|
237
|
+
stop(folder);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
function stop(folder) {
|
|
241
|
+
if (stateOf(folder) !== "running")
|
|
242
|
+
return;
|
|
243
|
+
try {
|
|
244
|
+
process.kill(-Number(readFileSync(join(folder, "pid"), "utf8")), "SIGTERM");
|
|
245
|
+
}
|
|
246
|
+
catch { }
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* The supervisor of a watch, which this module runs as when the engine starts one: it runs the watch, its output
|
|
250
|
+
* going where its own goes, and stops it with every process it started once its repo has had no prompt nor stop for
|
|
251
|
+
* the idle delay. Started detached, it leads a process group of its own, so stopping the group stops the watch and
|
|
252
|
+
* the tools under it.
|
|
253
|
+
*/
|
|
254
|
+
function supervise(activity, idle, cycleStart, file, args) {
|
|
255
|
+
// The time the last cycle started, which the stop compares with the changes of the turn. The start opens the first.
|
|
256
|
+
const cycle = join(dirname(activity), "cycle");
|
|
257
|
+
const opens = new RegExp(cycleStart);
|
|
258
|
+
writeFileSync(cycle, "");
|
|
259
|
+
const watch = spawn(file, args, { stdio: ["ignore", "pipe", "pipe"] });
|
|
260
|
+
const forward = (line) => {
|
|
261
|
+
// Printed before the time is kept, so a stop that sees the time also finds the cycle in the output.
|
|
262
|
+
console.log(line);
|
|
263
|
+
if (opens.test(line))
|
|
264
|
+
writeFileSync(cycle, "");
|
|
265
|
+
};
|
|
266
|
+
createInterface({ input: watch.stdout }).on("line", forward);
|
|
267
|
+
createInterface({ input: watch.stderr }).on("line", forward);
|
|
268
|
+
watch.on("error", (error) => {
|
|
269
|
+
console.log(error.message);
|
|
270
|
+
process.exit(1);
|
|
271
|
+
});
|
|
272
|
+
watch.on("close", (code) => process.exit(code ?? 1));
|
|
273
|
+
setInterval(() => {
|
|
274
|
+
if (Date.now() - changedAt(activity) < idle)
|
|
275
|
+
return;
|
|
276
|
+
writeFileSync(join(dirname(activity), "idle"), "");
|
|
277
|
+
process.kill(-process.pid, "SIGTERM");
|
|
278
|
+
}, Math.min(idle / 4, 10_000));
|
|
279
|
+
}
|
|
280
|
+
if (import.meta.main) {
|
|
281
|
+
const [activity = "", idle = "", cycleStart = "", file = "", ...args] = process.argv.slice(2);
|
|
282
|
+
supervise(activity, Number(idle), cycleStart, file, args);
|
|
283
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { extname, join } from "node:path";
|
|
3
|
+
import { createInterface } from "node:readline";
|
|
4
|
+
import { commandOf } from "../core/run.js";
|
|
5
|
+
import { COUNTS, HEADER } from "./vitest-state-reporter.js";
|
|
6
|
+
// The watch of an Angular project tested with Vitest: ng test in watch mode, with the reporter of the engine that
|
|
7
|
+
// prints the state of every spec at each run, and NG_TEST_LOG, which makes Angular say when a run ends. A change that
|
|
8
|
+
// leaves the build as it was reruns no spec, so no state prints: the last one is printed again, so that the cycle
|
|
9
|
+
// still tells which specs are red.
|
|
10
|
+
const NO_RERUN = /No test specifications to rerun/;
|
|
11
|
+
/**
|
|
12
|
+
* What to print for each line of the watch: the line, and before a run that reruns no spec, the last state of the
|
|
13
|
+
* specs, so that the cycle still tells which specs are red.
|
|
14
|
+
*/
|
|
15
|
+
export function replaying() {
|
|
16
|
+
let state = [];
|
|
17
|
+
let reading;
|
|
18
|
+
return (line) => {
|
|
19
|
+
if (line === HEADER)
|
|
20
|
+
reading = [];
|
|
21
|
+
reading?.push(line);
|
|
22
|
+
if (reading !== undefined && line.startsWith(COUNTS)) {
|
|
23
|
+
state = reading;
|
|
24
|
+
reading = undefined;
|
|
25
|
+
}
|
|
26
|
+
return NO_RERUN.test(line) ? [...state, line] : [line];
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
function main(root, args) {
|
|
30
|
+
const ng = commandOf(root, "@angular/cli");
|
|
31
|
+
if (ng.missing) {
|
|
32
|
+
console.log(ng.missing);
|
|
33
|
+
process.exit(1);
|
|
34
|
+
}
|
|
35
|
+
const reporter = join(import.meta.dirname, `vitest-state-reporter${extname(import.meta.filename)}`);
|
|
36
|
+
const watch = spawn(ng.file, [...ng.args, "test", "--watch", `--reporters=${reporter}`, ...args], {
|
|
37
|
+
env: { ...process.env, NG_TEST_LOG: "1" },
|
|
38
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
39
|
+
});
|
|
40
|
+
const replay = replaying();
|
|
41
|
+
const forward = (line) => console.log(replay(line).join("\n"));
|
|
42
|
+
createInterface({ input: watch.stdout }).on("line", forward);
|
|
43
|
+
createInterface({ input: watch.stderr }).on("line", forward);
|
|
44
|
+
watch.on("exit", (code) => process.exit(code ?? 1));
|
|
45
|
+
}
|
|
46
|
+
if (import.meta.main)
|
|
47
|
+
main(process.cwd(), process.argv.slice(2));
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { statSync } from "node:fs";
|
|
3
|
+
import { createRequire } from "node:module";
|
|
4
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
5
|
+
import { commandOf } from "../core/run.js";
|
|
6
|
+
// tsc, with the options it is given. A tsconfig that only references others, as the tsconfig.json of an Angular
|
|
7
|
+
// project, checks no file, and tsc says nothing of it: the gate would be green without checking anything, so it is
|
|
8
|
+
// refused, with the tsconfigs it references.
|
|
9
|
+
/** The tsconfig tsc reads: the one of -p or --project, a folder meaning its tsconfig.json, or the one of the root. */
|
|
10
|
+
function configOf(root, args) {
|
|
11
|
+
const at = args.findIndex((arg) => arg === "-p" || arg === "--project");
|
|
12
|
+
const given = at === -1 ? undefined : args[at + 1];
|
|
13
|
+
if (given === undefined)
|
|
14
|
+
return join(root, "tsconfig.json");
|
|
15
|
+
const path = resolve(root, given);
|
|
16
|
+
return statSync(path, { throwIfNoEntry: false })?.isDirectory() ? join(path, "tsconfig.json") : path;
|
|
17
|
+
}
|
|
18
|
+
function listed(names) {
|
|
19
|
+
return names.length > 1 ? `${names.slice(0, -1).join(", ")} and ${names.at(-1)}` : (names[0] ?? "");
|
|
20
|
+
}
|
|
21
|
+
/** Why tsc, with these options, would check no file, or nothing when it checks some, or will say itself what is wrong. */
|
|
22
|
+
export function nothingChecked(root, args) {
|
|
23
|
+
let ts;
|
|
24
|
+
try {
|
|
25
|
+
ts = createRequire(join(root, "package.json"))("typescript");
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
const file = configOf(root, args);
|
|
31
|
+
const read = ts.readConfigFile(file, (path) => ts.sys.readFile(path));
|
|
32
|
+
if (read.error !== undefined)
|
|
33
|
+
return undefined;
|
|
34
|
+
const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, dirname(file), undefined, file);
|
|
35
|
+
const references = parsed.projectReferences ?? [];
|
|
36
|
+
if (parsed.fileNames.length || !references.length)
|
|
37
|
+
return undefined;
|
|
38
|
+
const names = references.map((reference) => relative(root, ts.resolveProjectReferencePath(reference)));
|
|
39
|
+
return `${relative(root, file)} checks no file: it only references ${listed(names)}. Add -p and the one to check to the gate's run.`;
|
|
40
|
+
}
|
|
41
|
+
/** The tsc of the repo, once it is known to check files with these options: otherwise, it says why not and exits. */
|
|
42
|
+
export function checkingTsc(root, args) {
|
|
43
|
+
const tsc = commandOf(root, "typescript");
|
|
44
|
+
const refused = tsc.missing || nothingChecked(root, args);
|
|
45
|
+
if (refused) {
|
|
46
|
+
console.log(refused);
|
|
47
|
+
process.exit(1);
|
|
48
|
+
}
|
|
49
|
+
return tsc;
|
|
50
|
+
}
|
|
51
|
+
function main(root, args) {
|
|
52
|
+
const tsc = checkingTsc(root, args);
|
|
53
|
+
const child = spawn(tsc.file, [...tsc.args, ...args], { stdio: "inherit" });
|
|
54
|
+
child.on("close", (code) => process.exit(code ?? 1));
|
|
55
|
+
}
|
|
56
|
+
if (import.meta.main)
|
|
57
|
+
main(process.cwd(), process.argv.slice(2));
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createInterface } from "node:readline";
|
|
3
|
+
import { checkingTsc } from "./tsc.js";
|
|
4
|
+
// tsc, with the options it is given, such as strict ones a project turned off, printing its errors so that a gate can
|
|
5
|
+
// compare them with the ones of the turn start: one line per error, with its file and none of its line and column, so
|
|
6
|
+
// an error a change moves down is not new, and a count after an error its file already has, so one more of it is.
|
|
7
|
+
// tsc orders the members of a union as it happened to create them, which differs between the first compilation of a
|
|
8
|
+
// watch and the next ones: each union prints sorted, untruncated, and without the lines under the error, which name its
|
|
9
|
+
// first failing member, so the same error always prints the same.
|
|
10
|
+
// With --watch, tsc keeps watching, and each compilation prints between a line that starts it and one that ends it.
|
|
11
|
+
const STARTS = /Starting (compilation in watch mode|incremental compilation)/;
|
|
12
|
+
const ENDS = /Found \d+ errors?\. Watching for file changes/;
|
|
13
|
+
const POSITION = /^(.+)\(\d+,\d+\): (error TS\d+: .*)$/;
|
|
14
|
+
const OPENS = { "(": ")", "[": "]", "{": "}", "<": ">" };
|
|
15
|
+
// A property, parameter or index signature before its type, in an object, a tuple or a parameter list.
|
|
16
|
+
const LABEL = /^((?:\.\.\.)?(?:[\w$]+|"[^"]*"|\[[^\]]*\])\??: )(.*)$/s;
|
|
17
|
+
/** Where the bracket or the string that starts at index ends, or the index itself for any other character. */
|
|
18
|
+
function skipped(text, index) {
|
|
19
|
+
const char = text[index] ?? "";
|
|
20
|
+
if (char === '"' || char === "`") {
|
|
21
|
+
let end = index + 1;
|
|
22
|
+
while (end < text.length && text[end] !== char)
|
|
23
|
+
end += text[end] === "\\" ? 2 : 1;
|
|
24
|
+
return end;
|
|
25
|
+
}
|
|
26
|
+
const close = OPENS[char];
|
|
27
|
+
if (close === undefined)
|
|
28
|
+
return index;
|
|
29
|
+
let end = index + 1;
|
|
30
|
+
// The arrow of a function type closes no bracket.
|
|
31
|
+
while (end < text.length && text[end] !== close)
|
|
32
|
+
end = text.startsWith("=>", end) ? end + 2 : skipped(text, end) + 1;
|
|
33
|
+
return end;
|
|
34
|
+
}
|
|
35
|
+
/** The parts of a text between a separator that no bracket nor string encloses. */
|
|
36
|
+
function split(text, separator) {
|
|
37
|
+
const parts = [];
|
|
38
|
+
let start = 0;
|
|
39
|
+
for (let index = 0; index < text.length; index = skipped(text, index) + 1) {
|
|
40
|
+
if (text.startsWith("=>", index))
|
|
41
|
+
index++;
|
|
42
|
+
else if (text.startsWith(separator, index)) {
|
|
43
|
+
parts.push(text.slice(start, index));
|
|
44
|
+
start = index + separator.length;
|
|
45
|
+
index += separator.length - 1;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return [...parts, text.slice(start)];
|
|
49
|
+
}
|
|
50
|
+
/** A type as tsc prints it, with the members of each union and intersection sorted, at every depth. */
|
|
51
|
+
function sortedType(type) {
|
|
52
|
+
// A function type outside any bracket returns all the rest: a union of function types puts each in parentheses.
|
|
53
|
+
const [parameters = "", ...returned] = split(type, " => ");
|
|
54
|
+
if (returned.length)
|
|
55
|
+
return `${sortedInside(parameters)} => ${sortedType(returned.join(" => "))}`;
|
|
56
|
+
const sorted = (members) => (members.length > 1 ? members.sort() : members);
|
|
57
|
+
const union = split(type, " | ").map((member) => sorted(split(member, " & ").map(sortedInside)).join(" & "));
|
|
58
|
+
return sorted(union).join(" | ");
|
|
59
|
+
}
|
|
60
|
+
/** A type with the content of each of its brackets sorted. */
|
|
61
|
+
function sortedInside(type) {
|
|
62
|
+
let out = "";
|
|
63
|
+
for (let index = 0; index < type.length;) {
|
|
64
|
+
const end = skipped(type, index);
|
|
65
|
+
const char = type[index] ?? "";
|
|
66
|
+
if (OPENS[char] !== undefined) {
|
|
67
|
+
const separator = char === "{" ? ";" : ",";
|
|
68
|
+
const inner = split(type.slice(index + 1, end), separator).map((element) => {
|
|
69
|
+
const [, before = "", trimmed = "", after = ""] = /^(\s*)(.*?)(\s*)$/s.exec(element) ?? [];
|
|
70
|
+
const label = LABEL.exec(trimmed);
|
|
71
|
+
return before + (label ? `${label[1]}${sortedType(label[2] ?? "")}` : sortedType(trimmed)) + after;
|
|
72
|
+
});
|
|
73
|
+
out += `${char}${inner.join(separator)}${type[end] ?? ""}`;
|
|
74
|
+
}
|
|
75
|
+
else
|
|
76
|
+
out += type.slice(index, end + 1);
|
|
77
|
+
index = end + 1;
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
/** The errors tsc printed, each on one line, as the gate compares them. */
|
|
82
|
+
export function typeErrors(printed) {
|
|
83
|
+
const errors = [];
|
|
84
|
+
for (const line of printed) {
|
|
85
|
+
// The lines under an error explain it, and name its first failing member.
|
|
86
|
+
if (!line.trim() || /^\s/.test(line))
|
|
87
|
+
continue;
|
|
88
|
+
const located = line.replace(POSITION, "$1: $2");
|
|
89
|
+
// tsc quotes each type it names.
|
|
90
|
+
errors.push(located.replace(/'([^']*)'/g, (_quoted, type) => `'${sortedType(type)}'`));
|
|
91
|
+
}
|
|
92
|
+
const seen = new Map();
|
|
93
|
+
return errors.map((error) => {
|
|
94
|
+
const count = (seen.get(error) ?? 0) + 1;
|
|
95
|
+
seen.set(error, count);
|
|
96
|
+
return count === 1 ? error : `${error} (${count})`;
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
/** What to print for each line of tsc in watch mode: nothing until a compilation ends, then its errors. */
|
|
100
|
+
export function watching() {
|
|
101
|
+
let compiled = [];
|
|
102
|
+
return (line) => {
|
|
103
|
+
if (STARTS.test(line)) {
|
|
104
|
+
compiled = [];
|
|
105
|
+
return ["Type check started"];
|
|
106
|
+
}
|
|
107
|
+
if (ENDS.test(line))
|
|
108
|
+
return [...typeErrors(compiled), "Type check done"];
|
|
109
|
+
compiled.push(line);
|
|
110
|
+
return [];
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
function main(root, args) {
|
|
114
|
+
const tsc = checkingTsc(root, args);
|
|
115
|
+
const watch = args.includes("--watch");
|
|
116
|
+
const options = [
|
|
117
|
+
"--noEmit",
|
|
118
|
+
"--pretty",
|
|
119
|
+
"false",
|
|
120
|
+
"--noErrorTruncation",
|
|
121
|
+
...(watch ? ["--preserveWatchOutput"] : []),
|
|
122
|
+
...args,
|
|
123
|
+
];
|
|
124
|
+
const child = spawn(tsc.file, [...tsc.args, ...options], { stdio: ["ignore", "pipe", "inherit"] });
|
|
125
|
+
const printed = [];
|
|
126
|
+
const print = watching();
|
|
127
|
+
createInterface({ input: child.stdout }).on("line", (line) => {
|
|
128
|
+
if (watch)
|
|
129
|
+
for (const shown of print(line))
|
|
130
|
+
console.log(shown);
|
|
131
|
+
else
|
|
132
|
+
printed.push(line);
|
|
133
|
+
});
|
|
134
|
+
child.on("close", (code) => {
|
|
135
|
+
// 1 and 2 are tsc saying it found errors: the gate counts them, so only a tsc that broke fails.
|
|
136
|
+
if (watch || code === null || code > 2) {
|
|
137
|
+
console.log(printed.join("\n"));
|
|
138
|
+
process.exit(code ?? 1);
|
|
139
|
+
}
|
|
140
|
+
console.log(typeErrors(printed).join("\n"));
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
if (import.meta.main)
|
|
144
|
+
main(process.cwd(), process.argv.slice(2));
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { relative } from "node:path";
|
|
2
|
+
/** The header of the state, which the watch helper of the engine looks for. */
|
|
3
|
+
export const HEADER = "Spec states:";
|
|
4
|
+
export const COUNTS = "Specs:";
|
|
5
|
+
function indented(error) {
|
|
6
|
+
return (error.message ?? "").split("\n").map((line) => ` ${line}`);
|
|
7
|
+
}
|
|
8
|
+
function failuresOf(module) {
|
|
9
|
+
const spec = relative(process.cwd(), module.moduleId);
|
|
10
|
+
const lines = module.errors().flatMap((error) => [`FAIL ${spec}`, ...indented(error)]);
|
|
11
|
+
for (const test of module.children.allTests()) {
|
|
12
|
+
const { state, errors = [] } = test.result();
|
|
13
|
+
if (state === "failed")
|
|
14
|
+
lines.push(`FAIL ${spec} > ${test.fullName}`, ...errors.flatMap(indented));
|
|
15
|
+
}
|
|
16
|
+
return lines;
|
|
17
|
+
}
|
|
18
|
+
export default class StateReporter {
|
|
19
|
+
failures = new Map();
|
|
20
|
+
onTestRunEnd(modules) {
|
|
21
|
+
for (const module of modules)
|
|
22
|
+
this.failures.set(module.moduleId, failuresOf(module));
|
|
23
|
+
const red = [...this.failures.values()].filter((lines) => lines.length);
|
|
24
|
+
console.log([HEADER, ...red.flat(), `${COUNTS} ${red.length} red of ${this.failures.size}`].join("\n"));
|
|
25
|
+
}
|
|
26
|
+
}
|
package/dist/src/hook/hook.js
CHANGED
|
@@ -1,9 +1,15 @@
|
|
|
1
|
-
import { checkTurn, startTurn } from "../core/check.js";
|
|
1
|
+
import { checkTurn, startSession, startTurn } from "../core/check.js";
|
|
2
2
|
import { configuredRoot, gatesOf } 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
|
+
import { endSession } from "../core/watch.js";
|
|
6
7
|
import { forgetTold, forgetTurn, readTurn, tellOnce, turnRoot, writeTurn } from "../core/turn-state.js";
|
|
8
|
+
/** The events the plugin hooks, each named as the CLI takes it. */
|
|
9
|
+
export const HOOK_EVENTS = ["session-start", "turn-start", "check", "session-end"];
|
|
10
|
+
export function isHookEvent(word) {
|
|
11
|
+
return HOOK_EVENTS.some((event) => event === word);
|
|
12
|
+
}
|
|
7
13
|
export function parseHookInput(text) {
|
|
8
14
|
const input = parseJson(text);
|
|
9
15
|
if (!isRecord(input))
|
|
@@ -56,6 +62,18 @@ export function stopOutput(turn, judged) {
|
|
|
56
62
|
function cannotRun(error) {
|
|
57
63
|
return { systemMessage: broken(messageOf(error)) };
|
|
58
64
|
}
|
|
65
|
+
/**
|
|
66
|
+
* A session that starts starts the watches of its repo. Whatever stops them is told at the prompt, which reads the
|
|
67
|
+
* same gates.
|
|
68
|
+
*/
|
|
69
|
+
function sessionHook(session, cwd) {
|
|
70
|
+
try {
|
|
71
|
+
const root = configuredRoot(cwd);
|
|
72
|
+
if (root !== undefined)
|
|
73
|
+
startSession(session, root);
|
|
74
|
+
}
|
|
75
|
+
catch { }
|
|
76
|
+
}
|
|
59
77
|
/**
|
|
60
78
|
* A prompt ends the turn in progress; from a folder with no gates, or when the turn cannot start, no check will look
|
|
61
79
|
* for a new one. When the gates of the repo miss tools, the agent is asked once to install them.
|
|
@@ -113,6 +131,12 @@ export async function handleHook(event, text) {
|
|
|
113
131
|
if (event === "session-start") {
|
|
114
132
|
if (source !== "compact")
|
|
115
133
|
forgetTold(session);
|
|
134
|
+
sessionHook(session, cwd);
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
// Codex gives a session that ends 3 s at most: the hook only stops the watches no other session uses.
|
|
138
|
+
if (event === "session-end") {
|
|
139
|
+
endSession(session);
|
|
116
140
|
return undefined;
|
|
117
141
|
}
|
|
118
142
|
return event === "turn-start" ? promptHook(session, cwd) : stopHook(session, cwd, retry, message);
|
package/hooks/hooks.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tayomi/deterministic-gates",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
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
|
@@ -5,7 +5,7 @@ import { configuredRoot } from "./core/config.ts";
|
|
|
5
5
|
import { messageOf } from "./core/json.ts";
|
|
6
6
|
import { broken, reports, summary } from "./core/report.ts";
|
|
7
7
|
import { failed } from "./core/run.ts";
|
|
8
|
-
import { handleHook } from "./hook/hook.ts";
|
|
8
|
+
import { HOOK_EVENTS, handleHook, isHookEvent } from "./hook/hook.ts";
|
|
9
9
|
|
|
10
10
|
function readStdin(): string {
|
|
11
11
|
try {
|
|
@@ -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 =
|
|
19
|
+
export const USAGE = `Usage: deterministic-gates check, 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);
|
|
@@ -32,7 +32,7 @@ async function main([command, event]: string[]): Promise<void> {
|
|
|
32
32
|
console.error(oldNode);
|
|
33
33
|
process.exitCode = 2;
|
|
34
34
|
}
|
|
35
|
-
} else if (command === "hook" && (event
|
|
35
|
+
} else if (command === "hook" && isHookEvent(event)) {
|
|
36
36
|
const output = await handleHook(event, readStdin());
|
|
37
37
|
if (output) console.log(JSON.stringify(output));
|
|
38
38
|
} else if (command === "check" && event === undefined) {
|