crossexamdev 0.0.0-stage → 0.2.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/src/claims.js ADDED
@@ -0,0 +1,120 @@
1
+ // Claim detection: find sentences where an agent asserts something is done
2
+ // and classify what kind of claim it is.
3
+
4
+ /** @typedef {'tests'|'build'|'types'|'lint'|'refactor'|'migration'|'deps'|'security'} ClaimKind */
5
+
6
+ const KINDS = /** @type {const} */ ({
7
+ tests: [
8
+ /\b(?:all\s+)?(?:the\s+)?(?:\d+\s+)?(?:unit\s+|e2e\s+|integration\s+|existing\s+|new\s+)?tests?\s+(?:now\s+|still\s+|all\s+|are\s+all\s+)?(?:pass(?:es|ed|ing)?|are\s+(?:passing|green)|(?:is|are)\s+green|succeed(?:s|ed)?)\b/i,
9
+ /\btest\s+suite\s+(?:now\s+)?(?:passes|passed|is\s+green|is\s+passing)\b/i,
10
+ /\b\d+\s*(?:\/\s*\d+\s*)?(?:tests?\s+)?passing\b/i,
11
+ /\b(?:all|every)\s+(?:\d+\s+)?(?:specs?|test\s+cases?)\s+pass/i,
12
+ ],
13
+ build: [
14
+ /\b(?:the\s+)?build\s+(?:now\s+)?(?:succeeds|succeeded|passes|passed|is\s+green|is\s+clean|works)\b/i,
15
+ /\bbuilds?\s+(?:cleanly|successfully|without\s+errors)\b/i,
16
+ /\bcompiles\s+(?:cleanly|successfully|without\s+(?:any\s+)?errors|fine)\b/i,
17
+ ],
18
+ types: [
19
+ /\b(?:typecheck(?:ing)?|type[- ]check(?:ing)?|tsc)\s+(?:now\s+)?(?:passes|passed|is\s+clean|comes\s+back\s+clean|clean)\b/i,
20
+ /\bno\s+(?:remaining\s+)?(?:type|typescript|ts)\s+errors\b/i,
21
+ ],
22
+ lint: [
23
+ /\blint(?:er|ing)?\s+(?:now\s+)?(?:passes|passed|is\s+clean|comes\s+back\s+clean|clean)\b/i,
24
+ /\bno\s+(?:remaining\s+)?lint(?:ing)?\s+(?:errors|warnings|issues)\b/i,
25
+ ],
26
+ refactor: [
27
+ /\b(?:all|every)\s+(?:the\s+)?(?:remaining\s+)?(?:callers?|call\s*sites?|usages?|references?|imports?|occurrences?|consumers?|uses)\s+(?:\S+\s+){0,4}?(?:have\s+been\s+|has\s+been\s+|were\s+|are\s+(?:now\s+)?)?(?:updated|migrated|renamed|changed|replaced|switched|moved|fixed)\b/i,
28
+ /\brenamed\s+`?[\w.$]+`?\s+(?:to|→|->)\s+`?[\w.$]+`?\s+(?:everywhere|across|throughout)/i,
29
+ ],
30
+ migration: [
31
+ /\bmigrations?\s+(?:\S+\s+){0,3}?(?:ran|applied|succeeded|completed|went\s+through|(?:has|have)\s+been\s+(?:applied|run))\b/i,
32
+ /\b(?:applied|ran)\s+(?:the\s+)?(?:\S+\s+)?migrations?\s+(?:successfully|cleanly)\b/i,
33
+ ],
34
+ deps: [
35
+ /\b(?:upgraded|bumped|updated|pinned)\s+`?(@?[\w./-]+)`?\s+(?:from\s+`?v?[\w.^~-]+`?\s+)?to\s+`?v?\d[\w.-]*`?/i,
36
+ ],
37
+ security: [
38
+ /\b(?:fixed|patched|closed|resolved|mitigated|plugged)\s+(?:the\s+)?(?:\S+\s+){0,3}?(?:vulnerability|vuln|xss|injection|cve-\d{4}-\d+|ssrf|csrf|rce|security\s+(?:issue|bug|hole|flaw))/i,
39
+ ],
40
+ });
41
+
42
+ // A sentence that talks about a check rather than asserting its result.
43
+ const HEDGE =
44
+ /\b(?:make\s+sure|ensure|should|to\s+verify|to\s+confirm|check\s+(?:that|whether|if)|until|once|if|unless|whether|will|would|could|might|need(?:s)?\s+to|let'?s|let\s+me|i'?ll|want\s+to|try\s+to|expect(?:ed)?|hopefully|before)\b/i;
45
+ const NEGATION =
46
+ /\b(?:not|n't|never|no\s+longer|fail(?:s|ed|ing)?|broken|still\s+(?:fail|broken|red)|couldn'?t|unable|can'?t|without\s+running|didn'?t\s+run|haven'?t\s+run)\b/i;
47
+
48
+ /** Split assistant prose into sentence-ish units without breaking `code`. */
49
+ export function sentences(text) {
50
+ const clean = text
51
+ .replace(/```[\s\S]*?```/g, ' ')
52
+ .replace(/\r/g, '');
53
+ const out = [];
54
+ for (const line of clean.split(/\n+/)) {
55
+ const parts = line.split(/(?<=[.!?])\s+(?=[A-Z`*✅✓])/);
56
+ for (const p of parts) {
57
+ const s = p.replace(/^[\s>*\-•#|]+/, '').replace(/\*\*/g, '').trim();
58
+ if (s.length >= 8) out.push(s);
59
+ }
60
+ }
61
+ return out;
62
+ }
63
+
64
+ /**
65
+ * Find claims in a piece of assistant text.
66
+ * @returns {{kind: ClaimKind, sentence: string, subject?: {from?: string, to?: string, pkg?: string, version?: string}}[]}
67
+ */
68
+ export function detectClaims(text) {
69
+ const found = [];
70
+ for (const s of sentences(text)) {
71
+ for (const [kind, patterns] of Object.entries(KINDS)) {
72
+ const hit = patterns.map((re) => s.match(re)).find(Boolean);
73
+ if (!hit) continue;
74
+ // Look only at the words leading into the claim for hedges and negations,
75
+ // so "I fixed X, and all tests pass" counts but "make sure tests pass" doesn't.
76
+ const lead = s.slice(Math.max(0, hit.index - 60), hit.index);
77
+ const own = hit[0];
78
+ if (HEDGE.test(lead) || HEDGE.test(own)) continue;
79
+ if (NEGATION.test(lead.slice(-30)) || NEGATION.test(own)) continue;
80
+ if (/\?\s*$/.test(s)) continue;
81
+ // Quoting a claim ("the agent said “all tests pass”") isn't making one.
82
+ if (insideQuotes(s, hit.index)) continue;
83
+ found.push({ kind: /** @type {ClaimKind} */ (kind), sentence: s.slice(0, 280), subject: subjectOf(kind, s) });
84
+ }
85
+ }
86
+ return found;
87
+ }
88
+
89
+ function insideQuotes(s, at) {
90
+ const before = s.slice(0, at);
91
+ const straight = (before.match(/"/g) || []).length % 2 === 1;
92
+ const curly = before.lastIndexOf('“') > before.lastIndexOf('”');
93
+ return straight || curly;
94
+ }
95
+
96
+ function subjectOf(kind, s) {
97
+ if (kind === 'refactor') {
98
+ const r = s.match(/\brenamed\s+`([\w.$]+)`\s+(?:to|→|->)\s+`([\w.$]+)`/i) || s.match(/`([\w.$]+)`\s*(?:→|->)\s*`([\w.$]+)`/);
99
+ if (r) return { from: r[1].split('.').pop(), to: r[2].split('.').pop() };
100
+ const tick = s.match(/`([A-Za-z_$][\w$]{2,})`/);
101
+ return tick ? { from: tick[1] } : undefined;
102
+ }
103
+ if (kind === 'deps') {
104
+ const d = s.match(/\b(?:upgraded|bumped|updated|pinned)\s+`?(@?[\w./-]+)`?\s+(?:from\s+`?v?[\w.^~-]+`?\s+)?to\s+`?v?(\d+(?:\.\d+)*(?:-[\w.]+)?)`?/i);
105
+ return d ? { pkg: d[1], version: d[2] } : undefined;
106
+ }
107
+ return undefined;
108
+ }
109
+
110
+ /** Rough task type from the user's prompt, used to bucket reliability history. */
111
+ export function taskTypeOf(prompt = '') {
112
+ const p = prompt.toLowerCase();
113
+ if (/\bmigrat/.test(p)) return 'migration';
114
+ if (/\b(refactor|rename|extract|clean ?up|restructure|move\s+\w+\s+to)\b/.test(p)) return 'refactor';
115
+ if (/\b(upgrade|bump|dependenc|update\s+\w+\s+to\s+v?\d)/.test(p)) return 'dependency';
116
+ if (/\b(cve|vulnerab|xss|injection|security|auth bypass)/.test(p)) return 'security';
117
+ if (/\b(test|spec|coverage)\b/.test(p)) return 'tests';
118
+ if (/\b(fix|bug|broken|error|crash|fails?|issue)\b/.test(p)) return 'bugfix';
119
+ return 'feature';
120
+ }
@@ -0,0 +1,130 @@
1
+ // Evidence: which commands count as a check for which claim, and whether
2
+ // a given run passed, failed, or hid its own exit status.
3
+
4
+ export const RUNNERS = {
5
+ tests:
6
+ /\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test(?::[\w-]+)?\b|\b(?:npx\s+)?(?:vitest|jest|mocha|ava|playwright\s+test|cypress\s+run)\b|\bpytest\b|\bpython\d?\s+-m\s+(?:pytest|unittest)\b|\bgo\s+test\b|\bcargo\s+(?:test|nextest)\b|\brspec\b|\bphpunit\b|\bdotnet\s+test\b|\bmix\s+test\b|\bdeno\s+test\b|\bnode\s+--test\b|\bbun\s+test\b|\bgradlew?\s+test\b|\bmvn\s+test\b|\b(?:tox|nox)\b/i,
7
+ build:
8
+ /\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b|\bvite\s+build\b|\bnext\s+build\b|\bcargo\s+build\b|\bgo\s+build\b|\bmake\b|\bgradlew?\s+(?:build|assemble)\b|\bmvn\s+(?:package|install|compile)\b|\bdotnet\s+build\b|\bexpo\s+export\b|\bwebpack\b|\btsc\b(?![^|;&]*--noEmit)/i,
9
+ types:
10
+ /\btsc\b|\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:typecheck|type-check|check-types|tsc)\b|\bvue-tsc\b|\bmypy\b|\bpyright\b|\bflow\s+check\b|\bcargo\s+check\b|\bgo\s+vet\b/i,
11
+ lint:
12
+ /\b(?:npx\s+)?(?:eslint|biome|oxlint|ruff|flake8|pylint|golangci-lint|rubocop|stylelint)\b|\bcargo\s+clippy\b|\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,
13
+ migration:
14
+ /\bprisma\s+(?:migrate|db\s+push)\b|\bdrizzle-kit\s+(?:migrate|push)\b|\bknex\s+migrate\b|\balembic\s+upgrade\b|\b(?:rails|rake)\s+db:migrate\b|\bsupabase\s+(?:db\s+(?:push|reset)|migration\s+up)\b|\bsequelize\s+db:migrate\b|\bflyway\s+migrate\b|\bmanage\.py\s+migrate\b|\b(?:npm|pnpm|yarn)\s+(?:run\s+)?(?:db:)?migrat/i,
15
+ deps: /\b(?:npm|pnpm|yarn|bun)\s+(?:install|i|add|up(?:date|grade)?)\b|\bpip\d?\s+install\b|\buv\s+(?:add|pip|lock|sync)\b|\bpoetry\s+(?:add|update|lock)\b|\bcargo\s+(?:add|update)\b|\bgo\s+get\b|\bbundle\s+(?:update|install)\b/i,
16
+ };
17
+
18
+ export const SEARCH = /\b(?:rg|grep|ag|ack|git\s+grep|Select-String|findstr)\b/i;
19
+
20
+ // Wrappers that sit in front of the real program: env vars, cd, npx, uv run…
21
+ const PREFIX = /^(?:(?:\w+=\S*\s+)+|timeout\s+\d+\s+|(?:npx|bunx)\s+(?:-y\s+|--yes\s+)?|pnpm\s+(?:exec|dlx)\s+|yarn\s+dlx\s+|(?:uv|poetry|pipenv)\s+run\s+|python\d?(?:\.\d+)?\s+-m\s+|&\s*)+/i;
22
+
23
+ /**
24
+ * The programs a shell line actually runs, one per segment. Heredoc bodies
25
+ * and quoted strings are dropped, so `cat vitest.config.ts` or a script that
26
+ * merely mentions "jest" doesn't count as running tests.
27
+ */
28
+ export function commandHeads(cmd = '') {
29
+ const body = cmd
30
+ .replace(/<<-?\s*(['"]?)(\w+)\1[\s\S]*?\n\s*\2\s*(?:\n|$)/g, ' ')
31
+ .replace(/'[^'\n]*'|"[^"\n]*"/g, '""');
32
+ return body
33
+ .split(/&&|\|\||[;|\n]/)
34
+ .map((seg) => seg.trim().replace(PREFIX, ''))
35
+ .filter((seg) => seg && !/^(?:cd|echo|cat|type|less|head|tail|grep|rg|sed|awk|ls|which|git\s+(?:log|show|diff|status))\b/i.test(seg));
36
+ }
37
+
38
+ /** Did this shell line run a check from the given family? */
39
+ export function runsCheck(family, cmd) {
40
+ if (!cmd) return false;
41
+ const re = RUNNERS[family];
42
+ return commandHeads(cmd).some((seg) => {
43
+ const m = seg.match(re);
44
+ return m && m.index === 0;
45
+ });
46
+ }
47
+
48
+ /** Tools that change files. Bash edits are caught by pattern. */
49
+ const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit', 'apply_patch', 'str_replace_based_edit_tool', 'edit_file', 'write_file']);
50
+ const SHELL_EDIT = /\bsed\s+-i\b[^|;&\n]*|\bperl\s+-pi\b[^|;&\n]*|\bapply_patch\b|\bgit\s+(?:apply|checkout\s+--|restore)\b|(?:^|[^>&2])>\s*(?!\/dev\/null|&|\$null|nul\b)[\w./\\:$-]+\.(?:[cm]?[jt]sx?|py|go|rs|rb|java|kt|swift|css|json|sql|ya?ml|toml)\b/gi;
51
+ // Scratch files, notes and agent memory don't change what the tests see.
52
+ const IGNORED_PATH = /(?:^|[\\/])(?:tmp|temp|scratchpad)[\\/]|\$TEMP|\$TMPDIR|[\\/]\.claude[\\/]|\.(?:md|mdx|txt|log)\b/i;
53
+
54
+ export function isEdit(ev) {
55
+ if (ev.kind !== 'tool') return false;
56
+ if (EDIT_TOOLS.has(ev.name)) return !IGNORED_PATH.test(ev.file || '');
57
+ if (!ev.command) return false;
58
+ const hits = ev.command.replace(/<<-?\s*(['"]?)(\w+)\1[\s\S]*?\n\s*\2\s*(?:\n|$)/g, ' ').match(SHELL_EDIT);
59
+ return !!hits && hits.some((h) => !IGNORED_PATH.test(h));
60
+ }
61
+
62
+ /** Pipes or `|| true` that swallow a failing exit code. */
63
+ export function masksExit(cmd) {
64
+ return /\|\|\s*(?:true|:|exit\s+0|echo)\b|;\s*(?:true|exit\s+0)\s*$|\|\s*(?:tail|head|grep|Select-Object|Select-String|less|more|tee|cat|sort|wc)\b|2>\s*\/dev\/null\s*;\s*echo|\$LASTEXITCODE\s*=\s*0/i.test(cmd);
65
+ }
66
+
67
+ const FAIL_SIGNALS = [
68
+ /\b([1-9]\d*)\s+(?:tests?\s+)?(?:failed|failing|failures?|errors?)\b/i,
69
+ /\bTests?:\s+[1-9]\d*\s+failed/i,
70
+ /^\s*(?:FAIL|FAILED|✗|×|✕)\s/m,
71
+ /\bnot ok \d+/,
72
+ /\berror TS\d{3,5}\b/,
73
+ /\bFound [1-9]\d* errors?\b/,
74
+ /\b(?:Build|Compilation|Migration)\s+failed\b/i,
75
+ /\bnpm ERR!|ERR_PNPM_|\berror Command failed\b/,
76
+ /^\s*error(?:\[E\d+\])?:/m,
77
+ /\bTraceback \(most recent call last\)/,
78
+ /\bAssertionError\b/,
79
+ /^\s*✖\s+[1-9]\d* problems?/m,
80
+ /--- FAIL:/,
81
+ /\bpanicked at\b/,
82
+ ];
83
+ const PASS_SIGNALS = [
84
+ /\b(?:all\s+)?\d+\s+(?:tests?\s+)?pass(?:ed|ing)?\b(?![^\n]*\b[1-9]\d*\s+fail)/i,
85
+ /\bTests?:\s+\d+\s+passed,\s+\d+\s+total/i,
86
+ /^\s*ok\s+\S+\s+[\d.]+s/m,
87
+ /\bPASS\b/,
88
+ /\btest result: ok\b/,
89
+ /\bFound 0 errors\b/,
90
+ /\bbuilt in [\d.]+\s*m?s\b/i,
91
+ /\bCompiled successfully\b/i,
92
+ /\b0 (?:errors?|problems?)\b/i,
93
+ /\bAll checks passed\b/i,
94
+ ];
95
+
96
+ /**
97
+ * Judge one run of a checking command.
98
+ * @returns {{status: 'pass'|'fail'|'masked'|'unknown', why: string}}
99
+ */
100
+ export function judgeRun(ev) {
101
+ const out = ev.output || '';
102
+ const failHit = FAIL_SIGNALS.map((re) => out.match(re)).find(Boolean);
103
+ if (ev.exitCode != null && ev.exitCode !== 0) {
104
+ return { status: 'fail', why: `exited ${ev.exitCode}` + (failHit ? ` · ${clip(failHit[0])}` : '') };
105
+ }
106
+ if (ev.isError && ev.exitCode == null) return { status: 'fail', why: failHit ? clip(failHit[0]) : 'tool reported an error' };
107
+ if (failHit) return { status: 'fail', why: clip(failHit[0]) };
108
+ const masked = ev.command && masksExit(ev.command);
109
+ if (masked && !PASS_SIGNALS.some((re) => re.test(out))) {
110
+ return { status: 'masked', why: 'exit code hidden by a pipe, and no pass line in the output' };
111
+ }
112
+ if (ev.exitCode === 0 || PASS_SIGNALS.some((re) => re.test(out))) return { status: 'pass', why: ev.exitCode === 0 ? 'exited 0' : 'pass line in output' };
113
+ // Some agents (Cline, Aider) log output but no exit code: without a pass
114
+ // line there is nothing to trust.
115
+ if (ev.exitCode == null) return { status: 'masked', why: 'no exit code was recorded and the output has no pass line' };
116
+ return { status: masked ? 'masked' : 'pass', why: masked ? 'exit code hidden by a pipe' : 'no error reported' };
117
+ }
118
+
119
+ export function excerpt(out = '', max = 420) {
120
+ const lines = out.replace(/\r/g, '').split('\n');
121
+ const idx = lines.findIndex((l) => FAIL_SIGNALS.some((re) => re.test(l)));
122
+ const from = idx > 2 ? idx - 2 : 0;
123
+ const s = lines.slice(from, from + 10).join('\n');
124
+ return s.length > max ? s.slice(0, max) + '…' : s;
125
+ }
126
+
127
+ function clip(s) {
128
+ s = s.trim();
129
+ return s.length > 80 ? s.slice(0, 80) + '…' : s;
130
+ }
package/src/github.js ADDED
@@ -0,0 +1,69 @@
1
+ // Pull-request mode: every cloud agent that opens a PR (Copilot coding agent,
2
+ // Codex, Devin, Jules, Cursor background agents, Claude) writes its claims in
3
+ // the PR description. In CI the branch is checked out, so verify them there.
4
+
5
+ import crypto from 'node:crypto';
6
+ import fs from 'node:fs';
7
+
8
+ const BOTS = [
9
+ [/^copilot(-swe-agent)?(\[bot\])?$/i, 'copilot'],
10
+ [/^devin-ai-integration\[bot\]$/i, 'devin'],
11
+ [/^chatgpt-codex-connector\[bot\]$|codex/i, 'codex'],
12
+ [/^google-labs-jules\[bot\]$|jules/i, 'jules'],
13
+ [/^cursor(-agent)?\[bot\]$|^cursor$/i, 'cursor'],
14
+ [/^claude(\[bot\])?$|anthropic/i, 'claude-code'],
15
+ [/^sweep-ai\[bot\]$/i, 'sweep'],
16
+ ];
17
+
18
+ /** Read the PR from the Actions event payload. */
19
+ export function readPullRequest(eventPath = process.env.GITHUB_EVENT_PATH) {
20
+ if (!eventPath || !fs.existsSync(eventPath)) return null;
21
+ const ev = JSON.parse(fs.readFileSync(eventPath, 'utf8'));
22
+ const pr = ev.pull_request;
23
+ if (!pr) return null;
24
+ return { number: pr.number, title: pr.title || '', body: pr.body || '', author: pr.user?.login || '', agent: agentOf(pr.user?.login || '', pr.body || '') };
25
+ }
26
+
27
+ export function agentOf(login, body = '') {
28
+ for (const [re, name] of BOTS) if (re.test(login)) return name;
29
+ if (/Generated with \[?Claude Code/i.test(body)) return 'claude-code';
30
+ if (/codex/i.test(body) && /openai/i.test(body)) return 'codex';
31
+ return 'unknown';
32
+ }
33
+
34
+ const ICON = { verified: '✅', contradicted: '❌', review: '🔎', stale: '⏱️', unbacked: '⚪' };
35
+
36
+ export function markdownSummary(pr, r) {
37
+ const head = `### crossexam · ${r.ok ? 'claims hold up' : 'false claims in this PR'}`;
38
+ const who = pr ? `PR #${pr.number}${pr.agent !== 'unknown' ? ` by **${pr.agent}**` : pr.author ? ` by @​${pr.author}` : ''}` : '';
39
+ if (!r.results.length) return `${head}\n\n${who}\n\nNo checkable completion claims in the description.\n`;
40
+ const rows = r.results.map((x) => `| ${ICON[x.verdict]} ${x.verdict} | ${cell(x.claim)} | ${cell(x.reason)} |`);
41
+ const details = r.results
42
+ .filter((x) => x.verdict === 'contradicted' && x.evidence?.excerpt)
43
+ .map((x) => `<details><summary><code>${escapeHtml(x.evidence.command)}</code></summary>\n\n\`\`\`\n${x.evidence.excerpt}\n\`\`\`\n</details>`);
44
+ return `${head}\n\n${who}\n\n| Verdict | Claim | Why |\n|---|---|---|\n${rows.join('\n')}\n\n${details.join('\n\n')}\n`;
45
+ }
46
+
47
+ /** Workflow commands: annotations on the run, plus the job summary. */
48
+ export function emitActions(pr, r) {
49
+ for (const x of r.results) {
50
+ const msg = `${x.claim} → ${x.reason}`.replace(/\r?\n/g, ' ').replace(/%/g, '%25');
51
+ if (x.verdict === 'contradicted') console.log(`::error title=crossexam: false claim::${msg}`);
52
+ else if (x.verdict === 'review') console.log(`::warning title=crossexam: needs review::${msg}`);
53
+ else console.log(`::notice title=crossexam: verified::${msg}`);
54
+ }
55
+ const md = markdownSummary(pr, r);
56
+ if (process.env.GITHUB_STEP_SUMMARY) fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, md);
57
+ if (process.env.GITHUB_OUTPUT) {
58
+ const n = (v) => r.results.filter((x) => x.verdict === v).length;
59
+ fs.appendFileSync(process.env.GITHUB_OUTPUT, `ok=${r.ok}\ncontradicted=${n('contradicted')}\nverified=${n('verified')}\nagent=${pr?.agent ?? 'unknown'}\n`);
60
+ // A fresh delimiter each run, so test output or grepped repo text can't end
61
+ // the block early and set outputs of its own.
62
+ const eof = `CROSSEXAM_EOF_${crypto.randomUUID().replace(/-/g, '')}`;
63
+ fs.appendFileSync(process.env.GITHUB_OUTPUT, `summary<<${eof}\n${md}\n${eof}\n`);
64
+ }
65
+ return md;
66
+ }
67
+
68
+ const cell = (s) => String(s).replace(/\|/g, '\\|').replace(/\r?\n/g, ' ').replace(/`([^`]+)`/g, '<code>$1</code>');
69
+ const escapeHtml = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
package/src/init.js ADDED
@@ -0,0 +1,103 @@
1
+ // `crossexam init`: wire a repo up so whatever agent works in it checks
2
+ // itself. Two layers, both agent-neutral:
3
+ // 1. A rule in AGENTS.md (read by Codex, Cursor, Copilot, Jules, Amp,
4
+ // opencode and others), mirrored into CLAUDE.md / GEMINI.md if present.
5
+ // 2. With --mcp, project MCP configs for the agents that read them.
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ const START = '<!-- crossexam:start -->';
11
+ const END = '<!-- crossexam:end -->';
12
+
13
+ export function ruleBlock(cmd) {
14
+ return `${START}
15
+ ## Before you say a task is done
16
+
17
+ crossexam checks completion claims against the repo. Before you report that a task is finished:
18
+
19
+ 1. Call the \`verify_claims\` tool from the crossexam MCP server with the exact summary you are about to give, or run \`${cmd} verify "<your summary>"\`.
20
+ 2. If any claim comes back **contradicted**, fix it and verify again, or correct the summary to say what is actually true.
21
+ 3. Don't claim tests, the build, types or lint pass unless crossexam verified it. If you renamed or removed something, name it in \`backticks\` so it can be searched for.
22
+ ${END}`;
23
+ }
24
+
25
+ /** Insert or replace the crossexam block, leaving the rest of the file alone. */
26
+ export function upsertBlock(existing, block) {
27
+ if (existing == null) return block + '\n';
28
+ const i = existing.indexOf(START);
29
+ const j = existing.indexOf(END);
30
+ if (i >= 0 && j > i) return existing.slice(0, i) + block + existing.slice(j + END.length);
31
+ return existing.replace(/\s*$/, '') + '\n\n' + block + '\n';
32
+ }
33
+
34
+ export function mcpEntry(serverCmd) {
35
+ const [command, ...args] = serverCmd;
36
+ return { command, args };
37
+ }
38
+
39
+ /** The project-level MCP files each agent reads, in that agent's own shape. */
40
+ export function mcpTargets(serverCmd) {
41
+ const e = mcpEntry(serverCmd);
42
+ return [
43
+ { agent: 'Claude Code', file: '.mcp.json', key: 'mcpServers', value: e },
44
+ { agent: 'Cursor', file: '.cursor/mcp.json', key: 'mcpServers', value: e },
45
+ { agent: 'VS Code / Copilot', file: '.vscode/mcp.json', key: 'servers', value: { type: 'stdio', ...e } },
46
+ { agent: 'Gemini CLI', file: '.gemini/settings.json', key: 'mcpServers', value: e },
47
+ { agent: 'Roo Code', file: '.roo/mcp.json', key: 'mcpServers', value: e },
48
+ ];
49
+ }
50
+
51
+ /** Agents whose MCP config is per-user, not per-repo: print, don't write. */
52
+ export function globalSnippets(serverCmd) {
53
+ const [command, ...args] = serverCmd;
54
+ const json = JSON.stringify({ mcpServers: { crossexam: { command, args } } }, null, 2);
55
+ return [
56
+ ['Codex (~/.codex/config.toml)', `[mcp_servers.crossexam]\ncommand = ${JSON.stringify(command)}\nargs = ${JSON.stringify(args)}`],
57
+ ['Claude Code (all projects)', `claude mcp add --scope user crossexam -- ${serverCmd.map((a) => (/\s/.test(a) ? JSON.stringify(a) : a)).join(' ')}`],
58
+ ['Windsurf (~/.codeium/windsurf/mcp_config.json), Cline, Zed, Goose, anything else', json],
59
+ ];
60
+ }
61
+
62
+ /**
63
+ * @returns {{file: string, action: string}[]} what was (or would be) written
64
+ */
65
+ export function runInit({ cwd, cliCmd, serverCmd, mcp, dryRun }) {
66
+ const changes = [];
67
+ const write = (rel, text) => {
68
+ const p = path.join(cwd, rel);
69
+ const before = fs.existsSync(p) ? fs.readFileSync(p, 'utf8') : null;
70
+ if (before === text) return changes.push({ file: rel, action: 'unchanged' });
71
+ changes.push({ file: rel, action: before == null ? 'created' : 'updated' });
72
+ if (!dryRun) {
73
+ fs.mkdirSync(path.dirname(p), { recursive: true });
74
+ fs.writeFileSync(p, text);
75
+ }
76
+ };
77
+
78
+ const block = ruleBlock(cliCmd);
79
+ const agentsMd = path.join(cwd, 'AGENTS.md');
80
+ write('AGENTS.md', upsertBlock(fs.existsSync(agentsMd) ? fs.readFileSync(agentsMd, 'utf8') : null, block));
81
+ for (const f of ['CLAUDE.md', 'GEMINI.md']) {
82
+ const p = path.join(cwd, f);
83
+ if (fs.existsSync(p)) write(f, upsertBlock(fs.readFileSync(p, 'utf8'), block));
84
+ }
85
+
86
+ if (mcp) {
87
+ for (const t of mcpTargets(serverCmd)) {
88
+ const p = path.join(cwd, t.file);
89
+ let json = {};
90
+ if (fs.existsSync(p)) {
91
+ try {
92
+ json = JSON.parse(fs.readFileSync(p, 'utf8') || '{}');
93
+ } catch {
94
+ changes.push({ file: t.file, action: 'skipped (not valid JSON, left alone)' });
95
+ continue;
96
+ }
97
+ }
98
+ json[t.key] = { ...(json[t.key] || {}), crossexam: t.value };
99
+ write(t.file, JSON.stringify(json, null, 2) + '\n');
100
+ }
101
+ }
102
+ return changes;
103
+ }
package/src/live.js ADDED
@@ -0,0 +1,235 @@
1
+ // Live verification: check claims against the repo as it is right now.
2
+ //
3
+ // This is the agent-agnostic path. It needs nothing but the text an agent
4
+ // wrote ("all tests pass, build is clean, renamed getUserById everywhere")
5
+ // and a working copy, so it works for any agent, editor, CI job or PR bot.
6
+
7
+ import { execFileSync, spawn, spawnSync } from 'node:child_process';
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { detectClaims } from './claims.js';
11
+ import { excerpt, judgeRun } from './evidence.js';
12
+
13
+ const CONFIG_FILES = ['crossexam.json', '.crossexam.json'];
14
+
15
+ /** Optional per-repo overrides: { "commands": { "tests": "pnpm test:unit", "migration": "prisma migrate status" }, "timeoutSeconds": 300 } */
16
+ export function loadConfig(cwd) {
17
+ for (const f of CONFIG_FILES) {
18
+ const p = path.join(cwd, f);
19
+ if (fs.existsSync(p)) {
20
+ try {
21
+ return { ...JSON.parse(fs.readFileSync(p, 'utf8')), file: f };
22
+ } catch (e) {
23
+ throw new Error(`${f} is not valid JSON: ${e.message}`);
24
+ }
25
+ }
26
+ }
27
+ return {};
28
+ }
29
+
30
+ const read = (cwd, f) => {
31
+ try {
32
+ return fs.readFileSync(path.join(cwd, f), 'utf8');
33
+ } catch {
34
+ return null;
35
+ }
36
+ };
37
+ const has = (cwd, f) => fs.existsSync(path.join(cwd, f));
38
+
39
+ /**
40
+ * Which command backs each kind of claim in this repo.
41
+ * @returns {Record<'tests'|'build'|'types'|'lint'|'migration', {command: string, source: string} | undefined>}
42
+ */
43
+ export function detectCommands(cwd, config = loadConfig(cwd)) {
44
+ const out = {};
45
+ const set = (kind, command, source) => {
46
+ if (command && !out[kind]) out[kind] = { command, source };
47
+ };
48
+ for (const [k, v] of Object.entries(config.commands || {})) set(k, v, config.file);
49
+
50
+ const pkgRaw = read(cwd, 'package.json');
51
+ if (pkgRaw) {
52
+ let scripts = {};
53
+ try {
54
+ scripts = JSON.parse(pkgRaw).scripts || {};
55
+ } catch {}
56
+ const pm = has(cwd, 'pnpm-lock.yaml') ? 'pnpm' : has(cwd, 'yarn.lock') ? 'yarn' : has(cwd, 'bun.lockb') || has(cwd, 'bun.lock') ? 'bun' : 'npm';
57
+ const run = (s) => (pm === 'npm' && s === 'test' ? 'npm test' : `${pm} run ${s}`);
58
+ if (scripts.test && !/no test specified/.test(scripts.test)) set('tests', run('test'), 'package.json');
59
+ if (scripts.build) set('build', run('build'), 'package.json');
60
+ const typeScript = ['typecheck', 'type-check', 'check-types', 'types', 'tsc'].find((s) => scripts[s]);
61
+ if (typeScript) set('types', run(typeScript), 'package.json');
62
+ if (scripts.lint) set('lint', run('lint'), 'package.json');
63
+ if (has(cwd, 'tsconfig.json') && has(cwd, 'node_modules/.bin/tsc')) set('types', 'npx --no-install tsc --noEmit', 'tsconfig.json');
64
+ }
65
+
66
+ const pyproject = read(cwd, 'pyproject.toml') || '';
67
+ if (pyproject || has(cwd, 'pytest.ini') || has(cwd, 'setup.cfg') || has(cwd, 'requirements.txt')) {
68
+ if (/\[tool\.pytest|pytest/.test(pyproject) || has(cwd, 'pytest.ini') || has(cwd, 'tests') || has(cwd, 'conftest.py')) set('tests', 'python -m pytest -q', 'python project');
69
+ if (/\[tool\.ruff/.test(pyproject) || has(cwd, 'ruff.toml')) set('lint', 'ruff check .', 'ruff config');
70
+ if (/\[tool\.mypy/.test(pyproject) || has(cwd, 'mypy.ini')) set('types', 'mypy .', 'mypy config');
71
+ if (/\[tool\.pyright/.test(pyproject) || has(cwd, 'pyrightconfig.json')) set('types', 'pyright', 'pyright config');
72
+ }
73
+ if (has(cwd, 'go.mod')) {
74
+ set('tests', 'go test ./...', 'go.mod');
75
+ set('build', 'go build ./...', 'go.mod');
76
+ set('types', 'go vet ./...', 'go.mod');
77
+ }
78
+ if (has(cwd, 'Cargo.toml')) {
79
+ set('tests', 'cargo test', 'Cargo.toml');
80
+ set('build', 'cargo build', 'Cargo.toml');
81
+ set('types', 'cargo check', 'Cargo.toml');
82
+ set('lint', 'cargo clippy -- -D warnings', 'Cargo.toml');
83
+ }
84
+ if (has(cwd, 'Gemfile') && (has(cwd, 'spec') || has(cwd, '.rspec'))) set('tests', 'bundle exec rspec', 'Gemfile');
85
+ if (has(cwd, 'mix.exs')) set('tests', 'mix test', 'mix.exs');
86
+ if (has(cwd, 'gradlew')) set('tests', process.platform === 'win32' ? 'gradlew.bat test' : './gradlew test', 'gradlew');
87
+ else if (has(cwd, 'pom.xml')) set('tests', 'mvn -q test', 'pom.xml');
88
+ // Migrations touch a database, so they only run when the repo names a
89
+ // read-only status command in crossexam.json.
90
+ return out;
91
+ }
92
+
93
+ /** Run a shell command without blocking the event loop (the MCP server keeps answering pings). */
94
+ export function runCommand(command, { cwd, timeoutMs = 300000 } = {}) {
95
+ return new Promise((resolve) => {
96
+ const child = spawn(command, { cwd, shell: true, env: { ...process.env, CI: '1', FORCE_COLOR: '0', NO_COLOR: '1' }, windowsHide: true });
97
+ let output = '';
98
+ const keep = (d) => {
99
+ output += d;
100
+ if (output.length > 400000) output = output.slice(-200000);
101
+ };
102
+ child.stdout.on('data', keep);
103
+ child.stderr.on('data', keep);
104
+ const timer = setTimeout(() => {
105
+ output += `\n[crossexam] timed out after ${Math.round(timeoutMs / 1000)}s`;
106
+ child.kill('SIGTERM');
107
+ }, timeoutMs);
108
+ child.on('close', (code) => {
109
+ clearTimeout(timer);
110
+ resolve({ command, exitCode: code ?? 1, output, isError: code !== 0 });
111
+ });
112
+ child.on('error', (e) => {
113
+ clearTimeout(timer);
114
+ resolve({ command, exitCode: 127, output: String(e.message), isError: true });
115
+ });
116
+ });
117
+ }
118
+
119
+ export function runCommandSync(command, { cwd, timeoutMs = 300000 } = {}) {
120
+ const r = spawnSync(command, { cwd, shell: true, encoding: 'utf8', timeout: timeoutMs, env: { ...process.env, CI: '1', FORCE_COLOR: '0', NO_COLOR: '1' }, windowsHide: true });
121
+ return { command, exitCode: r.status ?? 1, output: (r.stdout || '') + (r.stderr || ''), isError: r.status !== 0 };
122
+ }
123
+
124
+ /** Where the old name still appears. null = can't tell (no git). */
125
+ export function grepRepo(cwd, sym, to) {
126
+ try {
127
+ const out = execFileSync('git', ['grep', '-n', '-w', '-I', '--', sym], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 8 << 20 });
128
+ return out.split('\n').filter((l) => l && (!to || !l.includes(to))).slice(0, 50);
129
+ } catch (e) {
130
+ if (e.status === 1) return [];
131
+ return null;
132
+ }
133
+ }
134
+
135
+ /** The version a manifest pins for a package, across ecosystems. */
136
+ export function manifestVersion(cwd, pkg) {
137
+ const pj = read(cwd, 'package.json');
138
+ if (pj) {
139
+ try {
140
+ const j = JSON.parse(pj);
141
+ const v = j.dependencies?.[pkg] || j.devDependencies?.[pkg] || j.peerDependencies?.[pkg] || j.optionalDependencies?.[pkg];
142
+ if (v) return { version: v, file: 'package.json' };
143
+ } catch {}
144
+ }
145
+ const esc = pkg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
146
+ const probes = [
147
+ ['requirements.txt', new RegExp(`^${esc}\\s*(?:\\[[^\\]]*\\])?\\s*[=<>~!]=?\\s*([\\w.*-]+)`, 'im')],
148
+ ['pyproject.toml', new RegExp(`["']?${esc}["']?\\s*(?:=\\s*["'][\\^~>=<]*|[=<>~!]=?\\s*)v?(\\d[\\w.]*)`, 'i')],
149
+ ['Cargo.toml', new RegExp(`^${esc}\\s*=\\s*(?:\\{[^}]*version\\s*=\\s*)?["'][\\^~=]*([\\w.-]+)`, 'im')],
150
+ ['go.mod', new RegExp(`${esc}\\s+v(\\d[\\w.+-]*)`, 'i')],
151
+ ['Gemfile', new RegExp(`gem\\s+["']${esc}["']\\s*,\\s*["'][~>=<\\s]*([\\w.]+)`, 'i')],
152
+ ];
153
+ for (const [file, re] of probes) {
154
+ const m = (read(cwd, file) || '').match(re);
155
+ if (m) return { version: m[1], file };
156
+ }
157
+ return null;
158
+ }
159
+
160
+ export function versionMatches(found, claimed) {
161
+ const f = String(found).replace(/^[\^~>=<v\s]+/, '');
162
+ const c = String(claimed).replace(/^v/, '');
163
+ // "3.23.8" matches "^3.23.8" and "3.23.8"; a claim of "3.23" matches "3.23.8".
164
+ return f === c || f.startsWith(c + '.') || c.startsWith(f + '.') || f.startsWith(c);
165
+ }
166
+
167
+ /**
168
+ * Verify free text against the working copy.
169
+ * @param {string} text what the agent said
170
+ * @param {{cwd: string, run?: boolean, timeoutMs?: number, agent?: string, onRun?: (cmd: string) => void}} opts
171
+ */
172
+ export async function verifyText(text, opts) {
173
+ const cwd = path.resolve(opts.cwd || process.cwd());
174
+ const config = loadConfig(cwd);
175
+ const commands = detectCommands(cwd, config);
176
+ const timeoutMs = opts.timeoutMs ?? (config.timeoutSeconds ? config.timeoutSeconds * 1000 : 300000);
177
+ const ran = new Map();
178
+ const runOnce = (cmd) => {
179
+ if (!ran.has(cmd)) {
180
+ opts.onRun?.(cmd);
181
+ ran.set(cmd, runCommand(cmd, { cwd, timeoutMs }));
182
+ }
183
+ return ran.get(cmd);
184
+ };
185
+
186
+ // One verdict per claim kind and subject; the agent's last word wins.
187
+ const seen = new Map();
188
+ for (const c of detectClaims(text)) seen.set(c.kind + (c.subject?.from || c.subject?.pkg || ''), c);
189
+
190
+ const results = [];
191
+ for (const c of seen.values()) {
192
+ const v = await judgeLive(c, { cwd, commands, run: opts.run !== false, runOnce });
193
+ results.push({ kind: c.kind, claim: c.sentence, subject: c.subject, ...v });
194
+ }
195
+ return { cwd, commands, results, ok: !results.some((r) => r.verdict === 'contradicted') };
196
+ }
197
+
198
+ async function judgeLive(c, { cwd, commands, run, runOnce }) {
199
+ if (c.kind === 'security') return { verdict: 'review', reason: 'Security fixes always go to a human reviewer.', evidence: null };
200
+
201
+ if (c.kind === 'refactor') {
202
+ const sym = c.subject?.from;
203
+ if (!sym) return { verdict: 'review', reason: 'No symbol named in the claim (put it in `backticks`), so there is nothing to search for.', evidence: null };
204
+ const hits = grepRepo(cwd, sym, c.subject?.to);
205
+ if (hits === null) return { verdict: 'review', reason: 'Not a git repository, so the old name could not be searched.', evidence: null };
206
+ const ev = { command: `git grep -nw ${sym}`, exitCode: hits.length ? 0 : 1, excerpt: hits.slice(0, 8).join('\n') };
207
+ return hits.length
208
+ ? { verdict: 'contradicted', reason: `\`${sym}\` is still referenced in ${hits.length} place${hits.length === 1 ? '' : 's'}.`, evidence: ev }
209
+ : { verdict: 'verified', reason: `No references to \`${sym}\` remain.`, evidence: ev };
210
+ }
211
+
212
+ if (c.kind === 'deps') {
213
+ const { pkg, version } = c.subject || {};
214
+ if (!pkg || !version) return { verdict: 'review', reason: 'Could not tell which package and version were claimed.', evidence: null };
215
+ const found = manifestVersion(cwd, pkg);
216
+ if (!found) return { verdict: 'review', reason: `${pkg} isn't in any manifest crossexam reads.`, evidence: null };
217
+ const ev = { command: `read ${found.file}`, exitCode: 0, excerpt: `${pkg} ${found.version}` };
218
+ return versionMatches(found.version, version)
219
+ ? { verdict: 'verified', reason: `${found.file} has ${pkg} at ${found.version}.`, evidence: ev }
220
+ : { verdict: 'contradicted', reason: `Claimed ${pkg} ${version}, but ${found.file} still has ${found.version}.`, evidence: ev };
221
+ }
222
+
223
+ const cmd = commands[c.kind]?.command;
224
+ if (!cmd) {
225
+ const hint = c.kind === 'migration' ? 'crossexam never touches your database on its own. Add a read-only status command to crossexam.json, e.g. {"commands": {"migration": "npx prisma migrate status"}}.' : `No ${c.kind} command found. Add one to crossexam.json under "commands".`;
226
+ return { verdict: 'review', reason: hint, evidence: null };
227
+ }
228
+ if (!run) return { verdict: 'review', reason: `Would run \`${cmd}\` (dry run).`, evidence: { command: cmd, exitCode: null, excerpt: '' } };
229
+
230
+ const res = await runOnce(cmd);
231
+ const j = judgeRun(res);
232
+ const ev = { command: cmd, exitCode: res.exitCode, excerpt: excerpt(res.output), rerun: true };
233
+ if (j.status === 'fail') return { verdict: 'contradicted', reason: `Ran \`${cmd}\` just now: ${j.why}.`, evidence: ev };
234
+ return { verdict: 'verified', reason: `Ran \`${cmd}\` just now and it passed.`, evidence: ev };
235
+ }