tripwire-e2e 0.0.0-stage → 0.1.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 (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +168 -2
  3. package/bin/tripwire.js +8 -0
  4. package/operators/_util.js +114 -0
  5. package/operators/agent-proposed.js +41 -0
  6. package/operators/auth-drop.js +30 -0
  7. package/operators/dead-control.js +23 -0
  8. package/operators/double-apply.js +20 -0
  9. package/operators/fake-success.js +21 -0
  10. package/operators/field-swap.js +42 -0
  11. package/operators/hide-control.js +30 -0
  12. package/operators/index.js +77 -0
  13. package/operators/item-drop.js +36 -0
  14. package/operators/item-dup.js +20 -0
  15. package/operators/label-swap.js +30 -0
  16. package/operators/missing-row-action.js +24 -0
  17. package/operators/number-drift.js +40 -0
  18. package/operators/silent-fail.js +19 -0
  19. package/operators/stale-read.js +34 -0
  20. package/operators/text-change.js +43 -0
  21. package/operators/validation-off.js +21 -0
  22. package/operators/wrong-link.js +28 -0
  23. package/operators/wrong-owner.js +41 -0
  24. package/package.json +41 -4
  25. package/policies/tripwire.clean.policy.yaml +23 -0
  26. package/policies/tripwire.mutant.policy.yaml +13 -0
  27. package/src/actions.js +59 -0
  28. package/src/agent.js +30 -0
  29. package/src/browser/mutate.js +113 -0
  30. package/src/browser/recorder.js +80 -0
  31. package/src/cli.js +37 -0
  32. package/src/commands/check.js +28 -0
  33. package/src/commands/fix.js +199 -0
  34. package/src/commands/list.js +24 -0
  35. package/src/commands/proxy.js +28 -0
  36. package/src/commands/report.js +11 -0
  37. package/src/commands/run.js +310 -0
  38. package/src/commands/sabotage.js +74 -0
  39. package/src/config.js +52 -0
  40. package/src/jsonpath.js +58 -0
  41. package/src/kane.js +150 -0
  42. package/src/ledger.js +53 -0
  43. package/src/mutant.js +26 -0
  44. package/src/profile.js +34 -0
  45. package/src/proxy.js +289 -0
  46. package/src/report.js +182 -0
@@ -0,0 +1,80 @@
1
+ // Injected by the Tripwire proxy during the baseline run only.
2
+ // Reports which controls and texts each page showed and which ones the test clicked,
3
+ // so mutants can target things a test saw (visible) but never interacted with.
4
+ (function () {
5
+ if (window.__twRecorder) return;
6
+ window.__twRecorder = true;
7
+ var ENDPOINT = '/_tw/dom';
8
+ var clean = function (s) { return (s || '').replace(/\s+/g, ' ').trim().slice(0, 120); };
9
+ var roleOf = function (el) {
10
+ var t = el.tagName;
11
+ if (t === 'BUTTON' || el.getAttribute('role') === 'button' || (t === 'INPUT' && /submit|button/.test(el.type))) return 'button';
12
+ if (t === 'A' && el.hasAttribute('href')) return 'link';
13
+ if (/^H[1-3]$/.test(t)) return 'heading';
14
+ return 'text';
15
+ };
16
+ var visible = function (el) {
17
+ var r = el.getBoundingClientRect();
18
+ var cs = getComputedStyle(el);
19
+ return r.width > 0 && r.height > 0 && cs.visibility !== 'hidden' && cs.display !== 'none';
20
+ };
21
+ var describe = function (el) {
22
+ return {
23
+ role: roleOf(el),
24
+ text: clean(el.innerText || el.value || el.getAttribute('aria-label')),
25
+ label: clean(el.getAttribute('aria-label')),
26
+ href: el.getAttribute('href') || undefined,
27
+ inRow: !!el.closest('tr, li'),
28
+ tag: el.tagName.toLowerCase(),
29
+ cls: (el.className && typeof el.className === 'string') ? el.className.slice(0, 60) : undefined
30
+ };
31
+ };
32
+ var SELECTOR = 'button, [role=button], a[href], input[type=submit], h1, h2, h3, [role=status], .status, .badge, .tag, strong';
33
+ var queue = [];
34
+ var timer = null;
35
+ function snapshot() {
36
+ var controls = [];
37
+ var seen = {};
38
+ document.querySelectorAll(SELECTOR).forEach(function (el) {
39
+ if (el.closest('#__tw')) return;
40
+ if (!visible(el)) return;
41
+ var d = describe(el);
42
+ if (!d.text) return;
43
+ var k = d.role + '|' + d.text;
44
+ seen[k] = (seen[k] || 0) + 1;
45
+ d.count = seen[k];
46
+ controls.push(d);
47
+ });
48
+ queue.push({ kind: 'page', url: location.pathname + location.search + location.hash, controls: controls, text: clean(document.body ? document.body.innerText : '').length ? (document.body.innerText || '').slice(0, 20000) : '' });
49
+ flushSoon();
50
+ }
51
+ function flushSoon() {
52
+ clearTimeout(timer);
53
+ timer = setTimeout(flush, 300);
54
+ }
55
+ function flush() {
56
+ if (!queue.length) return;
57
+ var batch = queue.splice(0, queue.length);
58
+ var body = JSON.stringify({ events: batch });
59
+ try {
60
+ if (navigator.sendBeacon) navigator.sendBeacon(ENDPOINT, new Blob([body], { type: 'application/json' }));
61
+ else fetch(ENDPOINT, { method: 'POST', body: body, keepalive: true, headers: { 'content-type': 'application/json' } });
62
+ } catch (e) { /* recording must never break the page */ }
63
+ }
64
+ var snapTimer = null;
65
+ function scheduleSnapshot() { clearTimeout(snapTimer); snapTimer = setTimeout(snapshot, 250); }
66
+ document.addEventListener('click', function (ev) {
67
+ var el = ev.target && ev.target.closest && ev.target.closest(SELECTOR);
68
+ if (!el) return;
69
+ var d = describe(el);
70
+ queue.push({ kind: 'click', url: location.pathname + location.search + location.hash, control: d });
71
+ flushSoon();
72
+ }, true);
73
+ window.addEventListener('hashchange', scheduleSnapshot);
74
+ window.addEventListener('pagehide', function () { snapshot(); flush(); });
75
+ var start = function () {
76
+ scheduleSnapshot();
77
+ new MutationObserver(scheduleSnapshot).observe(document.documentElement, { childList: true, subtree: true, characterData: true });
78
+ };
79
+ if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', start); else start();
80
+ })();
package/src/cli.js ADDED
@@ -0,0 +1,37 @@
1
+ // Command-line entry. Subcommands are loaded lazily so `tripwire proxy` starts instantly.
2
+ import { parseArgs } from 'node:util';
3
+
4
+ const HELP = `tripwire: break the app on purpose to find out whether a green Kane suite means anything
5
+
6
+ Usage:
7
+ tripwire proxy --target <url> [--port 8080] run the fault-injecting proxy in front of an app
8
+ tripwire run [--tests <glob>] [--max-mutants 40] baseline, generate mutants, replay, score
9
+ tripwire fix [--agent claude|codex] [--max-attempts 3] strengthen tests for every survivor
10
+ tripwire sabotage [--agent claude|codex] ask the agent for domain-specific mutants
11
+ tripwire report rebuild the HTML report and badge
12
+ tripwire list show the mutant catalogue for the last baseline
13
+ tripwire check [--threshold 80] exit 1 if the score is below the threshold (for hooks)
14
+
15
+ Run "tripwire <command> --help" for the options of one command.`;
16
+
17
+ export async function main(argv) {
18
+ const [cmd, ...rest] = argv;
19
+ if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') { console.log(HELP); return 0; }
20
+ if (cmd === '--version' || cmd === '-v') {
21
+ const { readFileSync } = await import('node:fs');
22
+ console.log(JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
23
+ return 0;
24
+ }
25
+ switch (cmd) {
26
+ case 'proxy': return (await import('./commands/proxy.js')).default(rest, parseArgs);
27
+ case 'run': return (await import('./commands/run.js')).default(rest, parseArgs);
28
+ case 'fix': return (await import('./commands/fix.js')).default(rest, parseArgs);
29
+ case 'sabotage': return (await import('./commands/sabotage.js')).default(rest, parseArgs);
30
+ case 'report': return (await import('./commands/report.js')).default(rest, parseArgs);
31
+ case 'list': return (await import('./commands/list.js')).default(rest, parseArgs);
32
+ case 'check': return (await import('./commands/check.js')).default(rest, parseArgs);
33
+ default:
34
+ console.error(`Unknown command "${cmd}".\n\n${HELP}`);
35
+ return 2;
36
+ }
37
+ }
@@ -0,0 +1,28 @@
1
+ // tripwire check: exit 1 when the latest score is below the threshold. Used by the Stop hook and CI.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { loadConfig } from '../config.js';
5
+ import { readLedger, latest, lastRunId, score } from '../ledger.js';
6
+
7
+ export default async function check(argv, parseArgs) {
8
+ const { values } = parseArgs({ args: argv, options: { threshold: { type: 'string' }, dir: { type: 'string' }, json: { type: 'boolean' }, help: { type: 'boolean', short: 'h' } } });
9
+ if (values.help) { console.log('tripwire check [--threshold 80] [--json] exit 1 if the latest mutation score is below the threshold'); return 0; }
10
+ const cfg = loadConfig();
11
+ const dir = path.resolve(values.dir || cfg.dir);
12
+ const threshold = Number(values.threshold ?? cfg.threshold);
13
+ const rows = readLedger(dir);
14
+ if (!rows.length) {
15
+ console.log('tripwire: no runs yet. Run `tripwire run` first.');
16
+ return 1;
17
+ }
18
+ const s = score(latest(rows, lastRunId(rows)));
19
+ const survivors = latest(rows, lastRunId(rows)).filter((r) => r.status === 'survived' || r.status === 'masked');
20
+ const ok = s.score !== null && s.score >= threshold;
21
+ if (values.json) console.log(JSON.stringify({ ok, threshold, ...s, survivors: survivors.map((r) => r.describe) }));
22
+ else {
23
+ console.log(`tripwire: score ${s.score ?? '-'}% (threshold ${threshold}%) · killed ${s.killed} · survived ${s.survived} · masked ${s.masked}`);
24
+ if (!ok) for (const r of survivors.slice(0, 8)) console.log(` - not caught: ${r.describe}`);
25
+ }
26
+ if (fs.existsSync(path.join(dir, 'report', 'index.html')) && !values.json) console.log(` report: ${path.join(dir, 'report', 'index.html')}`);
27
+ return ok ? 0 : 1;
28
+ }
@@ -0,0 +1,199 @@
1
+ // tripwire fix: the closed loop. Each surviving (or heal-masked) mutant goes to the coding agent,
2
+ // which appends one assertion step to one test. Kane then proves it twice:
3
+ // app clean -> the test must pass
4
+ // app broken -> the test must fail
5
+ // Both hold: the edit is kept and the proof (two Kane sessions and packs) is recorded.
6
+ // Otherwise: the test and its recording are restored and the agent tries again with the reason.
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { loadConfig } from '../config.js';
10
+ import { readLedger, latest, lastRunId, appendLedger } from '../ledger.js';
11
+ import { runTest } from '../kane.js';
12
+ import { runAgent } from '../agent.js';
13
+ import { lastScreenshot, imageExt } from '../report.js';
14
+ import { withProxy, resetApp, snapshotRecording } from './run.js';
15
+ import { generateAll } from '../../operators/index.js';
16
+ import { get } from '../jsonpath.js';
17
+
18
+ const HELP = `tripwire fix [options]
19
+
20
+ --agent claude|codex which coding agent strengthens the tests (default from config: claude)
21
+ --max-attempts <n> attempts per survivor (default 3)
22
+ --only <id,...> fix only these mutant ids (default: every survivor and masked mutant)
23
+ --limit <n> fix at most n mutants this time
24
+ --dir <path> state directory (default .tripwire)`;
25
+
26
+ const slug = (s) => s.replace(/[^\w.-]+/g, '_').slice(0, 80);
27
+
28
+ // What exactly changes on the page/response: the "before and after" for the agent.
29
+ export function beforeAfter(m, profile) {
30
+ const a = m.action;
31
+ const entry = profile?.tests.flatMap((t) => t.traffic).reverse().find((e) => e.method === m.match.method && e.path === m.match.path && e.json !== undefined);
32
+ if (a.type === 'json' && entry) {
33
+ return a.ops.map((op) => {
34
+ const before = get(entry.json, op.path);
35
+ const after = op.op === 'add' ? before + op.value : op.op === 'scale' ? Math.round(before * op.value * 100) / 100 : op.op === 'remove-index' ? `(list without item ${op.index}: ${before?.length - 1} items)` : op.op === 'dup-index' ? `(item ${op.index} repeated: ${before?.length + 1} items)` : op.op === 'swap' ? `(${op.a} and ${op.b} exchanged)` : op.op === 'push' ? '(an extra record owned by another user)' : JSON.stringify(op.value);
36
+ return `${m.match.method} ${m.match.path} ${op.path}: real ${JSON.stringify(before)} -> broken ${typeof after === 'string' ? after : JSON.stringify(after)}`;
37
+ }).join('\n');
38
+ }
39
+ if (a.type === 'respond') return `${m.match.method} ${m.match.path} answers ${a.status} without reaching the app${a.status < 400 ? ' (it looks successful, but nothing is saved)' : ''}`;
40
+ if (a.type === 'forward-twice') return `${m.match.method} ${m.match.path} reaches the app twice`;
41
+ if (a.type === 'status-map') return `${m.match.method} ${m.match.path}: a ${a.from.join('/')} validation error is turned into ${a.to}`;
42
+ if (a.type === 'stale-read') return `GET ${m.match.path} returns what it returned before the latest change`;
43
+ if (a.type === 'dom') return `On the page: ${JSON.stringify(a.dom)}`;
44
+ return JSON.stringify(a);
45
+ }
46
+
47
+ export function buildPrompt({ m, test, testText, change, shotPath, lessons, previousFailure, masked }) {
48
+ return `You are strengthening an end-to-end Kane CLI test (a *_test.md file). Do not change any application code.
49
+
50
+ This bug was live in the app and the test below still PASSED:
51
+ ${m.describe}
52
+ What changed: ${change}
53
+ ${masked ? `\nWith strict replay the test failed, but with Kane's default adaptive healing it re-authored its steps and passed on the broken app. The new assertion must state the expected outcome so plainly that no re-authored path can satisfy it on the broken app.\n` : ''}
54
+ A good test would: ${m.expect ? m.expect.charAt(0).toLowerCase() + m.expect.slice(1) : 'check the outcome a user relies on'}.
55
+ ${shotPath ? `Screenshot of the broken page at the end of the test: ${shotPath}\n` : ''}
56
+ Test file: ${test}
57
+ ----- current contents -----
58
+ ${testText}
59
+ ----- end -----
60
+
61
+ Edit ${test} by APPENDING exactly one new step at the very end of the file:
62
+ ## <short heading>
63
+ <one or two plain-English sentences: navigate if needed, then "Verify ..." with the exact expected value>
64
+
65
+ Rules:
66
+ - Only append. Do not modify, reorder, weaken or delete any existing line (Kane re-records every step after an edit, so editing earlier steps is expensive and is rejected).
67
+ - The new step must PASS on the real app and FAIL on the broken app described above.
68
+ - Use exact expected values a user would see (amounts with currency symbol, item names, counts, status words).
69
+ - Do not mention bugs, mutants or Tripwire in the test, and never name the broken value
70
+ (the wrong number, the extra record): assert the correct state, so the check stays general.
71
+ ${lessons ? `\nAssertion patterns that worked before in this repo:\n${lessons}\n` : ''}${previousFailure ? `\nYour previous attempt was rejected: ${previousFailure}\nTry a different assertion.\n` : ''}
72
+ Reply with one line describing the assertion you added.`;
73
+ }
74
+
75
+ // The agent may only append. Returns null when fine, or the reason it is not.
76
+ export function appendOnly(before, after) {
77
+ const b = before.replace(/\r\n/g, '\n').trimEnd();
78
+ const a = after.replace(/\r\n/g, '\n');
79
+ if (!a.startsWith(b)) return 'existing lines were changed; only appending a new final step is allowed';
80
+ const added = a.slice(b.length).trim();
81
+ if (!added) return 'nothing was added to the test';
82
+ if (!/^##\s+\S/m.test(added)) return 'the addition must be a new "## " step';
83
+ if ((added.match(/^##\s/gm) || []).length > 1) return 'add exactly one step';
84
+ if (/@import/.test(added)) return 'the new step must be prose, not an @import';
85
+ return null;
86
+ }
87
+
88
+ function appendLesson(dir, m, line) {
89
+ const f = path.join(dir, 'lessons.md');
90
+ const head = fs.existsSync(f) ? fs.readFileSync(f, 'utf8') : '# Assertion patterns that caught real bugs in this repo\n\n';
91
+ const lesson = `- ${m.expect || 'Check the visible outcome'} (caught: ${m.operator}; ${line.trim().slice(0, 160)})\n`;
92
+ if (!head.includes(lesson)) fs.writeFileSync(f, head + lesson);
93
+ }
94
+
95
+ export default async function fix(argv, parseArgs) {
96
+ const { values } = parseArgs({
97
+ args: argv,
98
+ options: {
99
+ agent: { type: 'string' }, 'max-attempts': { type: 'string' }, only: { type: 'string' },
100
+ limit: { type: 'string' }, dir: { type: 'string' }, help: { type: 'boolean', short: 'h' }
101
+ }
102
+ });
103
+ if (values.help) { console.log(HELP); return 0; }
104
+ const cfg = loadConfig();
105
+ const dir = path.resolve(values.dir || cfg.dir);
106
+ const agent = values.agent || cfg.agent || 'claude';
107
+ const maxAttempts = Number(values['max-attempts'] || 3);
108
+ const rows = readLedger(dir);
109
+ if (!rows.length) throw new Error('no ledger yet: run `tripwire run` first');
110
+ const profile = JSON.parse(fs.readFileSync(path.join(dir, 'traffic.json'), 'utf8'));
111
+ const defs = new Map(generateAll(profile, { dir }).candidates.map((m) => [m.id, m]));
112
+ const only = values.only ? new Set(values.only.split(',')) : null;
113
+ let todo = latest(rows, lastRunId(rows)).filter((r) => (r.status === 'survived' || r.status === 'masked') && (!only || only.has(r.id)));
114
+ if (values.limit) todo = todo.slice(0, Number(values.limit));
115
+ if (!todo.length) { console.log('Nothing to fix: no survivors in the latest run.'); return 0; }
116
+ const fixDir = path.join(dir, 'fix');
117
+ fs.mkdirSync(fixDir, { recursive: true });
118
+
119
+ return withProxy(cfg, async (tw, base) => {
120
+ let fixed = 0;
121
+ for (const row of todo) {
122
+ const m = defs.get(row.id);
123
+ if (!m) { console.log(`skip ${row.id}: no longer generated from the current baseline`); continue; }
124
+ const masked = row.status === 'masked';
125
+ // strengthen the test that touched the mutant and passed anyway (the killing test for masked ones)
126
+ const test = masked ? row.killed_by : (row.runs.find((x) => x.code === 0 && x.fired) || row.runs[0]).test;
127
+ const passedRun = row.runs.find((x) => x.test === test && x.code === 0) || row.runs[0];
128
+ const shot = lastScreenshot(passedRun?.pack);
129
+ const shotPath = shot ? path.join(fixDir, `${slug(m.id)}.${imageExt(shot)}`) : null;
130
+ if (shot) fs.writeFileSync(shotPath, shot);
131
+ const lessonsFile = path.join(dir, 'lessons.md');
132
+ const lessons = fs.existsSync(lessonsFile) ? fs.readFileSync(lessonsFile, 'utf8').split('\n').filter((l) => l.startsWith('- ')).slice(-12).join('\n') : '';
133
+
134
+ console.log(`\n${masked ? 'MASKED ' : 'SURVIVED'} ${m.describe}\n strengthening ${test} with ${agent}`);
135
+ let previousFailure = null;
136
+ let result = 'gave-up';
137
+ let proof = null;
138
+ let note = '';
139
+ let attempt = 0;
140
+ for (attempt = 1; attempt <= maxAttempts; attempt++) {
141
+ const original = fs.readFileSync(test, 'utf8');
142
+ const restore = snapshotRecording(test);
143
+ const prompt = buildPrompt({ m, test, testText: original, change: beforeAfter(m, profile), shotPath, lessons, previousFailure, masked });
144
+ fs.writeFileSync(path.join(fixDir, `${slug(m.id)}_prompt_${attempt}.txt`), prompt);
145
+ const a = await runAgent(agent, prompt);
146
+ if (a.code === 127) throw new Error(`could not start the ${agent} CLI: ${a.stderr.trim()}`);
147
+ note = a.stdout.trim().split('\n').slice(-1)[0] || '';
148
+ const edited = fs.readFileSync(test, 'utf8');
149
+ const bad = appendOnly(original, edited);
150
+ if (bad) { restore(); previousFailure = bad; console.log(` attempt ${attempt}: rejected (${bad})`); continue; }
151
+
152
+ // proof 1: clean app, the new step is authored once and everything must pass
153
+ await tw.disarm(); await resetApp(cfg, base); await tw.reset(test, false);
154
+ const clean = await runTest(test, { timeout: cfg.timeout, logFile: path.join(fixDir, `${slug(m.id)}_clean_${attempt}.ndjson`) });
155
+ if (clean.code !== 0) {
156
+ restore();
157
+ previousFailure = `on the REAL app the strengthened test failed (exit ${clean.code}${clean.failureReason ? `: ${clean.failureReason}` : ''}). The assertion must hold on the working app.`;
158
+ console.log(` attempt ${attempt}: clean run failed, reverted`);
159
+ continue;
160
+ }
161
+ // proof 2: broken app, replay must fail (healing on for masked mutants: it must survive a heal too)
162
+ await resetApp(cfg, base); await tw.reset(test, false); await tw.arm(m);
163
+ // keep the recording the clean run just committed; whatever Kane writes while the app is
164
+ // broken must not become the test's recording
165
+ const keep = snapshotRecording(test);
166
+ let broken;
167
+ try {
168
+ broken = await runTest(test, { heal: masked, timeout: cfg.timeout, logFile: path.join(fixDir, `${slug(m.id)}_mutant_${attempt}.ndjson`) });
169
+ } finally { keep(); }
170
+ const hits = (await tw.hit()).hits;
171
+ await tw.disarm();
172
+ if (broken.code === 1 && hits > 0) {
173
+ result = 'killed';
174
+ proof = { clean: { code: clean.code, session: clean.sessionId, pack: clean.pack }, mutant: { code: broken.code, session: broken.sessionId, pack: broken.pack, failure: broken.failureReason } };
175
+ appendLesson(dir, m, note);
176
+ console.log(` attempt ${attempt}: proven. Real app: pass. Broken app: fail. ${note}`);
177
+ break;
178
+ }
179
+ restore();
180
+ previousFailure = broken.code === 0
181
+ ? 'the strengthened test still PASSED on the broken app, so the assertion does not observe the bug. Assert the exact value or state that the bug changes.'
182
+ : `the run on the broken app ended with exit ${broken.code} (${hits ? 'mutant fired' : 'mutant never fired'}), not a clean assertion failure.`;
183
+ console.log(` attempt ${attempt}: not proven (${previousFailure.split('.')[0]}), reverted`);
184
+ }
185
+ const rec = { at: new Date().toISOString(), id: m.id, describe: m.describe, operator: m.operator, status_before: row.status, test, agent, attempts: Math.min(attempt, maxAttempts), result, proof, note };
186
+ fs.appendFileSync(path.join(dir, 'fixes.jsonl'), JSON.stringify(rec) + '\n');
187
+ // The proof's mutant run is a Kane run in which the strengthened suite caught this bug.
188
+ // Appending a step cannot un-catch any other mutant (earlier failures still fail first),
189
+ // so the run's score is updated by a superseding ledger row, marked as a fix.
190
+ if (result === 'killed') appendLedger(dir, { ...row, status: 'killed', killed_by: test, fixed: true, fix: { at: rec.at, attempts: rec.attempts, proof } });
191
+ if (result === 'killed') fixed++;
192
+ }
193
+ console.log(`\n${fixed} of ${todo.length} survivors now caught, each proven by a passing clean run and a failing mutant run.`);
194
+ console.log('Re-score with: tripwire run');
195
+ const { writeReport } = await import('../report.js');
196
+ writeReport(dir);
197
+ return fixed === todo.length ? 0 : 1;
198
+ });
199
+ }
@@ -0,0 +1,24 @@
1
+ // tripwire list: the operator catalogue, and the mutants the last baseline would produce.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { loadConfig } from '../config.js';
5
+ import { OPERATORS, generateAll } from '../../operators/index.js';
6
+ import { loadSaboteur } from '../../operators/agent-proposed.js';
7
+
8
+ export default async function list(argv, parseArgs) {
9
+ const { values } = parseArgs({ args: argv, options: { dir: { type: 'string' }, json: { type: 'boolean' }, help: { type: 'boolean', short: 'h' } } });
10
+ if (values.help) { console.log('tripwire list [--json] operators, then candidate mutants from .tripwire/traffic.json'); return 0; }
11
+ const dir = path.resolve(values.dir || loadConfig().dir);
12
+ const f = path.join(dir, 'traffic.json');
13
+ const profile = fs.existsSync(f) ? JSON.parse(fs.readFileSync(f, 'utf8')) : null;
14
+ const gen = profile ? generateAll(profile, { dir }) : null;
15
+ if (values.json) { console.log(JSON.stringify(gen ? gen.candidates : [], null, 2)); return 0; }
16
+ console.log('Operators');
17
+ for (const op of OPERATORS) console.log(` ${op.family.padEnd(10)} ${op.name.padEnd(19)} ${op.summary}${gen?.counts[op.name] ? ` (${gen.counts[op.name].generated ?? 0})` : ''}`);
18
+ const sab = loadSaboteur(dir);
19
+ if (sab.rejected.length) { console.log('\nRejected saboteur mutants'); for (const r of sab.rejected) console.log(` ${r.id}: ${r.errors.join('; ')}`); }
20
+ if (!gen) { console.log('\nNo baseline yet: run `tripwire run --baseline-only` to see concrete mutants.'); return 0; }
21
+ console.log(`\n${gen.candidates.length} candidate mutants from the last baseline`);
22
+ for (const m of gen.candidates) console.log(` ${m.operator.padEnd(19)} ${m.describe}`);
23
+ return 0;
24
+ }
@@ -0,0 +1,28 @@
1
+ import { createProxy } from '../proxy.js';
2
+
3
+ export default async function proxy(argv, parseArgs) {
4
+ const { values } = parseArgs({
5
+ args: argv,
6
+ options: {
7
+ target: { type: 'string', default: process.env.TRIPWIRE_TARGET || 'http://localhost:3000' },
8
+ port: { type: 'string', default: process.env.TRIPWIRE_PORT || '8080' },
9
+ record: { type: 'boolean', default: false },
10
+ quiet: { type: 'boolean', default: false },
11
+ help: { type: 'boolean', short: 'h' }
12
+ }
13
+ });
14
+ if (values.help) {
15
+ console.log('tripwire proxy --target <app url> [--port 8080] [--record] [--quiet]\n\nControl API: POST /_tw/arm, POST /_tw/disarm, POST /_tw/reset, GET /_tw/traffic, GET /_tw/dom, GET /_tw/hit');
16
+ return 0;
17
+ }
18
+ const p = createProxy({ target: values.target, port: Number(values.port), log: values.quiet ? () => {} : (m) => console.log(`[tripwire] ${m}`) });
19
+ p.state.record = values.record;
20
+ const port = await p.listen();
21
+ console.log(`tripwire proxy on http://localhost:${port} -> ${values.target}${values.record ? ' (recording)' : ''}`);
22
+ await new Promise((resolve) => {
23
+ process.on('SIGINT', resolve);
24
+ process.on('SIGTERM', resolve);
25
+ });
26
+ await p.close();
27
+ return 0;
28
+ }
@@ -0,0 +1,11 @@
1
+ import path from 'node:path';
2
+ import { loadConfig } from '../config.js';
3
+ import { writeReport } from '../report.js';
4
+
5
+ export default async function report(argv, parseArgs) {
6
+ const { values } = parseArgs({ args: argv, options: { dir: { type: 'string' }, help: { type: 'boolean', short: 'h' } } });
7
+ if (values.help) { console.log('tripwire report [--dir .tripwire] rebuild .tripwire/report/index.html and badge.svg from the ledger'); return 0; }
8
+ const dir = path.resolve(values.dir || loadConfig().dir);
9
+ console.log(writeReport(dir));
10
+ return 0;
11
+ }