@monkeytestai/monkeytester 0.0.0-stage → 0.5.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 (109) hide show
  1. package/CHANGELOG.md +172 -0
  2. package/LICENSE +661 -0
  3. package/NOTICE +12 -0
  4. package/README.md +196 -2
  5. package/dist/cli.d.ts +43 -0
  6. package/dist/cli.d.ts.map +1 -0
  7. package/dist/cli.js +771 -0
  8. package/dist/cli.js.map +1 -0
  9. package/dist/diff/index.d.ts +78 -0
  10. package/dist/diff/index.d.ts.map +1 -0
  11. package/dist/diff/index.js +119 -0
  12. package/dist/diff/index.js.map +1 -0
  13. package/dist/events.d.ts +66 -0
  14. package/dist/events.d.ts.map +1 -0
  15. package/dist/events.js +77 -0
  16. package/dist/events.js.map +1 -0
  17. package/dist/explorer/index.d.ts +54 -0
  18. package/dist/explorer/index.d.ts.map +1 -0
  19. package/dist/explorer/index.js +491 -0
  20. package/dist/explorer/index.js.map +1 -0
  21. package/dist/explorer/queue.d.ts +94 -0
  22. package/dist/explorer/queue.d.ts.map +1 -0
  23. package/dist/explorer/queue.js +277 -0
  24. package/dist/explorer/queue.js.map +1 -0
  25. package/dist/index.d.ts +36 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +22 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/llm/index.d.ts +79 -0
  30. package/dist/llm/index.d.ts.map +1 -0
  31. package/dist/llm/index.js +392 -0
  32. package/dist/llm/index.js.map +1 -0
  33. package/dist/llm/presets.d.ts +61 -0
  34. package/dist/llm/presets.d.ts.map +1 -0
  35. package/dist/llm/presets.js +101 -0
  36. package/dist/llm/presets.js.map +1 -0
  37. package/dist/monkey.d.ts +151 -0
  38. package/dist/monkey.d.ts.map +1 -0
  39. package/dist/monkey.js +323 -0
  40. package/dist/monkey.js.map +1 -0
  41. package/dist/persistence/index.d.ts +118 -0
  42. package/dist/persistence/index.d.ts.map +1 -0
  43. package/dist/persistence/index.js +196 -0
  44. package/dist/persistence/index.js.map +1 -0
  45. package/dist/planner/faults.d.ts +24 -0
  46. package/dist/planner/faults.d.ts.map +1 -0
  47. package/dist/planner/faults.js +128 -0
  48. package/dist/planner/faults.js.map +1 -0
  49. package/dist/planner/forms.d.ts +33 -0
  50. package/dist/planner/forms.d.ts.map +1 -0
  51. package/dist/planner/forms.js +163 -0
  52. package/dist/planner/forms.js.map +1 -0
  53. package/dist/planner/index.d.ts +31 -0
  54. package/dist/planner/index.d.ts.map +1 -0
  55. package/dist/planner/index.js +250 -0
  56. package/dist/planner/index.js.map +1 -0
  57. package/dist/planner/salvage.d.ts +16 -0
  58. package/dist/planner/salvage.d.ts.map +1 -0
  59. package/dist/planner/salvage.js +89 -0
  60. package/dist/planner/salvage.js.map +1 -0
  61. package/dist/runner/actions.d.ts +85 -0
  62. package/dist/runner/actions.d.ts.map +1 -0
  63. package/dist/runner/actions.js +610 -0
  64. package/dist/runner/actions.js.map +1 -0
  65. package/dist/runner/evidence.d.ts +37 -0
  66. package/dist/runner/evidence.d.ts.map +1 -0
  67. package/dist/runner/evidence.js +122 -0
  68. package/dist/runner/evidence.js.map +1 -0
  69. package/dist/runner/http5xx.d.ts +40 -0
  70. package/dist/runner/http5xx.d.ts.map +1 -0
  71. package/dist/runner/http5xx.js +189 -0
  72. package/dist/runner/http5xx.js.map +1 -0
  73. package/dist/runner/index.d.ts +88 -0
  74. package/dist/runner/index.d.ts.map +1 -0
  75. package/dist/runner/index.js +597 -0
  76. package/dist/runner/index.js.map +1 -0
  77. package/dist/runner/replay.d.ts +42 -0
  78. package/dist/runner/replay.d.ts.map +1 -0
  79. package/dist/runner/replay.js +440 -0
  80. package/dist/runner/replay.js.map +1 -0
  81. package/dist/runner/timeout.d.ts +16 -0
  82. package/dist/runner/timeout.d.ts.map +1 -0
  83. package/dist/runner/timeout.js +38 -0
  84. package/dist/runner/timeout.js.map +1 -0
  85. package/dist/trace/fingerprint.d.ts +78 -0
  86. package/dist/trace/fingerprint.d.ts.map +1 -0
  87. package/dist/trace/fingerprint.js +273 -0
  88. package/dist/trace/fingerprint.js.map +1 -0
  89. package/dist/trace/serialize.d.ts +15 -0
  90. package/dist/trace/serialize.d.ts.map +1 -0
  91. package/dist/trace/serialize.js +86 -0
  92. package/dist/trace/serialize.js.map +1 -0
  93. package/dist/triager/index.d.ts +64 -0
  94. package/dist/triager/index.d.ts.map +1 -0
  95. package/dist/triager/index.js +301 -0
  96. package/dist/triager/index.js.map +1 -0
  97. package/dist/types.d.ts +491 -0
  98. package/dist/types.d.ts.map +1 -0
  99. package/dist/types.js +10 -0
  100. package/dist/types.js.map +1 -0
  101. package/dist/verify/index.d.ts +52 -0
  102. package/dist/verify/index.d.ts.map +1 -0
  103. package/dist/verify/index.js +140 -0
  104. package/dist/verify/index.js.map +1 -0
  105. package/dist/verify/verdict.d.ts +34 -0
  106. package/dist/verify/verdict.d.ts.map +1 -0
  107. package/dist/verify/verdict.js +89 -0
  108. package/dist/verify/verdict.js.map +1 -0
  109. package/package.json +90 -4
