@tayomi/deterministic-gates 0.0.0-stage → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/.claude-plugin/marketplace.json +15 -0
  2. package/.claude-plugin/plugin.json +14 -0
  3. package/.codex-plugin/plugin.json +20 -0
  4. package/LICENSE +21 -0
  5. package/README.md +111 -2
  6. package/catalog/go.json +92 -0
  7. package/catalog/index.html +398 -0
  8. package/catalog/python.json +46 -0
  9. package/catalog/typescript.json +125 -0
  10. package/dist/src/cli.js +65 -0
  11. package/dist/src/core/check.js +157 -0
  12. package/dist/src/core/config.js +180 -0
  13. package/dist/src/core/json.js +32 -0
  14. package/dist/src/core/report-cache.js +35 -0
  15. package/dist/src/core/report.js +127 -0
  16. package/dist/src/core/run.js +172 -0
  17. package/dist/src/core/send-back.js +53 -0
  18. package/dist/src/core/snapshot.js +94 -0
  19. package/dist/src/core/turn-state.js +93 -0
  20. package/dist/src/core/waive-line.js +15 -0
  21. package/dist/src/helpers/new-clones.js +57 -0
  22. package/dist/src/helpers/new-suppressions.js +31 -0
  23. package/dist/src/helpers/related-tests.js +109 -0
  24. package/dist/src/helpers/test-reporter.js +57 -0
  25. package/dist/src/hook/display.js +22 -0
  26. package/dist/src/hook/hook.js +119 -0
  27. package/hooks/claude.json +17 -0
  28. package/hooks/hooks.json +38 -0
  29. package/hooks/register.ts +12 -0
  30. package/package.json +51 -4
  31. package/src/catalog/catalog.ts +168 -0
  32. package/src/cli.ts +61 -0
  33. package/src/core/check.ts +209 -0
  34. package/src/core/config.ts +225 -0
  35. package/src/core/json.ts +36 -0
  36. package/src/core/report-cache.ts +51 -0
  37. package/src/core/report.ts +159 -0
  38. package/src/core/run.ts +217 -0
  39. package/src/core/send-back.ts +87 -0
  40. package/src/core/snapshot.ts +105 -0
  41. package/src/core/turn-state.ts +153 -0
  42. package/src/core/waive-line.ts +19 -0
  43. package/src/helpers/new-clones.ts +58 -0
  44. package/src/helpers/new-suppressions.ts +44 -0
  45. package/src/helpers/related-tests.ts +119 -0
  46. package/src/helpers/test-reporter.ts +71 -0
  47. package/src/hook/display.ts +21 -0
  48. package/src/hook/hook.ts +144 -0
  49. package/src/testing.ts +39 -0
