@plune-ai/cairn 0.3.0 → 0.3.2

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 (44) hide show
  1. package/README.md +22 -3
  2. package/dist/agent/index.d.ts.map +1 -1
  3. package/dist/agent/index.js +10 -0
  4. package/dist/agent/index.js.map +1 -1
  5. package/dist/browser/backends/playwright-lib.d.ts.map +1 -1
  6. package/dist/browser/backends/playwright-lib.js +17 -6
  7. package/dist/browser/backends/playwright-lib.js.map +1 -1
  8. package/dist/browser/preflight.d.ts +46 -0
  9. package/dist/browser/preflight.d.ts.map +1 -0
  10. package/dist/browser/preflight.js +73 -0
  11. package/dist/browser/preflight.js.map +1 -0
  12. package/dist/cli/index.d.ts +10 -1
  13. package/dist/cli/index.d.ts.map +1 -1
  14. package/dist/cli/index.js +313 -367
  15. package/dist/cli/index.js.map +1 -1
  16. package/dist/core/config.d.ts +18 -0
  17. package/dist/core/config.d.ts.map +1 -0
  18. package/dist/core/config.js +23 -0
  19. package/dist/core/config.js.map +1 -0
  20. package/dist/core/index.d.ts +15 -0
  21. package/dist/core/index.d.ts.map +1 -0
  22. package/dist/core/index.js +13 -0
  23. package/dist/core/index.js.map +1 -0
  24. package/dist/core/modalities/explore.d.ts +3 -0
  25. package/dist/core/modalities/explore.d.ts.map +1 -0
  26. package/dist/core/modalities/explore.js +82 -0
  27. package/dist/core/modalities/explore.js.map +1 -0
  28. package/dist/core/modality.d.ts +49 -0
  29. package/dist/core/modality.d.ts.map +1 -0
  30. package/dist/core/modality.js +24 -0
  31. package/dist/core/modality.js.map +1 -0
  32. package/dist/core/registry.d.ts +11 -0
  33. package/dist/core/registry.d.ts.map +1 -0
  34. package/dist/core/registry.js +43 -0
  35. package/dist/core/registry.js.map +1 -0
  36. package/dist/core/reporting.d.ts +11 -0
  37. package/dist/core/reporting.d.ts.map +1 -0
  38. package/dist/core/reporting.js +13 -0
  39. package/dist/core/reporting.js.map +1 -0
  40. package/dist/validate/runner.d.ts +6 -0
  41. package/dist/validate/runner.d.ts.map +1 -1
  42. package/dist/validate/runner.js +20 -1
  43. package/dist/validate/runner.js.map +1 -1
  44. package/package.json +1 -1
package/dist/cli/index.js CHANGED
@@ -1,6 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * CLI `cairn`. Commands: observe · explore · design · automate · dataset-add · experiment.
3
+ * CLI `cairn`. Commands: observe · explore · design · automate · dataset-add · experiment ·
4
+ * promote · session · login, plus GATED modality stubs (ui|e2e / api / unit / docs — C1-01).
5
+ * The umbrella router is thin: each modality command dispatches through the shared core
6
+ * (`runModality`), so a future modality is a thin add, not a fork.
4
7
  * `lex-bot` stays as a hidden, deprecated alias (see ./lex-bot.ts) → same code path.
5
8
  */
6
9
  import "dotenv/config";
@@ -13,338 +16,15 @@ import { makeGateway } from "../browser/index.js";
13
16
  import { capture } from "../observe/index.js";
14
17
  import { SessionStore, captureSession } from "../session/index.js";
15
18
  import { loadConfig } from "../config/index.js";
16
- import { runExploration, runDesign, runAutomate } from "../agent/index.js";
19
+ import { runDesign, runAutomate } from "../agent/index.js";
17
20
  import { renderRunSummary } from "../agent/summary.js";
18
21
  import { promoteCase, locatorFor } from "../promote/index.js";
19
22
  import { makeModel, structuredMethodFor } from "../llm/index.js";
20
23
  import { structuredInvoker } from "../llm/structured.js";
21
24
  import { PromptRegistry, LOCAL_PROMPTS } from "../prompts/index.js";
22
25
  import { runExperiment } from "../eval/experiment.js";