package/dist/cli.js ADDED
@@ -0,0 +1,771 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * monkeytest CLI — the bug-finding loop on the command line.
4
+ *
5
+ * Subcommands:
6
+ *
7
+ * monkeytest init Scaffold a .monkeytest/ directory.
8
+ * monkeytest explore <url> Crawl + plan only. Writes plan.json.
9
+ * monkeytest run <url> Full pipeline: explore + plan + run + triage.
10
+ * Writes plan.json + runs/<id>.json + shots/.
11
+ * monkeytest rerun [<runId>] Replay the recorded action trace (no LLM).
12
+ * --heal re-resolves a step whose locator missed.
13
+ * monkeytest verify [run] Replay each bug trace and report fixed /
14
+ * still_broken / flaky / healed / blocked.
15
+ * monkeytest diff <a> <b> Diff two stored runs by bug fingerprint.
16
+ * "<a>" / "<b>" are run ids or "latest"/"prev".
17
+ * monkeytest report [<runId>] Pretty-print a stored run (flows, bugs, paths).
18
+ *
19
+ * Common flags:
20
+ * --dir <path> Working directory (default ./.monkeytest)
21
+ * --provider <id> openai | gemini | anthropic | mistral | groq | openai_compatible
22
+ * --model <id> Override model id (provider-specific)
23
+ * --quality <preset> cheap | balanced | smart (used by autoLLMConfig)
24
+ * --max <n> Max pages to crawl (explore/run only, default 8)
25
+ * --flows <n> Max flows to plan (explore/run only, default 6)
26
+ * --no-headless Show the browser window
27
+ * --label <text> Free-form label saved on the plan/run
28
+ * --heal Re-resolve a trace step when its locator misses
29
+ * --repeat <n> Replay each bug n times during `verify` (default 1)
30
+ * --bug <fingerprint> Verify a single bug
31
+ * --json Machine-readable output (run/diff/report/verify)
32
+ * --fail-on-5xx Fail a step that saw a same-origin HTTP ≥500 (default)
33
+ * --no-fail-on-5xx Leave those responses as evidence on a passed step
34
+ *
35
+ * Exit codes:
36
+ * 0 success / no blocking bugs / no bug still firing
37
+ * 1 blocking bugs (`run` / `rerun`), new or regressed bugs (`diff`),
38
+ * or any `still_broken` / `flaky` verdict (`verify`)
39
+ * 2 invalid args / setup error
40
+ * 3 engine / runtime error
41
+ */
42
+ import { mkdirSync, writeFileSync, existsSync, statSync } from 'node:fs';
43
+ import { resolve, relative } from 'node:path';
44
+ import { Monkey } from './monkey.js';
45
+ import { createLLM } from './llm/index.js';
46
+ import { autoLLMConfig, detectProviderFromEnv, CHEAP_FAST_MODEL } from './llm/presets.js';
47
+ import { savePlan, loadPlan, saveRun, loadRun, listRuns, } from './persistence/index.js';
48
+ import { bugMatchesFingerprint, diffRuns, summariseDiff } from './diff/index.js';
49
+ import { replayTraces } from './runner/replay.js';
50
+ import { triage } from './triager/index.js';
51
+ import { verifyBugs } from './verify/index.js';
52
+ /* ── Tiny ANSI helpers (no chalk dep) ─────────────────────────────────── */
53
+ const c = {
54
+ reset: '\x1b[0m',
55
+ bold: '\x1b[1m',
56
+ dim: '\x1b[2m',
57
+ red: '\x1b[31m',
58
+ green: '\x1b[32m',
59
+ yellow: '\x1b[33m',
60
+ blue: '\x1b[34m',
61
+ magenta: '\x1b[35m',
62
+ cyan: '\x1b[36m',
63
+ };
64
+ function tty(s, code) {
65
+ return process.stdout.isTTY ? `${c[code]}${s}${c.reset}` : s;
66
+ }
67
+ const ENGINE_VERSION = 'monkeytester@0.5.0';
68
+ function defaultCommonOpts() {
69
+ return {
70
+ dir: '.monkeytest',
71
+ quality: 'balanced',
72
+ maxPages: 8,
73
+ maxFlows: 6,
74
+ headless: true,
75
+ json: false,
76
+ heal: false,
77
+ repeat: 1,
78
+ failOn5xx: true,
79
+ };
80
+ }
81
+ function parseArgs(argv) {
82
+ const [, , rawCmd, ...rest] = argv;
83
+ // Treat top-level `--help`/`-h`/`--version`/`-v` as commands, not flags.
84
+ let cmd = rawCmd || 'help';
85
+ if (cmd === '-h' || cmd === '--help')
86
+ cmd = 'help';
87
+ if (cmd === '-v' || cmd === '--version')
88
+ cmd = 'version';
89
+ const out = {
90
+ command: cmd,
91
+ positional: [],
92
+ opts: defaultCommonOpts(),
93
+ showHelp: false,
94
+ };
95
+ for (let i = 0; i < rest.length; i++) {
96
+ const a = rest[i];
97
+ const next = () => rest[++i];
98
+ switch (a) {
99
+ case '-h':
100
+ case '--help':
101
+ out.showHelp = true;
102
+ break;
103
+ case '-v':
104
+ case '--version':
105
+ out.command = 'version';
106
+ break;
107
+ case '-d':
108
+ case '--dir':
109
+ out.opts.dir = next();
110
+ break;
111
+ case '--provider':
112
+ out.opts.provider = next();
113
+ break;
114
+ case '--model':
115
+ out.opts.model = next();
116
+ break;
117
+ case '--api-key':
118
+ case '--apikey':
119
+ out.opts.apiKey = next();
120
+ break;
121
+ case '--base-url':
122
+ out.opts.baseURL = next();
123
+ break;
124
+ case '--quality':
125
+ out.opts.quality = next();
126
+ break;
127
+ case '-m':
128
+ case '--max':
129
+ out.opts.maxPages = parseInt(next(), 10);
130
+ break;
131
+ case '--flows':
132
+ out.opts.maxFlows = parseInt(next(), 10);
133
+ break;
134
+ case '--no-headless':
135
+ out.opts.headless = false;
136
+ break;
137
+ case '--label':
138
+ out.opts.label = next();
139
+ break;
140
+ case '--json':
141
+ out.opts.json = true;
142
+ break;
143
+ case '--fail-on-5xx':
144
+ out.opts.failOn5xx = true;
145
+ break;
146
+ case '--no-fail-on-5xx':
147
+ out.opts.failOn5xx = false;
148
+ break;
149
+ case '--heal':
150
+ out.opts.heal = true;
151
+ break;
152
+ case '--bug': {
153
+ const fp = next();
154
+ if (!fp)
155
+ die(2, '--bug requires a fingerprint');
156
+ out.opts.bug = fp;
157
+ break;
158
+ }
159
+ case '--repeat': {
160
+ const n = parseInt(next(), 10);
161
+ if (!Number.isInteger(n) || n < 1)
162
+ die(2, '--repeat must be a positive integer');
163
+ out.opts.repeat = n;
164
+ break;
165
+ }
166
+ default:
167
+ if (a.startsWith('-')) {
168
+ die(2, `Unknown flag: ${a}`);
169
+ }
170
+ out.positional.push(a);
171
+ }
172
+ }
173
+ return out;
174
+ }
175
+ /* ── LLM config resolution ────────────────────────────────────────────── */
176
+ function buildLLMConfig(opts) {
177
+ // Honour explicit --provider, otherwise let autoLLMConfig pick from env.
178
+ if (opts.provider) {
179
+ const single = {
180
+ provider: opts.provider,
181
+ model: opts.model,
182
+ apiKey: opts.apiKey,
183
+ baseURL: opts.baseURL,
184
+ };
185
+ return {
186
+ explorer: { ...single, model: opts.model || CHEAP_FAST_MODEL[opts.provider] },
187
+ planner: single,
188
+ runner: { ...single, model: opts.model || CHEAP_FAST_MODEL[opts.provider] },
189
+ };
190
+ }
191
+ return autoLLMConfig({ quality: opts.quality });
192
+ }
193
+ function ensureLLMReady(opts) {
194
+ if (opts.provider)
195
+ return;
196
+ const detected = detectProviderFromEnv();
197
+ if (!detected) {
198
+ die(2, 'No LLM provider configured. Set one of: '
199
+ + 'GEMINI_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY, MISTRAL_API_KEY, '
200
+ + 'GROQ_API_KEY, or OPENAI_COMPATIBLE_BASE_URL — or pass --provider explicitly.');
201
+ }
202
+ }
203
+ /* ── Help ─────────────────────────────────────────────────────────────── */
204
+ function printHelp(cmd) {
205
+ if (!cmd || cmd === 'help') {
206
+ console.log(`
207
+ ${tty('monkeytest', 'bold')} — the AI bug-finding loop for any web app.
208
+
209
+ Usage:
210
+ monkeytest <command> [args] [flags]
211
+
212
+ Commands:
213
+ ${tty('init', 'cyan')} Scaffold a .monkeytest/ directory.
214
+ ${tty('explore', 'cyan')} <url> Crawl + plan only. Writes plan.json.
215
+ ${tty('run', 'cyan')} <url> Full pipeline: explore + plan + run + triage.
216
+ ${tty('rerun', 'cyan')} [<runId>] Replay a stored trace. No LLM unless --heal.
217
+ ${tty('verify', 'cyan')} [run] Replay each bug trace and print a verdict.
218
+ ${tty('diff', 'cyan')} <runA> <runB> Diff two stored runs by bug fingerprint.
219
+ ${tty('report', 'cyan')} [<runId>] Pretty-print a stored run.
220
+ ${tty('help', 'cyan')} [<command>] Show help (this page or per-command).
221
+ ${tty('version', 'cyan')} Print engine version and exit.
222
+
223
+ Common flags (apply to most commands):
224
+ -d, --dir <path> Working dir (default ./.monkeytest)
225
+ --provider <id> openai | gemini | anthropic | mistral | groq | openai_compatible
226
+ --model <id> Provider-specific model id
227
+ --api-key <key> Override env API key
228
+ --base-url <url> Required for openai_compatible (Ollama, vLLM, …)
229
+ --quality <preset> cheap | balanced | smart (default balanced)
230
+ -m, --max <n> Max pages to crawl (default 8)
231
+ --flows <n> Max flows to plan (default 6)
232
+ --no-headless Show the browser window
233
+ --label <text> Free-form label saved on the plan/run
234
+ --heal If a recorded locator misses, ask the LLM (rerun/verify)
235
+ --repeat <n> Replay each bug n times (verify, default 1)
236
+ --bug <fingerprint> Verify one bug
237
+ --json Machine-readable output
238
+ --fail-on-5xx Fail steps that saw a same-origin HTTP ≥500 (default)
239
+ --no-fail-on-5xx Keep those 5xx responses as evidence only
240
+
241
+ Exit codes: 0 ok · 1 bugs still firing · 2 bad args / setup · 3 engine error.
242
+
243
+ Environment:
244
+ GEMINI_API_KEY, OPENAI_API_KEY, ANTHROPIC_API_KEY, MISTRAL_API_KEY,
245
+ GROQ_API_KEY, OPENAI_COMPATIBLE_BASE_URL
246
+
247
+ Quick start:
248
+ monkeytest run https://example.com
249
+ monkeytest rerun # replay the latest trace, no LLM
250
+ monkeytest verify --repeat 3 # is each known bug actually fixed?
251
+ monkeytest diff prev latest # see what changed
252
+
253
+ Docs: https://docs.monkeytest.ai
254
+ `);
255
+ return;
256
+ }
257
+ // Per-command help
258
+ const text = {
259
+ init: `monkeytest init [--dir .monkeytest]
260
+ Scaffold a working directory with config defaults. Idempotent.`,
261
+ explore: `monkeytest explore <url> [--max 8] [--flows 6] [--no-headless]
262
+ Crawl <url>, summarise pages, generate a TestPlan. Writes plan.json + shots/.`,
263
+ run: `monkeytest run <url> [--max 8] [--flows 6] [--quality balanced]
264
+ Run the full pipeline (explore + plan + run + triage). Writes plan.json,
265
+ runs/<id>.json, and screenshots. Exits with code 1 if blocking bugs found.
266
+ Same-origin HTTP ≥500 responses fail the step (--no-fail-on-5xx opts out).
267
+ The crawl reserves room for help/contact/about pages under a small --max.
268
+ A crawled form, an enabled button, a link to a page the crawl did not open,
269
+ and a disabled button each keep a grounded flow when --flows has room.
270
+ Exits 3 when the explorer loads no pages.`,
271
+ rerun: `monkeytest rerun [<runId>] [--heal] [--dir .monkeytest]
272
+ Replay the action trace stored on a run. Does not call the LLM.
273
+ --heal re-resolves a step whose locator no longer matches and marks it healed.
274
+ If <runId> is omitted, the latest run is replayed. Runs recorded before
275
+ traces existed fall back to re-executing the stored plan with the LLM.`,
276
+ verify: `monkeytest verify [runDir|runId] [--bug <fingerprint>] [--repeat N] [--heal]
277
+ Replay each known bug's trace and print a verdict:
278
+ fixed the failing step passed on every attempt
279
+ still_broken the failing step failed on every attempt
280
+ flaky the bug fired on some but not all attempts
281
+ healed a stale locator was re-resolved (--heal) and the bug did not recur
282
+ blocked the failing step could not be reached
283
+ Exit 1 if any bug is still_broken or flaky. --json prints the report.`,
284
+ diff: `monkeytest diff <runA> <runB>
285
+ Diff two stored runs by stable bug fingerprint. Use "latest"/"prev" as
286
+ shortcuts. Prints new / fixed / persisting / regressed bugs.`,
287
+ report: `monkeytest report [<runId>] [--json]
288
+ Pretty-print a stored run (flows, bugs, evidence paths). Defaults to
289
+ "latest". Use --json for machine-readable output.`,
290
+ };
291
+ console.log(text[cmd] || `No help for "${cmd}". Try \`monkeytest help\`.`);
292
+ }
293
+ /* ── Commands ─────────────────────────────────────────────────────────── */
294
+ async function cmdInit(opts) {
295
+ const dir = resolve(opts.dir);
296
+ mkdirSync(dir, { recursive: true });
297
+ mkdirSync(resolve(dir, 'runs'), { recursive: true });
298
+ mkdirSync(resolve(dir, 'shots'), { recursive: true });
299
+ const config = resolve(dir, 'config.json');
300
+ if (!existsSync(config)) {
301
+ writeFileSync(config, JSON.stringify({
302
+ $schema: 'https://docs.monkeytest.ai/config-schema-v1.json',
303
+ provider: opts.provider || 'auto',
304
+ quality: opts.quality,
305
+ maxPages: opts.maxPages,
306
+ maxFlows: opts.maxFlows,
307
+ }, null, 2));
308
+ }
309
+ const gitignore = resolve(dir, '.gitignore');
310
+ if (!existsSync(gitignore)) {
311
+ writeFileSync(gitignore, [
312
+ '# MonkeyTest local artefacts',
313
+ 'shots/',
314
+ 'runs/',
315
+ '*.tmp',
316
+ '',
317
+ '# Keep config + plan tracked',
318
+ '!config.json',
319
+ '!plan.json',
320
+ '',
321
+ ].join('\n'));
322
+ }
323
+ console.log(`${tty('✓', 'green')} Initialised ${tty(relative(process.cwd(), dir) || '.', 'cyan')}/`);
324
+ console.log(` Tracked: config.json, plan.json (after first run)`);
325
+ console.log(` Ignored: shots/, runs/`);
326
+ console.log(`\nNext: ${tty('monkeytest run https://example.com', 'cyan')}`);
327
+ }
328
+ async function cmdExplore(url, opts) {
329
+ if (!url)
330
+ die(2, 'Usage: monkeytest explore <url>');
331
+ ensureLLMReady(opts);
332
+ const monkey = new Monkey({ llm: buildLLMConfig(opts), strictOracles: true, failOn5xx: opts.failOn5xx });
333
+ console.log(`\n→ Exploring ${tty(url, 'cyan')} (max ${opts.maxPages} pages, headless=${opts.headless})…\n`);
334
+ const t0 = Date.now();
335
+ const screenshotsDir = resolve(opts.dir, 'shots');
336
+ mkdirSync(screenshotsDir, { recursive: true });
337
+ const { siteMap, plan } = await monkey.exploreAndPlan(url, {
338
+ explore: {
339
+ maxPages: opts.maxPages,
340
+ headless: opts.headless,
341
+ screenshotsDir,
342
+ onPage: (p) => console.log(` · visited [${p.authGated ? 'auth' : 'open'}] ${p.url} — ${truncate(p.summary, 80)}`),
343
+ },
344
+ plan: { maxFlows: opts.maxFlows },
345
+ });
346
+ const dt = ((Date.now() - t0) / 1000).toFixed(1);
347
+ const sitemapFile = resolve(opts.dir, 'sitemap.json');
348
+ mkdirSync(opts.dir, { recursive: true });
349
+ writeFileSync(sitemapFile, JSON.stringify(siteMap, null, 2));
350
+ const planFile = savePlan(plan, { dir: opts.dir, label: opts.label, engine: ENGINE_VERSION });
351
+ console.log(summariseSiteMap(siteMap));
352
+ console.log(summarisePlan(plan));
353
+ console.log(`\n${tty('✓', 'green')} Done in ${dt}s.`);
354
+ console.log(` ${tty('sitemap', 'dim')} → ${relative(process.cwd(), sitemapFile)}`);
355
+ console.log(` ${tty('plan', 'dim')} → ${relative(process.cwd(), planFile)}\n`);
356
+ }
357
+ async function cmdRun(url, opts) {
358
+ if (!url)
359
+ die(2, 'Usage: monkeytest run <url>');
360
+ ensureLLMReady(opts);
361
+ const screenshotsDir = resolve(opts.dir, 'shots');
362
+ mkdirSync(screenshotsDir, { recursive: true });
363
+ const monkey = new Monkey({ llm: buildLLMConfig(opts), strictOracles: true, failOn5xx: opts.failOn5xx });
364
+ console.log(`\n→ Running ${tty(url, 'cyan')} (max ${opts.maxPages} pages, ${opts.maxFlows} flows, headless=${opts.headless})…\n`);
365
+ const t0 = Date.now();
366
+ const { siteMap, plan, run } = await monkey.executeAndTriage(url, {
367
+ explore: {
368
+ maxPages: opts.maxPages,
369
+ headless: opts.headless,
370
+ screenshotsDir,
371
+ onPage: (p) => console.log(` · visited ${p.url}`),
372
+ },
373
+ plan: { maxFlows: opts.maxFlows },
374
+ run: {
375
+ screenshotsDir,
376
+ headless: opts.headless,
377
+ onEvent: (evt) => {
378
+ if (evt.type === 'flow.start')
379
+ console.log(` ▶ ${tty(evt.flow.name, 'magenta')}`);
380
+ if (evt.type === 'step.complete') {
381
+ const sym = evt.result.status === 'passed' ? tty('✓', 'green') : evt.result.status === 'failed' ? tty('✗', 'red') : tty('·', 'dim');
382
+ console.log(` ${sym} step ${evt.index}: ${truncate(evt.result.observation, 80)}`);
383
+ }
384
+ },
385
+ },
386
+ });
387
+ const dt = ((Date.now() - t0) / 1000).toFixed(1);
388
+ const planFile = savePlan(plan, { dir: opts.dir, label: opts.label, engine: ENGINE_VERSION });
389
+ const { path: runFile, id: runId } = saveRun(run, {
390
+ dir: opts.dir,
391
+ planRef: { path: planFile, createdAt: new Date().toISOString() },
392
+ engine: ENGINE_VERSION,
393
+ });
394
+ if (opts.json) {
395
+ console.log(JSON.stringify({ siteMap, plan, run, runId, runFile, planFile }, null, 2));
396
+ }
397
+ else {
398
+ console.log(summariseSiteMap(siteMap));
399
+ console.log(summarisePlan(plan));
400
+ console.log(summariseRun(run));
401
+ }
402
+ console.log(`\n${tty('✓', 'green')} Done in ${dt}s.`);
403
+ console.log(` ${tty('plan', 'dim')} → ${relative(process.cwd(), planFile)}`);
404
+ console.log(` ${tty('run', 'dim')} → ${relative(process.cwd(), runFile)} (id: ${tty(runId, 'cyan')})`);
405
+ const blocking = run.bugs.filter(b => b.severity !== 'minor');
406
+ if (blocking.length) {
407
+ console.error(`\n${tty(`✗ ${blocking.length} blocking bug${blocking.length === 1 ? '' : 's'} found.`, 'red')}`);
408
+ process.exit(1);
409
+ }
410
+ if (siteMap.pages.length === 0) {
411
+ console.error(`\n${tty('✗ Explorer loaded no pages, so this run cannot judge the site.', 'red')}`);
412
+ process.exit(3);
413
+ }
414
+ }
415
+ async function cmdRerun(runId, opts) {
416
+ const stored = storedRunForRerun(runId, opts);
417
+ const traces = stored ? tracesOf(stored.run) : [];
418
+ if (stored && traces.length > 0) {
419
+ return replayStoredRun(stored, traces, opts);
420
+ }
421
+ if (stored) {
422
+ console.log(tty('No action trace on this run. Falling back to LLM re-resolution of the stored plan.', 'yellow'));
423
+ }
424
+ return rerunStoredPlan(stored, opts);
425
+ }
426
+ async function replayStoredRun(stored, traces, opts) {
427
+ if (opts.heal)
428
+ ensureLLMReady(opts);
429
+ const screenshotsDir = resolve(opts.dir, 'shots');
430
+ mkdirSync(screenshotsDir, { recursive: true });
431
+ console.log(`\n↻ Replaying ${traces.length} trace(s) from ${tty(stored.id, 'cyan')}${opts.heal ? ' (heal on)' : ''}…\n`);
432
+ const t0 = Date.now();
433
+ const raw = await replayTraces(traces, {
434
+ screenshotsDir,
435
+ headless: opts.headless,
436
+ heal: opts.heal,
437
+ llm: opts.heal ? runnerLLM(opts) : undefined,
438
+ strictOracles: true,
439
+ failOn5xx: opts.failOn5xx,
440
+ });
441
+ const run = triage(raw, { failOn5xx: opts.failOn5xx });
442
+ const dt = ((Date.now() - t0) / 1000).toFixed(1);
443
+ const { path: runFile, id: newRunId } = saveRun(run, {
444
+ dir: opts.dir,
445
+ planRef: stored.planRef,
446
+ engine: ENGINE_VERSION,
447
+ });
448
+ if (opts.json) {
449
+ console.log(JSON.stringify({ run, runId: newRunId, runFile, replay: true, heal: opts.heal }, null, 2));
450
+ }
451
+ else {
452
+ console.log(summariseRun(run));
453
+ const healed = run.flows.reduce((n, flow) => n + flow.steps.filter(step => step.resolution === 'healed').length, 0);
454
+ if (healed)
455
+ console.log(` healed steps: ${healed}`);
456
+ }
457
+ console.log(`\n${tty('✓', 'green')} Replay complete in ${dt}s.`);
458
+ console.log(` ${tty('run', 'dim')} → ${relative(process.cwd(), runFile)} (id: ${tty(newRunId, 'cyan')})`);
459
+ suggestDiff(opts.dir, newRunId);
460
+ exitIfBlocking(run);
461
+ }
462
+ async function rerunStoredPlan(stored, opts) {
463
+ ensureLLMReady(opts);
464
+ // Resolve plan: an explicit run means "use the plan stored alongside that run",
465
+ // otherwise just load the canonical plan.json.
466
+ let storedPlan;
467
+ let planSource;
468
+ if (stored?.planRef?.path) {
469
+ storedPlan = loadPlan(stored.planRef.path);
470
+ planSource = stored.planRef.path;
471
+ }
472
+ else if (stored) {
473
+ die(2, `Stored run ${stored.id} has no action trace and no planRef. Cannot rerun.`);
474
+ return;
475
+ }
476
+ else {
477
+ storedPlan = loadPlan(opts.dir);
478
+ planSource = resolve(opts.dir, 'plan.json');
479
+ }
480
+ const screenshotsDir = resolve(opts.dir, 'shots');
481
+ mkdirSync(screenshotsDir, { recursive: true });
482
+ const monkey = new Monkey({ llm: buildLLMConfig(opts), strictOracles: true, failOn5xx: opts.failOn5xx });
483
+ console.log(`\n↻ Re-running ${storedPlan.plan.flows.length} flow(s) from ${tty(relative(process.cwd(), planSource), 'cyan')}…\n`);
484
+ const t0 = Date.now();
485
+ const { run } = await monkey.runFromPlan(storedPlan.plan, {
486
+ run: {
487
+ screenshotsDir,
488
+ headless: opts.headless,
489
+ onEvent: (evt) => {
490
+ if (evt.type === 'flow.start')
491
+ console.log(` ▶ ${tty(evt.flow.name, 'magenta')}`);
492
+ if (evt.type === 'step.complete') {
493
+ const sym = evt.result.status === 'passed' ? tty('✓', 'green') : evt.result.status === 'failed' ? tty('✗', 'red') : tty('·', 'dim');
494
+ console.log(` ${sym} step ${evt.index}: ${truncate(evt.result.observation, 80)}`);
495
+ }
496
+ },
497
+ },
498
+ });
499
+ const dt = ((Date.now() - t0) / 1000).toFixed(1);
500
+ const { path: runFile, id: newRunId } = saveRun(run, {
501
+ dir: opts.dir,
502
+ planRef: { path: planSource, createdAt: storedPlan.createdAt },
503
+ engine: ENGINE_VERSION,
504
+ });
505
+ console.log(summariseRun(run));
506
+ console.log(`\n${tty('✓', 'green')} Re-run complete in ${dt}s.`);
507
+ console.log(` ${tty('run', 'dim')} → ${relative(process.cwd(), runFile)} (id: ${tty(newRunId, 'cyan')})`);
508
+ // Auto-suggest a diff if there's a previous run to compare against.
509
+ const ids = listRuns(opts.dir);
510
+ if (ids.length >= 2) {
511
+ const previousId = ids[1]; // listRuns returns newest-first; [0] is the run we just wrote
512
+ console.log(`\n${tty('Tip:', 'dim')} compare to previous run with:`);
513
+ console.log(` ${tty(`monkeytest diff ${previousId} ${newRunId}`, 'cyan')}`);
514
+ }
515
+ exitIfBlocking(run);
516
+ }
517
+ async function cmdVerify(positional, opts) {
518
+ const stored = resolveStoredRun(positional, opts);
519
+ if (opts.bug && !stored.run.bugs.some(bug => bugMatchesFingerprint(bug, opts.bug))) {
520
+ const known = stored.run.bugs.map(bug => bug.fingerprint).slice(0, 8).join(', ');
521
+ die(2, `No bug with fingerprint ${opts.bug} on run ${stored.id}.${known ? ` Known: ${known}` : ''}`);
522
+ }
523
+ if (opts.heal)
524
+ ensureLLMReady(opts);
525
+ const screenshotsDir = resolve(opts.dir, 'shots');
526
+ mkdirSync(screenshotsDir, { recursive: true });
527
+ if (!opts.json) {
528
+ const scope = opts.bug ? `bug ${opts.bug}` : `${stored.run.bugs.length} bug(s)`;
529
+ console.log(`\n→ Verifying ${scope} from ${tty(stored.id, 'cyan')} (repeat ${opts.repeat}${opts.heal ? ', heal' : ''})…\n`);
530
+ }
531
+ const report = await verifyBugs(stored.run, {
532
+ screenshotsDir,
533
+ headless: opts.headless,
534
+ heal: opts.heal,
535
+ llm: opts.heal ? runnerLLM(opts) : undefined,
536
+ repeat: opts.repeat,
537
+ fingerprints: opts.bug ? [opts.bug] : undefined,
538
+ recordVideo: false,
539
+ strictOracles: true,
540
+ failOn5xx: opts.failOn5xx,
541
+ });
542
+ if (opts.json) {
543
+ console.log(JSON.stringify({ runId: stored.id, ...report }, null, 2));
544
+ }
545
+ else {
546
+ printVerifyTable(stored.id, report);
547
+ }
548
+ if (report.exitCode !== 0) {
549
+ const broken = report.stats.still_broken + report.stats.flaky;
550
+ console.error(tty(`✗ ${broken} bug${broken === 1 ? '' : 's'} still firing.`, 'red'));
551
+ process.exit(report.exitCode);
552
+ }
553
+ }
554
+ function cmdDiff(a, b, opts) {
555
+ if (!a || !b)
556
+ die(2, 'Usage: monkeytest diff <runA> <runB>');
557
+ const ids = listRuns(opts.dir);
558
+ const resolveId = (s) => {
559
+ if (s === 'latest')
560
+ return ids[0];
561
+ if (s === 'prev')
562
+ return ids[1];
563
+ return s;
564
+ };
565
+ const idA = resolveId(a);
566
+ const idB = resolveId(b);
567
+ if (!idA || !idB)
568
+ die(2, `Could not resolve run id(s). Available: ${ids.slice(0, 5).join(', ') || '(none)'}`);
569
+ const runA = loadRun(idA, { dir: opts.dir });
570
+ const runB = loadRun(idB, { dir: opts.dir });
571
+ const diff = diffRuns(runA.run, runB.run);
572
+ if (opts.json) {
573
+ console.log(JSON.stringify({ from: idA, to: idB, diff }, null, 2));
574
+ return;
575
+ }
576
+ console.log(`\n${tty('Diff', 'bold')} ${tty(idA, 'dim')} → ${tty(idB, 'dim')}`);
577
+ console.log(` ${tty(summariseDiff(diff), 'bold')}\n`);
578
+ printDiffSection('New bugs', diff.newBugs, 'red');
579
+ printDiffSection('Regressed bugs', diff.regressedBugs, 'red');
580
+ printDiffSection('Fixed bugs', diff.fixedBugs, 'green');
581
+ printDiffSection('Still broken', diff.persistingBugs, 'yellow');
582
+ // Exit 1 if anything got worse, so CI can gate on this
583
+ if (diff.newBugs.length > 0 || diff.regressedBugs.length > 0) {
584
+ process.exit(1);
585
+ }
586
+ }
587
+ function cmdReport(runId, opts) {
588
+ const id = runId || 'latest';
589
+ const stored = loadRun(id, { dir: opts.dir });
590
+ const { run } = stored;
591
+ if (opts.json) {
592
+ console.log(JSON.stringify(stored, null, 2));
593
+ return;
594
+ }
595
+ console.log(`\n${tty('Report', 'bold')} for run ${tty(stored.id, 'cyan')} (${stored.createdAt})`);
596
+ if (stored.planRef?.path) {
597
+ console.log(` ${tty('plan', 'dim')}: ${stored.planRef.path}`);
598
+ }
599
+ console.log(summariseRun(run));
600
+ for (const flow of run.flows) {
601
+ const sym = flow.status === 'passed' ? tty('✓', 'green') : flow.status === 'failed' ? tty('✗', 'red') : tty('·', 'yellow');
602
+ console.log(`\n ${sym} ${tty(flow.name, 'bold')} (${flow.steps.length} steps, ${(flow.durationMs / 1000).toFixed(1)}s)`);
603
+ for (const s of flow.steps) {
604
+ const ssym = s.status === 'passed' ? tty('✓', 'green') : s.status === 'failed' ? tty('✗', 'red') : tty('·', 'dim');
605
+ console.log(` ${ssym} ${s.index}. ${truncate(s.action, 80)}`);
606
+ if (s.screenshotPath)
607
+ console.log(` ${tty('shot', 'dim')}: ${relative(process.cwd(), s.screenshotPath)}`);
608
+ }
609
+ }
610
+ if (run.bugs.length) {
611
+ console.log(`\n ${tty('Bugs:', 'bold')}`);
612
+ for (const b of run.bugs) {
613
+ const sev = b.severity === 'critical' ? tty(b.severity, 'red')
614
+ : b.severity === 'major' ? tty(b.severity, 'yellow')
615
+ : tty(b.severity, 'dim');
616
+ console.log(` [${sev}] ${b.title}`);
617
+ console.log(` ${tty('observed:', 'dim')} ${truncate(b.observed, 100)}`);
618
+ console.log(` ${tty('fingerprint:', 'dim')} ${b.fingerprint}`);
619
+ }
620
+ }
621
+ console.log();
622
+ }
623
+ /* ── Pretty-print helpers ─────────────────────────────────────────────── */
624
+ function summariseSiteMap(siteMap) {
625
+ return `\n${tty('SiteMap', 'bold')}
626
+ start: ${siteMap.startUrl}
627
+ type: ${siteMap.siteType}
628
+ summary: ${truncate(siteMap.summary, 200)}
629
+ pages: ${siteMap.pages.length} visited, ${siteMap.pendingUrls.length} pending, ${siteMap.failedUrls.length} failed`;
630
+ }
631
+ function summarisePlan(plan) {
632
+ if (plan.flows.length === 0)
633
+ return `\n${tty('Plan', 'bold')}\n (no flows)`;
634
+ const lines = plan.flows.map((f, i) => ` ${i + 1}. [${f.kind}] ${f.name} (${f.steps.length} steps)`);
635
+ return `\n${tty('Plan', 'bold')}\n${lines.join('\n')}${plan.notes ? `\n notes: ${plan.notes}` : ''}`;
636
+ }
637
+ function summariseRun(run) {
638
+ const { flowsTotal, flowsPassed, flowsFailed, bugsCritical, bugsMajor, bugsMinor } = run.stats;
639
+ return `\n${tty('Run', 'bold')}
640
+ flows: ${tty(`${flowsPassed}/${flowsTotal}`, flowsFailed === 0 ? 'green' : 'yellow')} passed, ${flowsFailed} failed
641
+ bugs: ${tty(String(bugsCritical), bugsCritical ? 'red' : 'dim')} critical, ${tty(String(bugsMajor), bugsMajor ? 'yellow' : 'dim')} major, ${tty(String(bugsMinor), 'dim')} minor`;
642
+ }
643
+ function printDiffSection(title, entries, colour) {
644
+ if (entries.length === 0)
645
+ return;
646
+ console.log(` ${tty(`${title} (${entries.length})`, colour)}`);
647
+ for (const e of entries) {
648
+ console.log(` [${e.bug.severity}] ${e.bug.title}`);
649
+ console.log(` ${tty('fingerprint:', 'dim')} ${e.fingerprint}`);
650
+ }
651
+ console.log();
652
+ }
653
+ function printVerifyTable(runId, report) {
654
+ const { stats } = report;
655
+ console.log(`${tty('Verify', 'bold')} ${tty(runId, 'dim')}`);
656
+ console.log(` ${tty(String(stats.fixed), 'green')} fixed, `
657
+ + `${tty(String(stats.still_broken), stats.still_broken ? 'red' : 'dim')} still broken, `
658
+ + `${tty(String(stats.flaky), stats.flaky ? 'yellow' : 'dim')} flaky, `
659
+ + `${tty(String(stats.healed), stats.healed ? 'cyan' : 'dim')} healed, `
660
+ + `${tty(String(stats.blocked), 'dim')} blocked\n`);
661
+ if (report.results.length === 0) {
662
+ console.log(' No bugs to verify.\n');
663
+ return;
664
+ }
665
+ console.log(` ${'fingerprint'.padEnd(18)} ${'verdict'.padEnd(14)} ${'fired'.padEnd(8)} title`);
666
+ for (const row of report.results) {
667
+ const colour = row.verdict === 'fixed' ? 'green'
668
+ : row.verdict === 'still_broken' ? 'red'
669
+ : row.verdict === 'flaky' ? 'yellow'
670
+ : row.verdict === 'healed' ? 'cyan'
671
+ : 'dim';
672
+ const shown = row.fingerprintV2 || row.fingerprint;
673
+ console.log(` ${shown.padEnd(18)} ${tty(row.verdict.padEnd(14), colour)} ${`${row.fired}/${row.repeat}`.padEnd(8)} ${truncate(row.title, 72)}`);
674
+ if (row.verdict !== 'fixed') {
675
+ console.log(` ${''.padEnd(18)} ${tty(truncate(row.detail, 110), 'dim')}`);
676
+ }
677
+ }
678
+ console.log();
679
+ }
680
+ function storedRunForRerun(runId, opts) {
681
+ if (runId)
682
+ return loadRun(runId, { dir: opts.dir });
683
+ const ids = listRuns(opts.dir);
684
+ if (ids.length === 0)
685
+ return undefined;
686
+ return loadRun(ids[0], { dir: opts.dir });
687
+ }
688
+ function resolveStoredRun(positional, opts) {
689
+ if (!positional || positional === 'latest' || positional === 'prev') {
690
+ const ids = listRuns(opts.dir);
691
+ const id = positional === 'prev' ? ids[1] : ids[0];
692
+ if (!id)
693
+ die(2, `No runs found under ${resolve(opts.dir, 'runs')}.`);
694
+ return loadRun(id, { dir: opts.dir });
695
+ }
696
+ const abs = resolve(positional);
697
+ if (existsSync(abs) && statSync(abs).isDirectory()) {
698
+ return loadRun('latest', { dir: abs });
699
+ }
700
+ if (positional.endsWith('.json') || existsSync(abs)) {
701
+ return loadRun(abs);
702
+ }
703
+ return loadRun(positional, { dir: opts.dir });
704
+ }
705
+ function tracesOf(run) {
706
+ return run.flows
707
+ .map(flow => flow.trace)
708
+ .filter((trace) => !!trace && trace.steps.length > 0);
709
+ }
710
+ function runnerLLM(opts) {
711
+ const cfg = buildLLMConfig(opts);
712
+ return createLLM(cfg.runner ?? cfg.planner);
713
+ }
714
+ function suggestDiff(dir, newRunId) {
715
+ const ids = listRuns(dir);
716
+ if (ids.length >= 2) {
717
+ const previousId = ids[1];
718
+ console.log(`\n${tty('Tip:', 'dim')} compare to previous run with:`);
719
+ console.log(` ${tty(`monkeytest diff ${previousId} ${newRunId}`, 'cyan')}`);
720
+ }
721
+ }
722
+ function exitIfBlocking(run) {
723
+ const blocking = run.bugs.filter(bug => bug.severity !== 'minor');
724
+ if (blocking.length) {
725
+ console.error(`\n${tty(`✗ ${blocking.length} blocking bug${blocking.length === 1 ? '' : 's'} still failing.`, 'red')}`);
726
+ process.exit(1);
727
+ }
728
+ }
729
+ function truncate(s, n) {
730
+ return s.length > n ? `${s.slice(0, n - 1)}…` : s;
731
+ }
732
+ function die(code, msg) {
733
+ console.error(tty(msg, 'red'));
734
+ process.exit(code);
735
+ }
736
+ /* ── Entrypoint ───────────────────────────────────────────────────────── */
737
+ async function main() {
738
+ const args = parseArgs(process.argv);
739
+ if (args.command === 'help' || args.showHelp) {
740
+ // If the user typed `monkeytest help <cmd>` we show that command's help.
741
+ // Otherwise (`monkeytest --help` or no command) show the top-level help.
742
+ const sub = args.command === 'help' ? args.positional[0] : args.command;
743
+ printHelp(sub);
744
+ return;
745
+ }
746
+ if (args.command === 'version') {
747
+ console.log(ENGINE_VERSION);
748
+ return;
749
+ }
750
+ switch (args.command) {
751
+ case 'init': return cmdInit(args.opts);
752
+ case 'explore': return cmdExplore(args.positional[0], args.opts);
753
+ case 'run': return cmdRun(args.positional[0], args.opts);
754
+ case 'rerun': return cmdRerun(args.positional[0], args.opts);
755
+ case 'verify': return cmdVerify(args.positional[0], args.opts);
756
+ case 'diff': return cmdDiff(args.positional[0], args.positional[1], args.opts);
757
+ case 'report': return cmdReport(args.positional[0], args.opts);
758
+ default:
759
+ console.error(tty(`Unknown command: ${args.command}`, 'red'));
760
+ printHelp();
761
+ process.exit(2);
762
+ }
763
+ }
764
+ main().catch((err) => {
765
+ console.error(`\n${tty('✗ monkeytest failed:', 'red')} ${err instanceof Error ? err.message : err}`);
766
+ if (process.env.MONKEYTEST_DEBUG && err instanceof Error && err.stack) {
767
+ console.error(err.stack);
768
+ }
769
+ process.exit(3);
770
+ });
771
+ //# sourceMappingURL=cli.js.map