@tayomi/deterministic-gates 0.3.0 → 0.4.2
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 +3 -2
- package/.codex-plugin/plugin.json +2 -2
- package/README.md +25 -41
- 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/register.ts +12 -0
- package/package.json +10 -2
- package/src/cli.ts +33 -25
- package/src/core/report.ts +1 -1
- package/src/core/run.ts +8 -2
- package/src/core/send-back.ts +2 -11
- package/src/core/waive-line.ts +19 -0
- package/src/helpers/related-tests.ts +3 -2
- package/src/hook/display.ts +21 -0
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { dirname, extname, join, resolve } from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import { listFiles } from "../core/snapshot.js";
|
|
6
|
+
// The node:test tests that a change can break: those that import a changed file, directly or through other files.
|
|
7
|
+
// Node has no "related" mode of its own, where Vitest has one.
|
|
8
|
+
const EXTENSIONS = [".ts", ".mts", ".cts", ".js", ".mjs", ".cjs"];
|
|
9
|
+
const EXTENSION = `\\.(${EXTENSIONS.map((extension) => extension.slice(1)).join("|")})`;
|
|
10
|
+
/** Node's own naming of test files, the TypeScript ones included. */
|
|
11
|
+
const NODE_TESTS = new RegExp(`(\\.test|[-_]test|^test|/test)${EXTENSION}$|/test/.*${EXTENSION}$|(^|/)test-[^/]*${EXTENSION}$`);
|
|
12
|
+
/** Fails on a changed file no test reaches, which the related tests alone pass in silence. */
|
|
13
|
+
const REQUIRE_TESTS = "--require-tests";
|
|
14
|
+
// An import of types only runs nothing: the type check is the gate that covers it.
|
|
15
|
+
const SPECIFIERS = /(?:^|[\s;])(?:import|export)\b(?!\s+type\b)[^'"]*?\bfrom\s*['"]([^'"]+)['"]|(?:^|[\s;])import\s*['"]([^'"]+)['"]/g;
|
|
16
|
+
// A relative specifier, resolved as Node would among the files of the repo, with the TypeScript file an import of
|
|
17
|
+
// its .js output names.
|
|
18
|
+
function resolveImport(files, from, specifier) {
|
|
19
|
+
if (!specifier.startsWith("."))
|
|
20
|
+
return undefined;
|
|
21
|
+
const base = resolve(dirname(from), specifier);
|
|
22
|
+
const candidates = [
|
|
23
|
+
base,
|
|
24
|
+
...EXTENSIONS.map((extension) => base + extension),
|
|
25
|
+
...(base.endsWith(".js") ? [base.replace(/\.js$/, ".ts")] : []),
|
|
26
|
+
...(base.endsWith(".mjs") ? [base.replace(/\.mjs$/, ".mts")] : []),
|
|
27
|
+
...EXTENSIONS.map((extension) => join(base, `index${extension}`)),
|
|
28
|
+
];
|
|
29
|
+
return candidates.find((candidate) => files.has(candidate));
|
|
30
|
+
}
|
|
31
|
+
function importsOf(files, file) {
|
|
32
|
+
let text;
|
|
33
|
+
try {
|
|
34
|
+
text = readFileSync(file, "utf8");
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
return [];
|
|
38
|
+
}
|
|
39
|
+
return [...text.matchAll(SPECIFIERS)].flatMap(([, named, bare]) => {
|
|
40
|
+
const resolved = resolveImport(files, file, named ?? bare ?? "");
|
|
41
|
+
return resolved === undefined ? [] : [resolved];
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* For each test file of the repo, by the given naming, the changed files it imports, directly or not. A changed test
|
|
46
|
+
* file reaches itself.
|
|
47
|
+
*/
|
|
48
|
+
function reachedBy(root, changed, tests) {
|
|
49
|
+
const files = listFiles(root);
|
|
50
|
+
const known = new Set(files.map((file) => resolve(root, file)));
|
|
51
|
+
const changedByPath = new Map(changed.map((file) => [resolve(root, file), file]));
|
|
52
|
+
const imports = new Map();
|
|
53
|
+
const walk = (file, seen, reached) => {
|
|
54
|
+
if (seen.has(file))
|
|
55
|
+
return;
|
|
56
|
+
seen.add(file);
|
|
57
|
+
const name = changedByPath.get(file);
|
|
58
|
+
if (name !== undefined)
|
|
59
|
+
reached.add(name);
|
|
60
|
+
if (!imports.has(file))
|
|
61
|
+
imports.set(file, importsOf(known, file));
|
|
62
|
+
for (const imported of imports.get(file) ?? [])
|
|
63
|
+
walk(imported, seen, reached);
|
|
64
|
+
};
|
|
65
|
+
return new Map(files
|
|
66
|
+
.filter((file) => tests.test(file))
|
|
67
|
+
.map((file) => {
|
|
68
|
+
const reached = new Set();
|
|
69
|
+
walk(resolve(root, file), new Set(), reached);
|
|
70
|
+
return [file, reached];
|
|
71
|
+
}));
|
|
72
|
+
}
|
|
73
|
+
// The tests that reach a changed file, in order.
|
|
74
|
+
function testsReaching(reached) {
|
|
75
|
+
return [...reached]
|
|
76
|
+
.filter(([, files]) => files.size)
|
|
77
|
+
.map(([test]) => test)
|
|
78
|
+
.sort();
|
|
79
|
+
}
|
|
80
|
+
/** The test files of the repo, by the given naming, that import one of the changed files, directly or not. */
|
|
81
|
+
export function relatedTests(root, changed, tests) {
|
|
82
|
+
return testsReaching(reachedBy(root, changed, tests));
|
|
83
|
+
}
|
|
84
|
+
function main(args) {
|
|
85
|
+
const option = args.indexOf("--tests");
|
|
86
|
+
const tests = option === -1 ? NODE_TESTS : new RegExp(args[option + 1] ?? "");
|
|
87
|
+
const rest = option === -1 ? args : [...args.slice(0, option), ...args.slice(option + 2)];
|
|
88
|
+
const requireTests = rest.includes(REQUIRE_TESTS);
|
|
89
|
+
const changed = rest.filter((arg) => arg !== REQUIRE_TESTS);
|
|
90
|
+
const reached = reachedBy(process.cwd(), changed, tests);
|
|
91
|
+
const tested = new Set([...reached.values()].flatMap((files) => [...files]));
|
|
92
|
+
const untested = requireTests ? changed.filter((file) => !tested.has(file)) : [];
|
|
93
|
+
for (const file of untested)
|
|
94
|
+
console.log(`No test reaches ${file}: write one that imports it.`);
|
|
95
|
+
if (untested.length)
|
|
96
|
+
process.exitCode = 1;
|
|
97
|
+
const related = testsReaching(reached);
|
|
98
|
+
if (!related.length)
|
|
99
|
+
return;
|
|
100
|
+
// Run as a test runner of its own, even from inside another node --test, as the tests of this engine do.
|
|
101
|
+
const { NODE_TEST_CONTEXT: _nested, ...env } = process.env;
|
|
102
|
+
// Beside this file, with its extension: .ts in the repo, .js in the npm package.
|
|
103
|
+
const reporter = pathToFileURL(join(import.meta.dirname, `test-reporter${extname(import.meta.filename)}`)).href;
|
|
104
|
+
const run = spawnSync(process.execPath, ["--test", `--test-reporter=${reporter}`, "--test-reporter-destination=stdout", ...related], { stdio: "inherit", env });
|
|
105
|
+
if (run.status !== 0)
|
|
106
|
+
process.exitCode = run.status ?? 1;
|
|
107
|
+
}
|
|
108
|
+
if (import.meta.main)
|
|
109
|
+
main(process.argv.slice(2));
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { relative } from "node:path";
|
|
2
|
+
// The frames of Node itself, and what it prints around an exception nothing caught.
|
|
3
|
+
const NOISE = /^(\s+at .*\((node:|<anonymous>)|\s+at node:|node:internal\/|\s+triggerUncaughtException\(| code: '|\}$|Node\.js v\d)/;
|
|
4
|
+
function cleaned(text) {
|
|
5
|
+
const lines = text.split("\n");
|
|
6
|
+
// The caret under triggerUncaughtException, and the blank line after it.
|
|
7
|
+
if (lines[0]?.startsWith("node:internal/"))
|
|
8
|
+
lines.splice(0, 4);
|
|
9
|
+
const cwd = process.cwd();
|
|
10
|
+
return lines
|
|
11
|
+
.filter((line) => !NOISE.test(line))
|
|
12
|
+
.map((line) => line.split(`file://${cwd}/`).join("").split(`${cwd}/`).join(""))
|
|
13
|
+
.join("\n")
|
|
14
|
+
.trimEnd();
|
|
15
|
+
}
|
|
16
|
+
function traceOf(error) {
|
|
17
|
+
const { cause } = error;
|
|
18
|
+
return cleaned(cause instanceof Error ? (cause.stack ?? cause.message) : String(cause ?? error.message));
|
|
19
|
+
}
|
|
20
|
+
/** Prints each distinct failure once, with the tests it hit, then the counts. */
|
|
21
|
+
export default async function* report(source) {
|
|
22
|
+
const stderr = new Map();
|
|
23
|
+
const names = new Map();
|
|
24
|
+
const hits = new Map();
|
|
25
|
+
let counts = "";
|
|
26
|
+
const hit = (trace, label) => hits.set(trace, [...(hits.get(trace) ?? []), label]);
|
|
27
|
+
for await (const { type, data } of source) {
|
|
28
|
+
const file = data.file === undefined ? data.name : relative(process.cwd(), data.file);
|
|
29
|
+
if (type === "test:stderr") {
|
|
30
|
+
stderr.set(file, (stderr.get(file) ?? "") + (data.message ?? ""));
|
|
31
|
+
}
|
|
32
|
+
else if (type === "test:start") {
|
|
33
|
+
const path = names.get(file) ?? [];
|
|
34
|
+
path.length = data.nesting;
|
|
35
|
+
path.push(data.name);
|
|
36
|
+
names.set(file, path);
|
|
37
|
+
}
|
|
38
|
+
else if (type === "test:fail") {
|
|
39
|
+
const error = data.details?.error;
|
|
40
|
+
if (error === undefined || error.failureType === "subtestsFailed")
|
|
41
|
+
continue;
|
|
42
|
+
// A file that could not run: its error went to stderr, with nothing in the failure.
|
|
43
|
+
if (data.nesting === 0 && data.name === file && !(error.cause instanceof Error)) {
|
|
44
|
+
hit(cleaned(stderr.get(file) ?? error.message), file);
|
|
45
|
+
}
|
|
46
|
+
else {
|
|
47
|
+
hit(traceOf(error), `${file}: ${(names.get(file) ?? []).slice(0, data.nesting + 1).join(" > ")}`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
else if (type === "test:summary" && data.counts) {
|
|
51
|
+
counts = `${data.counts.tests} tests, ${data.counts.failed} failed`;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
for (const [trace, labels] of hits)
|
|
55
|
+
yield `✖ ${labels.join(", ")}\n${trace}\n\n`;
|
|
56
|
+
yield `${counts}\n`;
|
|
57
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Claude Code's MessageDisplay hook, run on each batch of lines of a reply as it streams: it shows the batch without
|
|
2
|
+
// its waive lines, which Claude Code would print raw. Display only: the stored message, the one the stop reads, keeps
|
|
3
|
+
// them. A batch with no waive line gets no answer, so the hook never takes the place of another display hook there.
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
import { isRecord, parseJson } from "../core/json.js";
|
|
6
|
+
import { hideWaives } from "../core/waive-line.js";
|
|
7
|
+
/** What the hook prints for a batch: the batch without its waive lines, or nothing when it holds none. */
|
|
8
|
+
export function displayOf(input) {
|
|
9
|
+
const payload = parseJson(input);
|
|
10
|
+
if (!isRecord(payload) || typeof payload.delta !== "string")
|
|
11
|
+
return undefined;
|
|
12
|
+
const shown = hideWaives(payload.delta);
|
|
13
|
+
if (shown === payload.delta)
|
|
14
|
+
return undefined;
|
|
15
|
+
// An empty displayContent is the protocol's own way to show nothing for the batch.
|
|
16
|
+
return JSON.stringify({ hookSpecificOutput: { hookEventName: "MessageDisplay", displayContent: shown } });
|
|
17
|
+
}
|
|
18
|
+
if (import.meta.main) {
|
|
19
|
+
const output = displayOf(readFileSync(0, "utf8"));
|
|
20
|
+
if (output)
|
|
21
|
+
console.log(output);
|
|
22
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { checkTurn, startTurn } from "../core/check.js";
|
|
2
|
+
import { configuredRoot, gatesOf } from "../core/config.js";
|
|
3
|
+
import { isRecord, messageOf, parseJson } from "../core/json.js";
|
|
4
|
+
import { broken, failures, summary, toolsMissing, toolsToInstall } from "../core/report.js";
|
|
5
|
+
import { judge, waivesOf } from "../core/send-back.js";
|
|
6
|
+
import { forgetTold, forgetTurn, readTurn, tellOnce, turnRoot, writeTurn } from "../core/turn-state.js";
|
|
7
|
+
export function parseHookInput(text) {
|
|
8
|
+
const input = parseJson(text);
|
|
9
|
+
if (!isRecord(input))
|
|
10
|
+
return {};
|
|
11
|
+
const { session_id, stop_hook_active, cwd, source, last_assistant_message } = input;
|
|
12
|
+
return {
|
|
13
|
+
...(typeof session_id === "string" ? { session_id } : {}),
|
|
14
|
+
...(typeof stop_hook_active === "boolean" ? { stop_hook_active } : {}),
|
|
15
|
+
...(typeof cwd === "string" ? { cwd } : {}),
|
|
16
|
+
...(typeof source === "string" ? { source } : {}),
|
|
17
|
+
...(typeof last_assistant_message === "string" ? { last_assistant_message } : {}),
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
function sendBacks(count) {
|
|
21
|
+
return count === 1 ? "1 send-back" : `${count} send-backs`;
|
|
22
|
+
}
|
|
23
|
+
// How the stop ends, after the totals: sent back, stopped by the cap, or handed back once the agent was sent back.
|
|
24
|
+
function ending({ sendBack, count, max, open }) {
|
|
25
|
+
if (sendBack)
|
|
26
|
+
return `the agent is sent back to fix it (${count} of ${max})`;
|
|
27
|
+
if (open.length)
|
|
28
|
+
return max === 0 ? "send-backs are off" : `stopped after ${sendBacks(count)}`;
|
|
29
|
+
return count ? `after ${sendBacks(count)}` : "";
|
|
30
|
+
}
|
|
31
|
+
// What the agent is told besides the reports: where it stands, and what became of its waive lines.
|
|
32
|
+
function told({ count, max, waived, fallen, unknown, gates }) {
|
|
33
|
+
const names = (list) => list.join(", ");
|
|
34
|
+
return [
|
|
35
|
+
`This is send-back ${count} of ${max}.`,
|
|
36
|
+
...(waived.length ? [`Waived this turn, not to fix: ${names(waived.map(({ name }) => name))}.`] : []),
|
|
37
|
+
...(fallen.length
|
|
38
|
+
? [`Your waiver of ${names(fallen)} no longer holds: its report changed. Fix it, or waive it again.`]
|
|
39
|
+
: []),
|
|
40
|
+
...(unknown.length ? [`No gate is named ${names(unknown)}. The gates of this turn: ${names(gates)}.`] : []),
|
|
41
|
+
];
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* A red gate the agent did not waive sends it back with the reports, until the turn reaches its cap: a fix that
|
|
45
|
+
* breaks another gate is caught, and a gate the agent cannot satisfy never loops. The owner sees each stop, the
|
|
46
|
+
* waived gates with their reasons, and why the turn ended.
|
|
47
|
+
*/
|
|
48
|
+
export function stopOutput(turn, judged) {
|
|
49
|
+
const systemMessage = summary(turn, ending(judged), judged.waived);
|
|
50
|
+
if (!judged.sendBack)
|
|
51
|
+
return { systemMessage };
|
|
52
|
+
return { decision: "block", reason: failures({ ...turn, outcomes: judged.open }, told(judged)), systemMessage };
|
|
53
|
+
}
|
|
54
|
+
// When the gates cannot run, such as with a gates file that does not parse, only the owner is told: a crash would
|
|
55
|
+
// show them a stack trace at best, and the agent is not to blame.
|
|
56
|
+
function cannotRun(error) {
|
|
57
|
+
return { systemMessage: broken(messageOf(error)) };
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* A prompt ends the turn in progress; from a folder with no gates, or when the turn cannot start, no check will look
|
|
61
|
+
* for a new one. When the gates of the repo miss tools, the agent is asked once to install them.
|
|
62
|
+
*/
|
|
63
|
+
async function promptHook(session, cwd) {
|
|
64
|
+
try {
|
|
65
|
+
forgetTurn(session);
|
|
66
|
+
const root = configuredRoot(cwd);
|
|
67
|
+
if (root === undefined)
|
|
68
|
+
return undefined;
|
|
69
|
+
const missing = await startTurn(session, root);
|
|
70
|
+
if (!tellOnce(session, root, missing))
|
|
71
|
+
return undefined;
|
|
72
|
+
return {
|
|
73
|
+
systemMessage: toolsMissing(missing),
|
|
74
|
+
hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: toolsToInstall(missing) },
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
return cannotRun(error);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* A stop checks the repo its turn started in, whatever folder the agent stops in, or that folder's repo otherwise,
|
|
83
|
+
* reads the gates the agent's last message waives, and records what it told the agent for the next stop of the turn.
|
|
84
|
+
*/
|
|
85
|
+
async function stopHook(session, cwd, retry, message) {
|
|
86
|
+
const root = turnRoot(session, retry) ?? configuredRoot(cwd);
|
|
87
|
+
if (root === undefined)
|
|
88
|
+
return undefined;
|
|
89
|
+
try {
|
|
90
|
+
const checked = await checkTurn(session, root);
|
|
91
|
+
const turn = readTurn(session, root);
|
|
92
|
+
if (turn === undefined)
|
|
93
|
+
throw new Error("the turn was not recorded after its check.");
|
|
94
|
+
const { gates, refused, maxSendBacks } = gatesOf(turn.config);
|
|
95
|
+
const names = [...gates.map(({ name }) => name), ...refused.map(({ name }) => name)];
|
|
96
|
+
const judged = judge(checked, waivesOf(message), names, maxSendBacks, turn.sendBacks);
|
|
97
|
+
writeTurn(session, root, { ...turn, sendBacks: judged.state });
|
|
98
|
+
return stopOutput(checked, judged);
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
return cannotRun(error);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Handles a hook event of a coding agent: Claude Code and Codex send the same input and read the same output. It does
|
|
106
|
+
* nothing outside git, or in a repo with no gates file.
|
|
107
|
+
*/
|
|
108
|
+
export async function handleHook(event, text) {
|
|
109
|
+
const { session_id: session, stop_hook_active: retry = false, cwd = process.cwd(), source, last_assistant_message: message = "", } = parseHookInput(text);
|
|
110
|
+
if (session === undefined)
|
|
111
|
+
return undefined;
|
|
112
|
+
// A session that starts, resumes or is cleared asks again for the missing tools; a compaction goes on as it was.
|
|
113
|
+
if (event === "session-start") {
|
|
114
|
+
if (source !== "compact")
|
|
115
|
+
forgetTold(session);
|
|
116
|
+
return undefined;
|
|
117
|
+
}
|
|
118
|
+
return event === "turn-start" ? promptHook(session, cwd) : stopHook(session, cwd, retry, message);
|
|
119
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"description": "Claude Code alone: hide the waive lines Claude Code would print raw, which Codex hides itself",
|
|
3
|
+
"modules": ["./register.ts"],
|
|
4
|
+
"hooks": {
|
|
5
|
+
"MessageDisplay": [
|
|
6
|
+
{
|
|
7
|
+
"hooks": [
|
|
8
|
+
{
|
|
9
|
+
"type": "command",
|
|
10
|
+
"command": "node \"${CLAUDE_PLUGIN_ROOT}/src/hook/display.ts\"",
|
|
11
|
+
"timeout": 5
|
|
12
|
+
}
|
|
13
|
+
]
|
|
14
|
+
}
|
|
15
|
+
]
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// The Claude Code mod of the plugin: it draws each reply without its waive lines, a resumed session's included, which
|
|
2
|
+
// the MessageDisplay hook never sees again. The rest of the chain, a mod that draws views among it, gets the text
|
|
3
|
+
// already clean. Display only: the stored message, the one the stop reads, keeps them.
|
|
4
|
+
import type { Register } from "claude-code";
|
|
5
|
+
import { hideWaives } from "../src/core/waive-line.ts";
|
|
6
|
+
|
|
7
|
+
export const register: Register = (on) => {
|
|
8
|
+
on("ui.render", { component: "AssistantMessage" }, ($, e, next) => {
|
|
9
|
+
const text = hideWaives(e.props.text);
|
|
10
|
+
return text === e.props.text ? next(e) : next({ ...e, props: { ...e.props, text } });
|
|
11
|
+
});
|
|
12
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tayomi/deterministic-gates",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.2",
|
|
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",
|
|
@@ -8,7 +8,10 @@
|
|
|
8
8
|
"name": "Pierre Moati",
|
|
9
9
|
"url": "https://github.com/mopi1402"
|
|
10
10
|
},
|
|
11
|
-
"repository":
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "git+https://github.com/mopi1402/tayomi-deterministic-gates.git"
|
|
14
|
+
},
|
|
12
15
|
"keywords": [
|
|
13
16
|
"coding-agents",
|
|
14
17
|
"quality-gates",
|
|
@@ -25,12 +28,14 @@
|
|
|
25
28
|
".claude-plugin",
|
|
26
29
|
".codex-plugin",
|
|
27
30
|
"catalog",
|
|
31
|
+
"dist",
|
|
28
32
|
"hooks",
|
|
29
33
|
"src",
|
|
30
34
|
"!src/**/*.test.ts"
|
|
31
35
|
],
|
|
32
36
|
"scripts": {
|
|
33
37
|
"catalog": "node src/catalog/catalog.ts",
|
|
38
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
34
39
|
"check": "tsc && prettier --check . && node --test \"src/**/*.test.ts\"",
|
|
35
40
|
"test": "node --test \"src/**/*.test.ts\"",
|
|
36
41
|
"integration": "node --test \"integration/*.test.ts\""
|
|
@@ -41,5 +46,8 @@
|
|
|
41
46
|
"knip": "6.44.1",
|
|
42
47
|
"prettier": "3.9.10",
|
|
43
48
|
"typescript": "6.0.3"
|
|
49
|
+
},
|
|
50
|
+
"bin": {
|
|
51
|
+
"deterministic-gates": "dist/src/cli.js"
|
|
44
52
|
}
|
|
45
53
|
}
|
package/src/cli.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
1
2
|
import { readFileSync } from "node:fs";
|
|
2
3
|
import { checkAll } from "./core/check.ts";
|
|
3
4
|
import { configuredRoot } from "./core/config.ts";
|
|
@@ -14,7 +15,8 @@ function readStdin(): string {
|
|
|
14
15
|
}
|
|
15
16
|
}
|
|
16
17
|
|
|
17
|
-
|
|
18
|
+
/** What the command prints when it is called with words it does not know, named by the bin of the npm package. */
|
|
19
|
+
export const USAGE = "Usage: deterministic-gates check, or deterministic-gates hook <session-start|turn-start|check>";
|
|
18
20
|
|
|
19
21
|
// The helpers of the engine run only on import.meta.main, which came with Node 24.2: below, they are a silent green.
|
|
20
22
|
const [major = 0, minor = 0] = process.versions.node.split(".").map(Number);
|
|
@@ -23,31 +25,37 @@ const oldNode =
|
|
|
23
25
|
? `Node 24.2 or later is needed, this is ${process.versions.node}.`
|
|
24
26
|
: undefined;
|
|
25
27
|
|
|
26
|
-
|
|
27
|
-
if (
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
}
|
|
32
|
-
} else if (command === "hook" && (event === "session-start" || event === "turn-start" || event === "check")) {
|
|
33
|
-
const output = await handleHook(event, readStdin());
|
|
34
|
-
if (output) console.log(JSON.stringify(output));
|
|
35
|
-
} else if (command === "check" && event === undefined) {
|
|
36
|
-
const root = configuredRoot(process.cwd());
|
|
37
|
-
if (root === undefined) {
|
|
38
|
-
console.error("Not in a git repository, or no .gates.json in it.");
|
|
39
|
-
process.exitCode = 2;
|
|
40
|
-
} else {
|
|
41
|
-
try {
|
|
42
|
-
const all = await checkAll(root);
|
|
43
|
-
console.log([summary(all), ...reports(all.outcomes)].join("\n\n"));
|
|
44
|
-
if (all.outcomes.some(failed)) process.exitCode = 1;
|
|
45
|
-
} catch (error) {
|
|
46
|
-
console.error(`Could not run: ${messageOf(error)}`);
|
|
28
|
+
async function main([command, event]: string[]): Promise<void> {
|
|
29
|
+
if (oldNode !== undefined) {
|
|
30
|
+
if (command === "hook") console.log(JSON.stringify({ systemMessage: broken(oldNode) }));
|
|
31
|
+
else {
|
|
32
|
+
console.error(oldNode);
|
|
47
33
|
process.exitCode = 2;
|
|
48
34
|
}
|
|
35
|
+
} else if (command === "hook" && (event === "session-start" || event === "turn-start" || event === "check")) {
|
|
36
|
+
const output = await handleHook(event, readStdin());
|
|
37
|
+
if (output) console.log(JSON.stringify(output));
|
|
38
|
+
} else if (command === "check" && event === undefined) {
|
|
39
|
+
const root = configuredRoot(process.cwd());
|
|
40
|
+
if (root === undefined) {
|
|
41
|
+
console.error("Not in a git repository, or no .gates.json in it.");
|
|
42
|
+
process.exitCode = 2;
|
|
43
|
+
} else {
|
|
44
|
+
try {
|
|
45
|
+
const all = await checkAll(root);
|
|
46
|
+
console.log([summary(all), ...reports(all.outcomes)].join("\n\n"));
|
|
47
|
+
if (all.outcomes.some(failed)) process.exitCode = 1;
|
|
48
|
+
} catch (error) {
|
|
49
|
+
console.error(`Could not run: ${messageOf(error)}`);
|
|
50
|
+
process.exitCode = 2;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
} else {
|
|
54
|
+
console.error(USAGE);
|
|
55
|
+
process.exitCode = 2;
|
|
49
56
|
}
|
|
50
|
-
} else {
|
|
51
|
-
console.error("Usage: node src/cli.ts hook <session-start|turn-start|check>, or node src/cli.ts check");
|
|
52
|
-
process.exitCode = 2;
|
|
53
57
|
}
|
|
58
|
+
|
|
59
|
+
// Run as a program, never as a test imports it. Below Node 24.2, import.meta.main is undefined: the program runs then,
|
|
60
|
+
// to say that Node is too old.
|
|
61
|
+
if (import.meta.main !== false) await main(process.argv.slice(2));
|
package/src/core/report.ts
CHANGED
package/src/core/run.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { execFile, type ExecFileException } from "node:child_process";
|
|
2
|
-
import { accessSync, constants } from "node:fs";
|
|
2
|
+
import { accessSync, constants, existsSync } from "node:fs";
|
|
3
3
|
import { delimiter, isAbsolute, join, resolve, sep } from "node:path";
|
|
4
4
|
import { stripVTControlCharacters } from "node:util";
|
|
5
5
|
import { FILES, type Gate, isCompared, TURN } from "./config.ts";
|
|
@@ -24,6 +24,12 @@ const ENGINE = resolve(import.meta.dirname, "..", "..");
|
|
|
24
24
|
const MAX_OUTPUT_MB = 16;
|
|
25
25
|
const ENGINE_PREFIX = "{engine}/";
|
|
26
26
|
|
|
27
|
+
/** A script of this engine: its .ts source, or the .js it is built to when the engine runs from its npm package. */
|
|
28
|
+
function engineScript(name: string): string {
|
|
29
|
+
const file = resolve(ENGINE, name);
|
|
30
|
+
return file.endsWith(".ts") && !existsSync(file) ? `${file.slice(0, -".ts".length)}.js` : file;
|
|
31
|
+
}
|
|
32
|
+
|
|
27
33
|
/** How a gate's command starts: the program to execute, the arguments before the gate's own, and why it may be missing. */
|
|
28
34
|
export interface Command {
|
|
29
35
|
file: string;
|
|
@@ -56,7 +62,7 @@ export function packageScript(root: string, name: string): string | undefined {
|
|
|
56
62
|
*/
|
|
57
63
|
export function commandOf(root: string, name: string): Command {
|
|
58
64
|
if (name.startsWith(ENGINE_PREFIX)) {
|
|
59
|
-
return { file: process.execPath, args: [
|
|
65
|
+
return { file: process.execPath, args: [engineScript(name.slice(ENGINE_PREFIX.length))], missing: "" };
|
|
60
66
|
}
|
|
61
67
|
const interpreter = INTERPRETERS.find(([extension]) => extension.test(name))?.[1];
|
|
62
68
|
if (interpreter !== undefined) {
|
package/src/core/send-back.ts
CHANGED
|
@@ -2,9 +2,7 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import type { CheckedTurn } from "./check.ts";
|
|
3
3
|
import { failed, type Outcome } from "./run.ts";
|
|
4
4
|
import type { SendBacks, Waiver } from "./turn-state.ts";
|
|
5
|
-
|
|
6
|
-
/** The tag that opens a waive line: the plugin's name, so a mod can hide the line without hiding anything else. */
|
|
7
|
-
export const WAIVE_TAG = "deterministic-gates";
|
|
5
|
+
import { waiveLines } from "./waive-line.ts";
|
|
8
6
|
|
|
9
7
|
/** A gate the agent's last message waives, with why. */
|
|
10
8
|
export interface Said {
|
|
@@ -12,16 +10,9 @@ export interface Said {
|
|
|
12
10
|
reason: string;
|
|
13
11
|
}
|
|
14
12
|
|
|
15
|
-
// A markdown link reference definition, which Codex hides: [deterministic-gates:<gate>]: waive "<reason>". The
|
|
16
|
-
// reason may also sit between single quotes or parentheses, as a link title may.
|
|
17
|
-
const WAIVE_LINE = new RegExp(
|
|
18
|
-
`^ {0,3}\\[${WAIVE_TAG}:([^\\]\\s]+)\\]:[ \\t]*waive[ \\t]+(?:"([^"]*)"|'([^']*)'|\\(([^)]*)\\))[ \\t]*$`,
|
|
19
|
-
"gm",
|
|
20
|
-
);
|
|
21
|
-
|
|
22
13
|
/** The gates the agent's last message waives, in order: a later line for the same gate wins. */
|
|
23
14
|
export function waivesOf(message: string): Said[] {
|
|
24
|
-
return [...message.matchAll(
|
|
15
|
+
return [...message.matchAll(waiveLines())].map(([, gate = "", ...titles]) => ({
|
|
25
16
|
gate,
|
|
26
17
|
reason: (titles.find((title) => title !== undefined) ?? "").trim(),
|
|
27
18
|
}));
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// The waive line on its own, with no import: the engine reads it, and the display hooks of Claude Code hide it, the mod
|
|
2
|
+
// among them, which runs with no Node.
|
|
3
|
+
|
|
4
|
+
/** The tag that opens a waive line: the plugin's name, so the display can hide the line without hiding anything else. */
|
|
5
|
+
export const WAIVE_TAG = "deterministic-gates";
|
|
6
|
+
|
|
7
|
+
// A markdown link reference definition, which Codex hides: [deterministic-gates:<gate>]: waive "<reason>". The
|
|
8
|
+
// reason may also sit between single quotes or parentheses, as a link title may.
|
|
9
|
+
const WAIVE_SOURCE = `^ {0,3}\\[${WAIVE_TAG}:([^\\]\\s]+)\\]:[ \\t]*waive[ \\t]+(?:"([^"]*)"|'([^']*)'|\\(([^)]*)\\))[ \\t]*$`;
|
|
10
|
+
|
|
11
|
+
/** Every waive line of a text, its gate and its reason captured. */
|
|
12
|
+
export function waiveLines(): RegExp {
|
|
13
|
+
return new RegExp(WAIVE_SOURCE, "gm");
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** The text with its waive lines taken out, line ending included; the same text when it holds none. */
|
|
17
|
+
export function hideWaives(text: string): string {
|
|
18
|
+
return text.replace(new RegExp(`${WAIVE_SOURCE}\\r?\\n?`, "gm"), "");
|
|
19
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
2
|
import { readFileSync } from "node:fs";
|
|
3
|
-
import { dirname, join, resolve } from "node:path";
|
|
3
|
+
import { dirname, extname, join, resolve } from "node:path";
|
|
4
4
|
import { pathToFileURL } from "node:url";
|
|
5
5
|
import { listFiles } from "../core/snapshot.ts";
|
|
6
6
|
|
|
@@ -106,7 +106,8 @@ function main(args: string[]): void {
|
|
|
106
106
|
if (!related.length) return;
|
|
107
107
|
// Run as a test runner of its own, even from inside another node --test, as the tests of this engine do.
|
|
108
108
|
const { NODE_TEST_CONTEXT: _nested, ...env } = process.env;
|
|
109
|
-
|
|
109
|
+
// Beside this file, with its extension: .ts in the repo, .js in the npm package.
|
|
110
|
+
const reporter = pathToFileURL(join(import.meta.dirname, `test-reporter${extname(import.meta.filename)}`)).href;
|
|
110
111
|
const run = spawnSync(
|
|
111
112
|
process.execPath,
|
|
112
113
|
["--test", `--test-reporter=${reporter}`, "--test-reporter-destination=stdout", ...related],
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// Claude Code's MessageDisplay hook, run on each batch of lines of a reply as it streams: it shows the batch without
|
|
2
|
+
// its waive lines, which Claude Code would print raw. Display only: the stored message, the one the stop reads, keeps
|
|
3
|
+
// them. A batch with no waive line gets no answer, so the hook never takes the place of another display hook there.
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
import { isRecord, parseJson } from "../core/json.ts";
|
|
6
|
+
import { hideWaives } from "../core/waive-line.ts";
|
|
7
|
+
|
|
8
|
+
/** What the hook prints for a batch: the batch without its waive lines, or nothing when it holds none. */
|
|
9
|
+
export function displayOf(input: string): string | undefined {
|
|
10
|
+
const payload = parseJson(input);
|
|
11
|
+
if (!isRecord(payload) || typeof payload.delta !== "string") return undefined;
|
|
12
|
+
const shown = hideWaives(payload.delta);
|
|
13
|
+
if (shown === payload.delta) return undefined;
|
|
14
|
+
// An empty displayContent is the protocol's own way to show nothing for the batch.
|
|
15
|
+
return JSON.stringify({ hookSpecificOutput: { hookEventName: "MessageDisplay", displayContent: shown } });
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
if (import.meta.main) {
|
|
19
|
+
const output = displayOf(readFileSync(0, "utf8"));
|
|
20
|
+
if (output) console.log(output);
|
|
21
|
+
}
|