@@ -0,0 +1,119 @@
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.ts";
6
+
7
+ // The node:test tests that a change can break: those that import a changed file, directly or through other files.
8
+ // Node has no "related" mode of its own, where Vitest has one.
9
+
10
+ const EXTENSIONS = [".ts", ".mts", ".cts", ".js", ".mjs", ".cjs"];
11
+ const EXTENSION = `\\.(${EXTENSIONS.map((extension) => extension.slice(1)).join("|")})`;
12
+
13
+ /** Node's own naming of test files, the TypeScript ones included. */
14
+ const NODE_TESTS = new RegExp(
15
+ `(\\.test|[-_]test|^test|/test)${EXTENSION}$|/test/.*${EXTENSION}$|(^|/)test-[^/]*${EXTENSION}$`,
16
+ );
17
+
18
+ /** Fails on a changed file no test reaches, which the related tests alone pass in silence. */
19
+ const REQUIRE_TESTS = "--require-tests";
20
+
21
+ // An import of types only runs nothing: the type check is the gate that covers it.
22
+ const SPECIFIERS =
23
+ /(?:^|[\s;])(?:import|export)\b(?!\s+type\b)[^'"]*?\bfrom\s*['"]([^'"]+)['"]|(?:^|[\s;])import\s*['"]([^'"]+)['"]/g;
24
+
25
+ // A relative specifier, resolved as Node would among the files of the repo, with the TypeScript file an import of
26
+ // its .js output names.
27
+ function resolveImport(files: Set<string>, from: string, specifier: string): string | undefined {
28
+ if (!specifier.startsWith(".")) return undefined;
29
+ const base = resolve(dirname(from), specifier);
30
+ const candidates = [
31
+ base,
32
+ ...EXTENSIONS.map((extension) => base + extension),
33
+ ...(base.endsWith(".js") ? [base.replace(/\.js$/, ".ts")] : []),
34
+ ...(base.endsWith(".mjs") ? [base.replace(/\.mjs$/, ".mts")] : []),
35
+ ...EXTENSIONS.map((extension) => join(base, `index${extension}`)),
36
+ ];
37
+ return candidates.find((candidate) => files.has(candidate));
38
+ }
39
+
40
+ function importsOf(files: Set<string>, file: string): string[] {
41
+ let text: string;
42
+ try {
43
+ text = readFileSync(file, "utf8");
44
+ } catch {
45
+ return [];
46
+ }
47
+ return [...text.matchAll(SPECIFIERS)].flatMap(([, named, bare]) => {
48
+ const resolved = resolveImport(files, file, named ?? bare ?? "");
49
+ return resolved === undefined ? [] : [resolved];
50
+ });
51
+ }
52
+
53
+ /**
54
+ * For each test file of the repo, by the given naming, the changed files it imports, directly or not. A changed test
55
+ * file reaches itself.
56
+ */
57
+ function reachedBy(root: string, changed: string[], tests: RegExp): Map<string, Set<string>> {
58
+ const files = listFiles(root);
59
+ const known = new Set(files.map((file) => resolve(root, file)));
60
+ const changedByPath = new Map(changed.map((file) => [resolve(root, file), file]));
61
+ const imports = new Map<string, string[]>();
62
+ const walk = (file: string, seen: Set<string>, reached: Set<string>): void => {
63
+ if (seen.has(file)) return;
64
+ seen.add(file);
65
+ const name = changedByPath.get(file);
66
+ if (name !== undefined) reached.add(name);
67
+ if (!imports.has(file)) imports.set(file, importsOf(known, file));
68
+ for (const imported of imports.get(file) ?? []) walk(imported, seen, reached);
69
+ };
70
+ return new Map(
71
+ files
72
+ .filter((file) => tests.test(file))
73
+ .map((file) => {
74
+ const reached = new Set<string>();
75
+ walk(resolve(root, file), new Set(), reached);
76
+ return [file, reached] as const;
77
+ }),
78
+ );
79
+ }
80
+
81
+ // The tests that reach a changed file, in order.
82
+ function testsReaching(reached: Map<string, Set<string>>): string[] {
83
+ return [...reached]
84
+ .filter(([, files]) => files.size)
85
+ .map(([test]) => test)
86
+ .sort();
87
+ }
88
+
89
+ /** The test files of the repo, by the given naming, that import one of the changed files, directly or not. */
90
+ export function relatedTests(root: string, changed: string[], tests: RegExp): string[] {
91
+ return testsReaching(reachedBy(root, changed, tests));
92
+ }
93
+
94
+ function main(args: string[]): void {
95
+ const option = args.indexOf("--tests");
96
+ const tests = option === -1 ? NODE_TESTS : new RegExp(args[option + 1] ?? "");
97
+ const rest = option === -1 ? args : [...args.slice(0, option), ...args.slice(option + 2)];
98
+ const requireTests = rest.includes(REQUIRE_TESTS);
99
+ const changed = rest.filter((arg) => arg !== REQUIRE_TESTS);
100
+ const reached = reachedBy(process.cwd(), changed, tests);
101
+ const tested = new Set([...reached.values()].flatMap((files) => [...files]));
102
+ const untested = requireTests ? changed.filter((file) => !tested.has(file)) : [];
103
+ for (const file of untested) console.log(`No test reaches ${file}: write one that imports it.`);
104
+ if (untested.length) process.exitCode = 1;
105
+ const related = testsReaching(reached);
106
+ if (!related.length) return;
107
+ // Run as a test runner of its own, even from inside another node --test, as the tests of this engine do.
108
+ const { NODE_TEST_CONTEXT: _nested, ...env } = process.env;
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;
111
+ const run = spawnSync(
112
+ process.execPath,
113
+ ["--test", `--test-reporter=${reporter}`, "--test-reporter-destination=stdout", ...related],
114
+ { stdio: "inherit", env },
115
+ );
116
+ if (run.status !== 0) process.exitCode = run.status ?? 1;
117
+ }
118
+
119
+ if (import.meta.main) main(process.argv.slice(2));
@@ -0,0 +1,71 @@
1
+ import { relative } from "node:path";
2
+
3
+ // The reporter of the related tests: one trace per distinct failure, with every test it hit, where Node's own
4
+ // reporters print the same trace once per test file. A module that does not compile fails every test file that
5
+ // imports it, with the same error each time.
6
+
7
+ interface TestEvent {
8
+ type: string;
9
+ data: {
10
+ name: string;
11
+ nesting: number;
12
+ file?: string;
13
+ message?: string;
14
+ details?: { error?: Error & { failureType?: string; cause?: unknown } };
15
+ counts?: { tests: number; failed: number };
16
+ };
17
+ }
18
+
19
+ // The frames of Node itself, and what it prints around an exception nothing caught.
20
+ const NOISE =
21
+ /^(\s+at .*\((node:|<anonymous>)|\s+at node:|node:internal\/|\s+triggerUncaughtException\(| code: '|\}$|Node\.js v\d)/;
22
+
23
+ function cleaned(text: string): string {
24
+ const lines = text.split("\n");
25
+ // The caret under triggerUncaughtException, and the blank line after it.
26
+ if (lines[0]?.startsWith("node:internal/")) lines.splice(0, 4);
27
+ const cwd = process.cwd();
28
+ return lines
29
+ .filter((line) => !NOISE.test(line))
30
+ .map((line) => line.split(`file://${cwd}/`).join("").split(`${cwd}/`).join(""))
31
+ .join("\n")
32
+ .trimEnd();
33
+ }
34
+
35
+ function traceOf(error: Error & { cause?: unknown }): string {
36
+ const { cause } = error;
37
+ return cleaned(cause instanceof Error ? (cause.stack ?? cause.message) : String(cause ?? error.message));
38
+ }
39
+
40
+ /** Prints each distinct failure once, with the tests it hit, then the counts. */
41
+ export default async function* report(source: AsyncIterable<TestEvent>): AsyncGenerator<string> {
42
+ const stderr = new Map<string, string>();
43
+ const names = new Map<string, string[]>();
44
+ const hits = new Map<string, string[]>();
45
+ let counts = "";
46
+ const hit = (trace: string, label: string) => hits.set(trace, [...(hits.get(trace) ?? []), label]);
47
+ for await (const { type, data } of source) {
48
+ const file = data.file === undefined ? data.name : relative(process.cwd(), data.file);
49
+ if (type === "test:stderr") {
50
+ stderr.set(file, (stderr.get(file) ?? "") + (data.message ?? ""));
51
+ } else if (type === "test:start") {
52
+ const path = names.get(file) ?? [];
53
+ path.length = data.nesting;
54
+ path.push(data.name);
55
+ names.set(file, path);
56
+ } else if (type === "test:fail") {
57
+ const error = data.details?.error;
58
+ if (error === undefined || error.failureType === "subtestsFailed") continue;
59
+ // A file that could not run: its error went to stderr, with nothing in the failure.
60
+ if (data.nesting === 0 && data.name === file && !(error.cause instanceof Error)) {
61
+ hit(cleaned(stderr.get(file) ?? error.message), file);
62
+ } else {
63
+ hit(traceOf(error), `${file}: ${(names.get(file) ?? []).slice(0, data.nesting + 1).join(" > ")}`);
64
+ }
65
+ } else if (type === "test:summary" && data.counts) {
66
+ counts = `${data.counts.tests} tests, ${data.counts.failed} failed`;
67
+ }
68
+ }
69
+ for (const [trace, labels] of hits) yield `✖ ${labels.join(", ")}\n${trace}\n\n`;
70
+ yield `${counts}\n`;
71
+ }
@@ -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
+ }
@@ -0,0 +1,144 @@
1
+ import { type CheckedTurn, checkTurn, startTurn } from "../core/check.ts";
2
+ import { configuredRoot, gatesOf } from "../core/config.ts";
3
+ import { isRecord, messageOf, parseJson } from "../core/json.ts";
4
+ import { broken, failures, summary, toolsMissing, toolsToInstall } from "../core/report.ts";
5
+ import { type Judged, judge, waivesOf } from "../core/send-back.ts";
6
+ import { forgetTold, forgetTurn, readTurn, tellOnce, turnRoot, writeTurn } from "../core/turn-state.ts";
7
+
8
+ export interface HookInput {
9
+ session_id?: string;
10
+ stop_hook_active?: boolean;
11
+ cwd?: string;
12
+ source?: string;
13
+ last_assistant_message?: string;
14
+ }
15
+
16
+ export interface HookOutput {
17
+ decision?: "block";
18
+ reason?: string;
19
+ systemMessage: string;
20
+ hookSpecificOutput?: { hookEventName: "UserPromptSubmit"; additionalContext: string };
21
+ }
22
+
23
+ export type HookEvent = "session-start" | "turn-start" | "check";
24
+
25
+ export function parseHookInput(text: string): HookInput {
26
+ const input = parseJson(text);
27
+ if (!isRecord(input)) return {};
28
+ const { session_id, stop_hook_active, cwd, source, last_assistant_message } = input;
29
+ return {
30
+ ...(typeof session_id === "string" ? { session_id } : {}),
31
+ ...(typeof stop_hook_active === "boolean" ? { stop_hook_active } : {}),
32
+ ...(typeof cwd === "string" ? { cwd } : {}),
33
+ ...(typeof source === "string" ? { source } : {}),
34
+ ...(typeof last_assistant_message === "string" ? { last_assistant_message } : {}),
35
+ };
36
+ }
37
+
38
+ function sendBacks(count: number): string {
39
+ return count === 1 ? "1 send-back" : `${count} send-backs`;
40
+ }
41
+
42
+ // How the stop ends, after the totals: sent back, stopped by the cap, or handed back once the agent was sent back.
43
+ function ending({ sendBack, count, max, open }: Judged): string {
44
+ if (sendBack) return `the agent is sent back to fix it (${count} of ${max})`;
45
+ if (open.length) return max === 0 ? "send-backs are off" : `stopped after ${sendBacks(count)}`;
46
+ return count ? `after ${sendBacks(count)}` : "";
47
+ }
48
+
49
+ // What the agent is told besides the reports: where it stands, and what became of its waive lines.
50
+ function told({ count, max, waived, fallen, unknown, gates }: Judged): string[] {
51
+ const names = (list: string[]) => list.join(", ");
52
+ return [
53
+ `This is send-back ${count} of ${max}.`,
54
+ ...(waived.length ? [`Waived this turn, not to fix: ${names(waived.map(({ name }) => name))}.`] : []),
55
+ ...(fallen.length
56
+ ? [`Your waiver of ${names(fallen)} no longer holds: its report changed. Fix it, or waive it again.`]
57
+ : []),
58
+ ...(unknown.length ? [`No gate is named ${names(unknown)}. The gates of this turn: ${names(gates)}.`] : []),
59
+ ];
60
+ }
61
+
62
+ /**
63
+ * A red gate the agent did not waive sends it back with the reports, until the turn reaches its cap: a fix that
64
+ * breaks another gate is caught, and a gate the agent cannot satisfy never loops. The owner sees each stop, the
65
+ * waived gates with their reasons, and why the turn ended.
66
+ */
67
+ export function stopOutput(turn: CheckedTurn, judged: Judged): HookOutput {
68
+ const systemMessage = summary(turn, ending(judged), judged.waived);
69
+ if (!judged.sendBack) return { systemMessage };
70
+ return { decision: "block", reason: failures({ ...turn, outcomes: judged.open }, told(judged)), systemMessage };
71
+ }
72
+
73
+ // When the gates cannot run, such as with a gates file that does not parse, only the owner is told: a crash would
74
+ // show them a stack trace at best, and the agent is not to blame.
75
+ function cannotRun(error: unknown): HookOutput {
76
+ return { systemMessage: broken(messageOf(error)) };
77
+ }
78
+
79
+ /**
80
+ * A prompt ends the turn in progress; from a folder with no gates, or when the turn cannot start, no check will look
81
+ * for a new one. When the gates of the repo miss tools, the agent is asked once to install them.
82
+ */
83
+ async function promptHook(session: string, cwd: string): Promise<HookOutput | undefined> {
84
+ try {
85
+ forgetTurn(session);
86
+ const root = configuredRoot(cwd);
87
+ if (root === undefined) return undefined;
88
+ const missing = await startTurn(session, root);
89
+ if (!tellOnce(session, root, missing)) return undefined;
90
+ return {
91
+ systemMessage: toolsMissing(missing),
92
+ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext: toolsToInstall(missing) },
93
+ };
94
+ } catch (error) {
95
+ return cannotRun(error);
96
+ }
97
+ }
98
+
99
+ /**
100
+ * A stop checks the repo its turn started in, whatever folder the agent stops in, or that folder's repo otherwise,
101
+ * reads the gates the agent's last message waives, and records what it told the agent for the next stop of the turn.
102
+ */
103
+ async function stopHook(
104
+ session: string,
105
+ cwd: string,
106
+ retry: boolean,
107
+ message: string,
108
+ ): Promise<HookOutput | undefined> {
109
+ const root = turnRoot(session, retry) ?? configuredRoot(cwd);
110
+ if (root === undefined) return undefined;
111
+ try {
112
+ const checked = await checkTurn(session, root);
113
+ const turn = readTurn(session, root);
114
+ if (turn === undefined) throw new Error("the turn was not recorded after its check.");
115
+ const { gates, refused, maxSendBacks } = gatesOf(turn.config);
116
+ const names = [...gates.map(({ name }) => name), ...refused.map(({ name }) => name)];
117
+ const judged = judge(checked, waivesOf(message), names, maxSendBacks, turn.sendBacks);
118
+ writeTurn(session, root, { ...turn, sendBacks: judged.state });
119
+ return stopOutput(checked, judged);
120
+ } catch (error) {
121
+ return cannotRun(error);
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Handles a hook event of a coding agent: Claude Code and Codex send the same input and read the same output. It does
127
+ * nothing outside git, or in a repo with no gates file.
128
+ */
129
+ export async function handleHook(event: HookEvent, text: string): Promise<HookOutput | undefined> {
130
+ const {
131
+ session_id: session,
132
+ stop_hook_active: retry = false,
133
+ cwd = process.cwd(),
134
+ source,
135
+ last_assistant_message: message = "",
136
+ } = parseHookInput(text);
137
+ if (session === undefined) return undefined;
138
+ // A session that starts, resumes or is cleared asks again for the missing tools; a compaction goes on as it was.
139
+ if (event === "session-start") {
140
+ if (source !== "compact") forgetTold(session);
141
+ return undefined;
142
+ }
143
+ return event === "turn-start" ? promptHook(session, cwd) : stopHook(session, cwd, retry, message);
144
+ }
package/src/testing.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { mkdtempSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import type { CheckedTurn } from "./core/check.ts";
6
+ import type { Outcome } from "./core/run.ts";
7
+
8
+ // What the tests of the engine build again and again: a repo of their own, its commits, its gates, and a turn. It
9
+ // runs git by itself: every test imports this file, so a module of the engine imported here would make every test
10
+ // related to it.
11
+
12
+ export function git(repo: string, args: string[]): string {
13
+ return execFileSync("git", args, { cwd: repo, encoding: "utf8", stdio: "pipe" }).trim();
14
+ }
15
+
16
+ /** A fresh git repo in a temporary folder, for the test to remove. */
17
+ export function tempRepo(): string {
18
+ const repo = mkdtempSync(join(tmpdir(), "gates-test-"));
19
+ git(repo, ["init", "--quiet", "--template="]);
20
+ return repo;
21
+ }
22
+
23
+ /** Commits every file, with an identity git may not have on the machine. */
24
+ export function commitAll(repo: string, message: string): void {
25
+ git(repo, ["add", "--all"]);
26
+ git(repo, ["-c", "user.name=test", "-c", "user.email=test@test.invalid", "commit", "--quiet", "-m", message]);
27
+ }
28
+
29
+ export function writeGates(repo: string, ...gates: object[]): void {
30
+ writeFileSync(join(repo, ".gates.json"), JSON.stringify({ gates }));
31
+ }
32
+
33
+ export function outcome(name: string, ok: boolean, ms = 10): Outcome {
34
+ return { name, ok, ms, output: `${name} report`, report: `${name} report` };
35
+ }
36
+
37
+ export function ran(outcomes: Outcome[], skipped: string[] = [], ms = 20): CheckedTurn {
38
+ return { changed: ["src/a.ts"], outcomes, skipped, ms };
39
+ }