@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.
- package/LICENSE +21 -0
- package/README.md +319 -2
- package/action.yml +356 -0
- package/bin/hook.js +81 -0
- package/bin/init.js +142 -0
- package/bin/mcp.js +166 -0
- package/bin/scope.js +78 -0
- package/bin/shots.js +52 -0
- package/bin/statute.js +362 -0
- package/examples/expect/newsletter_test.md +22 -0
- package/examples/expect/output-newsletter/.internal/execution.json +2053 -0
- package/examples/expect/output-newsletter/.internal/meta.json +39 -0
- package/examples/expect/output-newsletter/.internal/steps/1-d2368411/flows/0/actions.ndjson +2 -0
- package/examples/expect/output-newsletter/.internal/steps/2-a9e761f8/flows/0/actions.ndjson +6 -0
- package/examples/expect/output-newsletter/.internal/steps/3-63305a01/flows/0/actions.ndjson +2 -0
- package/examples/expect/output-newsletter/Result.md +21 -0
- package/examples/expect/search_test.md +20 -0
- package/laws/README.md +24 -0
- package/laws/accept_still_works_test.md +12 -0
- package/laws/cancel_as_easy_as_signup_test.md +15 -0
- package/laws/output-reject_means_reject/.internal/execution.json +1279 -0
- package/laws/output-reject_means_reject/.internal/meta.json +18 -0
- package/laws/output-reject_means_reject/.internal/steps/1-567cc234/flows/0/actions.ndjson +6 -0
- package/laws/output-reject_means_reject/.internal/steps/2-e3c06462/flows/0/actions.ndjson +1 -0
- package/laws/output-reject_means_reject/.internal/steps/3-3040a29b/flows/0/actions.ndjson +2 -0
- package/laws/output-reject_means_reject/Result.md +21 -0
- package/laws/price_shown_is_price_paid_test.md +12 -0
- package/laws/reject_means_reject_test.md +15 -0
- package/package.json +65 -4
- package/replays/cancel-demo-shop/evidence/cancel-1794754943192.evidence +0 -0
- package/replays/cancel-demo-shop/evidence/cancel-1794755110410.evidence +0 -0
- package/replays/cancel-demo-shop/loop.json +32 -0
- package/replays/demo-shop/evidence/consent-1794751413210.evidence +0 -0
- package/replays/demo-shop/evidence/consent-1794751523524.evidence +0 -0
- package/replays/demo-shop/evidence/consent-accept-1794751588395.evidence +0 -0
- package/replays/demo-shop/loop.json +40 -0
- package/replays/haxcms/evidence/consent-1794831086682.evidence +0 -0
- package/replays/haxcms/evidence/consent-1794831262757.evidence +0 -0
- package/replays/haxcms/evidence/consent-accept-1794831347132.evidence +0 -0
- package/replays/haxcms/loop.json +56 -0
- package/replays/in-the-wake-check/consent.json +67 -0
- package/replays/in-the-wake-check/consent.md +32 -0
- package/replays/kane-testmd-demo-shop/evidence/consent-1794935266000.evidence +0 -0
- package/replays/kane-testmd-demo-shop/loop.json +18 -0
- package/replays/lumen-pr-2/evidence/consent-1794929771799.evidence +0 -0
- package/replays/lumen-pr-2/evidence/consent-1794929845913.evidence +0 -0
- package/replays/lumen-pr-2/evidence/consent-accept-1794929886905.evidence +0 -0
- package/replays/lumen-pr-2/loop.json +57 -0
- package/replays/newsletter-expect/evidence/newsletter_test-round1-1795518837738.evidence +0 -0
- package/replays/newsletter-expect/evidence/newsletter_test-round2-1795519079029.evidence +0 -0
- package/replays/newsletter-expect/loop.json +99 -0
- package/replays/price-demo-shop/evidence/price-1794837093949.evidence +0 -0
- package/replays/price-demo-shop/evidence/price-1794837311639.evidence +0 -0
- package/replays/price-demo-shop/loop.json +43 -0
- package/rules/trackers.json +61 -0
- package/site/assets/fonts/OFL-archivo.txt +93 -0
- package/site/assets/fonts/OFL-geist.txt +93 -0
- package/site/assets/fonts/OFL-instrument-serif.txt +93 -0
- package/site/assets/fonts/archivo.woff2 +0 -0
- package/site/assets/fonts/geist.woff2 +0 -0
- package/site/assets/fonts/instrument-serif-italic.woff2 +0 -0
- package/site/assets/fonts/instrument-serif.woff2 +0 -0
- package/site/assets/fonts/inter.woff2 +0 -0
- package/site/assets/fonts/jetbrains-mono.woff2 +0 -0
- package/skill/statute/SKILL.md +57 -0
- package/src/agent.js +70 -0
- package/src/app.js +41 -0
- package/src/evidence.js +80 -0
- package/src/expect-cli.js +296 -0
- package/src/expect-view.js +79 -0
- package/src/expect.js +392 -0
- package/src/infer.js +32 -0
- package/src/kane.js +124 -0
- package/src/pack.js +128 -0
- package/src/packs/cancel.js +83 -0
- package/src/packs/consent-accept.js +57 -0
- package/src/packs/consent.js +237 -0
- package/src/packs/price.js +104 -0
- package/src/page.js +360 -0
- package/src/report.js +59 -0
- package/src/zip.js +38 -0
package/src/app.js
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
// Starts and stops the app under test so each Kane run sees the latest code.
|
|
2
|
+
const { spawn, execSync } = require("child_process");
|
|
3
|
+
const http = require("http");
|
|
4
|
+
const https = require("https");
|
|
5
|
+
|
|
6
|
+
function start(command, cwd) {
|
|
7
|
+
const child = spawn(command, { cwd, shell: true, stdio: "ignore", detached: process.platform !== "win32" });
|
|
8
|
+
return child;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function stop(child) {
|
|
12
|
+
if (!child || child.exitCode !== null) return;
|
|
13
|
+
try {
|
|
14
|
+
if (process.platform === "win32") execSync(`taskkill /pid ${child.pid} /T /F`, { stdio: "ignore" });
|
|
15
|
+
else process.kill(-child.pid, "SIGTERM");
|
|
16
|
+
} catch {
|
|
17
|
+
try { child.kill(); } catch { /* already gone */ }
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function ping(url) {
|
|
22
|
+
return new Promise((resolve) => {
|
|
23
|
+
const lib = /^https:/i.test(url) ? https : http;
|
|
24
|
+
let req;
|
|
25
|
+
try { req = lib.get(url, { headers: { "user-agent": "Mozilla/5.0 (Statute reachability check)" } }, (res) => { res.resume(); resolve(res.statusCode < 500); }); }
|
|
26
|
+
catch { return resolve(false); }
|
|
27
|
+
req.on("error", () => resolve(false));
|
|
28
|
+
req.setTimeout(2000, () => { req.destroy(); resolve(false); });
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function waitUntilUp(url, ms = 20000) {
|
|
33
|
+
const until = Date.now() + ms;
|
|
34
|
+
while (Date.now() < until) {
|
|
35
|
+
if (await ping(url)) return true;
|
|
36
|
+
await new Promise((r) => setTimeout(r, 400));
|
|
37
|
+
}
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
module.exports = { start, stop, waitUntilUp, ping };
|
package/src/evidence.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Reads what Kane recorded: network traffic (HAR) from a sealed evidence pack.
|
|
2
|
+
const fs = require("fs");
|
|
3
|
+
const path = require("path");
|
|
4
|
+
const zip = require("./zip");
|
|
5
|
+
|
|
6
|
+
function newestPack(sessionDir) {
|
|
7
|
+
const dir = path.join(sessionDir, "evidence");
|
|
8
|
+
if (!fs.existsSync(dir)) return null;
|
|
9
|
+
const packs = fs.readdirSync(dir)
|
|
10
|
+
.filter((f) => f.endsWith(".evidence"))
|
|
11
|
+
.map((f) => path.join(dir, f))
|
|
12
|
+
.sort((a, b) => fs.statSync(b).mtimeMs - fs.statSync(a).mtimeMs);
|
|
13
|
+
return packs[0] || null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function networkFromPack(packPath) {
|
|
17
|
+
const buf = fs.readFileSync(packPath);
|
|
18
|
+
const list = zip.entries(buf);
|
|
19
|
+
const requests = [];
|
|
20
|
+
for (const e of list) {
|
|
21
|
+
if (!/logs\/[^/]*network\.har$/.test(e.name)) continue;
|
|
22
|
+
let har;
|
|
23
|
+
try { har = JSON.parse(zip.read(buf, e).toString("utf8")); } catch { continue; }
|
|
24
|
+
for (const h of (har.log && har.log.entries) || []) {
|
|
25
|
+
const setCookies = ((h.response && h.response.headers) || [])
|
|
26
|
+
.filter((x) => x.name.toLowerCase() === "set-cookie")
|
|
27
|
+
.map((x) => x.value.split("=")[0].trim());
|
|
28
|
+
// Cookies the browser sent with this request: proves which cookies existed
|
|
29
|
+
// at that moment, including ones set by JavaScript (like _ga).
|
|
30
|
+
const req = h.request || {};
|
|
31
|
+
const sent = new Set(((req.cookies) || []).map((c) => c.name));
|
|
32
|
+
for (const x of req.headers || []) {
|
|
33
|
+
if (x.name.toLowerCase() !== "cookie") continue;
|
|
34
|
+
for (const part of x.value.split(";")) {
|
|
35
|
+
const n = part.split("=")[0].trim();
|
|
36
|
+
if (n) sent.add(n);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
requests.push({
|
|
40
|
+
time: h.startedDateTime,
|
|
41
|
+
method: req.method,
|
|
42
|
+
url: req.url,
|
|
43
|
+
status: h.response && h.response.status,
|
|
44
|
+
setCookies,
|
|
45
|
+
sentCookies: [...sent],
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
// Kane's own log of what it did and when (used to find the moment of a click).
|
|
50
|
+
const actions = [];
|
|
51
|
+
for (const e of list) {
|
|
52
|
+
if (!/logs\/[^/]*actions\.ndjson$/.test(e.name)) continue;
|
|
53
|
+
for (const line of zip.read(buf, e).toString("utf8").split("\n")) {
|
|
54
|
+
if (!line.trim()) continue;
|
|
55
|
+
try {
|
|
56
|
+
const a = JSON.parse(line);
|
|
57
|
+
actions.push({
|
|
58
|
+
type: a.action_type,
|
|
59
|
+
instruction: a.action_instruction || "",
|
|
60
|
+
intent: a.intent || "",
|
|
61
|
+
status: a.status,
|
|
62
|
+
time: a.timestamp,
|
|
63
|
+
outputVariable: a.output_variable || null,
|
|
64
|
+
outputValue: a.output_value == null ? null : a.output_value,
|
|
65
|
+
});
|
|
66
|
+
} catch { /* skip */ }
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
// Shareable Kane run link, if the pack carries one.
|
|
70
|
+
let shareLink = null;
|
|
71
|
+
const result = list.find((e) => /result\.yaml$/.test(e.name));
|
|
72
|
+
if (result) {
|
|
73
|
+
const m = zip.read(buf, result).toString("utf8").match(/sharable_link:\s*(\S+)/);
|
|
74
|
+
if (m) shareLink = m[1];
|
|
75
|
+
}
|
|
76
|
+
const screenshots = list.filter((e) => /steps\/[^/]+\/screenshot\.(png|jpg)$/.test(e.name)).map((e) => e.name);
|
|
77
|
+
return { requests, actions, shareLink, screenshots, harFiles: list.filter((e) => e.name.endsWith(".har")).length };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
module.exports = { newestPack, networkFromPack };
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
// `statute expect`: run a Kane CLI test file (or take a sealed pack) and check
|
|
2
|
+
// its expectations against what Kane recorded. Optional --fix hands broken
|
|
3
|
+
// expectations to Claude Code and has Kane run the test again until they hold.
|
|
4
|
+
const fs = require("fs");
|
|
5
|
+
const path = require("path");
|
|
6
|
+
const crypto = require("crypto");
|
|
7
|
+
const { spawn } = require("child_process");
|
|
8
|
+
const packReader = require("./pack");
|
|
9
|
+
const expect = require("./expect");
|
|
10
|
+
const { infer } = require("./infer");
|
|
11
|
+
const kane = require("./kane");
|
|
12
|
+
const app = require("./app");
|
|
13
|
+
const agent = require("./agent");
|
|
14
|
+
|
|
15
|
+
const sha256 = (b) => crypto.createHash("sha256").update(b).digest("hex");
|
|
16
|
+
const ICON = { pass: "PASS", fail: "FAIL", unknown: "----" };
|
|
17
|
+
const creditsLine = (n) => (n > 0 ? ` Credits used: ${n.toFixed(1)}` : "");
|
|
18
|
+
|
|
19
|
+
// A sidecar in Kane's own verdict format (evidence-cli verdict.schema.json),
|
|
20
|
+
// next to the pack, like `kane-cli evidence verdict` writes its own.
|
|
21
|
+
function writeVerdict(packPath, rules, judged) {
|
|
22
|
+
let run = {};
|
|
23
|
+
try {
|
|
24
|
+
const buf = fs.readFileSync(packPath);
|
|
25
|
+
const zip = require("./zip");
|
|
26
|
+
const e = zip.entries(buf).find((x) => x.name === "run.yaml");
|
|
27
|
+
if (e) {
|
|
28
|
+
const y = zip.read(buf, e).toString("utf8");
|
|
29
|
+
run = { id: (y.match(/^id:\s*(\S+)/m) || y.match(/^run_id:\s*(\S+)/m) || [])[1] || null, contract: (y.match(/^evidence:\s*'?([^'\s]+)/m) || [])[1] || null };
|
|
30
|
+
}
|
|
31
|
+
} catch {}
|
|
32
|
+
const gates = judged.results.map((r, i) => ({
|
|
33
|
+
id: `expect-${i + 1}`,
|
|
34
|
+
expr: r.rule,
|
|
35
|
+
where: null,
|
|
36
|
+
op: "expr",
|
|
37
|
+
expected: true,
|
|
38
|
+
actual: r.status === "unknown" ? null : r.status === "pass",
|
|
39
|
+
severity: "blocking",
|
|
40
|
+
status: r.status === "unknown" ? "errored" : r.status,
|
|
41
|
+
trust: r.status === "unknown" ? null : "recomputed",
|
|
42
|
+
message: r.detail,
|
|
43
|
+
error: r.status === "unknown" ? { code: "statute.unresolved", message: r.detail, hint: null } : null,
|
|
44
|
+
stored: null,
|
|
45
|
+
}));
|
|
46
|
+
const failed = gates.filter((g) => g.status === "fail").map((g) => g.id);
|
|
47
|
+
const errored = gates.filter((g) => g.status === "errored").map((g) => g.id);
|
|
48
|
+
const result = errored.length ? "errored" : failed.length ? "fail" : "pass";
|
|
49
|
+
const doc = {
|
|
50
|
+
result,
|
|
51
|
+
evaluated_at: new Date().toISOString(),
|
|
52
|
+
evaluator: `statute ${require("../package.json").version}`,
|
|
53
|
+
pack: { run_id: run.id || null, sha256: sha256(fs.readFileSync(packPath)), contract: run.contract || null },
|
|
54
|
+
policy: { id: "statute", sha256: sha256(rules.join("\n")) },
|
|
55
|
+
catalog: null,
|
|
56
|
+
error: null,
|
|
57
|
+
gates,
|
|
58
|
+
failed_gates: failed,
|
|
59
|
+
warnings: [],
|
|
60
|
+
errored_gates: errored,
|
|
61
|
+
exit_code: result === "pass" ? 0 : result === "fail" ? 1 : 3,
|
|
62
|
+
};
|
|
63
|
+
const dir = `${packPath}.verdicts`;
|
|
64
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
65
|
+
const file = path.join(dir, "statute.verdict.json");
|
|
66
|
+
fs.writeFileSync(file, JSON.stringify(doc, null, 2));
|
|
67
|
+
return file;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function reportMd(judged, { testName, packPath, kaneStatus, shareLink }) {
|
|
71
|
+
const L = [];
|
|
72
|
+
L.push(`## Statute: ${judged.verdict.toUpperCase()}${testName ? ` · ${testName}` : ""}`, "");
|
|
73
|
+
L.push(`Kane's own result: ${kaneStatus || "unknown"} (that only says the steps ran). Statute checked what the page did, from Kane's sealed evidence${judged.site ? ` on ${judged.site}` : ""}:`, "");
|
|
74
|
+
if (judged.inferred) L.push("The test had no expectations, so Statute wrote them from what Kane did (where it typed, where it refused cookies).", "");
|
|
75
|
+
L.push("| | Expectation | What Kane recorded |", "|---|---|---|");
|
|
76
|
+
for (const r of judged.results) L.push(`| ${ICON[r.status]} | ${r.rule.replace(/\|/g, "\\|")} | ${r.detail.replace(/\|/g, "\\|")} |`);
|
|
77
|
+
L.push("");
|
|
78
|
+
for (const r of judged.results.filter((x) => x.status === "fail" && x.evidence && x.evidence.length)) {
|
|
79
|
+
L.push(`**${r.rule}**`, "");
|
|
80
|
+
for (const e of r.evidence.slice(0, 8)) L.push(`- ${[e.time, e.method, e.status, e.host, e.how, e.url, e.text].filter(Boolean).join(" · ")}`);
|
|
81
|
+
L.push("");
|
|
82
|
+
}
|
|
83
|
+
if (shareLink) L.push(`Kane run: ${shareLink}`, "");
|
|
84
|
+
if (packPath) L.push(`Evidence pack: \`${packPath}\``, "");
|
|
85
|
+
return L.join("\n");
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Content hashes of the app's files, to tell whether the agent really changed anything.
|
|
89
|
+
function fingerprint(dir) {
|
|
90
|
+
const map = new Map();
|
|
91
|
+
const walk = (d, depth) => {
|
|
92
|
+
let list;
|
|
93
|
+
try { list = fs.readdirSync(d, { withFileTypes: true }); } catch { return; }
|
|
94
|
+
for (const e of list) {
|
|
95
|
+
if (/^(node_modules|\.git|statute-report|\.testmuai)$/.test(e.name) || /^output-/.test(e.name)) continue;
|
|
96
|
+
const p = path.join(d, e.name);
|
|
97
|
+
if (e.isDirectory() && depth < 6) walk(p, depth + 1);
|
|
98
|
+
else if (e.isFile()) { try { if (fs.statSync(p).size < 2e6) map.set(path.relative(dir, p), sha256(fs.readFileSync(p))); } catch {} }
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
walk(dir, 0);
|
|
102
|
+
return map;
|
|
103
|
+
}
|
|
104
|
+
const changedFiles = (a, b) => [...new Set([...a.keys(), ...b.keys()])].filter((k) => a.get(k) !== b.get(k)).sort();
|
|
105
|
+
|
|
106
|
+
function newestPackSince(dir, since) {
|
|
107
|
+
const found = [];
|
|
108
|
+
const walk = (d, depth) => {
|
|
109
|
+
let list;
|
|
110
|
+
try { list = fs.readdirSync(d, { withFileTypes: true }); } catch { return; }
|
|
111
|
+
for (const e of list) {
|
|
112
|
+
const p = path.join(d, e.name);
|
|
113
|
+
if (e.isDirectory() && depth < 4 && !e.name.endsWith(".verdicts")) walk(p, depth + 1);
|
|
114
|
+
else if (e.name.endsWith(".evidence")) { const t = fs.statSync(p).mtimeMs; if (t >= since) found.push({ p, t }); }
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
walk(dir, 0);
|
|
118
|
+
found.sort((a, b) => b.t - a.t);
|
|
119
|
+
return found.length ? found[0].p : null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// kane-cli testmd run <file> --agent --url <url>: returns the NDJSON events and the sealed pack.
|
|
123
|
+
function runTest(file, { url, headless = true, maxSteps, timeout = 600, onEvent }) {
|
|
124
|
+
const bin = kane.binary();
|
|
125
|
+
const args = ["testmd", "run", file, "--agent", "--timeout", String(timeout)];
|
|
126
|
+
if (url) {
|
|
127
|
+
// {{url}} in the test file: Kane reads variables from a file (safe on every shell).
|
|
128
|
+
const vf = path.join(require("os").tmpdir(), `statute-vars-${process.pid}.json`);
|
|
129
|
+
fs.writeFileSync(vf, JSON.stringify({ url: { value: url } }));
|
|
130
|
+
args.push("--url", url, "--variables-file", vf);
|
|
131
|
+
}
|
|
132
|
+
if (headless) args.push("--headless");
|
|
133
|
+
if (maxSteps) args.push("--max-steps", String(maxSteps));
|
|
134
|
+
if (process.env.LT_USERNAME && process.env.LT_ACCESS_KEY) args.push("--username", process.env.LT_USERNAME, "--access-key", process.env.LT_ACCESS_KEY);
|
|
135
|
+
const started = Date.now() - 1000;
|
|
136
|
+
const child = bin
|
|
137
|
+
? spawn(process.execPath, [bin, ...args], { stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, KANE_CLI_USER_AGENT: "statute" } })
|
|
138
|
+
: spawn("kane-cli", args, { shell: process.platform === "win32", stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, KANE_CLI_USER_AGENT: "statute" } });
|
|
139
|
+
return kane.collect(child, onEvent, timeout).then((res) => {
|
|
140
|
+
const packPath = newestPackSince(path.join(process.cwd(), ".testmuai"), started) || newestPackSince(path.dirname(path.resolve(file)), started);
|
|
141
|
+
return { ...res, packPath };
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function judgePack(packPath, { rulesFile, testName, kaneStatus } = {}) {
|
|
146
|
+
const pack = packReader.read(packPath);
|
|
147
|
+
let rules = pack.expectations;
|
|
148
|
+
if (rulesFile) rules = fs.readFileSync(rulesFile, "utf8").split(/\r?\n/).map((l) => l.replace(/^\s*[-*]\s+/, "").trim()).filter((l) => l && !l.startsWith("#"));
|
|
149
|
+
let inferred = null;
|
|
150
|
+
if (!rules.length) {
|
|
151
|
+
// No expectations written: work them out from what Kane did.
|
|
152
|
+
inferred = infer(pack);
|
|
153
|
+
rules = inferred.map((r) => r.rule);
|
|
154
|
+
}
|
|
155
|
+
const judged = expect.judge(pack, rules);
|
|
156
|
+
judged.inferred = inferred;
|
|
157
|
+
const md = reportMd(judged, { testName: testName || (pack.testMd && (pack.testMd.match(/^#\s+(.+)$/m) || [])[1]), packPath, kaneStatus: kaneStatus || pack.kaneStatus, shareLink: pack.shareLink });
|
|
158
|
+
const verdictFile = writeVerdict(packPath, rules, judged);
|
|
159
|
+
return { judged, md, verdictFile, rules, pack };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function print(judged, verdictFile) {
|
|
163
|
+
console.log("");
|
|
164
|
+
if (judged.inferred) {
|
|
165
|
+
console.log("This test has no expectations, so Statute wrote these from what Kane did.\nTo keep them, paste this into the test file:\n\n<!-- expect");
|
|
166
|
+
for (const r of judged.inferred) console.log(`- ${r.rule}`);
|
|
167
|
+
console.log("-->\n");
|
|
168
|
+
}
|
|
169
|
+
for (const r of judged.results) console.log(` ${ICON[r.status]} ${r.rule}\n ${r.detail}`);
|
|
170
|
+
console.log(`\n${judged.verdict.toUpperCase()}: ${judged.why}`);
|
|
171
|
+
if (judged.kaneStatus) console.log(`(Kane's own result for the same run: ${judged.kaneStatus}.)`);
|
|
172
|
+
console.log(`Verdict file: ${verdictFile}`);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const HELP = `statute expect: check what the page did while Kane ran your test.
|
|
176
|
+
|
|
177
|
+
statute expect <name>_test.md --url <url> [--start "<cmd>"] [--show]
|
|
178
|
+
statute expect <name>_test.md --url <url> --start "<cmd>" --fix [--app <dir>] [--rounds 3]
|
|
179
|
+
statute expect <pack.evidence> | --latest judge a sealed pack again, no credits
|
|
180
|
+
options: --rules <file> --out <dir> --json
|
|
181
|
+
|
|
182
|
+
No expectations in the test? Statute writes them from what Kane did: what was
|
|
183
|
+
typed never leaves the site, nothing tracks after a refusal, no server errors.
|
|
184
|
+
Or write your own in the test file, in a comment Kane ignores:
|
|
185
|
+
|
|
186
|
+
<!-- expect
|
|
187
|
+
- no request to a tracker after "Refuse cookies"
|
|
188
|
+
- what was typed in "Newsletter" never leaves this site
|
|
189
|
+
-->
|
|
190
|
+
|
|
191
|
+
Rules Statute understands (steps are your "## headings"; after/before = after
|
|
192
|
+
or before the last thing Kane did in that step):
|
|
193
|
+
|
|
194
|
+
no request to a tracker | a third party | <host> [after|before|during "<step>"]
|
|
195
|
+
no visitor ID sent to a tracker [after|before|during "<step>"]
|
|
196
|
+
no tracker cookie [after|before|during "<step>"]
|
|
197
|
+
what was typed in "<step>" never leaves this site (plain, URL-encoded, Base64 or SHA-256)
|
|
198
|
+
text "<value>" never leaves this site
|
|
199
|
+
value of $<kane_variable> never leaves this site
|
|
200
|
+
no server errors | no failed requests to this site | no console errors
|
|
201
|
+
value $<a> equals | is at most | is at least $<b> [plus $<c> | <number>]
|
|
202
|
+
clicks in "<step>" at most clicks in "<step>" [plus <n>]
|
|
203
|
+
|
|
204
|
+
Exit codes: 0 every expectation held, 1 one broke, 3 could not be checked.
|
|
205
|
+
A verdict in Kane's own format is written next to the pack: <pack>.verdicts/statute.verdict.json`;
|
|
206
|
+
|
|
207
|
+
async function main(argv, { arg, latestPack, writableBase }) {
|
|
208
|
+
const target = argv[0];
|
|
209
|
+
if (!target || target === "--help" || target === "-h") { console.log(HELP); return 0; }
|
|
210
|
+
const out = path.resolve(arg("out", path.join(writableBase(), "statute-report")));
|
|
211
|
+
fs.mkdirSync(out, { recursive: true });
|
|
212
|
+
const rulesFile = arg("rules") === true ? null : arg("rules", null);
|
|
213
|
+
const finish = (r) => {
|
|
214
|
+
fs.writeFileSync(path.join(out, "expect.md"), "" + r.md);
|
|
215
|
+
fs.writeFileSync(path.join(out, "expect.json"), JSON.stringify(r.judged, null, 2));
|
|
216
|
+
if (arg("json")) console.log(JSON.stringify(r.judged, null, 2)); else print(r.judged, r.verdictFile);
|
|
217
|
+
console.log(`Report: ${path.join(out, "expect.md")}`);
|
|
218
|
+
return r.judged.verdict === "pass" ? 0 : r.judged.verdict === "violation" ? 1 : 3;
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
if (target === "--latest" || target.endsWith(".evidence")) {
|
|
222
|
+
const p = target === "--latest" ? latestPack() : path.resolve(target);
|
|
223
|
+
if (!p || !fs.existsSync(p)) { console.error("No sealed Kane evidence pack found. Run a Kane test first, or pass the .evidence file."); return 3; }
|
|
224
|
+
console.log(`Checking ${p}`);
|
|
225
|
+
return finish(judgePack(p, { rulesFile }));
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (!/_test\.md$/i.test(target) || !fs.existsSync(target)) { console.error(`Not a Kane test file: ${target} (expected <name>_test.md)\n\n${HELP}`); return 2; }
|
|
229
|
+
const url = arg("url");
|
|
230
|
+
if (!url || url === true) { console.error("--url is required to run the test"); return 2; }
|
|
231
|
+
const start = arg("start") === true ? null : arg("start", null);
|
|
232
|
+
const testText = fs.readFileSync(target, "utf8");
|
|
233
|
+
if (!kane.available()) { console.error("Statute needs Kane CLI: npm install -g @testmuai/kane-cli, then kane-cli login"); return 3; }
|
|
234
|
+
const testName = (testText.match(/^#\s+(.+)$/m) || [])[1] || path.basename(target);
|
|
235
|
+
const fixing = !!arg("fix");
|
|
236
|
+
const rounds = fixing ? Number(arg("rounds", 3)) : 1;
|
|
237
|
+
const appDir = path.resolve(arg("app", "."));
|
|
238
|
+
const timeline = [];
|
|
239
|
+
let spent = 0;
|
|
240
|
+
|
|
241
|
+
for (let round = 1; round <= rounds; round++) {
|
|
242
|
+
let child = null;
|
|
243
|
+
if (start) {
|
|
244
|
+
child = app.start(start, process.cwd());
|
|
245
|
+
if (!(await app.waitUntilUp(url))) { app.stop(child); console.error(`The app did not come up at ${url} after "${start}"`); return 3; }
|
|
246
|
+
} else if (/^https?:\/\/(localhost|127\.|\[::1\])/i.test(url) && !(await app.ping(url))) { console.error(`Nothing is answering at ${url}; start the app or pass --start "<command>"`); return 3; }
|
|
247
|
+
let res;
|
|
248
|
+
try {
|
|
249
|
+
console.log(`\nStatute · ${testName}${fixing ? ` · round ${round}` : ""}\nKane is running ${path.basename(target)} against ${url}...`);
|
|
250
|
+
res = await runTest(target, {
|
|
251
|
+
url, headless: !arg("show"), maxSteps: arg("max-steps") === true ? undefined : arg("max-steps"),
|
|
252
|
+
onEvent: (e) => { if (e.step && e.status && e.status !== "running") console.log(` step ${e.step} ${e.status}: ${e.remark || ""}`); },
|
|
253
|
+
});
|
|
254
|
+
} finally { app.stop(child); }
|
|
255
|
+
if (!res.packPath) { console.error("Kane sealed no evidence pack.\n" + String(res.stderr || "").slice(-1200)); return 3; }
|
|
256
|
+
// Keep a copy with the report, so the case file travels with its evidence.
|
|
257
|
+
fs.mkdirSync(path.join(out, "evidence"), { recursive: true });
|
|
258
|
+
const kept = path.join(out, "evidence", `${path.basename(target, ".md")}-round${round}-${Date.now()}.evidence`);
|
|
259
|
+
fs.copyFileSync(res.packPath, kept);
|
|
260
|
+
res.packPath = kept;
|
|
261
|
+
const credits = Number((res.end && res.end.credits_consumed) || 0);
|
|
262
|
+
spent += credits;
|
|
263
|
+
const r = judgePack(res.packPath, { rulesFile, testName, kaneStatus: res.end && res.end.status });
|
|
264
|
+
timeline.push({ round, step: "kane", verdict: r.judged.verdict, why: r.judged.why, kaneStatus: res.end && res.end.status, credits, evidence: res.packPath, results: r.judged.results, at: new Date().toISOString() });
|
|
265
|
+
const code = finish(r);
|
|
266
|
+
fs.writeFileSync(path.join(out, "expect-loop.json"), JSON.stringify({ test: testName, url, timeline, credits: spent }, null, 2));
|
|
267
|
+
if (!fixing || code !== 1 || round === rounds) {
|
|
268
|
+
const agentChanged = timeline.some((t) => t.step === "agent" && t.changed && t.changed.length);
|
|
269
|
+
if (fixing) console.log(code === 0 ? `\n${agentChanged ? "FIXED and proven" : "PASSED"} in ${round} round(s).${creditsLine(spent)}` : `\nStopped after ${round} round(s): ${code === 1 ? "still broken" : "could not be checked"}.${creditsLine(spent)}`);
|
|
270
|
+
return code;
|
|
271
|
+
}
|
|
272
|
+
console.log(`\nHanding the broken expectations to Claude Code (round ${round})...`);
|
|
273
|
+
const before = fingerprint(appDir);
|
|
274
|
+
let summary;
|
|
275
|
+
try {
|
|
276
|
+
summary = await agent.fix({ appDir, text: agent.promptExpect({ reportMd: r.md, appDir, testName }), onLine: (l) => console.log(" claude │ " + l) });
|
|
277
|
+
} catch (e) {
|
|
278
|
+
console.log(`\n${e.message}\nNOT FIXED: the expectations above are still broken. Nothing was changed.${creditsLine(spent)}`);
|
|
279
|
+
timeline.push({ round, step: "agent", agent: "claude-code", error: e.message, at: new Date().toISOString() });
|
|
280
|
+
fs.writeFileSync(path.join(out, "expect-loop.json"), JSON.stringify({ test: testName, url, timeline, credits: spent }, null, 2));
|
|
281
|
+
return 1;
|
|
282
|
+
}
|
|
283
|
+
const changed = changedFiles(before, fingerprint(appDir));
|
|
284
|
+
if (!changed.length) {
|
|
285
|
+
console.log(`\nClaude Code answered but changed no file, so there is nothing for Kane to prove. NOT FIXED.${creditsLine(spent)}`);
|
|
286
|
+
timeline.push({ round, step: "agent", agent: "claude-code", summary, changed, at: new Date().toISOString() });
|
|
287
|
+
fs.writeFileSync(path.join(out, "expect-loop.json"), JSON.stringify({ test: testName, url, timeline, credits: spent }, null, 2));
|
|
288
|
+
return 1;
|
|
289
|
+
}
|
|
290
|
+
console.log(` Claude Code changed ${changed.join(", ")}`);
|
|
291
|
+
timeline.push({ round, step: "agent", agent: "claude-code", summary, changed, at: new Date().toISOString() });
|
|
292
|
+
}
|
|
293
|
+
return 1;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
module.exports = { main, judgePack, writeVerdict, reportMd, runTest, HELP };
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// What the judge page draws: the run on one time axis. Each step's recorded
|
|
2
|
+
// window, the gaps Kane didn't record, every request (site, tracker or other
|
|
3
|
+
// host), page loads, and which requests broke an expectation.
|
|
4
|
+
const expect = require("./expect");
|
|
5
|
+
const { REFUSE, PARTIAL } = require("./infer");
|
|
6
|
+
|
|
7
|
+
const MAX_REQUESTS = 2500;
|
|
8
|
+
|
|
9
|
+
function pathOf(u) {
|
|
10
|
+
try { const x = new URL(u); return x.pathname; } catch { return ""; }
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function view(pack, judged) {
|
|
14
|
+
const times = [...pack.actions.map((a) => a.time), ...pack.requests.map((r) => r.time)].filter(Boolean);
|
|
15
|
+
if (!times.length) return null;
|
|
16
|
+
const t0 = Math.min(...times);
|
|
17
|
+
const end = Math.max(...times);
|
|
18
|
+
const rel = (t) => (t == null ? null : t - t0);
|
|
19
|
+
const home = expect.homeSite(pack);
|
|
20
|
+
|
|
21
|
+
// A request is flagged when a broken expectation names it (same URL, and the
|
|
22
|
+
// same moment when the evidence has one).
|
|
23
|
+
const flags = [];
|
|
24
|
+
for (const r of judged.results) {
|
|
25
|
+
if (r.status !== "fail") continue;
|
|
26
|
+
for (const e of r.evidence || []) if (e && e.url) flags.push({ url: e.url, time: e.time ? Date.parse(e.time) : null, rule: r.rule, value: e.value || null });
|
|
27
|
+
}
|
|
28
|
+
const short = (u) => { try { const x = new URL(u); return x.host + x.pathname; } catch { return u; } };
|
|
29
|
+
const flagFor = (r) => flags.find((f) => (f.url === r.url || f.url === short(r.url)) && (f.time == null || f.time === r.time));
|
|
30
|
+
|
|
31
|
+
const steps = pack.sections.map((s) => {
|
|
32
|
+
const t = [...s.actions.map((a) => a.time), ...s.requests.map((r) => r.time)].filter(Boolean);
|
|
33
|
+
return {
|
|
34
|
+
index: s.index,
|
|
35
|
+
title: s.title,
|
|
36
|
+
from: t.length ? rel(Math.min(...t)) : null,
|
|
37
|
+
to: t.length ? rel(Math.max(...t)) : null,
|
|
38
|
+
actions: s.actions.filter((a) => a.time).map((a) => ({ t: rel(a.time), type: a.type, text: (a.instruction || a.intent || "").slice(0, 140) })),
|
|
39
|
+
};
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
const requests = pack.requests.filter((r) => r.time).slice(0, MAX_REQUESTS).map((r) => {
|
|
43
|
+
const host = expect.hostOf(r.url);
|
|
44
|
+
const hit = expect.trackerHit(r);
|
|
45
|
+
const f = flagFor(r);
|
|
46
|
+
return {
|
|
47
|
+
t: rel(r.time), step: r.section, method: r.method, status: r.status, host,
|
|
48
|
+
path: pathOf(r.url).slice(0, 120),
|
|
49
|
+
kind: expect.site(host) === home ? "site" : hit ? (hit.counted ? "tracker" : "tracker-quiet") : "other",
|
|
50
|
+
tracker: hit ? hit.tracker : null,
|
|
51
|
+
flagged: f ? { rule: f.rule, value: f.value } : null,
|
|
52
|
+
url: f ? r.url.slice(0, 4000) : null,
|
|
53
|
+
};
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const loads = pack.requests
|
|
57
|
+
.filter((r) => r.time && expect.site(expect.hostOf(r.url)) === home && (r.mime ? /html/i.test(r.mime) : r.method === "GET" && !/\.(js|css|png|jpe?g|gif|svg|webp|ico|woff2?|json)(\?|$)/i.test(r.url)))
|
|
58
|
+
.map((r) => ({ t: rel(r.time), path: pathOf(r.url) }));
|
|
59
|
+
|
|
60
|
+
// Gaps: stretches between recorded windows, longer than half a second.
|
|
61
|
+
const windows = steps.filter((s) => s.from != null).map((s) => [s.from, s.to]).sort((a, b) => a[0] - b[0]);
|
|
62
|
+
const gaps = [];
|
|
63
|
+
for (let i = 1; i < windows.length; i++) {
|
|
64
|
+
const a = Math.max(...windows.slice(0, i).map((w) => w[1]));
|
|
65
|
+
const b = windows[i][0];
|
|
66
|
+
if (b - a > 500) gaps.push({ from: a, to: b });
|
|
67
|
+
}
|
|
68
|
+
const early = expect.settle(pack);
|
|
69
|
+
const refusals = pack.actions
|
|
70
|
+
.filter((a) => a.time && /click|tap|press/i.test(a.type || "") && REFUSE.test(a.instruction || "") && !PARTIAL.test(a.instruction || ""))
|
|
71
|
+
.map((a) => ({ t: rel(a.time), text: a.instruction.slice(0, 100) }));
|
|
72
|
+
|
|
73
|
+
return {
|
|
74
|
+
duration: end - t0, home, steps, requests, truncated: pack.requests.length > MAX_REQUESTS,
|
|
75
|
+
loads, gaps, refusals, settle: early ? { recorded: early.gap, needed: expect.SETTLE_MS, path: pathOf(early.url) } : null,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
module.exports = { view };
|