@miracle352/statute 0.0.0-stage → 0.3.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.
Files changed (81) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +319 -2
  3. package/action.yml +356 -0
  4. package/bin/hook.js +81 -0
  5. package/bin/init.js +142 -0
  6. package/bin/mcp.js +166 -0
  7. package/bin/scope.js +78 -0
  8. package/bin/shots.js +52 -0
  9. package/bin/statute.js +362 -0
  10. package/examples/expect/newsletter_test.md +22 -0
  11. package/examples/expect/output-newsletter/.internal/execution.json +2053 -0
  12. package/examples/expect/output-newsletter/.internal/meta.json +39 -0
  13. package/examples/expect/output-newsletter/.internal/steps/1-d2368411/flows/0/actions.ndjson +2 -0
  14. package/examples/expect/output-newsletter/.internal/steps/2-a9e761f8/flows/0/actions.ndjson +6 -0
  15. package/examples/expect/output-newsletter/.internal/steps/3-63305a01/flows/0/actions.ndjson +2 -0
  16. package/examples/expect/output-newsletter/Result.md +21 -0
  17. package/examples/expect/search_test.md +20 -0
  18. package/laws/README.md +24 -0
  19. package/laws/accept_still_works_test.md +12 -0
  20. package/laws/cancel_as_easy_as_signup_test.md +15 -0
  21. package/laws/output-reject_means_reject/.internal/execution.json +1279 -0
  22. package/laws/output-reject_means_reject/.internal/meta.json +18 -0
  23. package/laws/output-reject_means_reject/.internal/steps/1-567cc234/flows/0/actions.ndjson +6 -0
  24. package/laws/output-reject_means_reject/.internal/steps/2-e3c06462/flows/0/actions.ndjson +1 -0
  25. package/laws/output-reject_means_reject/.internal/steps/3-3040a29b/flows/0/actions.ndjson +2 -0
  26. package/laws/output-reject_means_reject/Result.md +21 -0
  27. package/laws/price_shown_is_price_paid_test.md +12 -0
  28. package/laws/reject_means_reject_test.md +15 -0
  29. package/package.json +65 -4
  30. package/replays/cancel-demo-shop/evidence/cancel-1794754943192.evidence +0 -0
  31. package/replays/cancel-demo-shop/evidence/cancel-1794755110410.evidence +0 -0
  32. package/replays/cancel-demo-shop/loop.json +32 -0
  33. package/replays/demo-shop/evidence/consent-1794751413210.evidence +0 -0
  34. package/replays/demo-shop/evidence/consent-1794751523524.evidence +0 -0
  35. package/replays/demo-shop/evidence/consent-accept-1794751588395.evidence +0 -0
  36. package/replays/demo-shop/loop.json +40 -0
  37. package/replays/haxcms/evidence/consent-1794831086682.evidence +0 -0
  38. package/replays/haxcms/evidence/consent-1794831262757.evidence +0 -0
  39. package/replays/haxcms/evidence/consent-accept-1794831347132.evidence +0 -0
  40. package/replays/haxcms/loop.json +56 -0
  41. package/replays/in-the-wake-check/consent.json +67 -0
  42. package/replays/in-the-wake-check/consent.md +32 -0
  43. package/replays/kane-testmd-demo-shop/evidence/consent-1794935266000.evidence +0 -0
  44. package/replays/kane-testmd-demo-shop/loop.json +18 -0
  45. package/replays/lumen-pr-2/evidence/consent-1794929771799.evidence +0 -0
  46. package/replays/lumen-pr-2/evidence/consent-1794929845913.evidence +0 -0
  47. package/replays/lumen-pr-2/evidence/consent-accept-1794929886905.evidence +0 -0
  48. package/replays/lumen-pr-2/loop.json +57 -0
  49. package/replays/newsletter-expect/evidence/newsletter_test-round1-1795518837738.evidence +0 -0
  50. package/replays/newsletter-expect/evidence/newsletter_test-round2-1795519079029.evidence +0 -0
  51. package/replays/newsletter-expect/loop.json +99 -0
  52. package/replays/price-demo-shop/evidence/price-1794837093949.evidence +0 -0
  53. package/replays/price-demo-shop/evidence/price-1794837311639.evidence +0 -0
  54. package/replays/price-demo-shop/loop.json +43 -0
  55. package/rules/trackers.json +61 -0
  56. package/site/assets/fonts/OFL-archivo.txt +93 -0
  57. package/site/assets/fonts/OFL-geist.txt +93 -0
  58. package/site/assets/fonts/OFL-instrument-serif.txt +93 -0
  59. package/site/assets/fonts/archivo.woff2 +0 -0
  60. package/site/assets/fonts/geist.woff2 +0 -0
  61. package/site/assets/fonts/instrument-serif-italic.woff2 +0 -0
  62. package/site/assets/fonts/instrument-serif.woff2 +0 -0
  63. package/site/assets/fonts/inter.woff2 +0 -0
  64. package/site/assets/fonts/jetbrains-mono.woff2 +0 -0
  65. package/skill/statute/SKILL.md +57 -0
  66. package/src/agent.js +70 -0
  67. package/src/app.js +41 -0
  68. package/src/evidence.js +80 -0
  69. package/src/expect-cli.js +296 -0
  70. package/src/expect-view.js +79 -0
  71. package/src/expect.js +392 -0
  72. package/src/infer.js +32 -0
  73. package/src/kane.js +124 -0
  74. package/src/pack.js +128 -0
  75. package/src/packs/cancel.js +83 -0
  76. package/src/packs/consent-accept.js +57 -0
  77. package/src/packs/consent.js +237 -0
  78. package/src/packs/price.js +104 -0
  79. package/src/page.js +360 -0
  80. package/src/report.js +59 -0
  81. package/src/zip.js +38 -0