23
- /** Print the per-role cost + token summary (L1-01). */
24
- function printCost(cost) {
25
- if (cost.perRole.length === 0)
26
- return;
27
- process.stdout.write("\n=== Cost (per role) ===\n");
28
- for (const c of cost.perRole) {
29
- const usd = c.costUsd === null ? "n/a" : `$${c.costUsd.toFixed(4)}`;
30
- process.stdout.write(` ${c.role.padEnd(9)} ${c.calls} call(s) ${c.inputTokens}→${c.outputTokens} tok ${usd}\n`);
31
- }
32
- const total = cost.totalCostUsd === null ? "n/a (some prices unknown)" : `$${cost.totalCostUsd.toFixed(4)}`;
33
- process.stdout.write(` ${"total".padEnd(9)} ${cost.totalTokens} tok ${total}\n`);
34
- }
35
- const program = new Command();
36
- program
37
- .name("cairn")
38
- .description(`${BOT_NAME} — autonomous UI test generator`)
39
- .version(BOT_VERSION);
40
- program
41
- .command("observe")
42
- .description("Explore a page: ARIA snapshot + interactive elements + screenshot")
43
- .requiredOption("--url <url>", "page URL")
44
- .option("--backend <kind>", "lib | cli", "lib")
45
- .option("--session <name>", "name of the saved session (.auth/<name>.storageState.json)")
46
- .option("--out <file>", "where to save the screenshot", "observe-screenshot.png")
47
- .action(async (opts) => {
48
- const backend = opts.backend === "cli" ? "cli" : "lib";
49
- const config = loadConfig(process.env);
50
- let storageState;
51
- if (opts.session) {
52
- storageState = await new SessionStore(resolve(".auth")).load(opts.session);
53
- }
54
- const gateway = makeGateway({ backend, storageState, channel: config.browser.channel });
55
- try {
56
- const study = await capture(gateway, opts.url);
57
- const interactive = study.elements.filter((e) => e.interactive);
58
- process.stdout.write(`URL: ${study.url} (backend: ${study.capturedBy})\n`);
59
- process.stdout.write(`Elements: ${study.elements.length}, interactive: ${interactive.length}\n\n`);
60
- process.stdout.write(`${study.ariaYaml}\n\nInteractive:\n`);
61
- for (const e of interactive) {
62
- process.stdout.write(` [${e.ref}] ${e.role}${e.name ? ` "${e.name}"` : ""}\n`);
63
- }
64
- await mkdir(dirname(opts.out), { recursive: true });
65
- await writeFile(opts.out, Buffer.from(study.screenshotB64, "base64"));
66
- process.stdout.write(`\nScreenshot → ${opts.out}\n`);
67
- }
68
- finally {
69
- await gateway.close();
70
- }
71
- });
72
- program
73
- .command("explore")
74
- .description("Explore a page and generate methodology-based test cases (Sprint 2: no code)")
75
- .requiredOption("--url <url>", "page URL")
76
- .option("--backend <kind>", "lib | cli (overrides BROWSER_BACKEND)")
77
- .option("--session <name>", "name of the saved session (.auth/<name>.storageState.json)")
78
- .option("--session-file <path>", "direct path to a storageState file (any name)")
79
- .option("--headed", "visible browser (debug)")
80
- .option("--checklist <file>", "checklist file (md/text) — guides what to test")
81
- .option("--style <s>", "planning style: happy | negative | coverage | all")
82
- .option("--routing <preset>", "role-routing preset: fast (Groq worker) | volume (OpenRouter worker) (sets LLM_ROUTING)")
83
- .action(async (opts) => {
84
- const env = { ...process.env };
85
- if (opts.backend)
86
- env.BROWSER_BACKEND = opts.backend;
87
- if (opts.routing)
88
- env.LLM_ROUTING = opts.routing;
89
- const config = loadConfig(env);
90
- const checklistText = opts.checklist ? await readFile(opts.checklist, "utf8") : undefined;
91
- process.stderr.write(`▸ Exploring ${opts.url}${opts.session ? ` (session: ${opts.session})` : ""}${opts.checklist ? ` (checklist: ${opts.checklist})` : ""}…\n`);
92
- const result = await runExploration({
93
- url: opts.url,
94
- config,
95
- sessionName: opts.session,
96
- sessionFile: opts.sessionFile,
97
- headed: opts.headed,
98
- checklistText,
99
- style: opts.style,
100
- onProgress: (e) => process.stderr.write(` ▸ ${e}\n`),
101
- });
102
- process.stdout.write(`\n=== Exploration of ${result.study.url} (run ${result.runId}) ===\n`);
103
- process.stdout.write(`Purpose: ${result.analysis.pageSemantics}\n`);
104
- process.stdout.write(`LLM profile: ${config.llmProfile} · test cases: ${result.testCases.length}\n\n`);
105
- for (const tc of result.testCases) {
106
- process.stdout.write(`[${tc.id}] (${tc.priority} · ${tc.technique}) ${tc.title}\n`);
107
- for (const step of tc.steps)
108
- process.stdout.write(` - ${step}\n`);
109
- process.stdout.write(` ⇒ ${tc.expected}\n`);
110
- if (tc.elementRefs.length)
111
- process.stdout.write(` refs: ${tc.elementRefs.join(", ")}\n`);
112
- process.stdout.write("\n");
113
- }
114
- if (result.validation) {
115
- const v = result.validation;
116
- process.stdout.write(`=== Validation: ${Math.round(v.greenRatio * 100)}% green (flaky: ${v.flakyCount}) ===\n`);
117
- for (const r of v.results) {
118
- const mark = r.status === "passed" ? "✓" : r.status === "flaky" ? "~" : "✗";
119
- process.stdout.write(` ${mark} ${r.test}\n`);
120
- }
121
- }
122
- if (result.scores.length > 0) {
123
- process.stdout.write("\n=== Metrics ===\n");
124
- for (const s of result.scores) {
125
- process.stdout.write(` ${s.name}: ${s.value.toFixed(2)}${s.comment ? ` — ${s.comment}` : ""}\n`);
126
- }
127
- }
128
- if (result.pilot) {
129
- process.stdout.write(`\n=== Pilot: ${result.pilot.verdict.toUpperCase()} ===\n ${result.pilot.reason}\n → ${result.pilot.guidance}\n`);
130
- }
131
- printCost(result.cost);
132
- // L1-04 (Box 4): one unambiguous footer — pass/fail · cost+tokens · budget used · artifact path.
133
- process.stdout.write("\n");
134
- for (const line of renderRunSummary({
135
- runDir: result.runDir,
136
- validation: result.validation,
137
- cost: result.cost,
138
- budget: result.budget,
139
- testCaseCount: result.testCases.length,
140
- stoppedEarly: result.stoppedEarly,
141
- })) {
142
- process.stdout.write(`${line}\n`);
143
- }
144
- // #39: explore now also writes ATC/MTC cases, and points at the review-first flow for next time.
145
- if (result.testCaseFiles.length > 0) {
146
- process.stdout.write(` Cases (ATC/MTC .md): ${result.runDir}\\testcases\\\n`);
147
- }
148
- process.stdout.write("\nTip: to review cases BEFORE generating code, run `cairn design` then `cairn automate`.\n");
149
- });
150
- program
151
- .command("dataset-add")
152
- .description("Add a run (study.json) to an experiment dataset")
153
- .requiredOption("--from-run <dir>", "runs/<id> folder")
154
- .requiredOption("--to <file>", "dataset file (JSON)")
155
- .action(async (opts) => {
156
- const study = JSON.parse(await readFile(join(opts.fromRun, "study.json"), "utf8"));
157
- let pageSemantics = "";
158
- try {
159
- const rep = JSON.parse(await readFile(join(opts.fromRun, "report.json"), "utf8"));
160
- pageSemantics = rep.pageSemantics ?? "";
161
- }
162
- catch {
163
- // report.json is optional
164
- }
165
- let ds = { items: [] };
166
- try {
167
- ds = JSON.parse(await readFile(opts.to, "utf8"));
168
- }
169
- catch {
170
- // new dataset
171
- }
172
- const id = `item-${ds.items.length + 1}`;
173
- ds.items.push({ id, study, pageSemantics });
174
- await mkdir(dirname(opts.to) || ".", { recursive: true });
175
- await writeFile(opts.to, JSON.stringify(ds, null, 2), "utf8");
176
- process.stdout.write(`Added ${id} → ${opts.to} (total items: ${ds.items.length})\n`);
177
- });
178
- program
179
- .command("experiment")
180
- .description("Compare prompt versions on a dataset (B2 self-improvement)")
181
- .requiredOption("--dataset <file>", "dataset file (JSON)")
182
- .option("--candidate <spec>", "promptName=file.md — candidate prompt vs production")
183
- .option("--target <metric>", "target verdict metric", "grounding")
184
- .action(async (opts) => {
185
- const config = loadConfig(process.env);
186
- const keys = {
187
- anthropicApiKey: config.anthropicApiKey,
188
- openrouterApiKey: config.openrouterApiKey,
189
- groqApiKey: config.groqApiKey,
190
- };
191
- const ds = JSON.parse(await readFile(opts.dataset, "utf8"));
192
- const variants = [{ label: "production", prompts: new PromptRegistry() }];
193
- if (opts.candidate) {
194
- const eq = opts.candidate.indexOf("=");
195
- const name = opts.candidate.slice(0, eq);
196
- const text = await readFile(opts.candidate.slice(eq + 1), "utf8");
197
- variants.push({
198
- label: "candidate",
199
- prompts: new PromptRegistry({ local: { ...LOCAL_PROMPTS, [name]: text } }),
200
- });
201
- }
202
- process.stderr.write(`▸ Experiment: ${ds.items.length} items × ${variants.length} versions…\n`);
203
- const result = await runExperiment(ds.items, variants, {
204
- designInvoke: structuredInvoker(makeModel(config.models.reasoning, keys), structuredMethodFor(config.models.reasoning.provider)),
205
- judgeInvoke: structuredInvoker(makeModel(config.models.judge, keys), structuredMethodFor(config.models.judge.provider)),
206
- }, { target: opts.target });
207
- process.stdout.write(`\n=== Experiment (${ds.items.length} items) ===\n`);
208
- for (const v of result.perVariant) {
209
- process.stdout.write(`\n[${v.label}]\n`);
210
- for (const [name, val] of Object.entries(v.meanScores)) {
211
- process.stdout.write(` ${name}: ${val.toFixed(3)}\n`);
212
- }
213
- }
214
- if (result.verdict) {
215
- const vd = result.verdict;
216
- const reg = vd.guardrailRegressions.length ? `; regressions: ${vd.guardrailRegressions.join(", ")}` : "";
217
- process.stdout.write(`\n=== Verdict: candidate ${vd.improved ? "BETTER ✓" : "NOT better ✗"} (${vd.target} Δ=${vd.delta.toFixed(3)})${reg} ===\n`);
218
- process.stdout.write(vd.improved
219
- ? " → the version can be promoted (Langfuse label=production) — runbook promote-prompt.\n"
220
- : " → reject/iterate the prompt.\n");
221
- }
222
- });
223
- program
224
- .command("design")
225
- .description("Explore a page and WRITE test cases in ATC format (.md, with selectors), WITHOUT code")
226
- .requiredOption("--url <url>", "page URL")
227
- .option("--session <name>", "name of the saved session")
228
- .option("--session-file <path>", "path to a storageState file")
229
- .option("--checklist <file>", "checklist file — guides what to test")
230
- .option("--style <s>", "planning style: happy | negative | coverage | all")
231
- .option("--routing <preset>", "role-routing preset: fast (Groq worker) | volume (OpenRouter worker) (sets LLM_ROUTING)")
232
- .option("--headed", "visible browser (debug)")
233
- .action(async (opts) => {
234
- const env = { ...process.env };
235
- if (opts.routing)
236
- env.LLM_ROUTING = opts.routing;
237
- const config = loadConfig(env);
238
- const checklistText = opts.checklist ? await readFile(opts.checklist, "utf8") : undefined;
239
- process.stderr.write(`▸ Designing test cases for ${opts.url}${opts.session ? ` (session: ${opts.session})` : ""}…\n`);
240
- const result = await runDesign({
241
- url: opts.url,
242
- config,
243
- sessionName: opts.session,
244
- sessionFile: opts.sessionFile,
245
- checklistText,
246
- style: opts.style,
247
- headed: opts.headed,
248
- onProgress: (e) => process.stderr.write(` ▸ ${e}\n`),
249
- });
250
- process.stdout.write(`\n=== ${result.testCases.length} test cases → ${result.runDir}\\testcases\\ ===\n`);
251
- for (const tc of result.testCases) {
252
- const exec = tc.execution === "manual" ? "MTC/manual" : "ATC/auto";
253
- process.stdout.write(`[${exec} · ${tc.priority}/${tc.type}] ${tc.title}\n`);
254
- }
255
- for (const f of result.testCaseFiles)
256
- process.stdout.write(` ${f}\n`);
257
- if (result.scores.length > 0) {
258
- process.stdout.write("\n=== Metrics ===\n");
259
- for (const s of result.scores) {
260
- process.stdout.write(` ${s.name}: ${s.value.toFixed(2)}${s.comment ? ` — ${s.comment}` : ""}\n`);
261
- }
262
- }
263
- printCost(result.cost);
264
- });
265
- program
266
- .command("automate")
267
- .description("Generate @playwright/test from ready cases (runs/<id>/testcases/*.md)")
268
- .requiredOption("--run <dir>", "design run folder (runs/<id>)")
269
- .option("--validate", "run the generated tests (a session is required)")
270
- .option("--session <name>", "session name for validation")
271
- .option("--session-file <path>", "path to storageState for validation")
272
- .option("--routing <preset>", "role-routing preset: fast (Groq worker) | volume (OpenRouter worker) (sets LLM_ROUTING)")
273
- .action(async (opts) => {
274
- const env = { ...process.env };
275
- if (opts.routing)
276
- env.LLM_ROUTING = opts.routing;
277
- const config = loadConfig(env);
278
- process.stderr.write(`▸ Automating cases from ${opts.run}…\n`);
279
- const result = await runAutomate({
280
- runDir: opts.run,
281
- config,
282
- validate: opts.validate,
283
- sessionName: opts.session,
284
- sessionFile: opts.sessionFile,
285
- onProgress: (e) => process.stderr.write(` ▸ ${e}\n`),
286
- });
287
- process.stdout.write(`\n=== ${result.specFiles.length} spec files → ${result.runDir}\\tests\\ ===\n`);
288
- for (const f of result.specFiles)
289
- process.stdout.write(` ${f}\n`);
290
- if (result.validation) {
291
- process.stdout.write(`\nValidation: ${Math.round(result.validation.greenRatio * 100)}% green out of ${result.validation.results.length} tests\n`);
292
- }
293
- printCost(result.cost);
294
- // L1-04 (Box 4): same consolidated footer as `explore` — pass/fail · cost · budget · path.
295
- process.stdout.write("\n");
296
- for (const line of renderRunSummary({
297
- runDir: result.runDir,
298
- validation: result.validation,
299
- cost: result.cost,
300
- budget: result.budget,
301
- stoppedEarly: result.stoppedEarly,
302
- })) {
303
- process.stdout.write(`${line}\n`);
304
- }
305
- });
306
- program
307
- .command("promote")
308
- .description("Promote manual MTC case(s) to automatable ATC (.md only; run `automate` to generate code)")
309
- .requiredOption("--run <dir>", "run folder (runs/<id>)")
310
- .requiredOption("--cases <ids>", "comma-separated MTC ids, e.g. MTC-DEMO-001,MTC-DEMO-003")
311
- .option("--session <name>", "session for the live selector fallback")
312
- .option("--session-file <path>", "storageState path for the live selector fallback")
313
- .action(async (opts) => {
314
- const config = loadConfig(process.env);
315
- const runDir = resolve(opts.run);
316
- const ids = opts.cases.split(",").map((s) => s.trim()).filter(Boolean);
317
- // Live fallback only when a session is provided (best-effort — see note).
318
- let collectLive;
319
- let storageState;
320
- if (opts.sessionFile)
321
- storageState = await new SessionStore(resolve(".auth")).loadFile(resolve(opts.sessionFile));
322
- else if (opts.session)
323
- storageState = await new SessionStore(resolve(".auth")).load(opts.session);
324
- if (storageState) {
325
- collectLive = async (url, refs) => {
326
- const gateway = makeGateway({ backend: config.browser.backend, storageState, channel: config.browser.channel });
327
- try {
328
- await gateway.observe({ url });
329
- const verified = await gateway.verify(refs.map((ref) => ({ ref, role: "", name: undefined, interactive: true, rank: 0 })));
330
- const out = new Map();
331
- for (const v of verified)
332
- if (v.verified)
333
- out.set(v.ref, locatorFor(v));
334
- return out;
335
- }
336
- finally {
337
- await gateway.close();
338
- }
339
- };
340
- }
341
- process.stderr.write(`▸ Promoting ${String(ids.length)} case(s) from ${opts.run}…\n`);
342
- for (const id of ids) {
343
- const res = await promoteCase(runDir, id, { collectLive });
344
- process.stdout.write(`${res.oldId} → ${res.newId}${res.warning ? ` (⚠ ${res.warning})` : ""}\n`);
345
- }
346
- process.stdout.write(`\nDone. Run \`cairn automate --run ${opts.run}\` to generate code for the new ATC case(s).\n`);
347
- });
26
+ // C1-01 — shared umbrella core: flag→config, the cost footer, and the modality registry/dispatch.
27
+ import { resolveConfig, printCost, runModality, MODALITIES } from "../core/index.js";
348
28
  /**
349
29
  * Shared capture action for `cairn session capture` and the flat `cairn login` alias.
350
30
  * Opens a headed browser, waits for login, and persists the session (L1-05). Never prints secrets.
@@ -363,52 +43,318 @@ async function runCapture(opts) {
363
43
  process.stdout.write(` Next: cairn explore --url <app-url> --session ${res.name}\n`);
364
44
  process.stdout.write(` Note: .auth/ is gitignored — never commit session files.\n`);
365
45
  }
366
- // `cairn session <capture|ls|rm>` — first-class management of saved login sessions (L1-05).
367
- const session = program.command("session").description("Manage saved login sessions (.auth/)");
368
- session
369
- .command("capture")
370
- .description("Capture a login session interactively (opens a headed browser; press Enter when logged in)")
371
- .requiredOption("--url <loginUrl>", "login page URL to open")
372
- .option("--name <name>", "session name (default: derived from the URL host)")
373
- .option("--channel <channel>", "browser channel, e.g. chrome (helps with OAuth; default from config)")
374
- .option("--dir <dir>", "sessions directory", ".auth")
375
- .action(runCapture);
376
- session
377
- .command("ls")
378
- .description("List saved sessions")
379
- .option("--dir <dir>", "sessions directory", ".auth")
380
- .action(async (opts) => {
381
- const names = await new SessionStore(resolve(opts.dir)).list();
382
- if (names.length === 0) {
383
- process.stdout.write("No saved sessions. Capture one: cairn session capture --url <loginUrl> --name <name>\n");
384
- return;
46
+ /**
47
+ * Build the `cairn` commander program. Exported (C1-02) so tests can drive commands and snapshot
48
+ * `--help` without running the process entry point. Each call returns a fresh, independent program.
49
+ */
50
+ export function buildProgram() {
51
+ const program = new Command();
52
+ program
53
+ .name("cairn")
54
+ .description(`${BOT_NAME} — autonomous UI test generator`)
55
+ .version(BOT_VERSION);
56
+ program
57
+ .command("observe")
58
+ .description("Explore a page: ARIA snapshot + interactive elements + screenshot")
59
+ .requiredOption("--url <url>", "page URL")
60
+ .option("--backend <kind>", "lib | cli", "lib")
61
+ .option("--session <name>", "name of the saved session (.auth/<name>.storageState.json)")
62
+ .option("--out <file>", "where to save the screenshot", "observe-screenshot.png")
63
+ .action(async (opts) => {
64
+ const backend = opts.backend === "cli" ? "cli" : "lib";
65
+ const config = loadConfig(process.env);
66
+ let storageState;
67
+ if (opts.session) {
68
+ storageState = await new SessionStore(resolve(".auth")).load(opts.session);
69
+ }
70
+ const gateway = makeGateway({ backend, storageState, channel: config.browser.channel });
71
+ try {
72
+ const study = await capture(gateway, opts.url);
73
+ const interactive = study.elements.filter((e) => e.interactive);
74
+ process.stdout.write(`URL: ${study.url} (backend: ${study.capturedBy})\n`);
75
+ process.stdout.write(`Elements: ${study.elements.length}, interactive: ${interactive.length}\n\n`);
76
+ process.stdout.write(`${study.ariaYaml}\n\nInteractive:\n`);
77
+ for (const e of interactive) {
78
+ process.stdout.write(` [${e.ref}] ${e.role}${e.name ? ` "${e.name}"` : ""}\n`);
79
+ }
80
+ await mkdir(dirname(opts.out), { recursive: true });
81
+ await writeFile(opts.out, Buffer.from(study.screenshotB64, "base64"));
82
+ process.stdout.write(`\nScreenshot → ${opts.out}\n`);
83
+ }
84
+ finally {
85
+ await gateway.close();
86
+ }
87
+ });
88
+ // explore = the first REAL modality. The command keeps its exact flags/description (parity,
89
+ // C1-02); its action delegates to the shared core (runModality → exploreModality.run).
90
+ program
91
+ .command("explore")
92
+ .description("Explore a page and generate methodology-based test cases (Sprint 2: no code)")
93
+ .requiredOption("--url <url>", "page URL")
94
+ .option("--backend <kind>", "lib | cli (overrides BROWSER_BACKEND)")
95
+ .option("--session <name>", "name of the saved session (.auth/<name>.storageState.json)")
96
+ .option("--session-file <path>", "direct path to a storageState file (any name)")
97
+ .option("--headed", "visible browser (debug)")
98
+ .option("--checklist <file>", "checklist file (md/text) — guides what to test")
99
+ .option("--style <s>", "planning style: happy | negative | coverage | all")
100
+ .option("--routing <preset>", "role-routing preset: fast (Groq worker) | volume (OpenRouter worker) (sets LLM_ROUTING)")
101
+ .action(async (opts) => {
102
+ await runModality("explore", opts);
103
+ });
104
+ program
105
+ .command("dataset-add")
106
+ .description("Add a run (study.json) to an experiment dataset")
107
+ .requiredOption("--from-run <dir>", "runs/<id> folder")
108
+ .requiredOption("--to <file>", "dataset file (JSON)")
109
+ .action(async (opts) => {
110
+ const study = JSON.parse(await readFile(join(opts.fromRun, "study.json"), "utf8"));
111
+ let pageSemantics = "";
112
+ try {
113
+ const rep = JSON.parse(await readFile(join(opts.fromRun, "report.json"), "utf8"));
114
+ pageSemantics = rep.pageSemantics ?? "";
115
+ }
116
+ catch {
117
+ // report.json is optional
118
+ }
119
+ let ds = { items: [] };
120
+ try {
121
+ ds = JSON.parse(await readFile(opts.to, "utf8"));
122
+ }
123
+ catch {
124
+ // new dataset
125
+ }
126
+ const id = `item-${ds.items.length + 1}`;
127
+ ds.items.push({ id, study, pageSemantics });
128
+ await mkdir(dirname(opts.to) || ".", { recursive: true });
129
+ await writeFile(opts.to, JSON.stringify(ds, null, 2), "utf8");
130
+ process.stdout.write(`Added ${id} → ${opts.to} (total items: ${ds.items.length})\n`);
131
+ });
132
+ program
133
+ .command("experiment")
134
+ .description("Compare prompt versions on a dataset (B2 self-improvement)")
135
+ .requiredOption("--dataset <file>", "dataset file (JSON)")
136
+ .option("--candidate <spec>", "promptName=file.md — candidate prompt vs production")
137
+ .option("--target <metric>", "target verdict metric", "grounding")
138
+ .action(async (opts) => {
139
+ const config = loadConfig(process.env);
140
+ const keys = {
141
+ anthropicApiKey: config.anthropicApiKey,
142
+ openrouterApiKey: config.openrouterApiKey,
143
+ groqApiKey: config.groqApiKey,
144
+ };
145
+ const ds = JSON.parse(await readFile(opts.dataset, "utf8"));
146
+ const variants = [{ label: "production", prompts: new PromptRegistry() }];
147
+ if (opts.candidate) {
148
+ const eq = opts.candidate.indexOf("=");
149
+ const name = opts.candidate.slice(0, eq);
150
+ const text = await readFile(opts.candidate.slice(eq + 1), "utf8");
151
+ variants.push({
152
+ label: "candidate",
153
+ prompts: new PromptRegistry({ local: { ...LOCAL_PROMPTS, [name]: text } }),
154
+ });
155
+ }
156
+ process.stderr.write(`▸ Experiment: ${ds.items.length} items × ${variants.length} versions…\n`);
157
+ const result = await runExperiment(ds.items, variants, {
158
+ designInvoke: structuredInvoker(makeModel(config.models.reasoning, keys), structuredMethodFor(config.models.reasoning.provider)),
159
+ judgeInvoke: structuredInvoker(makeModel(config.models.judge, keys), structuredMethodFor(config.models.judge.provider)),
160
+ }, { target: opts.target });
161
+ process.stdout.write(`\n=== Experiment (${ds.items.length} items) ===\n`);
162
+ for (const v of result.perVariant) {
163
+ process.stdout.write(`\n[${v.label}]\n`);
164
+ for (const [name, val] of Object.entries(v.meanScores)) {
165
+ process.stdout.write(` ${name}: ${val.toFixed(3)}\n`);
166
+ }
167
+ }
168
+ if (result.verdict) {
169
+ const vd = result.verdict;
170
+ const reg = vd.guardrailRegressions.length ? `; regressions: ${vd.guardrailRegressions.join(", ")}` : "";
171
+ process.stdout.write(`\n=== Verdict: candidate ${vd.improved ? "BETTER ✓" : "NOT better ✗"} (${vd.target} Δ=${vd.delta.toFixed(3)})${reg} ===\n`);
172
+ process.stdout.write(vd.improved
173
+ ? " → the version can be promoted (Langfuse label=production) — runbook promote-prompt.\n"
174
+ : " → reject/iterate the prompt.\n");
175
+ }
176
+ });
177
+ program
178
+ .command("design")
179
+ .description("Explore a page and WRITE test cases in ATC format (.md, with selectors), WITHOUT code")
180
+ .requiredOption("--url <url>", "page URL")
181
+ .option("--session <name>", "name of the saved session")
182
+ .option("--session-file <path>", "path to a storageState file")
183
+ .option("--checklist <file>", "checklist file — guides what to test")
184
+ .option("--style <s>", "planning style: happy | negative | coverage | all")
185
+ .option("--routing <preset>", "role-routing preset: fast (Groq worker) | volume (OpenRouter worker) (sets LLM_ROUTING)")
186
+ .option("--headed", "visible browser (debug)")
187
+ .action(async (opts) => {
188
+ const config = resolveConfig({ routing: opts.routing });
189
+ const checklistText = opts.checklist ? await readFile(opts.checklist, "utf8") : undefined;
190
+ process.stderr.write(`▸ Designing test cases for ${opts.url}${opts.session ? ` (session: ${opts.session})` : ""}…\n`);
191
+ const result = await runDesign({
192
+ url: opts.url,
193
+ config,
194
+ sessionName: opts.session,
195
+ sessionFile: opts.sessionFile,
196
+ checklistText,
197
+ style: opts.style,
198
+ headed: opts.headed,
199
+ onProgress: (e) => process.stderr.write(` ▸ ${e}\n`),
200
+ });
201
+ process.stdout.write(`\n=== ${result.testCases.length} test cases → ${result.runDir}\\testcases\\ ===\n`);
202
+ for (const tc of result.testCases) {
203
+ const exec = tc.execution === "manual" ? "MTC/manual" : "ATC/auto";
204
+ process.stdout.write(`[${exec} · ${tc.priority}/${tc.type}] ${tc.title}\n`);
205
+ }
206
+ for (const f of result.testCaseFiles)
207
+ process.stdout.write(` ${f}\n`);
208
+ if (result.scores.length > 0) {
209
+ process.stdout.write("\n=== Metrics ===\n");
210
+ for (const s of result.scores) {
211
+ process.stdout.write(` ${s.name}: ${s.value.toFixed(2)}${s.comment ? ` — ${s.comment}` : ""}\n`);
212
+ }
213
+ }
214
+ printCost(result.cost);
215
+ });
216
+ program
217
+ .command("automate")
218
+ .description("Generate @playwright/test from ready cases (runs/<id>/testcases/*.md)")
219
+ .requiredOption("--run <dir>", "design run folder (runs/<id>)")
220
+ .option("--validate", "run the generated tests (a session is required)")
221
+ .option("--session <name>", "session name for validation")
222
+ .option("--session-file <path>", "path to storageState for validation")
223
+ .option("--routing <preset>", "role-routing preset: fast (Groq worker) | volume (OpenRouter worker) (sets LLM_ROUTING)")
224
+ .action(async (opts) => {
225
+ const config = resolveConfig({ routing: opts.routing });
226
+ process.stderr.write(`▸ Automating cases from ${opts.run}…\n`);
227
+ const result = await runAutomate({
228
+ runDir: opts.run,
229
+ config,
230
+ validate: opts.validate,
231
+ sessionName: opts.session,
232
+ sessionFile: opts.sessionFile,
233
+ onProgress: (e) => process.stderr.write(` ▸ ${e}\n`),
234
+ });
235
+ process.stdout.write(`\n=== ${result.specFiles.length} spec files → ${result.runDir}\\tests\\ ===\n`);
236
+ for (const f of result.specFiles)
237
+ process.stdout.write(` ${f}\n`);
238
+ if (result.validation) {
239
+ process.stdout.write(`\nValidation: ${Math.round(result.validation.greenRatio * 100)}% green out of ${result.validation.results.length} tests\n`);
240
+ }
241
+ printCost(result.cost);
242
+ // L1-04 (Box 4): same consolidated footer as `explore` — pass/fail · cost · budget · path.
243
+ process.stdout.write("\n");
244
+ for (const line of renderRunSummary({
245
+ runDir: result.runDir,
246
+ validation: result.validation,
247
+ cost: result.cost,
248
+ budget: result.budget,
249
+ stoppedEarly: result.stoppedEarly,
250
+ })) {
251
+ process.stdout.write(`${line}\n`);
252
+ }
253
+ });
254
+ program
255
+ .command("promote")
256
+ .description("Promote manual MTC case(s) to automatable ATC (.md only; run `automate` to generate code)")
257
+ .requiredOption("--run <dir>", "run folder (runs/<id>)")
258
+ .requiredOption("--cases <ids>", "comma-separated MTC ids, e.g. MTC-DEMO-001,MTC-DEMO-003")
259
+ .option("--session <name>", "session for the live selector fallback")
260
+ .option("--session-file <path>", "storageState path for the live selector fallback")
261
+ .action(async (opts) => {
262
+ const config = loadConfig(process.env);
263
+ const runDir = resolve(opts.run);
264
+ const ids = opts.cases.split(",").map((s) => s.trim()).filter(Boolean);
265
+ // Live fallback only when a session is provided (best-effort — see note).
266
+ let collectLive;
267
+ let storageState;
268
+ if (opts.sessionFile)
269
+ storageState = await new SessionStore(resolve(".auth")).loadFile(resolve(opts.sessionFile));
270
+ else if (opts.session)
271
+ storageState = await new SessionStore(resolve(".auth")).load(opts.session);
272
+ if (storageState) {
273
+ collectLive = async (url, refs) => {
274
+ const gateway = makeGateway({ backend: config.browser.backend, storageState, channel: config.browser.channel });
275
+ try {
276
+ await gateway.observe({ url });
277
+ const verified = await gateway.verify(refs.map((ref) => ({ ref, role: "", name: undefined, interactive: true, rank: 0 })));
278
+ const out = new Map();
279
+ for (const v of verified)
280
+ if (v.verified)
281
+ out.set(v.ref, locatorFor(v));
282
+ return out;
283
+ }
284
+ finally {
285
+ await gateway.close();
286
+ }
287
+ };
288
+ }
289
+ process.stderr.write(`▸ Promoting ${String(ids.length)} case(s) from ${opts.run}…\n`);
290
+ for (const id of ids) {
291
+ const res = await promoteCase(runDir, id, { collectLive });
292
+ process.stdout.write(`${res.oldId} → ${res.newId}${res.warning ? ` (⚠ ${res.warning})` : ""}\n`);
293
+ }
294
+ process.stdout.write(`\nDone. Run \`cairn automate --run ${opts.run}\` to generate code for the new ATC case(s).\n`);
295
+ });
296
+ // `cairn session <capture|ls|rm>` — first-class management of saved login sessions (L1-05).
297
+ const session = program.command("session").description("Manage saved login sessions (.auth/)");
298
+ session
299
+ .command("capture")
300
+ .description("Capture a login session interactively (opens a headed browser; press Enter when logged in)")
301
+ .requiredOption("--url <loginUrl>", "login page URL to open")
302
+ .option("--name <name>", "session name (default: derived from the URL host)")
303
+ .option("--channel <channel>", "browser channel, e.g. chrome (helps with OAuth; default from config)")
304
+ .option("--dir <dir>", "sessions directory", ".auth")
305
+ .action(runCapture);
306
+ session
307
+ .command("ls")
308
+ .description("List saved sessions")
309
+ .option("--dir <dir>", "sessions directory", ".auth")
310
+ .action(async (opts) => {
311
+ const names = await new SessionStore(resolve(opts.dir)).list();
312
+ if (names.length === 0) {
313
+ process.stdout.write("No saved sessions. Capture one: cairn session capture --url <loginUrl> --name <name>\n");
314
+ return;
315
+ }
316
+ process.stdout.write(`Saved sessions (${opts.dir}):\n`);
317
+ for (const n of names)
318
+ process.stdout.write(` ${n}\n`);
319
+ });
320
+ session
321
+ .command("rm <name>")
322
+ .description("Remove a saved session")
323
+ .option("--dir <dir>", "sessions directory", ".auth")
324
+ .action(async (name, opts) => {
325
+ const removed = await new SessionStore(resolve(opts.dir)).remove(name);
326
+ process.stdout.write(removed ? `✓ Removed session "${name}".\n` : `No session "${name}" to remove.\n`);
327
+ });
328
+ // Flat alias: `cairn login` == `cairn session capture` (issue #27 — acceptable shorthand).
329
+ program
330
+ .command("login")
331
+ .description("Alias for `cairn session capture` — capture a login session interactively")
332
+ .requiredOption("--url <loginUrl>", "login page URL to open")
333
+ .option("--name <name>", "session name (default: derived from the URL host)")
334
+ .option("--channel <channel>", "browser channel, e.g. chrome (helps with OAuth; default from config)")
335
+ .option("--dir <dir>", "sessions directory", ".auth")
336
+ .action(runCapture);
337
+ // C1-01: GATED modality stubs (ui|e2e, api, unit, docs). Discoverable placeholders with ZERO
338
+ // generation logic — each dispatches through runModality, which prints the coming-soon notice and
339
+ // exits 0. #21–24 stay gated behind a named-user pull (L-G2 / #25): build by demand, one at a time.
340
+ for (const m of MODALITIES.filter((x) => x.gated)) {
341
+ const c = program
342
+ .command(m.name)
343
+ .description(`${m.summary} — coming soon (gated; see L-G2)`)
344
+ .action(async () => {
345
+ await runModality(m.name, {});
346
+ });
347
+ if (m.aliases?.length)
348
+ c.aliases(m.aliases);
385
349
  }
386
- process.stdout.write(`Saved sessions (${opts.dir}):\n`);
387
- for (const n of names)
388
- process.stdout.write(` ${n}\n`);
389
- });
390
- session
391
- .command("rm <name>")
392
- .description("Remove a saved session")
393
- .option("--dir <dir>", "sessions directory", ".auth")
394
- .action(async (name, opts) => {
395
- const removed = await new SessionStore(resolve(opts.dir)).remove(name);
396
- process.stdout.write(removed ? `✓ Removed session "${name}".\n` : `No session "${name}" to remove.\n`);
397
- });
398
- // Flat alias: `cairn login` == `cairn session capture` (issue #27 — acceptable shorthand).
399
- program
400
- .command("login")
401
- .description("Alias for `cairn session capture` — capture a login session interactively")
402
- .requiredOption("--url <loginUrl>", "login page URL to open")
403
- .option("--name <name>", "session name (default: derived from the URL host)")
404
- .option("--channel <channel>", "browser channel, e.g. chrome (helps with OAuth; default from config)")
405
- .option("--dir <dir>", "sessions directory", ".auth")
406
- .action(runCapture);
350
+ return program;
351
+ }
407
352
  /**
408
353
  * Run the CLI. Shared by the primary `cairn` entry (this file) and the deprecated
409
354
  * `lex-bot` alias shim (./lex-bot.ts), so both go through the exact same code path.
410
355
  */
411
356
  export async function runCli() {
357
+ const program = buildProgram();
412
358
  const cliArgs = process.argv.slice(2);
413
359
  if (cliArgs.length === 0 && process.stdin.isTTY && process.stdout.isTTY) {
414
360
  // No command in an interactive terminal → launch the TUI (lazy: keeps React/Ink