@tayomi/deterministic-gates 0.10.0 → 0.12.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.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/catalog/go.json +9 -5
- package/catalog/index.html +9 -5
- package/dist/src/cli.js +2 -2
- package/dist/src/core/check.js +59 -21
- package/dist/src/core/config.js +22 -5
- package/dist/src/core/head.js +76 -22
- package/dist/src/core/projects.js +43 -0
- package/dist/src/core/report.js +41 -17
- package/dist/src/core/run.js +115 -21
- package/dist/src/core/snapshot.js +72 -15
- package/dist/src/core/turn-state.js +14 -2
- package/dist/src/helpers/new-clones.js +90 -16
- package/package.json +1 -1
- package/src/cli.ts +2 -2
- package/src/core/check.ts +67 -29
- package/src/core/config.ts +28 -4
- package/src/core/head.ts +99 -30
- package/src/core/projects.ts +54 -0
- package/src/core/report.ts +44 -16
- package/src/core/run.ts +144 -18
- package/src/core/snapshot.ts +87 -20
- package/src/core/turn-state.ts +20 -3
- package/src/helpers/new-clones.ts +105 -15
package/dist/src/core/report.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { failed } from "./run.js";
|
|
1
|
+
import { failed, notJudged, underFolder } from "./run.js";
|
|
2
2
|
import { WAIVE_TAG } from "./waive-line.js";
|
|
3
3
|
const LABEL = "● gates";
|
|
4
4
|
const SHOWN_PASSES = 6;
|
|
@@ -35,8 +35,12 @@ export function excerpt(report, max = REPORT_CHARS) {
|
|
|
35
35
|
export function duration(ms) {
|
|
36
36
|
return ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`;
|
|
37
37
|
}
|
|
38
|
+
// The gate, with the projects it concerns when it runs in each: one line whatever their number.
|
|
39
|
+
function named({ name, projects = [] }) {
|
|
40
|
+
return projects.length ? `${name} [${projects.join(", ")}]` : name;
|
|
41
|
+
}
|
|
38
42
|
function gateLine(mark, outcome) {
|
|
39
|
-
return `${mark} ${outcome
|
|
43
|
+
return `${mark} ${named(outcome)} ${paint("dim", duration(outcome.ms))}`;
|
|
40
44
|
}
|
|
41
45
|
function skippedLine(skipped) {
|
|
42
46
|
return paint("dim", `${skipped.map((name) => `- ${name}`).join(" ")} · no matching file changed`);
|
|
@@ -53,7 +57,7 @@ function nothingChecked({ changed, skipped }, after) {
|
|
|
53
57
|
// The gate in orange, then the reason the agent gave, under a star.
|
|
54
58
|
function waivedLines(outcome, reason) {
|
|
55
59
|
return [
|
|
56
|
-
`${paint("warn", `${WARNING} ${outcome
|
|
60
|
+
`${paint("warn", `${WARNING} ${named(outcome)}`)} ${paint("dim", duration(outcome.ms))}`,
|
|
57
61
|
` ${paint("warn", "*")} ${reason}`,
|
|
58
62
|
];
|
|
59
63
|
}
|
|
@@ -135,16 +139,23 @@ function sent(report, omitLines) {
|
|
|
135
139
|
const kept = report.split("\n").filter((line) => !omitted.test(line));
|
|
136
140
|
return kept.some((line) => line.trim()) ? kept.join("\n") : report;
|
|
137
141
|
}
|
|
138
|
-
// A helper of the engine counts apart the errors of one source line, with `(2)`
|
|
139
|
-
// so that one more of them is new. The agent reads each of them once, with how many
|
|
142
|
+
// A helper of the engine counts apart the errors of one source line, with `(2)` after the source it quotes and before
|
|
143
|
+
// the tab that ends their key, so that one more of them is new. The agent reads each of them once, with how many
|
|
144
|
+
// times it stands. A line of another tool is left as it is.
|
|
145
|
+
const COUNTED_APART = /` \(\d+\)\t/;
|
|
140
146
|
function saidOnce(report) {
|
|
141
|
-
|
|
147
|
+
if (!COUNTED_APART.test(report))
|
|
148
|
+
return report;
|
|
149
|
+
const lines = report.split("\n");
|
|
150
|
+
const keyed = lines.map((line) => line.replace(COUNTED_APART, "`\t"));
|
|
151
|
+
const counted = new Set(keyed.filter((line, at) => line !== lines[at]));
|
|
142
152
|
const times = new Map();
|
|
143
|
-
for (const line of
|
|
144
|
-
if (
|
|
153
|
+
for (const line of keyed)
|
|
154
|
+
if (counted.has(line))
|
|
145
155
|
times.set(line, (times.get(line) ?? 0) + 1);
|
|
146
|
-
|
|
147
|
-
|
|
156
|
+
const said = new Set();
|
|
157
|
+
return keyed
|
|
158
|
+
.filter((line) => !times.has(line) || (!said.has(line) && said.add(line)))
|
|
148
159
|
.map((line) => ((times.get(line) ?? 1) > 1 ? `${line} (×${times.get(line)})` : line))
|
|
149
160
|
.join("\n");
|
|
150
161
|
}
|
|
@@ -180,21 +191,33 @@ export function toolsToInstall(missing, prompt) {
|
|
|
180
191
|
}
|
|
181
192
|
/**
|
|
182
193
|
* The report of each failed gate, under its name, how to act on one the turn broke, and the prompt of the repo for it:
|
|
183
|
-
* each line a helper counts apart said once,
|
|
194
|
+
* less the lines the gate omits, each line a helper counts apart said once, in the characters it has, and in its share of a total when the reports have one.
|
|
195
|
+
* A gate that failed in several projects shares its characters between their blocks the same way, each under its
|
|
196
|
+
* folder, then names the projects it ran out of time for.
|
|
184
197
|
*/
|
|
185
198
|
export function reports({ outcomes, wording = {} }) {
|
|
186
199
|
const { gates = [], prompts, maxTotalReportChars = Infinity } = wording;
|
|
187
|
-
const
|
|
200
|
+
const all = outcomes.filter(failed);
|
|
201
|
+
const red = all.map(({ name, output, broken, blocks = [{ dir: ".", output }] }) => {
|
|
188
202
|
const gate = gates.find((known) => known.name === name);
|
|
189
|
-
const
|
|
203
|
+
const said = blocks.map((block) => ({ ...block, output: saidOnce(sent(block.output, gate?.omitLines)) }));
|
|
190
204
|
const told = [
|
|
191
205
|
...(broken ? [worded(BROKEN_GATE, prompts?.brokenGate, "\n")] : []),
|
|
192
206
|
...(gate?.prompt ? [gate.prompt.text] : []),
|
|
193
207
|
];
|
|
194
|
-
|
|
208
|
+
const length = said.reduce((sum, block) => sum + block.output.length, 0);
|
|
209
|
+
return { name, told, said, needs: Math.min(length, gate?.maxReportChars ?? REPORT_CHARS) };
|
|
195
210
|
});
|
|
196
211
|
const given = shares(red.map(({ needs }) => needs), maxTotalReportChars);
|
|
197
|
-
return red.map(({ name, told,
|
|
212
|
+
return red.map(({ name, told, said }, at) => {
|
|
213
|
+
const each = shares(said.map((block) => block.output.length), given[at] ?? 0);
|
|
214
|
+
const { unjudged = [] } = all[at] ?? {};
|
|
215
|
+
const report = [
|
|
216
|
+
...said.map((block, of) => underFolder({ ...block, output: excerpt(block.output, each[of]) })),
|
|
217
|
+
...(unjudged.length ? [notJudged(unjudged)] : []),
|
|
218
|
+
];
|
|
219
|
+
return [`## ${name}`, ...told, report.join("\n\n")].join("\n");
|
|
220
|
+
});
|
|
198
221
|
}
|
|
199
222
|
/**
|
|
200
223
|
* What the agent gets when it is sent back: how to act on a failure, in the words of the engine or of the repo, how
|
|
@@ -214,12 +237,13 @@ function gateResult({ name, ok, ms, output, timedOut, broken }) {
|
|
|
214
237
|
}
|
|
215
238
|
/**
|
|
216
239
|
* A check for a tool to read, such as a CI or a script, where the summary is for its owner and the send-back for the
|
|
217
|
-
* agent: whether it passed, each gate with its status and its whole report, and
|
|
240
|
+
* agent: whether it passed, which a gate out of time keeps it from, each gate with its status and its whole report, and
|
|
241
|
+
* the notes of the check.
|
|
218
242
|
*/
|
|
219
243
|
export function results({ outcomes, skipped, ms, note }) {
|
|
220
244
|
const gates = [
|
|
221
245
|
...outcomes.map(gateResult),
|
|
222
246
|
...skipped.map((name) => ({ name, status: "skipped" })),
|
|
223
247
|
];
|
|
224
|
-
return { ok:
|
|
248
|
+
return { ok: outcomes.every(({ ok }) => ok), durationMs: Math.round(ms), gates, notes: note ? note.split("\n") : [] };
|
|
225
249
|
}
|
package/dist/src/core/run.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
2
|
import { accessSync, constants, existsSync } from "node:fs";
|
|
3
|
+
import { availableParallelism } from "node:os";
|
|
3
4
|
import { delimiter, isAbsolute, join, resolve, sep } from "node:path";
|
|
4
5
|
import { stripVTControlCharacters } from "node:util";
|
|
5
|
-
import { FILES, isCompared, TURN } from "./config.js";
|
|
6
|
+
import { DIRS, ENGINE_PREFIX, FILES, isCompared, TURN } from "./config.js";
|
|
6
7
|
import { isRecord, messageOf, readJsonFile } from "./json.js";
|
|
7
8
|
/** A gate that judged the turn and found a problem, or that broke: the only kinds that send the agent back. */
|
|
8
9
|
export function failed(outcome) {
|
|
@@ -32,7 +33,6 @@ export function headed(own, lines, env = process.env) {
|
|
|
32
33
|
return [...(env[PROMPT_REPLACED] ? [] : [own]), ...lines].join("\n");
|
|
33
34
|
}
|
|
34
35
|
const MAX_OUTPUT_MB = 16;
|
|
35
|
-
const ENGINE_PREFIX = "{engine}/";
|
|
36
36
|
/** A script of this engine: its .ts source, or the .js it is built to when the engine runs from its npm package. */
|
|
37
37
|
function engineScript(name) {
|
|
38
38
|
const file = resolve(ENGINE, name);
|
|
@@ -114,13 +114,23 @@ function missingProgram(root, name) {
|
|
|
114
114
|
export function missingTool(root, gate) {
|
|
115
115
|
return missingProgram(root, gate.run[0] ?? "") ?? (gate.watch && missingProgram(root, gate.watch.run[0] ?? ""));
|
|
116
116
|
}
|
|
117
|
-
export function argumentsOf(gate, files, turn) {
|
|
118
|
-
return gate.run.slice(1).flatMap((argument) =>
|
|
117
|
+
export function argumentsOf(gate, files, turn, dirs = []) {
|
|
118
|
+
return gate.run.slice(1).flatMap((argument) => {
|
|
119
|
+
if (argument === FILES)
|
|
120
|
+
return files;
|
|
121
|
+
if (argument === DIRS)
|
|
122
|
+
return dirs;
|
|
123
|
+
return [argument.replaceAll(TURN, turn)];
|
|
124
|
+
});
|
|
119
125
|
}
|
|
120
126
|
/** Whether the gate is given the changed files, where another reads the whole project. */
|
|
121
127
|
export function givenFiles(gate) {
|
|
122
128
|
return gate.run.includes(FILES);
|
|
123
129
|
}
|
|
130
|
+
/** Whether the gate is given the folders of the changed files. */
|
|
131
|
+
export function givenDirs(gate) {
|
|
132
|
+
return gate.run.includes(DIRS);
|
|
133
|
+
}
|
|
124
134
|
export function filesOf(gate, changed) {
|
|
125
135
|
const pattern = new RegExp(gate.files);
|
|
126
136
|
return changed.filter((file) => pattern.test(file));
|
|
@@ -159,7 +169,8 @@ export function newLines(before, after, ignore, key, changed = []) {
|
|
|
159
169
|
.filter((line) => !restOf(line) || written(line) || !stillOld((was) => restOf(was) === restOf(line)))
|
|
160
170
|
.filter((line) => placeOf(line) === undefined || !stillOld((was) => placeOf(was) === placeOf(line)));
|
|
161
171
|
}
|
|
162
|
-
|
|
172
|
+
/** Starts the command of a gate, found from the root of the repo, in the folder given: the root, or a project. */
|
|
173
|
+
async function execute(root, gate, args, cwd = root) {
|
|
163
174
|
const started = performance.now();
|
|
164
175
|
const [name = ""] = gate.run;
|
|
165
176
|
// A gate that cannot start fails alone: the other gates of the turn still report.
|
|
@@ -178,14 +189,15 @@ async function execute(root, gate, args) {
|
|
|
178
189
|
}
|
|
179
190
|
return new Promise((resolve) => {
|
|
180
191
|
execFile(command.file, [...command.args, ...args], {
|
|
181
|
-
cwd
|
|
182
|
-
|
|
192
|
+
cwd,
|
|
193
|
+
// In whole milliseconds, as Node wants them: what is left of a shared time is not.
|
|
194
|
+
timeout: Math.ceil(gate.timeoutSeconds * 1000),
|
|
183
195
|
maxBuffer: MAX_OUTPUT_MB * 1024 * 1024,
|
|
184
196
|
env: { ...toolEnv(root), ...(gate.prompt?.replace ? { [PROMPT_REPLACED]: "1" } : {}) },
|
|
185
197
|
}, (error, stdout, stderr) => {
|
|
186
198
|
resolve({
|
|
187
199
|
ok: !error,
|
|
188
|
-
output: outputOf(root, gate, command, error, `${stdout}${stderr}
|
|
200
|
+
output: outputOf(root, gate, command, error, `${stdout}${stderr}`, cwd),
|
|
189
201
|
ms: performance.now() - started,
|
|
190
202
|
timedOut: error?.killed === true && error.code !== "ERR_CHILD_PROCESS_STDIO_MAXBUFFER",
|
|
191
203
|
cannotStart: error?.code === "ENOENT",
|
|
@@ -194,21 +206,26 @@ async function execute(root, gate, args) {
|
|
|
194
206
|
});
|
|
195
207
|
});
|
|
196
208
|
}
|
|
197
|
-
function outputOf(root, gate, command, error, printed) {
|
|
209
|
+
function outputOf(root, gate, command, error, printed, cwd) {
|
|
198
210
|
if (error?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER")
|
|
199
211
|
return `Printed more than ${MAX_OUTPUT_MB} MB: too much for the end of a turn. Make it quieter, or move it to CI.`;
|
|
200
212
|
if (error?.killed === true)
|
|
201
|
-
return
|
|
213
|
+
return outOfTime(gate);
|
|
202
214
|
if (error?.code === "ENOENT")
|
|
203
215
|
return command.missing;
|
|
204
|
-
const said = cleaned(root, printed);
|
|
216
|
+
const said = cleaned(root, printed, cwd);
|
|
205
217
|
if (said || !error)
|
|
206
218
|
return said;
|
|
207
219
|
return `exit code ${String(error.code)}, no output`;
|
|
208
220
|
}
|
|
209
|
-
/**
|
|
210
|
-
|
|
211
|
-
|
|
221
|
+
/**
|
|
222
|
+
* What a tool printed, for the agent: some tools colour despite NO_COLOR, and absolute paths only cost it tokens. A
|
|
223
|
+
* tool that ran in a project loses the path of that folder first, so its files read as the relative paths it prints.
|
|
224
|
+
*/
|
|
225
|
+
export function cleaned(root, printed, cwd = root) {
|
|
226
|
+
return [cwd, root]
|
|
227
|
+
.reduce((text, dir) => text.split(`${dir}${sep}`).join(""), stripVTControlCharacters(printed))
|
|
228
|
+
.trim();
|
|
212
229
|
}
|
|
213
230
|
/**
|
|
214
231
|
* Runs a compared gate on the whole project, as the turn starts, in the time the gate has or less: nothing when it
|
|
@@ -232,19 +249,96 @@ export function namesFiles(gate) {
|
|
|
232
249
|
* code but 0: the same crash at the start and at the end of a turn prints no new line. Another gate is broken on the
|
|
233
250
|
* exit codes it names as such. A gate out of time is neither.
|
|
234
251
|
*/
|
|
235
|
-
export async function check(root, gate, files, turn, baseline, elsewhere = false) {
|
|
236
|
-
const
|
|
252
|
+
export async function check(root, gate, files, turn, baseline, elsewhere = false, dirs = []) {
|
|
253
|
+
const outcome = await ranIn(root, gate, files, turn, dirs);
|
|
254
|
+
if (!outcome.ok || !isCompared(gate))
|
|
255
|
+
return outcome;
|
|
256
|
+
return { ...outcome, ...addedLines(gate, outcome.output, baseline, files, elsewhere) };
|
|
257
|
+
}
|
|
258
|
+
/** What the command of a gate says of the files given, run once in a folder: by its exit code alone. */
|
|
259
|
+
async function ranIn(root, gate, files, turn, dirs = [], cwd = root) {
|
|
260
|
+
const executed = await execute(root, gate, argumentsOf(gate, files, turn, dirs), cwd);
|
|
237
261
|
const { ok, output, ms, timedOut, cannotStart, exitCode = 0 } = executed;
|
|
238
262
|
const ran = { name: gate.name, ms, report: ok ? output : undefined };
|
|
239
263
|
if (timedOut)
|
|
240
264
|
return { ...ran, ok, output, timedOut };
|
|
241
265
|
// A compared gate exits with 0 when it finds problems: any other code is its command that broke.
|
|
242
266
|
const broke = cannotStart || isCompared(gate) || gate.brokenExitCodes?.includes(exitCode);
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
267
|
+
return { ...ran, ok, output, ...(!ok && broke ? { broken: true } : {}) };
|
|
268
|
+
}
|
|
269
|
+
const ROOT = ".";
|
|
270
|
+
/** What a project said, under its folder: a tool prints its paths from where it runs. The root needs no telling. */
|
|
271
|
+
export function underFolder({ dir, output }) {
|
|
272
|
+
return dir === ROOT ? output : `in ${dir}, paths relative to it:\n${output}`;
|
|
273
|
+
}
|
|
274
|
+
/** What a failed gate says last of the projects it ran out of time for. */
|
|
275
|
+
export function notJudged(dirs) {
|
|
276
|
+
return `out of time, so not judged: ${dirs.join(", ")}`;
|
|
277
|
+
}
|
|
278
|
+
function outOfTime(gate) {
|
|
279
|
+
return `Out of time after ${gate.timeoutSeconds} s, so not judged. Make it faster, or move it to CI.`;
|
|
280
|
+
}
|
|
281
|
+
// Runs a task on each item, at most so many at once, and gives what they returned in the order of the items.
|
|
282
|
+
async function pooled(items, limit, run) {
|
|
283
|
+
const results = [];
|
|
284
|
+
let next = 0;
|
|
285
|
+
const worker = async () => {
|
|
286
|
+
for (let at = next++; at < items.length; at = next++)
|
|
287
|
+
results[at] = await run(items[at]);
|
|
288
|
+
};
|
|
289
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
290
|
+
return results;
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Runs a gate once in each project given, from the folder of the project, and gives one outcome for them all: the
|
|
294
|
+
* gate stays one gate, with one name to report under and to waive. It is red when a project failed, with the report
|
|
295
|
+
* of each failed project under its folder, broken when one broke, and out of time when none failed and one ran out
|
|
296
|
+
* of it. As many projects run at once as the machine has cores: a build takes them all by itself. With a shared
|
|
297
|
+
* time, as at the stop, the time of the gate is for all its projects, and one whose turn comes too late is not
|
|
298
|
+
* started; otherwise each has it whole.
|
|
299
|
+
*/
|
|
300
|
+
export async function checkEach(root, gate, projects, turn, sharedTime = false) {
|
|
301
|
+
const started = performance.now();
|
|
302
|
+
const ran = await pooled(projects, availableParallelism(), async ({ dir, files, dirs }) => {
|
|
303
|
+
const left = sharedTime ? gate.timeoutSeconds - (performance.now() - started) / 1000 : gate.timeoutSeconds;
|
|
304
|
+
if (left <= 0)
|
|
305
|
+
return { dir, name: gate.name, ok: false, ms: 0, output: "", report: undefined, timedOut: true };
|
|
306
|
+
return { dir, ...(await ranIn(root, { ...gate, timeoutSeconds: left }, files, turn, dirs, join(root, dir))) };
|
|
307
|
+
});
|
|
308
|
+
const merged = { name: gate.name, ms: performance.now() - started, report: undefined };
|
|
309
|
+
const named = (outcomes) => outcomes.map(({ dir }) => dir).filter((dir) => dir !== ROOT);
|
|
310
|
+
const red = ran.filter(failed);
|
|
311
|
+
const late = ran.filter(({ timedOut }) => timedOut);
|
|
312
|
+
if (red.length) {
|
|
313
|
+
const blocks = red.map(({ dir, output }) => ({ dir, output }));
|
|
314
|
+
// The root is named here, where nothing else would say a project was left.
|
|
315
|
+
const unjudged = late.map(({ dir }) => dir);
|
|
316
|
+
return {
|
|
317
|
+
...merged,
|
|
318
|
+
ok: false,
|
|
319
|
+
output: [...blocks.map(underFolder), ...(unjudged.length ? [notJudged(unjudged)] : [])].join("\n\n"),
|
|
320
|
+
blocks,
|
|
321
|
+
...(red.some(({ broken }) => broken) ? { broken: true } : {}),
|
|
322
|
+
...(named(red).length ? { projects: named(red) } : {}),
|
|
323
|
+
...(unjudged.length ? { unjudged } : {}),
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
if (late.length)
|
|
327
|
+
return {
|
|
328
|
+
...merged,
|
|
329
|
+
ok: false,
|
|
330
|
+
output: outOfTime(gate),
|
|
331
|
+
timedOut: true,
|
|
332
|
+
...(named(late).length ? { projects: named(late) } : {}),
|
|
333
|
+
};
|
|
334
|
+
return {
|
|
335
|
+
...merged,
|
|
336
|
+
ok: true,
|
|
337
|
+
output: ran
|
|
338
|
+
.map(({ output }) => output)
|
|
339
|
+
.filter(Boolean)
|
|
340
|
+
.join("\n"),
|
|
341
|
+
};
|
|
248
342
|
}
|
|
249
343
|
/**
|
|
250
344
|
* Judges the output of a compared gate that ran clean: it fails on the lines the turn added to the report of the turn
|
|
@@ -2,9 +2,20 @@ import { execFileSync } from "node:child_process";
|
|
|
2
2
|
import { cpSync, existsSync, mkdtempSync, rmSync } from "node:fs";
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { join, resolve } from "node:path";
|
|
5
|
-
/**
|
|
5
|
+
/**
|
|
6
|
+
* Runs git in the repo, and gives what it printed, without the line break that ends it, however long. Nothing else is
|
|
7
|
+
* trimmed: the name of a file may start with a space.
|
|
8
|
+
*/
|
|
6
9
|
function git(root, args, { env = process.env, input } = {}) {
|
|
7
|
-
|
|
10
|
+
const printed = execFileSync("git", args, {
|
|
11
|
+
cwd: root,
|
|
12
|
+
encoding: "utf8",
|
|
13
|
+
env,
|
|
14
|
+
input,
|
|
15
|
+
stdio: "pipe",
|
|
16
|
+
maxBuffer: Infinity,
|
|
17
|
+
});
|
|
18
|
+
return printed.replace(/\n$/, "");
|
|
8
19
|
}
|
|
9
20
|
// One NUL after each path, which git otherwise quotes and escapes when it holds an accent.
|
|
10
21
|
function paths(printed) {
|
|
@@ -107,22 +118,68 @@ export function fileAt(root, commit, file) {
|
|
|
107
118
|
export function changedSince(root, start, end = workingTree(root)) {
|
|
108
119
|
return paths(git(root, ["diff", "-z", "--name-only", start, end])).sort();
|
|
109
120
|
}
|
|
110
|
-
/** The
|
|
111
|
-
export function
|
|
121
|
+
/** The commit HEAD is on, and the tips of the branches: nothing in a repo with no commit. */
|
|
122
|
+
export function branchTips(root) {
|
|
123
|
+
try {
|
|
124
|
+
const head = git(root, ["rev-parse", "--verify", "--quiet", "HEAD"]);
|
|
125
|
+
const tips = git(root, ["for-each-ref", "--format=%(objectname)", "refs/heads"]).split("\n");
|
|
126
|
+
return { head, tips: [...new Set([head, ...tips.filter(Boolean)])] };
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
return { tips: [] };
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/** The folder of git that the worktrees of a repo share: what tells that two of them are of the same repo. */
|
|
133
|
+
export function sharedDir(root) {
|
|
112
134
|
try {
|
|
113
|
-
|
|
114
|
-
const reached = entries.map((entry) => entry.slice(0, entry.indexOf(" ")));
|
|
115
|
-
return entries.map((entry, at) => ({
|
|
116
|
-
from: reached[at - 1],
|
|
117
|
-
to: reached[at] ?? "",
|
|
118
|
-
how: entry.slice(entry.indexOf(" ") + 1),
|
|
119
|
-
}));
|
|
135
|
+
return git(root, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
|
|
120
136
|
}
|
|
121
137
|
catch {
|
|
122
|
-
return
|
|
138
|
+
return root;
|
|
123
139
|
}
|
|
124
140
|
}
|
|
125
|
-
/**
|
|
126
|
-
export function
|
|
127
|
-
|
|
141
|
+
/** Whether a commit is another one, or one it holds. */
|
|
142
|
+
export function isIn(root, commit, other) {
|
|
143
|
+
try {
|
|
144
|
+
git(root, ["merge-base", "--is-ancestor", commit, other]);
|
|
145
|
+
return true;
|
|
146
|
+
}
|
|
147
|
+
catch {
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/** The commits these tips hold that none of the known commits does. It throws when git no longer has one of them. */
|
|
152
|
+
export function commitsPast(root, tips, known) {
|
|
153
|
+
const input = known.map((commit) => `^${commit}\n`).join("");
|
|
154
|
+
// Two lines a commit: "commit", its hash and its parents, then its time.
|
|
155
|
+
const lines = git(root, ["rev-list", "--parents", "--format=%ct", "--stdin", ...tips], { input }).split("\n");
|
|
156
|
+
return lines.filter(Boolean).flatMap((line, at, all) => {
|
|
157
|
+
if (at % 2)
|
|
158
|
+
return [];
|
|
159
|
+
const [, hash = "", ...parents] = line.split(" ");
|
|
160
|
+
return [{ hash, parents, at: Number(all[at + 1]) }];
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* The lines of a file the working tree wrote since a commit that has the file. The file is compared with the one of
|
|
165
|
+
* the commit, not through the index, which does not know a file nobody added; and with the diff of git itself, plain,
|
|
166
|
+
* whatever colours or program the owner set for it.
|
|
167
|
+
*/
|
|
168
|
+
export function writtenSince(root, commit, file) {
|
|
169
|
+
const plain = ["--no-color", "--no-ext-diff", "--no-textconv", "--unified=0", "--inter-hunk-context=0"];
|
|
170
|
+
// The name as it is: git would otherwise read the brackets of a file such as [slug].ts as a pattern.
|
|
171
|
+
const diff = git(root, ["--literal-pathspecs", "diff", ...plain, `${commit}:${file}`, "--", file]);
|
|
172
|
+
const hunks = diff.matchAll(/^@@ -\S+ \+(\d+)(?:,(\d+))? @@/gm);
|
|
173
|
+
return [...hunks].map(([, at, lines = "1"]) => ({ at: Number(at), lines: Number(lines) }));
|
|
174
|
+
}
|
|
175
|
+
// Fewer names at once than a command line holds.
|
|
176
|
+
const NAMES_AT_ONCE = 500;
|
|
177
|
+
/** The ones of these files a commit has. */
|
|
178
|
+
export function filesAt(root, commit, files) {
|
|
179
|
+
const found = [];
|
|
180
|
+
for (let at = 0; at < files.length; at += NAMES_AT_ONCE) {
|
|
181
|
+
const names = files.slice(at, at + NAMES_AT_ONCE);
|
|
182
|
+
found.push(...paths(git(root, ["--literal-pathspecs", "ls-tree", "-r", "--name-only", "-z", commit, "--", ...names])));
|
|
183
|
+
}
|
|
184
|
+
return found;
|
|
128
185
|
}
|
|
@@ -25,19 +25,23 @@ function isTurnState(value) {
|
|
|
25
25
|
return (isRecord(value) &&
|
|
26
26
|
typeof value.start === "string" &&
|
|
27
27
|
(value.head === undefined || typeof value.head === "string") &&
|
|
28
|
-
(value.
|
|
28
|
+
(value.at === undefined || typeof value.at === "number") &&
|
|
29
29
|
isStringRecord(value.baselines) &&
|
|
30
30
|
isGatesFiles(value.config) &&
|
|
31
31
|
typeof value.checked === "boolean" &&
|
|
32
32
|
(value.sendBacks === undefined || isSendBacks(value.sendBacks)));
|
|
33
33
|
}
|
|
34
|
+
function isThere(value) {
|
|
35
|
+
return isRecord(value) && isStringArray(value.known) && isStringArray(value.made);
|
|
36
|
+
}
|
|
34
37
|
function isSessionState(value) {
|
|
35
38
|
return (isRecord(value) &&
|
|
36
39
|
(value.current === undefined || typeof value.current === "string") &&
|
|
37
40
|
isRecord(value.turns) &&
|
|
38
41
|
Object.values(value.turns).every(isTurnState) &&
|
|
39
42
|
(value.told === undefined || (isRecord(value.told) && Object.values(value.told).every(isStringArray))) &&
|
|
40
|
-
(value.conductTold === undefined || isStringArray(value.conductTold))
|
|
43
|
+
(value.conductTold === undefined || isStringArray(value.conductTold)) &&
|
|
44
|
+
(value.there === undefined || (isRecord(value.there) && Object.values(value.there).every(isThere))));
|
|
41
45
|
}
|
|
42
46
|
function readSession(session) {
|
|
43
47
|
const state = readJsonFile(stateFile(session));
|
|
@@ -59,6 +63,14 @@ export function writeTurn(session, root, turn) {
|
|
|
59
63
|
const unchecked = Object.entries(turns).filter(([, kept]) => !kept.checked);
|
|
60
64
|
writeSession(session, { ...state, current: root, turns: { ...Object.fromEntries(unchecked), [root]: turn } });
|
|
61
65
|
}
|
|
66
|
+
/** What the session knows of the commits of a repo, or nothing before its first turn there. */
|
|
67
|
+
export function readThere(session, root) {
|
|
68
|
+
return readSession(session).there?.[root];
|
|
69
|
+
}
|
|
70
|
+
export function writeThere(session, root, there) {
|
|
71
|
+
const state = readSession(session);
|
|
72
|
+
writeSession(session, { ...state, there: { ...state.there, [root]: there } });
|
|
73
|
+
}
|
|
62
74
|
/** Ends the turn in progress without a check, as a prompt from a folder with no gates, or a failed start, does. */
|
|
63
75
|
export function forgetTurn(session) {
|
|
64
76
|
forget(session, "current");
|
|
@@ -1,33 +1,95 @@
|
|
|
1
1
|
import { execFileSync } from "node:child_process";
|
|
2
|
-
import { mkdtempSync, rmSync } from "node:fs";
|
|
2
|
+
import { mkdtempSync, readFileSync, 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
6
|
import { headed, packageScript } from "../core/run.js";
|
|
7
|
+
import { filesAt, writtenSince } from "../core/snapshot.js";
|
|
7
8
|
// jscpd compared with the tree the turn started from. Its own console report lists every clone of the repo, the old
|
|
8
9
|
// ones included, so this prints only the clones the turn added, one per line.
|
|
10
|
+
//
|
|
11
|
+
// jscpd tells a clone by its two files and where it stands in them, so it also calls new an old clone the turn only
|
|
12
|
+
// disturbed: two old files it pairs once the turn takes their copy out of a third, or a clone the turn cut in two by a
|
|
13
|
+
// line written in its middle. A clone is the turn's only when the turn wrote in one of its sides.
|
|
9
14
|
function refuse() {
|
|
10
15
|
throw new Error("Not a jscpd report.");
|
|
11
16
|
}
|
|
12
|
-
function
|
|
17
|
+
function placeOf(value, line, column) {
|
|
18
|
+
if (isRecord(value) && typeof value.line === "number" && typeof value.column === "number")
|
|
19
|
+
return { line: value.line, column: value.column };
|
|
20
|
+
return { line, column };
|
|
21
|
+
}
|
|
22
|
+
// Without the columns of a clone, as from another jscpd, its first and last lines count as whole.
|
|
23
|
+
function sideOf(value) {
|
|
13
24
|
if (!isRecord(value))
|
|
14
25
|
refuse();
|
|
15
|
-
const { name, start, end } = value;
|
|
26
|
+
const { name, start, end, startLoc, endLoc } = value;
|
|
16
27
|
if (typeof name !== "string" || typeof start !== "number" || typeof end !== "number")
|
|
17
28
|
refuse();
|
|
18
|
-
return
|
|
29
|
+
return { name, start: placeOf(startLoc, start, 0), end: placeOf(endLoc, end, Infinity) };
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Whether the turn wrote in a side of a clone: a line it wrote stands whole in it, or it cut lines out of its middle.
|
|
33
|
+
* A clone starts and ends between two tokens, often inside a line: a line it only starts or ends in is not in it, nor
|
|
34
|
+
* an empty one, which jscpd does not read.
|
|
35
|
+
*/
|
|
36
|
+
export function wroteIn({ start, end }, text, written) {
|
|
37
|
+
const lines = text.split("\n");
|
|
38
|
+
const whole = (at) => {
|
|
39
|
+
const line = lines[at - 1] ?? "";
|
|
40
|
+
if (!line.trim())
|
|
41
|
+
return false;
|
|
42
|
+
const starts = at > start.line || (at === start.line && start.column <= line.length - line.trimStart().length);
|
|
43
|
+
const ends = at < end.line || (at === end.line && end.column >= line.trimEnd().length);
|
|
44
|
+
return starts && ends;
|
|
45
|
+
};
|
|
46
|
+
return written.some(({ at, lines: count }) => count === 0 ? start.line <= at && at < end.line : Array.from({ length: count }, (_, more) => at + more).some(whole));
|
|
19
47
|
}
|
|
20
|
-
|
|
48
|
+
/** The clones jscpd calls new, each as its two sides. */
|
|
49
|
+
function newPairs(report) {
|
|
21
50
|
if (!isRecord(report) || !Array.isArray(report.duplicates))
|
|
22
51
|
refuse();
|
|
23
52
|
return report.duplicates.flatMap((clone) => {
|
|
24
53
|
if (!isRecord(clone))
|
|
25
54
|
refuse();
|
|
26
|
-
const
|
|
27
|
-
return clone.isNew === true ? [
|
|
55
|
+
const sides = [sideOf(clone.firstFile), sideOf(clone.secondFile)];
|
|
56
|
+
return clone.isNew === true ? [sides] : [];
|
|
28
57
|
});
|
|
29
58
|
}
|
|
30
|
-
|
|
59
|
+
/** The clones jscpd calls new, one per line, less the ones the turn wrote in neither side of. */
|
|
60
|
+
export function newClones(report, wrote = () => true) {
|
|
61
|
+
return newPairs(report)
|
|
62
|
+
.filter((sides) => sides.some(wrote))
|
|
63
|
+
.map((sides) => sides.map(({ name, start, end }) => `${name}:${start.line}-${end.line}`).join(" ~ "));
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Whether the turn wrote in a side of a clone, for the clones of a report. Each file is read once, however many
|
|
67
|
+
* clones it has: the whole check finds every clone of the repo new.
|
|
68
|
+
*/
|
|
69
|
+
function turnWrote(root, turn, report) {
|
|
70
|
+
const names = [...new Set(newPairs(report).flatMap((sides) => sides.map(({ name }) => name)))];
|
|
71
|
+
const old = new Set(filesAt(root, turn, names));
|
|
72
|
+
const files = new Map();
|
|
73
|
+
return (side) => {
|
|
74
|
+
// A file the turn created is all its own, and one jscpd names from another folder is unknown here: checking too
|
|
75
|
+
// much beats leaving a hole.
|
|
76
|
+
if (!old.has(side.name))
|
|
77
|
+
return true;
|
|
78
|
+
try {
|
|
79
|
+
const file = files.get(side.name) ?? {
|
|
80
|
+
text: readFileSync(join(root, side.name), "utf8"),
|
|
81
|
+
written: writtenSince(root, turn, side.name),
|
|
82
|
+
};
|
|
83
|
+
files.set(side.name, file);
|
|
84
|
+
return wroteIn(side, file.text, file.written);
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/** The clones the turn added to the repo, as jscpd finds them. It throws what jscpd said when jscpd fails. */
|
|
92
|
+
export function turnClones(root, turn) {
|
|
31
93
|
const jscpd = packageScript(root, "jscpd");
|
|
32
94
|
if (jscpd === undefined)
|
|
33
95
|
throw new Error("jscpd is not installed in node_modules: install the dependencies of the repo.");
|
|
@@ -39,19 +101,31 @@ function main(root, turn) {
|
|
|
39
101
|
catch (error) {
|
|
40
102
|
// What jscpd said, without the stack of this script around it.
|
|
41
103
|
const said = isRecord(error) && typeof error.stderr === "string" ? error.stderr.trim() : String(error);
|
|
42
|
-
|
|
43
|
-
process.exitCode = 1;
|
|
44
|
-
return;
|
|
104
|
+
throw new Error(`jscpd failed: ${said}`, { cause: error });
|
|
45
105
|
}
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
return;
|
|
49
|
-
console.log(headed("New clones: reuse the code already there, or factor it out.", clones));
|
|
50
|
-
process.exitCode = 1;
|
|
106
|
+
const report = readJsonFile(join(output, "jscpd-report.json"));
|
|
107
|
+
return newClones(report, turnWrote(root, turn, report));
|
|
51
108
|
}
|
|
52
109
|
finally {
|
|
53
110
|
rmSync(output, { recursive: true, force: true });
|
|
54
111
|
}
|
|
55
112
|
}
|
|
113
|
+
function main(root, turn) {
|
|
114
|
+
let clones;
|
|
115
|
+
try {
|
|
116
|
+
clones = turnClones(root, turn);
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
if (!(error instanceof Error) || !error.message.startsWith("jscpd failed: "))
|
|
120
|
+
throw error;
|
|
121
|
+
console.log(error.message);
|
|
122
|
+
process.exitCode = 1;
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
if (!clones.length)
|
|
126
|
+
return;
|
|
127
|
+
console.log(headed("New clones: reuse the code already there, or factor it out.", clones));
|
|
128
|
+
process.exitCode = 1;
|
|
129
|
+
}
|
|
56
130
|
if (import.meta.main)
|
|
57
131
|
main(process.cwd(), process.argv[2] ?? "HEAD");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tayomi/deterministic-gates",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.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
|
@@ -4,7 +4,6 @@ import { checkAll } from "./core/check.ts";
|
|
|
4
4
|
import { configuredRoot } from "./core/config.ts";
|
|
5
5
|
import { messageOf } from "./core/json.ts";
|
|
6
6
|
import { broken, reports, results, summary } from "./core/report.ts";
|
|
7
|
-
import { failed } from "./core/run.ts";
|
|
8
7
|
import { HOOK_EVENTS, handleHook, isHookEvent } from "./hook/hook.ts";
|
|
9
8
|
|
|
10
9
|
function readStdin(): string {
|
|
@@ -47,7 +46,8 @@ async function main([command, ...words]: string[]): Promise<void> {
|
|
|
47
46
|
try {
|
|
48
47
|
const all = await checkAll(root);
|
|
49
48
|
console.log(json ? JSON.stringify(results(all), null, 2) : [summary(all), ...reports(all)].join("\n\n"));
|
|
50
|
-
|
|
49
|
+
// A gate out of time judged nothing: a CI never passes on it.
|
|
50
|
+
if (!all.outcomes.every(({ ok }) => ok)) process.exitCode = 1;
|
|
51
51
|
} catch (error) {
|
|
52
52
|
console.error(`Could not run: ${messageOf(error)}`);
|
|
53
53
|
process.exitCode = 2;
|