package/bin/mcp.js ADDED
@@ -0,0 +1,166 @@
1
+ #!/usr/bin/env node
2
+ // Statute as an MCP server (stdio). Any coding agent that speaks MCP (Claude Code,
3
+ // Cursor, Codex...) can ask Kane CLI to check a page against a law and get the
4
+ // verdict back in its own conversation.
5
+ //
6
+ // claude mcp add statute -- npx -y @miracle352/statute mcp
7
+ //
8
+ // Each check runs `statute check` in a child process, so Kane's progress output
9
+ // never mixes with the protocol on stdout.
10
+ const { spawn } = require("child_process");
11
+ const fs = require("fs");
12
+ const os = require("os");
13
+ const path = require("path");
14
+
15
+ const ROOT = path.join(__dirname, "..");
16
+ const PACKS = {
17
+ consent: require("../src/packs/consent"),
18
+ price: require("../src/packs/price"),
19
+ cancel: require("../src/packs/cancel"),
20
+ };
21
+ const VERSION = require("../package.json").version;
22
+
23
+ const TOOLS = [
24
+ {
25
+ name: "statute_check",
26
+ description:
27
+ "Have Kane CLI open a page in a real browser and check it against a consumer-protection rule. " +
28
+ "The verdict (pass, violation or inconclusive) is computed by code from Kane's sealed evidence. " +
29
+ "Checks: consent (after Reject, no tracker may load), price (the price shown is the price paid), " +
30
+ "cancel (cancelling online takes no more steps than signing up). Takes one to four minutes and " +
31
+ "spends Kane credits. Use it after changing cookie banners, analytics tags, pricing or subscription flows.",
32
+ inputSchema: {
33
+ type: "object",
34
+ properties: {
35
+ check: { type: "string", enum: Object.keys(PACKS), description: "Which rule to check." },
36
+ url: { type: "string", description: "Address Kane should visit, for example http://localhost:3000/." },
37
+ start: { type: "string", description: "Optional command that starts the app first, for example `npm run dev`. Statute stops it afterwards." },
38
+ cwd: { type: "string", description: "Folder to run `start` in. Defaults to the folder the agent is working in." },
39
+ },
40
+ required: ["check", "url"],
41
+ },
42
+ },
43
+ {
44
+ name: "statute_expect",
45
+ description:
46
+ "Run a Kane CLI test file (<name>_test.md) and check what the page did while Kane ran it: requests to trackers " +
47
+ "or third parties, data typed by the user leaving the site (plain, encoded or hashed), cookies, server and console " +
48
+ "errors, numbers Kane read, clicks per step. The expectations are written in the test file in a comment " +
49
+ "(<!-- expect ... -->). Kane's own pass only says the steps ran; this says whether the page behaved. Spends Kane credits. " +
50
+ "Also judges an existing .evidence pack again for free when `test` is a pack path.",
51
+ inputSchema: {
52
+ type: "object",
53
+ properties: {
54
+ test: { type: "string", description: "Path to a *_test.md file with expectations, or to a sealed .evidence pack." },
55
+ url: { type: "string", description: "Address the test starts at (needed for a test file)." },
56
+ start: { type: "string", description: "Optional command that starts the app first." },
57
+ cwd: { type: "string", description: "Folder to run in. Defaults to the agent's folder." },
58
+ },
59
+ required: ["test"],
60
+ },
61
+ },
62
+ {
63
+ name: "statute_rules",
64
+ description: "List Statute's checks with the rule each one enforces and the laws behind it. Instant, no credits.",
65
+ inputSchema: { type: "object", properties: {} },
66
+ },
67
+ ];
68
+
69
+ function rulesText() {
70
+ return Object.values(PACKS).map((p) =>
71
+ `## ${p.id}: ${p.title}\n${p.rule}\n${p.laws.map((l) => `- ${l.ref}: ${l.gist}`).join("\n")}\nHow to fix: ${p.fixHint}`
72
+ ).join("\n\n");
73
+ }
74
+
75
+ function runCheck({ check, url, start, cwd }) {
76
+ return new Promise((resolve) => {
77
+ if (!PACKS[check]) return resolve({ text: `Unknown check "${check}". Use one of: ${Object.keys(PACKS).join(", ")}.`, isError: true });
78
+ if (!/^https?:\/\//i.test(url || "")) return resolve({ text: "url must start with http:// or https://", isError: true });
79
+ const out = fs.mkdtempSync(path.join(os.tmpdir(), "statute-mcp-"));
80
+ const args = [path.join(ROOT, "bin", "statute.js"), "check", check, "--url", url, "--out", out];
81
+ if (start) args.push("--start", start);
82
+ const child = spawn(process.execPath, args, { cwd: cwd || process.cwd(), env: process.env, stdio: ["ignore", "pipe", "pipe"] });
83
+ let log = "";
84
+ child.stdout.on("data", (d) => { log += d; process.stderr.write(d); });
85
+ child.stderr.on("data", (d) => { log += d; process.stderr.write(d); });
86
+ child.on("close", (code) => {
87
+ const verdict = code === 0 ? "pass" : code === 1 ? "violation" : "inconclusive";
88
+ let report = "";
89
+ try { report = fs.readFileSync(path.join(out, `${check}.md`), "utf8").replace(/^/, ""); } catch {}
90
+ const caseFile = path.join(out, "index.html");
91
+ const tail = log.trim().split("\n").slice(-6).join("\n");
92
+ const text = report
93
+ ? `Statute verdict: ${verdict.toUpperCase()}\n\n${report}\n\nCase file with Kane's screenshots: ${caseFile}`
94
+ : `Statute could not finish the ${check} check (exit ${code}).\n\n${tail}`;
95
+ resolve({ text, isError: !report, verdict });
96
+ });
97
+ });
98
+ }
99
+
100
+ function runExpect({ test, url, start, cwd }) {
101
+ return new Promise((resolve) => {
102
+ const isPack = /\.evidence$/i.test(test || "");
103
+ if (!isPack && !/^https?:\/\//i.test(url || "")) return resolve({ text: "url (http:// or https://) is needed to run a test file", isError: true });
104
+ const out = fs.mkdtempSync(path.join(os.tmpdir(), "statute-mcp-"));
105
+ const args = [path.join(ROOT, "bin", "statute.js"), "expect", test, "--out", out];
106
+ if (!isPack) args.push("--url", url);
107
+ if (start && !isPack) args.push("--start", start);
108
+ const child = spawn(process.execPath, args, { cwd: cwd || process.cwd(), env: process.env, stdio: ["ignore", "pipe", "pipe"] });
109
+ let log = "";
110
+ child.stdout.on("data", (d) => { log += d; process.stderr.write(d); });
111
+ child.stderr.on("data", (d) => { log += d; process.stderr.write(d); });
112
+ child.on("close", (code) => {
113
+ let report = "";
114
+ try { report = fs.readFileSync(path.join(out, "expect.md"), "utf8").replace(/^\uFEFF/, ""); } catch {}
115
+ const tail = log.trim().split("\n").slice(-8).join("\n");
116
+ resolve({ text: report || `Statute could not finish (exit ${code}).\n\n${tail}`, isError: !report });
117
+ });
118
+ });
119
+ }
120
+
121
+ // --- MCP over stdio: newline-delimited JSON-RPC 2.0 ---
122
+ const send = (msg) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...msg }) + "\n");
123
+
124
+ async function handle(msg) {
125
+ const { id, method, params } = msg;
126
+ if (method === "initialize") {
127
+ return send({ id, result: {
128
+ protocolVersion: (params && params.protocolVersion) || "2025-06-18",
129
+ capabilities: { tools: {} },
130
+ serverInfo: { name: "statute", version: VERSION },
131
+ instructions: "Statute checks web pages against consumer-protection law with Kane CLI. Call statute_check after changing consent banners, tracking tags, prices or subscription flows, and fix any violation it reports before finishing.",
132
+ } });
133
+ }
134
+ if (method === "tools/list") return send({ id, result: { tools: TOOLS } });
135
+ if (method === "tools/call") {
136
+ const name = params && params.name;
137
+ const a = (params && params.arguments) || {};
138
+ if (name === "statute_rules") return send({ id, result: { content: [{ type: "text", text: rulesText() }] } });
139
+ if (name === "statute_expect") {
140
+ const r = await runExpect(a);
141
+ return send({ id, result: { content: [{ type: "text", text: r.text }], isError: !!r.isError } });
142
+ }
143
+ if (name === "statute_check") {
144
+ const r = await runCheck(a);
145
+ return send({ id, result: { content: [{ type: "text", text: r.text }], isError: !!r.isError } });
146
+ }
147
+ return send({ id, error: { code: -32602, message: `Unknown tool: ${name}` } });
148
+ }
149
+ if (method === "ping") return send({ id, result: {} });
150
+ if (id !== undefined && !String(method || "").startsWith("notifications/")) send({ id, error: { code: -32601, message: `Method not found: ${method}` } });
151
+ }
152
+
153
+ let buf = "";
154
+ process.stdin.setEncoding("utf8");
155
+ process.stdin.on("data", (chunk) => {
156
+ buf += chunk;
157
+ let i;
158
+ while ((i = buf.indexOf("\n")) >= 0) {
159
+ const line = buf.slice(0, i).trim();
160
+ buf = buf.slice(i + 1);
161
+ if (!line) continue;
162
+ let msg;
163
+ try { msg = JSON.parse(line); } catch { continue; }
164
+ handle(msg).catch((e) => msg.id !== undefined && send({ id: msg.id, error: { code: -32603, message: String(e.message || e) } }));
165
+ }
166
+ });
package/bin/scope.js ADDED
@@ -0,0 +1,78 @@
1
+ #!/usr/bin/env node
2
+ // Decides which Statute checks a code change could affect, by reading the diff.
3
+ // No AI, no Kane credits: plain pattern matching on the changed lines.
4
+ //
5
+ // git diff origin/main...HEAD | node bin/scope.js -> prints e.g. "consent price"
6
+ // node bin/scope.js --base origin/main -> runs git diff itself
7
+ // --json -> reasons per check
8
+ const { execSync } = require("child_process");
9
+ const fs = require("fs");
10
+ const path = require("path");
11
+
12
+ const trackers = require("../rules/trackers.json").domains.map((d) => d.split("/")[0]);
13
+ const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
14
+
15
+ const RULES = {
16
+ consent: [
17
+ { why: "a tracker domain", re: new RegExp(trackers.map(esc).join("|"), "i") },
18
+ { why: "an analytics or ads call", re: /\b(gtag\s*\(|fbq\s*\(|ttq\.|_hsq|dataLayer\.push|analytics\.(track|page|identify)|posthog\.|mixpanel\.|amplitude\.|hotjar|clarity\(|plausible|umami|segment)/i },
19
+ { why: "cookie or consent code", re: /\b(cookie|consent|gdpr|ccpa|onetrust|cookiebot|didomi|usercentrics|iubenda|tcf|__tcfapi|reject[_\- ]?all|accept[_\- ]?all)/i },
20
+ ],
21
+ price: [
22
+ { why: "a fee or surcharge", re: /\b(fee|fees|surcharge|service[_\- ]?charge|handling|convenience|booking[_\- ]?fee|processing)\b/i },
23
+ { why: "price or total calculation", re: /\b(price|subtotal|total|checkout|cart|basket|amount|currency)\b/i },
24
+ ],
25
+ cancel: [
26
+ { why: "subscription or cancellation flow", re: /\b(subscri\w*|cancel\w*|unsubscribe|membership|renew\w*|billing|plan[_\- ]?(change|cancel))\b/i },
27
+ ],
28
+ };
29
+
30
+ // Files whose changes never affect what a visitor's browser does.
31
+ const IGNORE = /(^|\/)(README|CHANGELOG|LICENSE)[^/]*$|\.(md|txt|lock)$|(^|\/)(test|tests|__tests__|spec|docs)\//i;
32
+
33
+ // Code glues words together (SERVICE_FEE, cartTotal, cancelSubscription); split them
34
+ // so "fee", "total" and "cancel" are seen as words.
35
+ const splitWords = (line) => line.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_\-]+/g, " ");
36
+
37
+ function parseDiff(text) {
38
+ const files = [];
39
+ let cur = null;
40
+ for (const line of text.split("\n")) {
41
+ const m = line.match(/^\+\+\+ b\/(.+)$/);
42
+ if (m) { cur = { file: m[1], lines: [] }; files.push(cur); continue; }
43
+ if (!cur) continue;
44
+ if ((line.startsWith("+") && !line.startsWith("+++")) || (line.startsWith("-") && !line.startsWith("---"))) cur.lines.push(line.slice(1));
45
+ }
46
+ return files;
47
+ }
48
+
49
+ function scope(diffText) {
50
+ const all = parseDiff(diffText);
51
+ const files = all.filter((f) => !IGNORE.test(f.file));
52
+ const hits = {};
53
+ for (const [check, rules] of Object.entries(RULES)) {
54
+ for (const f of files) {
55
+ for (const line of f.lines) {
56
+ const words = splitWords(line);
57
+ const r = rules.find((x) => x.re.test(line) || x.re.test(words));
58
+ if (r) {
59
+ (hits[check] = hits[check] || []).push({ file: f.file, why: r.why, line: line.trim().slice(0, 120) });
60
+ break;
61
+ }
62
+ }
63
+ }
64
+ }
65
+ return { changed: all.map((f) => f.file), files: files.map((f) => f.file), checks: Object.keys(hits), reasons: hits };
66
+ }
67
+
68
+ if (require.main === module) {
69
+ const i = process.argv.indexOf("--base");
70
+ let diff;
71
+ if (i > 0) diff = execSync(`git diff ${process.argv[i + 1]}...HEAD`, { encoding: "utf8", maxBuffer: 64 << 20 });
72
+ else diff = fs.readFileSync(0, "utf8");
73
+ const r = scope(diff);
74
+ if (process.argv.includes("--json")) console.log(JSON.stringify(r, null, 2));
75
+ else console.log(r.checks.join(" "));
76
+ }
77
+
78
+ module.exports = { scope, parseDiff };
package/bin/shots.js ADDED
@@ -0,0 +1,52 @@
1
+ #!/usr/bin/env node
2
+ // Pulls the one screenshot that matters out of each Kane evidence pack in a report folder,
3
+ // so a pull request comment can show what Kane saw.
4
+ // node bin/shots.js <report-dir> <out-dir> -> writes images and shots.json
5
+ const fs = require("fs");
6
+ const path = require("path");
7
+ const { steps } = require("../src/page");
8
+
9
+ const PICK = {
10
+ consent: /reject|declin|refus/i,
11
+ "consent-accept": /accept|agree|allow/i,
12
+ };
13
+
14
+ function packsIn(dir) {
15
+ const found = [];
16
+ (function walk(d) {
17
+ for (const e of fs.readdirSync(d, { withFileTypes: true })) {
18
+ const p = path.join(d, e.name);
19
+ if (e.isDirectory()) walk(p);
20
+ else if (e.name.endsWith(".evidence")) found.push(p);
21
+ }
22
+ })(dir);
23
+ // file names end in -<timestamp>.evidence: keep the order Kane ran them in
24
+ const ts = (p) => Number((p.match(/-(\d+)\.evidence$/) || [])[1] || 0);
25
+ return found.sort((a, b) => ts(a) - ts(b));
26
+ }
27
+
28
+ function main() {
29
+ const [dir, out] = process.argv.slice(2);
30
+ if (!dir || !out) { console.error("usage: shots.js <report-dir> <out-dir>"); process.exit(2); }
31
+ fs.mkdirSync(out, { recursive: true });
32
+ const list = [];
33
+ const seen = new Set();
34
+ for (const pack of packsIn(dir)) {
35
+ const id = path.basename(pack).replace(/-\d+\.evidence$/, "");
36
+ const all = steps(pack).filter((s) => s.img);
37
+ if (!all.length) continue;
38
+ const re = PICK[id];
39
+ const shot = (re && [...all].reverse().find((s) => re.test(s.caption))) || all[all.length - 1];
40
+ const m = shot.img.match(/^data:image\/(\w+);base64,(.+)$/);
41
+ if (!m) continue;
42
+ const hash = require("crypto").createHash("sha1").update(m[2]).digest("hex");
43
+ if (seen.has(hash)) continue;
44
+ seen.add(hash);
45
+ const file = `${String(list.length + 1).padStart(2, "0")}-${id}.${m[1] === "png" ? "png" : "jpg"}`;
46
+ fs.writeFileSync(path.join(out, file), Buffer.from(m[2], "base64"));
47
+ list.push({ file, pack: id, step: shot.n, caption: shot.caption });
48
+ }
49
+ fs.writeFileSync(path.join(out, "shots.json"), JSON.stringify(list, null, 2));
50
+ console.log(`${list.length} screenshot(s) written to ${out}`);
51
+ }
52
+ main();
package/bin/statute.js ADDED
@@ -0,0 +1,362 @@
1
+ #!/usr/bin/env node
2
+ // Statute: laws that test themselves.
3
+ //
4
+ // statute check consent --url <url> [--start "<cmd>"] [--show]
5
+ // statute judge consent re-judge the last run, no credits
6
+ // statute fix consent --url <url> --start "<cmd>" --app <dir> [--rounds 3]
7
+ // statute report rebuild statute-report/index.html
8
+ // statute reset-demo put the demo store's bugs back
9
+ const fs = require("fs");
10
+ const path = require("path");
11
+ const kane = require("../src/kane");
12
+ const evidence = require("../src/evidence");
13
+ const report = require("../src/report");
14
+ const app = require("../src/app");
15
+ const agent = require("../src/agent");
16
+ const page = require("../src/page");
17
+
18
+ const PACKS = {
19
+ consent: require("../src/packs/consent"),
20
+ "consent-accept": require("../src/packs/consent-accept"),
21
+ cancel: require("../src/packs/cancel"),
22
+ price: require("../src/packs/price"),
23
+ };
24
+ const ROOT = path.resolve(__dirname, "..");
25
+
26
+ function arg(name, def) {
27
+ const i = process.argv.indexOf("--" + name);
28
+ if (i < 0) return def;
29
+ const v = process.argv[i + 1];
30
+ return v && !v.startsWith("--") ? v : true;
31
+ }
32
+
33
+ const when = { after: "after Reject", before: "before choice", unknown: "during visit" };
34
+ const firstLine = (s) => String(s || "").split("\n")[0];
35
+
36
+ // One Kane run of one pack, judged by code. Starts/stops the app if asked.
37
+ async function check(pack, { url, out, start, cwd, show }) {
38
+ let child = null;
39
+ if (start) {
40
+ child = app.start(start, cwd);
41
+ if (!(await app.waitUntilUp(url))) {
42
+ app.stop(child);
43
+ throw new Error(`the app did not come up at ${url} after "${start}"`);
44
+ }
45
+ } else if (!(await app.ping(url))) {
46
+ throw new Error(`nothing is answering at ${url}; start the app or pass --start "<command>"`);
47
+ }
48
+ try {
49
+ console.log(`\nStatute · ${pack.title}\nKane is visiting ${url}...`);
50
+ const res = await kane.run(pack.objective(url), {
51
+ headless: !show,
52
+ maxSteps: Number(arg("max-steps", 25)),
53
+ timeout: Number(arg("timeout", 300)),
54
+ // CI and servers sign in with keys from the environment; locally, kane-cli login is used.
55
+ username: process.env.LT_USERNAME || undefined,
56
+ accessKey: process.env.LT_ACCESS_KEY || undefined,
57
+ onEvent: (e) => { if (e.step && e.status && e.status !== "running") console.log(` step ${e.step} ${e.status}: ${e.remark || ""}`); },
58
+ });
59
+ if (!res.end) throw new Error("Kane ended without a result.\n" + res.stderr.slice(-1500));
60
+ let packPath = res.end.session_dir ? evidence.newestPack(res.end.session_dir) : null;
61
+ fs.mkdirSync(path.join(out, "evidence"), { recursive: true });
62
+ if (packPath) {
63
+ const copy = path.join(out, "evidence", `${pack.id}-${Date.now()}.evidence`);
64
+ fs.copyFileSync(packPath, copy);
65
+ packPath = copy;
66
+ }
67
+ fs.writeFileSync(path.join(out, `${pack.id}.last-run.json`), JSON.stringify({ end: res.end, events: res.events, packPath }, null, 2));
68
+ return judgeAndReport(pack, { end: res.end, events: res.events, packPath, out });
69
+ } finally {
70
+ app.stop(child);
71
+ }
72
+ }
73
+
74
+ function judgeAndReport(pack, { end, events, packPath, out }) {
75
+ if (!packPath) throw new Error("No evidence pack found.");
76
+ const network = evidence.networkFromPack(packPath);
77
+ const result = pack.judge({ end, events, network, strict: true });
78
+ const file = report.write(out, pack, result, {
79
+ evidence: packPath,
80
+ testUrl: (end && end.test_url) || network.shareLink,
81
+ credits: end && end.credits_consumed,
82
+ kaneStatus: end && end.status,
83
+ kaneSummary: end && end.summary,
84
+ });
85
+ if (end && end.status === "failed") console.log(`Note: Kane's run ended early (${firstLine(end.summary)}); the verdict uses what it recorded up to that point.`);
86
+ console.log(`\n${result.verdict.toUpperCase()}: ${result.why}`);
87
+ for (const r of result.trackerRequests || []) console.log(` · ${when[r.phase]}: ${r.tracker} ${r.url} ×${r.count}`);
88
+ for (const i of result.idsAfterReject || []) console.log(` · visitor ID sent after Reject: ${i}`);
89
+ if (result.signup) {
90
+ console.log(` · subscribe (${result.signup.length}): ${result.signup.join(" → ")}`);
91
+ console.log(` · cancel (${result.cancel.length}): ${result.cancel.join(" → ") || "(nothing)"}`);
92
+ }
93
+ const credits = end && end.credits_consumed != null ? Number(end.credits_consumed) : 0;
94
+ if (credits) console.log(`Credits used: ${credits.toFixed(1)}`);
95
+ console.log(`Report: ${file}`);
96
+ return { result, file, credits, packPath, kaneStatus: end && end.status, kaneSummary: end && end.summary, testUrl: (end && end.test_url) || network.shareLink };
97
+ }
98
+
99
+ // The closed loop: Kane finds it, the agent fixes it, Kane proves it.
100
+ async function fixLoop(pack, opts) {
101
+ const rounds = Number(arg("rounds", 3));
102
+ const timeline = [];
103
+ let spent = 0;
104
+ const log = path.join(opts.out, "loop.json");
105
+ const save = () => fs.writeFileSync(log, JSON.stringify({ pack: pack.id, url: opts.url, app: path.relative(ROOT, opts.app) || ".", strict: true, timeline, credits: spent }, null, 2));
106
+
107
+ for (let round = 1; round <= rounds; round++) {
108
+ const r = await check(pack, opts);
109
+ spent += r.credits;
110
+ timeline.push({ round, step: "kane", pack: pack.id, verdict: r.result.verdict, why: r.result.why, run: r.testUrl, evidence: r.packPath, credits: r.credits, kaneStatus: r.kaneStatus, kaneSummary: r.kaneSummary, at: new Date().toISOString() });
111
+ save();
112
+ if (r.result.verdict === "inconclusive") {
113
+ console.log("\nKane's run could not prove anything either way, so the loop stops here instead of guessing.");
114
+ break;
115
+ }
116
+ if (r.result.verdict === "pass") {
117
+ // Guard against "fixed" by deleting analytics: Accept must still work.
118
+ const guard = PACKS[`${pack.id}-accept`];
119
+ if (guard) {
120
+ const g = await check(guard, opts);
121
+ spent += g.credits;
122
+ timeline.push({ round, step: "kane", pack: guard.id, verdict: g.result.verdict, why: g.result.why, run: g.testUrl, evidence: g.packPath, credits: g.credits, kaneStatus: g.kaneStatus, kaneSummary: g.kaneSummary, at: new Date().toISOString() });
123
+ save();
124
+ if (g.result.verdict !== "pass") {
125
+ if (round === rounds) break;
126
+ await agentRound(guard, g.file, opts, timeline, round, save);
127
+ continue;
128
+ }
129
+ }
130
+ console.log(`\nDONE in ${round} round(s): Kane proved "${pack.title}" holds${guard ? " and Accept still works" : ""}. Credits used: ${spent.toFixed(1)}`);
131
+ writeTimeline(opts.out, pack, timeline, spent, true);
132
+ return 0;
133
+ }
134
+ if (round === rounds) break;
135
+ await agentRound(pack, r.file, opts, timeline, round, save);
136
+ }
137
+ console.log(`\nNot fixed after ${rounds} round(s). Credits used: ${spent.toFixed(1)}. See ${path.join(opts.out, "loop.md")}`);
138
+ writeTimeline(opts.out, pack, timeline, spent, false);
139
+ return 1;
140
+ }
141
+
142
+ async function agentRound(pack, reportFile, opts, timeline, round, save) {
143
+ console.log(`\nHanding the report to Claude Code (round ${round})...`);
144
+ const summary = await agent.fix({
145
+ pack,
146
+ reportMd: fs.readFileSync(reportFile, "utf8"),
147
+ appDir: opts.app,
148
+ onLine: (l) => console.log(" claude │ " + l),
149
+ });
150
+ timeline.push({ round, step: "agent", agent: "claude-code", summary, at: new Date().toISOString() });
151
+ save();
152
+ }
153
+
154
+ function writeTimeline(out, pack, timeline, spent, fixed) {
155
+ const changed = timeline.some((t) => t.step === "agent");
156
+ const head = fixed ? (changed ? "FIXED" : "PASSED") : (changed ? "NOT FIXED" : "VIOLATION");
157
+ const note = fixed && !changed ? "Kane found nothing to fix, so Claude Code was not called." : fixed ? "Kane found a violation, Claude Code fixed it, and Kane passed the fix." : "";
158
+ const L = [`### ${head}: ${pack.title}`, ""];
159
+ if (note) L.push(note, "");
160
+ for (const t of timeline) {
161
+ if (t.step === "kane") L.push(`- **Round ${t.round} · Kane · ${t.pack}: ${t.verdict.toUpperCase()}**. ${t.why}${t.run ? ` [Kane run](${t.run})` : ""}`);
162
+ else L.push(`- **Round ${t.round} · Claude Code fixed the app:** ${t.summary.replace(/\n+/g, " ")}`);
163
+ }
164
+ L.push("", `Credits used: ${spent.toFixed(1)}`, "");
165
+ fs.writeFileSync(path.join(out, "loop.md"), "\ufeff" + L.join("\n"));
166
+ const html = page.build({ out, packs: PACKS });
167
+ console.log(`Case file: ${html}`);
168
+ }
169
+
170
+ // Zero-credit demo: re-judge recorded Kane runs from their sealed evidence packs
171
+ // and rebuild each case file. Nothing is sent to Kane.
172
+ function replay(only) {
173
+ const base = path.join(ROOT, "replays");
174
+ if (!fs.existsSync(base)) { console.error("This copy of Statute has no recorded runs (replays/). Get them with: git clone https://github.com/miracle352/statute"); process.exit(1); }
175
+ const names = fs.readdirSync(base).filter((n) => fs.existsSync(path.join(base, n, "loop.json")) && (!only || n === only));
176
+ if (!names.length) { console.error("No recorded runs found in replays/."); process.exit(1); }
177
+ for (const name of names) {
178
+ const src = path.join(base, name);
179
+ const out = path.join(writableBase(), "statute-report", "replay", name);
180
+ fs.mkdirSync(out, { recursive: true });
181
+ fs.copyFileSync(path.join(src, "loop.json"), path.join(out, "loop.json"));
182
+ fs.cpSync(path.join(src, "evidence"), path.join(out, "evidence"), { recursive: true });
183
+ const loop = JSON.parse(fs.readFileSync(path.join(src, "loop.json"), "utf8"));
184
+ console.log(`\n${loop.title || name}`);
185
+ if (loop.pack === "expect") { replayExpect(src, loop, out); continue; }
186
+ for (const t of loop.timeline) {
187
+ if (t.step === "agent") { console.log(` round ${t.round} Claude Code changed the app`); continue; }
188
+ const pk = PACKS[t.pack];
189
+ const dir = path.join(src, "evidence");
190
+ const f = String(t.evidence || "").split(/[\\/]/).pop();
191
+ if (!f || !pk || !fs.existsSync(path.join(dir, f))) continue;
192
+ const network = evidence.networkFromPack(path.join(dir, f));
193
+ const r = pk.judge({ end: null, events: [], network, strict: !!loop.strict });
194
+ console.log(` round ${t.round} ${pk.title.padEnd(26)} ${r.verdict.toUpperCase().padEnd(12)} ${r.why}`);
195
+ }
196
+ page.build({ out, packs: PACKS, url: loop.url });
197
+ console.log(` case file: ${path.join(out, "index.html")}`);
198
+ }
199
+ console.log("\nNo Kane runs and no credits: every verdict above was recomputed from the sealed evidence packs in replays/.");
200
+ }
201
+
202
+ // Expectation runs: re-judge each round's pack against the expectations in its own test.md.
203
+ function replayExpect(src, loop, out) {
204
+ const pack = require("../src/pack");
205
+ const expect = require("../src/expect");
206
+ const cli = require("../src/expect-cli");
207
+ for (const t of loop.timeline) {
208
+ if (t.step === "agent") { console.log(` round ${t.round} Claude Code changed ${(t.changed || []).join(", ") || "the app"}`); continue; }
209
+ const f = String(t.evidence || "").split(/[\\/]/).pop();
210
+ const file = path.join(out, "evidence", f);
211
+ if (!f || !fs.existsSync(file)) continue;
212
+ const p = pack.read(file);
213
+ const r = expect.judge(p, p.expectations);
214
+ console.log(` round ${t.round} Kane: ${String(r.kaneStatus).padEnd(8)} Statute: ${r.verdict.toUpperCase().padEnd(12)} ${r.why}`);
215
+ cli.writeVerdict(file, p.expectations, r);
216
+ }
217
+ console.log(` verdicts: ${path.join(out, "evidence")} (*.verdicts/statute.verdict.json)`);
218
+ }
219
+
220
+ function resetDemo() {
221
+ const src = path.join(ROOT, "demo-store", ".buggy");
222
+ const dst = path.join(ROOT, "demo-store");
223
+ const copy = (from, to) => {
224
+ for (const f of fs.readdirSync(from, { withFileTypes: true })) {
225
+ const a = path.join(from, f.name);
226
+ const b = path.join(to, f.name);
227
+ if (f.isDirectory()) { fs.mkdirSync(b, { recursive: true }); copy(a, b); } else fs.copyFileSync(a, b);
228
+ }
229
+ };
230
+ copy(src, dst);
231
+ console.log("Demo store reset: its compliance bugs are back.");
232
+ }
233
+
234
+ // Copies the Statute agent skill where Claude Code finds it (user-wide, or this project with --project).
235
+ function installSkill() {
236
+ const os = require("os");
237
+ const src = path.join(ROOT, "skill", "statute", "SKILL.md");
238
+ const base = process.argv.includes("--project") ? path.join(process.cwd(), ".claude") : path.join(os.homedir(), ".claude");
239
+ const dest = path.join(base, "skills", "statute", "SKILL.md");
240
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
241
+ fs.copyFileSync(src, dest);
242
+ console.log(`Installed the Statute skill for Claude Code: ${dest}`);
243
+ console.log("Claude Code now runs Statute after changes to tracking, prices or subscriptions, and isn't done until Kane passes.");
244
+ console.log("Codex or Gemini CLI: point AGENTS.md or GEMINI.md at the same file.");
245
+ }
246
+
247
+ // Newest sealed Kane pack: a project's .testmuai folder first, then Kane's own sessions.
248
+ function latestPack() {
249
+ const os = require("os");
250
+ const roots = [path.join(process.cwd(), ".testmuai"), path.join(os.homedir(), ".testmuai", "kaneai", "sessions")];
251
+ const found = [];
252
+ const walk = (d, depth) => {
253
+ let list;
254
+ try { list = fs.readdirSync(d, { withFileTypes: true }); } catch { return; }
255
+ for (const e of list) {
256
+ const p = path.join(d, e.name);
257
+ if (e.isDirectory() && depth < 5) walk(p, depth + 1);
258
+ else if (e.name.endsWith(".evidence")) { try { found.push({ p, t: fs.statSync(p).mtimeMs }); } catch {} }
259
+ }
260
+ };
261
+ for (const r of roots) walk(r, 0);
262
+ found.sort((a, b) => b.t - a.t);
263
+ return found.length ? found[0].p : null;
264
+ }
265
+
266
+ // The current folder, unless the user can't write there (for example a shell opened in C:\Windows\System32).
267
+ let _base;
268
+ function writableBase() {
269
+ if (_base) return _base;
270
+ const os = require("os");
271
+ for (const dir of [process.cwd(), os.homedir(), os.tmpdir()]) {
272
+ try { fs.mkdirSync(path.join(dir, "statute-report"), { recursive: true }); fs.accessSync(path.join(dir, "statute-report"), fs.constants.W_OK); return (_base = dir); } catch {}
273
+ }
274
+ return (_base = os.tmpdir());
275
+ }
276
+
277
+ const HELP = `Statute: Kane CLI checks your app against consumer law in a real browser.
278
+ Code, not a model, decides the verdict. Run any command with npx @miracle352/statute <command>
279
+
280
+ demo see it work: re-judge recorded Kane runs (no account, no credits)
281
+ check consent --url <url> Kane clicks Reject on the cookie banner; Statute reports what still tracked
282
+ check price --url <url> is the price shown the price paid at checkout?
283
+ check cancel --url <url> is cancelling as easy as subscribing?
284
+ fix <check> --url <url> --start "<cmd>" --app <dir>
285
+ Kane finds it, Claude Code fixes it, Kane proves the fix
286
+ init [--fix] [--live <url>] add the GitHub workflows: every pull request, and production every night
287
+ judge <check> --latest judge the newest sealed Kane pack (for example after kane-cli testmd run laws/...)
288
+ expect <name>_test.md --url <u> run any Kane test and check what the page did: requests, data leaving
289
+ the site, cookies, errors, numbers (rules in the test file; --fix to repair)
290
+ skill [--project] install the agent skill: Claude Code runs Statute after risky changes
291
+ hook Claude Code Stop hook: no "done" until Kane passes
292
+ mcp MCP server: gives any agent a statute_check tool
293
+
294
+ Checks need Kane CLI: npm install -g @testmuai/kane-cli, then kane-cli login
295
+ (or set LT_USERNAME and LT_ACCESS_KEY). Docs: https://github.com/miracle352/statute`;
296
+
297
+ async function main() {
298
+ const [cmd, packId] = process.argv.slice(2);
299
+ if (!cmd || cmd === "help" || cmd === "--help" || cmd === "-h") { console.log(HELP); return; }
300
+ if (cmd === "--version" || cmd === "-v") { console.log(require("../package.json").version); return; }
301
+ if (cmd === "init") return require("./init.js")();
302
+ if (cmd === "skill") return installSkill();
303
+ if (cmd === "demo") return replay(packId);
304
+ if (cmd === "reset-demo") return resetDemo();
305
+ if (cmd === "mcp") return require("./mcp.js");
306
+ if (cmd === "hook") return require("./hook.js");
307
+ if (cmd === "replay") return replay(packId);
308
+ if (cmd === "expect") process.exit(await require("../src/expect-cli").main(process.argv.slice(3), { arg, latestPack, writableBase }));
309
+ if (cmd === "report") {
310
+ const html = page.build({ out: path.resolve(arg("out", "statute-report")), packs: PACKS });
311
+ console.log(`Case file: ${html}`);
312
+ return;
313
+ }
314
+ const pack = PACKS[packId];
315
+ const usage =
316
+ "usage:\n" +
317
+ " statute check <pack> --url <url> [--start \"<cmd>\"] [--show]\n" +
318
+ " statute judge <pack> [--latest | --evidence <file>] judge a sealed Kane pack, no credits\n" +
319
+ " statute fix <pack> --url <url> --start \"<cmd>\" --app <dir> [--rounds 3]\n" +
320
+ " statute report rebuild the case file (statute-report/index.html)\n" +
321
+ " statute reset-demo\n" +
322
+ `packs: ${Object.keys(PACKS).join(", ")}`;
323
+ if (!["check", "judge", "fix"].includes(cmd) || !pack) { console.error(usage); process.exit(2); }
324
+
325
+ const out = path.resolve(arg("out", "statute-report"));
326
+ fs.mkdirSync(out, { recursive: true });
327
+ const start = arg("start") === true ? null : arg("start", null);
328
+ const opts = { url: arg("url"), out, start, cwd: process.cwd(), show: !!arg("show", false), app: path.resolve(arg("app", ".")) };
329
+
330
+ if (cmd === "judge") {
331
+ const last = path.join(out, `${pack.id}.last-run.json`);
332
+ let saved = fs.existsSync(last) ? JSON.parse(fs.readFileSync(last, "utf8")) : {};
333
+ const ev = arg("evidence");
334
+ const positional = process.argv.slice(4).find((a) => a.endsWith(".evidence"));
335
+ if (ev && ev !== true) saved = { ...saved, packPath: ev };
336
+ else if (positional) saved = { ...saved, packPath: positional };
337
+ else if (arg("latest")) {
338
+ const found = latestPack();
339
+ if (!found) { console.error("No sealed Kane evidence pack found in .testmuai/evidence/ or your Kane sessions folder. Run a Kane test first, or pass --evidence <file>."); process.exit(3); }
340
+ console.log(`Judging ${found}`);
341
+ saved = { packPath: found };
342
+ }
343
+ const r = judgeAndReport(pack, { ...saved, out });
344
+ process.exit(r.result.verdict === "pass" ? 0 : r.result.verdict === "violation" ? 1 : 3);
345
+ }
346
+ if (!opts.url || opts.url === true) { console.error("--url is required\n\n" + usage); process.exit(2); }
347
+ if (!kane.available()) {
348
+ console.error("Statute needs Kane CLI to visit the site.\n npm install -g @testmuai/kane-cli\n kane-cli login (or set LT_USERNAME and LT_ACCESS_KEY)\n\nNo account yet? Free credits: https://www.testmuai.com/kane-cli/\nTo see Statute work without Kane: npx @miracle352/statute demo");
349
+ process.exit(3);
350
+ }
351
+ if (cmd === "check") {
352
+ fs.rmSync(path.join(out, "loop.json"), { force: true });
353
+ const r = await check(pack, opts);
354
+ console.log(`Case file: ${page.build({ out, packs: PACKS })}`);
355
+ process.exit(r.result.verdict === "pass" ? 0 : r.result.verdict === "violation" ? 1 : 3);
356
+ }
357
+ if (!start) { console.error("fix needs --start \"<command that runs your app>\" so Statute can restart it after each change"); process.exit(2); }
358
+ fs.rmSync(path.join(out, "loop.json"), { force: true });
359
+ process.exit(await fixLoop(pack, opts));
360
+ }
361
+
362
+ main().catch((e) => { console.error("\nStatute stopped: " + (e.message || e)); process.exit(3); });