@plune-ai/cairn 0.3.5 → 0.4.1

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 (97) hide show
  1. package/README.md +60 -10
  2. package/dist/agent/graph.d.ts +17 -530
  3. package/dist/agent/graph.d.ts.map +1 -1
  4. package/dist/agent/graph.js +144 -215
  5. package/dist/agent/graph.js.map +1 -1
  6. package/dist/agent/index.d.ts +4 -2
  7. package/dist/agent/index.d.ts.map +1 -1
  8. package/dist/agent/index.js +222 -205
  9. package/dist/agent/index.js.map +1 -1
  10. package/dist/agent/repair-loop.d.ts +8 -0
  11. package/dist/agent/repair-loop.d.ts.map +1 -1
  12. package/dist/agent/repair-loop.js +17 -5
  13. package/dist/agent/repair-loop.js.map +1 -1
  14. package/dist/agent/summary.d.ts +7 -0
  15. package/dist/agent/summary.d.ts.map +1 -1
  16. package/dist/agent/summary.js +11 -2
  17. package/dist/agent/summary.js.map +1 -1
  18. package/dist/artifacts/report.d.ts.map +1 -1
  19. package/dist/artifacts/report.js +7 -2
  20. package/dist/artifacts/report.js.map +1 -1
  21. package/dist/cli/index.d.ts.map +1 -1
  22. package/dist/cli/index.js +12 -7
  23. package/dist/cli/index.js.map +1 -1
  24. package/dist/codegen/lint.d.ts +11 -0
  25. package/dist/codegen/lint.d.ts.map +1 -0
  26. package/dist/codegen/lint.js +37 -0
  27. package/dist/codegen/lint.js.map +1 -0
  28. package/dist/config/index.d.ts.map +1 -1
  29. package/dist/config/index.js +7 -0
  30. package/dist/config/index.js.map +1 -1
  31. package/dist/config/schema.d.ts +2 -0
  32. package/dist/config/schema.d.ts.map +1 -1
  33. package/dist/core/modalities/explore.d.ts.map +1 -1
  34. package/dist/core/modalities/explore.js +7 -4
  35. package/dist/core/modalities/explore.js.map +1 -1
  36. package/dist/design/dedup.d.ts +14 -0
  37. package/dist/design/dedup.d.ts.map +1 -0
  38. package/dist/design/dedup.js +64 -0
  39. package/dist/design/dedup.js.map +1 -0
  40. package/dist/design/index.d.ts.map +1 -1
  41. package/dist/design/index.js +3 -1
  42. package/dist/design/index.js.map +1 -1
  43. package/dist/eval/collect.d.ts +15 -0
  44. package/dist/eval/collect.d.ts.map +1 -1
  45. package/dist/eval/collect.js +14 -0
  46. package/dist/eval/collect.js.map +1 -1
  47. package/dist/eval/legend.d.ts +19 -0
  48. package/dist/eval/legend.d.ts.map +1 -0
  49. package/dist/eval/legend.js +27 -0
  50. package/dist/eval/legend.js.map +1 -0
  51. package/dist/eval/scorers.d.ts.map +1 -1
  52. package/dist/eval/scorers.js +33 -0
  53. package/dist/eval/scorers.js.map +1 -1
  54. package/dist/index.d.ts +4 -2
  55. package/dist/index.d.ts.map +1 -1
  56. package/dist/index.js +2 -1
  57. package/dist/index.js.map +1 -1
  58. package/dist/llm/routing.d.ts +5 -1
  59. package/dist/llm/routing.d.ts.map +1 -1
  60. package/dist/llm/routing.js +7 -2
  61. package/dist/llm/routing.js.map +1 -1
  62. package/dist/llm/structured.d.ts +1 -1
  63. package/dist/llm/structured.d.ts.map +1 -1
  64. package/dist/llm/structured.js +2 -2
  65. package/dist/llm/structured.js.map +1 -1
  66. package/dist/prompts/local/qa-playwright-ts-writer.d.ts +1 -1
  67. package/dist/prompts/local/qa-playwright-ts-writer.d.ts.map +1 -1
  68. package/dist/prompts/local/qa-playwright-ts-writer.js +1 -0
  69. package/dist/prompts/local/qa-playwright-ts-writer.js.map +1 -1
  70. package/dist/prompts/local/qa-testcase-from-ui.d.ts +1 -1
  71. package/dist/prompts/local/qa-testcase-from-ui.d.ts.map +1 -1
  72. package/dist/prompts/local/qa-testcase-from-ui.js +2 -1
  73. package/dist/prompts/local/qa-testcase-from-ui.js.map +1 -1
  74. package/dist/telemetry/index.d.ts +6 -0
  75. package/dist/telemetry/index.d.ts.map +1 -1
  76. package/dist/telemetry/index.js +15 -2
  77. package/dist/telemetry/index.js.map +1 -1
  78. package/dist/tui/hooks/use-runner.d.ts.map +1 -1
  79. package/dist/tui/hooks/use-runner.js +6 -2
  80. package/dist/tui/hooks/use-runner.js.map +1 -1
  81. package/dist/tui/index.d.ts.map +1 -1
  82. package/dist/tui/index.js +18 -3
  83. package/dist/tui/index.js.map +1 -1
  84. package/dist/tui/screens/form-screen.d.ts.map +1 -1
  85. package/dist/tui/screens/form-screen.js +51 -4
  86. package/dist/tui/screens/form-screen.js.map +1 -1
  87. package/dist/tui/types.d.ts +5 -0
  88. package/dist/tui/types.d.ts.map +1 -1
  89. package/dist/validate/index.d.ts +4 -0
  90. package/dist/validate/index.d.ts.map +1 -1
  91. package/dist/validate/index.js +7 -2
  92. package/dist/validate/index.js.map +1 -1
  93. package/dist/validate/runner.d.ts +5 -1
  94. package/dist/validate/runner.d.ts.map +1 -1
  95. package/dist/validate/runner.js +7 -4
  96. package/dist/validate/runner.js.map +1 -1
  97. package/package.json +7 -8
@@ -11,19 +11,20 @@ import { ArtifactStore } from "../artifacts/index.js";
11
11
  import { renderReportMd } from "../artifacts/report.js";
12
12
  import { parseTestCaseMd } from "../artifacts/testcase-md.js";
13
13
  import { automateCases } from "../codegen/index.js";
14
+ import { lintSuite, lintHint } from "../codegen/lint.js";
14
15
  import { deterministicScores } from "../eval/scorers.js";
15
16
  import { judgeTestCases, judgeChecklistCoverage } from "../eval/judge.js";
16
17
  import { pilotReview } from "../eval/pilot.js";
17
- import { collectPriorRuns, unionPassedTitles, formatExperience } from "../eval/collect.js";
18
+ import { collectPriorRuns, unionPassedTitles, experienceForUrl } from "../eval/collect.js";
18
19
  import { ingestChecklist, formatChecklist, coverageScore, styleDirective } from "../checklist/index.js";
19
20
  import { loadKnowledge } from "../knowledge/index.js";
20
21
  import { validateSuite } from "../validate/index.js";
21
22
  import { SessionStore } from "../session/index.js";
22
- import { buildExploreGraph } from "./graph.js";
23
+ import { runExploreGraph } from "./graph.js";
23
24
  import { finalizeFailure } from "./finalize.js";
24
25
  import { runRepairLoop } from "./repair-loop.js";
25
26
  import { buildTestCaseDocs } from "./testcase-docs.js";
26
- export { buildExploreGraph, ExploreState } from "./graph.js";
27
+ export { runExploreGraph } from "./graph.js";
27
28
  /**
28
29
  * End-to-end exploration → methodological cases → runnable @playwright/test → validation/repair (MVP, Sprint 3).
29
30
  * Artifacts land in runsBaseDir/<runId>/; everything is traced in Langfuse.
@@ -54,7 +55,8 @@ export async function runExploration(input) {
54
55
  onProgress(`⚠ approaching the LLM-call budget (${used}/${max} calls — cost guardrail)`);
55
56
  }
56
57
  };
57
- const router = new RoleRouter(cfg, keys, budget, undefined, undefined, onCharge); // L1-01: routing + cost ledger
58
+ const telemetry = await initTelemetry(cfg);
59
+ const router = new RoleRouter(cfg, keys, budget, undefined, undefined, onCharge, telemetry.callbackHandler ? [telemetry.callbackHandler] : undefined); // L1-01: routing + cost ledger
58
60
  // Auth: load storageState into the gateway (observe) and pass the path to the runner (validate).
59
61
  let storageState;
60
62
  let sessionPath;
@@ -74,7 +76,6 @@ export async function runExploration(input) {
74
76
  channel: cfg.browser.channel,
75
77
  headless: !input.headed,
76
78
  });
77
- const telemetry = await initTelemetry(cfg);
78
79
  const prompts = new PromptRegistry();
79
80
  const artifacts = new ArtifactStore(resolve(input.runsBaseDir ?? resolve(process.cwd(), "runs")));
80
81
  const runId = randomUUID();
@@ -85,7 +86,14 @@ export async function runExploration(input) {
85
86
  const checklistItems = input.checklistText ? ingestChecklist(input.checklistText) : [];
86
87
  const checklistFormatted = formatChecklist(checklistItems);
87
88
  const knowledgeText = await loadKnowledge(resolve(input.knowledgeDir ?? "knowledge"), input.url);
88
- const experienceText = formatExperience(unionPassedTitles((await collectPriorRuns(resolve(input.runsBaseDir ?? resolve(process.cwd(), "runs")), input.url)).filter((r) => r.runId !== runId)));
89
+ // `--fresh` skips this disk read entirely → no "previously STABLE cases" dedup block, so the run
90
+ // generates a full set (clean A/B comparison) instead of only the delta vs. past runs of this URL.
91
+ const experienceText = await experienceForUrl({
92
+ runsBaseDir: resolve(input.runsBaseDir ?? resolve(process.cwd(), "runs")),
93
+ url: input.url,
94
+ currentRunId: runId,
95
+ fresh: input.fresh,
96
+ });
89
97
  const styleText = styleDirective(input.style ?? "all");
90
98
  const languageText = input.language ?? cfg.testCaseLanguage;
91
99
  // L1-01: resolve per-role tiers (override ?? profile tier), then build metered invokers.
@@ -93,7 +101,7 @@ export async function runExploration(input) {
93
101
  const analyzeTier = router.tierFor("worker", visionTier);
94
102
  const designTier = router.tierFor("reasoner", cfg.models.reasoning);
95
103
  const codegenTier = router.tierFor("worker", cfg.models.bulk);
96
- const graph = buildExploreGraph({
104
+ const deps = {
97
105
  gateway,
98
106
  prompts,
99
107
  analyzeInvoke: router.invoke("worker", analyzeTier),
@@ -106,7 +114,7 @@ export async function runExploration(input) {
106
114
  styleText,
107
115
  languageText,
108
116
  runWriter,
109
- validate: (runDir) => validateSuite(runDir, { storageStatePath: sessionPath, channel: cfg.browser.channel }),
117
+ validate: (runDir) => validateSuite(runDir, { storageStatePath: sessionPath, channel: cfg.browser.channel, workers: cfg.playwrightWorkers }),
110
118
  maxRepair: cfg.maxRepair,
111
119
  onProgress,
112
120
  // #38: persist study + snapshots the moment observe succeeds, so a mid-run kill still leaves
@@ -137,153 +145,154 @@ export async function runExploration(input) {
137
145
  // L1-05: a session was supplied → fail fast if the first page is a login screen (expired session).
138
146
  expectAuthenticated: Boolean(input.sessionName || input.sessionFile),
139
147
  sessionName: input.sessionName,
140
- });
148
+ };
141
149
  try {
142
- const out = await graph.invoke({ url: input.url, runId }, {
143
- callbacks: telemetry.callbackHandler ? [telemetry.callbackHandler] : [],
144
- runName: "exploration",
145
- metadata: { runId, backend: cfg.browser.backend, profile: cfg.llmProfile },
146
- });
147
- if (!out.study || !out.analysis)
148
- throw new Error("The graph did not return study/analysis.");
149
- // (Expired-session detection now fails fast inside the graph's identifyElements node — L1-05.)
150
- // keep-best: final = the BEST suite/validation across all attempts (repair could not make it worse).
151
- const suite = out.bestSuite ?? out.suite;
152
- const validation = out.bestValidation ?? out.validation;
153
- if (out.bestSuite)
154
- await runWriter.writeSuite(out.bestSuite); // restore the best code on disk
155
- // Phase 4: study prior runs of this URL + collect the best (collect-best).
156
- const runsBase = resolve(input.runsBaseDir ?? resolve(process.cwd(), "runs"));
157
- const priorRuns = (await collectPriorRuns(runsBase, out.study.url)).filter((r) => r.runId !== runId);
158
- const currentPassed = (validation?.results ?? [])
159
- .filter((r) => r.status === "passed")
160
- .map((r) => r.test);
161
- const allTimePassing = unionPassedTitles([
162
- ...priorRuns,
163
- { runId, url: out.study.url, greenRatio: validation?.greenRatio ?? 0, passedTests: currentPassed },
164
- ]);
165
- const bestPriorGreen = priorRuns[0]?.greenRatio;
166
- onProgress(`collect — prior runs for URL: ${priorRuns.length}` +
167
- (bestPriorGreen !== undefined ? `; best so far: ${Math.round(bestPriorGreen * 100)}%` : "") +
168
- `; stable cases total (all-time): ${allTimePassing.length}`);
169
- // B1: run metrics — deterministic scorers + LLM-judge (SDK-side).
170
- onProgress("score — scoring (scorers + LLM-judge)…");
171
- const scores = deterministicScores({
172
- study: out.study,
173
- verified: out.verified,
174
- testCases: out.testCases,
175
- suite,
176
- validation,
177
- });
178
- try {
179
- scores.push(...(await judgeTestCases(out.testCases, out.analysis.pageSemantics, router.invoke("judge", cfg.models.judge), prompts)));
180
- }
181
- catch {
182
- // the judge is not critical for the run
183
- }
184
- if (checklistItems.length > 0) {
150
+ // Task 2: wrap in a root trace so nested LangChain CallbackHandler generations attach to ONE trace.
151
+ // Fix 2: the entire post-graph evaluation (scores + judges + pilot + score-attach) runs INSIDE
152
+ // the callback so judge/pilot LLM calls fire the handler while the root span is still active.
153
+ const result = await telemetry.runInTrace("exploration", { runId, backend: cfg.browser.backend, profile: cfg.llmProfile }, async () => {
154
+ const out = await runExploreGraph(deps, { url: input.url, runId });
155
+ // (Expired-session detection now fails fast inside the graph's identifyElements node — L1-05.)
156
+ // keep-best: final = the BEST suite/validation across all attempts (repair could not make it worse).
157
+ const suite = out.bestSuite ?? out.suite;
158
+ const validation = out.bestValidation ?? out.validation;
159
+ if (out.bestSuite)
160
+ await runWriter.writeSuite(out.bestSuite); // restore the best code on disk
161
+ // Phase 4: study prior runs of this URL + collect the best (collect-best).
162
+ const runsBase = resolve(input.runsBaseDir ?? resolve(process.cwd(), "runs"));
163
+ const priorRuns = (await collectPriorRuns(runsBase, out.study.url)).filter((r) => r.runId !== runId);
164
+ const currentPassed = (validation?.results ?? [])
165
+ .filter((r) => r.status === "passed")
166
+ .map((r) => r.test);
167
+ const allTimePassing = unionPassedTitles([
168
+ ...priorRuns,
169
+ { runId, url: out.study.url, greenRatio: validation?.greenRatio ?? 0, passedTests: currentPassed },
170
+ ]);
171
+ const bestPriorGreen = priorRuns[0]?.greenRatio;
172
+ onProgress(`collect — prior runs for URL: ${priorRuns.length}` +
173
+ (bestPriorGreen !== undefined ? `; best so far: ${Math.round(bestPriorGreen * 100)}%` : "") +
174
+ `; stable cases total (all-time): ${allTimePassing.length}`);
175
+ // B1: run metrics — deterministic scorers + LLM-judge (SDK-side).
176
+ onProgress("score — scoring (scorers + LLM-judge)…");
177
+ const scores = deterministicScores({
178
+ study: out.study,
179
+ verified: out.verified,
180
+ testCases: out.testCases,
181
+ suite,
182
+ validation,
183
+ });
185
184
  try {
186
- const cov = await judgeChecklistCoverage(checklistItems, out.testCases, router.invoke("judge", cfg.models.judge), prompts);
187
- scores.push({ name: "checklist_coverage", value: cov.value, comment: cov.comment });
185
+ scores.push(...(await judgeTestCases(out.testCases, out.analysis.pageSemantics, router.invoke("judge", cfg.models.judge), prompts)));
188
186
  }
189
187
  catch {
190
- // fallback: token-based coverage (offline / judge unavailable)
191
- scores.push({ name: "checklist_coverage", value: coverageScore(checklistItems, out.testCases) });
188
+ // the judge is not critical for the run
192
189
  }
193
- }
194
- onProgress(`score — ${scores.length} metrics`);
195
- // Best-effort: write scores to Langfuse against the trace (requires a self-hosted instance).
196
- const traceId = telemetry.callbackHandler?.last_trace_id;
197
- if (telemetry.enabled && telemetry.client && traceId) {
198
- try {
199
- for (const sc of scores) {
200
- telemetry.client.score.create({
201
- traceId,
202
- name: sc.name,
203
- value: sc.value,
204
- comment: sc.comment,
205
- dataType: "NUMERIC",
206
- });
190
+ if (checklistItems.length > 0) {
191
+ try {
192
+ const cov = await judgeChecklistCoverage(checklistItems, out.testCases, router.invoke("judge", cfg.models.judge), prompts);
193
+ scores.push({ name: "checklist_coverage", value: cov.value, comment: cov.comment });
194
+ }
195
+ catch {
196
+ // fallback: token-based coverage (offline / judge unavailable)
197
+ scores.push({ name: "checklist_coverage", value: coverageScore(checklistItems, out.testCases) });
198
+ }
199
+ }
200
+ onProgress(`score — ${scores.length} metrics`);
201
+ // Best-effort: write scores to Langfuse against the trace (requires a self-hosted instance).
202
+ // The trace is still active here (inside runInTrace) so last_trace_id is set.
203
+ const traceId = telemetry.callbackHandler?.last_trace_id;
204
+ if (telemetry.enabled && telemetry.client && traceId) {
205
+ try {
206
+ for (const sc of scores) {
207
+ telemetry.client.score.create({
208
+ traceId,
209
+ name: sc.name,
210
+ value: sc.value,
211
+ comment: sc.comment,
212
+ dataType: "NUMERIC",
213
+ });
214
+ }
215
+ }
216
+ catch {
217
+ // best-effort
207
218
  }
208
219
  }
220
+ // Pilot supervisor: a holistic verdict for the run (idea from explorbot).
221
+ let pilot;
222
+ try {
223
+ pilot = await pilotReview(out.analysis.pageSemantics, validation, out.testCases,
224
+ // L1-01: Pilot verdict now runs on the strong `reasoner` role (was the cheap `judge` tier) —
225
+ // intended behavior change toward a "smart judge". See ADR-0011.
226
+ router.invoke("reasoner", router.tierFor("reasoner", cfg.models.reasoning)), prompts);
227
+ onProgress(`pilot — verdict: ${pilot.verdict} — ${pilot.reason}`);
228
+ }
209
229
  catch {
210
- // best-effort
230
+ // pilot is not critical
211
231
  }
212
- }
213
- // Pilot supervisor: a holistic verdict for the run (idea from explorbot).
214
- let pilot;
215
- try {
216
- pilot = await pilotReview(out.analysis.pageSemantics, validation, out.testCases,
217
- // L1-01: Pilot verdict now runs on the strong `reasoner` role (was the cheap `judge` tier) —
218
- // intended behavior change toward a "smart judge". See ADR-0011.
219
- router.invoke("reasoner", router.tierFor("reasoner", cfg.models.reasoning)), prompts);
220
- onProgress(`pilot — verdict: ${pilot.verdict} — ${pilot.reason}`);
221
- }
222
- catch {
223
- // pilot is not critical
224
- }
225
- const cost = router.ledger.report(); // L1-01: per-role cost + tokens for this run
226
- const budgetReport = { used: budget.spent, max: budget.max }; // L1-04 (Box 3)
227
- const stoppedEarly = Boolean(out.stoppedEarly); // L1-04 (Box 2)
228
- // #39: also emit ATC/MTC case docs (.md) — explore now produces the human-readable cases like
229
- // design, so manual MTC cases are visible deliverables (not just buried inside report.md).
230
- const caseSuite = suiteFromUrl(out.study.url);
231
- const caseDocs = buildTestCaseDocs(out.testCases, out.verified, caseSuite, checklistItems.length > 0);
232
- const testCaseFiles = await runWriter.writeTestCases(caseDocs.docs);
233
- onProgress(`explore — wrote ${testCaseFiles.length} cases: ${caseDocs.autoN} ATC, ${caseDocs.manualN} MTC → testcases/`);
234
- await runWriter.writeStudy(out.study);
235
- if (out.study.screenshotB64)
236
- await runWriter.writeScreenshot(out.study.screenshotB64);
237
- await runWriter.writeAria(out.study.ariaYaml);
238
- await runWriter.writeReport({
239
- runId,
240
- url: out.study.url,
241
- pageSemantics: out.analysis.pageSemantics,
242
- testCases: out.testCases,
243
- validation,
244
- scores,
245
- pilot,
246
- cost,
247
- budget: budgetReport,
248
- stoppedEarly,
249
- history: {
250
- priorRuns: priorRuns.length,
251
- bestPriorGreen: bestPriorGreen ?? null,
252
- allTimePassing,
253
- },
232
+ const cost = router.ledger.report(); // L1-01: per-role cost + tokens for this run
233
+ const budgetReport = { used: budget.spent, max: budget.max }; // L1-04 (Box 3)
234
+ const stoppedEarly = Boolean(out.stoppedEarly); // L1-04 (Box 2)
235
+ // #39: also emit ATC/MTC case docs (.md) — explore now produces the human-readable cases like
236
+ // design, so manual MTC cases are visible deliverables (not just buried inside report.md).
237
+ const caseSuite = suiteFromUrl(out.study.url);
238
+ const caseDocs = buildTestCaseDocs(out.testCases, out.verified, caseSuite, checklistItems.length > 0);
239
+ const testCaseFiles = await runWriter.writeTestCases(caseDocs.docs);
240
+ onProgress(`explore — wrote ${testCaseFiles.length} cases: ${caseDocs.autoN} ATC, ${caseDocs.manualN} MTC → testcases/`);
241
+ await runWriter.writeStudy(out.study);
242
+ if (out.study.screenshotB64)
243
+ await runWriter.writeScreenshot(out.study.screenshotB64);
244
+ await runWriter.writeAria(out.study.ariaYaml);
245
+ await runWriter.writeReport({
246
+ runId,
247
+ url: out.study.url,
248
+ pageSemantics: out.analysis.pageSemantics,
249
+ testCases: out.testCases,
250
+ validation,
251
+ scores,
252
+ pilot,
253
+ cost,
254
+ budget: budgetReport,
255
+ stoppedEarly,
256
+ history: {
257
+ priorRuns: priorRuns.length,
258
+ bestPriorGreen: bestPriorGreen ?? null,
259
+ allTimePassing,
260
+ },
261
+ });
262
+ await runWriter.writeReportMd(renderReportMd({
263
+ runId,
264
+ url: out.study.url,
265
+ backend: cfg.browser.backend,
266
+ profile: cfg.llmProfile,
267
+ pageSemantics: out.analysis.pageSemantics,
268
+ elements: out.study.elements,
269
+ testCases: out.testCases,
270
+ validation,
271
+ scores,
272
+ consoleErrors: out.study.consoleErrors,
273
+ cost,
274
+ budget: budgetReport,
275
+ stoppedEarly,
276
+ }));
277
+ const green = validation ? `${Math.round(validation.greenRatio * 100)}%` : "—";
278
+ await runWriter.writeLog([...logLines, "", `summary: green=${green} testCases=${out.testCases.length} runId=${runId}`].join("\n"));
279
+ return {
280
+ runId,
281
+ runDir: runWriter.dir,
282
+ study: out.study,
283
+ analysis: out.analysis,
284
+ testCases: out.testCases,
285
+ suite,
286
+ validation,
287
+ scores,
288
+ pilot,
289
+ cost,
290
+ budget: budgetReport,
291
+ stoppedEarly,
292
+ testCaseFiles,
293
+ };
254
294
  });
255
- await runWriter.writeReportMd(renderReportMd({
256
- runId,
257
- url: out.study.url,
258
- backend: cfg.browser.backend,
259
- profile: cfg.llmProfile,
260
- pageSemantics: out.analysis.pageSemantics,
261
- elements: out.study.elements,
262
- testCases: out.testCases,
263
- validation,
264
- scores,
265
- consoleErrors: out.study.consoleErrors,
266
- cost,
267
- budget: budgetReport,
268
- stoppedEarly,
269
- }));
270
- const green = validation ? `${Math.round(validation.greenRatio * 100)}%` : "—";
271
- await runWriter.writeLog([...logLines, "", `summary: green=${green} testCases=${out.testCases.length} runId=${runId}`].join("\n"));
272
- return {
273
- runId,
274
- runDir: runWriter.dir,
275
- study: out.study,
276
- analysis: out.analysis,
277
- testCases: out.testCases,
278
- suite,
279
- validation,
280
- scores,
281
- pilot,
282
- cost,
283
- budget: budgetReport,
284
- stoppedEarly,
285
- testCaseFiles,
286
- };
295
+ return result;
287
296
  }
288
297
  catch (err) {
289
298
  // L1-04 (Box 1/3/4): the single failure path — write a partial report + a readable, actionable
@@ -324,7 +333,6 @@ export async function runDesign(input) {
324
333
  ensureBrowsersInstalled({ channel: cfg.browser.channel });
325
334
  const keys = { anthropicApiKey: cfg.anthropicApiKey, openrouterApiKey: cfg.openrouterApiKey, groqApiKey: cfg.groqApiKey };
326
335
  const budget = new CallBudget(80); // cost-guardrail: safeguard (normally ~6-10 calls/run)
327
- const router = new RoleRouter(cfg, keys, budget); // L1-01: per-role routing + cost ledger
328
336
  const logLines = [];
329
337
  // Parity with runExploration (#38): buffer progress into run.log, flushed incrementally so a
330
338
  // mid-run kill leaves the log on disk. `persistLog` is wired once the run dir exists.
@@ -334,6 +342,8 @@ export async function runDesign(input) {
334
342
  input.onProgress?.(event);
335
343
  persistLog();
336
344
  };
345
+ const telemetry = await initTelemetry(cfg);
346
+ const router = new RoleRouter(cfg, keys, budget, undefined, undefined, undefined, telemetry.callbackHandler ? [telemetry.callbackHandler] : undefined); // L1-01: per-role routing + cost ledger
337
347
  let storageState;
338
348
  const sessionStore = new SessionStore(resolve(input.sessionsDir ?? ".auth"));
339
349
  if (input.sessionFile)
@@ -347,7 +357,6 @@ export async function runDesign(input) {
347
357
  channel: cfg.browser.channel,
348
358
  headless: !input.headed,
349
359
  });
350
- const telemetry = await initTelemetry(cfg);
351
360
  const prompts = new PromptRegistry();
352
361
  const artifacts = new ArtifactStore(resolve(input.runsBaseDir ?? resolve(process.cwd(), "runs")));
353
362
  const runId = randomUUID();
@@ -356,7 +365,14 @@ export async function runDesign(input) {
356
365
  persistLog = () => void runWriter.writeLog(logLines.join("\n")).catch(() => undefined);
357
366
  const checklistItems = input.checklistText ? ingestChecklist(input.checklistText) : [];
358
367
  const knowledgeText = await loadKnowledge(resolve(input.knowledgeDir ?? "knowledge"), input.url);
359
- const experienceText = formatExperience(unionPassedTitles((await collectPriorRuns(resolve(input.runsBaseDir ?? resolve(process.cwd(), "runs")), input.url)).filter((r) => r.runId !== runId)));
368
+ // `--fresh` skips this disk read entirely → no "previously STABLE cases" dedup block, so the run
369
+ // generates a full set (clean A/B comparison) instead of only the delta vs. past runs of this URL.
370
+ const experienceText = await experienceForUrl({
371
+ runsBaseDir: resolve(input.runsBaseDir ?? resolve(process.cwd(), "runs")),
372
+ url: input.url,
373
+ currentRunId: runId,
374
+ fresh: input.fresh,
375
+ });
360
376
  const styleText = styleDirective(input.style ?? "all");
361
377
  const languageText = input.language ?? cfg.testCaseLanguage;
362
378
  // L1-01: resolve per-role tiers (override ?? profile tier), then build metered invokers.
@@ -364,7 +380,7 @@ export async function runDesign(input) {
364
380
  const analyzeTier = router.tierFor("worker", visionTier);
365
381
  const designTier = router.tierFor("reasoner", cfg.models.reasoning);
366
382
  const codegenTier = router.tierFor("worker", cfg.models.bulk);
367
- const graph = buildExploreGraph({
383
+ const designDeps = {
368
384
  gateway,
369
385
  prompts,
370
386
  analyzeInvoke: router.invoke("worker", analyzeTier),
@@ -408,67 +424,67 @@ export async function runDesign(input) {
408
424
  // L1-05: a session was supplied → fail fast if the first page is a login screen (expired session).
409
425
  expectAuthenticated: Boolean(input.sessionName || input.sessionFile),
410
426
  sessionName: input.sessionName,
411
- });
427
+ };
412
428
  try {
413
- const out = await graph.invoke({ url: input.url, runId }, {
414
- callbacks: telemetry.callbackHandler ? [telemetry.callbackHandler] : [],
415
- runName: "design",
416
- metadata: { runId, backend: cfg.browser.backend, profile: cfg.llmProfile, mode: "design" },
417
- });
418
- if (!out.study || !out.analysis)
419
- throw new Error("The graph did not return study/analysis.");
420
- // (Expired-session detection now fails fast inside the graph's identifyElements node — L1-05.)
421
- const suite = suiteFromUrl(out.study.url);
422
- const { docs, autoN, manualN } = buildTestCaseDocs(out.testCases, out.verified, suite, checklistItems.length > 0);
423
- const testCaseFiles = await runWriter.writeTestCases(docs);
424
- onProgress(`design — wrote ${testCaseFiles.length} cases: ${autoN} auto/ATC, ${manualN} manual/MTC (${suite}) → testcases/`);
425
- const scores = deterministicScores({
426
- study: out.study,
427
- verified: out.verified,
428
- testCases: out.testCases,
429
- });
430
- try {
431
- scores.push(...(await judgeTestCases(out.testCases, out.analysis.pageSemantics, router.invoke("judge", cfg.models.judge), prompts)));
432
- }
433
- catch {
434
- // judge optional
435
- }
436
- if (checklistItems.length > 0) {
429
+ // Task 2: wrap in a root trace so nested LangChain CallbackHandler generations attach to ONE trace.
430
+ // Fix 2: the entire post-graph evaluation (scores + judges + score-attach) runs INSIDE
431
+ // the callback so judge LLM calls fire the handler while the root span is still active.
432
+ const result = await telemetry.runInTrace("design", { runId, backend: cfg.browser.backend, profile: cfg.llmProfile, mode: "design" }, async () => {
433
+ const out = await runExploreGraph(designDeps, { url: input.url, runId });
434
+ // (Expired-session detection now fails fast inside the graph's identifyElements node — L1-05.)
435
+ const suite = suiteFromUrl(out.study.url);
436
+ const { docs, autoN, manualN } = buildTestCaseDocs(out.testCases, out.verified, suite, checklistItems.length > 0);
437
+ const testCaseFiles = await runWriter.writeTestCases(docs);
438
+ onProgress(`design — wrote ${testCaseFiles.length} cases: ${autoN} auto/ATC, ${manualN} manual/MTC (${suite}) → testcases/`);
439
+ const scores = deterministicScores({
440
+ study: out.study,
441
+ verified: out.verified,
442
+ testCases: out.testCases,
443
+ });
437
444
  try {
438
- const cov = await judgeChecklistCoverage(checklistItems, out.testCases, router.invoke("judge", cfg.models.judge), prompts);
439
- scores.push({ name: "checklist_coverage", value: cov.value, comment: cov.comment });
445
+ scores.push(...(await judgeTestCases(out.testCases, out.analysis.pageSemantics, router.invoke("judge", cfg.models.judge), prompts)));
440
446
  }
441
447
  catch {
442
- scores.push({ name: "checklist_coverage", value: coverageScore(checklistItems, out.testCases) });
448
+ // judge optional
443
449
  }
444
- }
445
- await runWriter.writeStudy(out.study);
446
- if (out.study.screenshotB64)
447
- await runWriter.writeScreenshot(out.study.screenshotB64);
448
- await runWriter.writeAria(out.study.ariaYaml);
449
- const cost = router.ledger.report(); // L1-01: per-role cost + tokens for this run
450
- await runWriter.writeReport({
451
- runId,
452
- url: out.study.url,
453
- mode: "design",
454
- suite,
455
- pageSemantics: out.analysis.pageSemantics,
456
- testCases: out.testCases,
457
- testCaseFiles,
458
- scores,
459
- cost,
450
+ if (checklistItems.length > 0) {
451
+ try {
452
+ const cov = await judgeChecklistCoverage(checklistItems, out.testCases, router.invoke("judge", cfg.models.judge), prompts);
453
+ scores.push({ name: "checklist_coverage", value: cov.value, comment: cov.comment });
454
+ }
455
+ catch {
456
+ scores.push({ name: "checklist_coverage", value: coverageScore(checklistItems, out.testCases) });
457
+ }
458
+ }
459
+ await runWriter.writeStudy(out.study);
460
+ if (out.study.screenshotB64)
461
+ await runWriter.writeScreenshot(out.study.screenshotB64);
462
+ await runWriter.writeAria(out.study.ariaYaml);
463
+ const cost = router.ledger.report(); // L1-01: per-role cost + tokens for this run
464
+ await runWriter.writeReport({
465
+ runId,
466
+ url: out.study.url,
467
+ mode: "design",
468
+ suite,
469
+ pageSemantics: out.analysis.pageSemantics,
470
+ testCases: out.testCases,
471
+ testCaseFiles,
472
+ scores,
473
+ cost,
474
+ });
475
+ await runWriter.writeLog([...logLines, "", `summary: mode=design testCases=${out.testCases.length} suite=${suite} runId=${runId}`].join("\n"));
476
+ return {
477
+ runId,
478
+ runDir: runWriter.dir,
479
+ study: out.study,
480
+ analysis: out.analysis,
481
+ testCases: out.testCases,
482
+ testCaseFiles,
483
+ scores,
484
+ cost,
485
+ };
460
486
  });
461
- await runWriter.writeLog([...logLines, "", `summary: mode=design testCases=${out.testCases.length} suite=${suite} runId=${runId}`].join("\n"));
462
- return {
463
- runId,
464
- runDir: runWriter.dir,
465
- study: out.study,
466
- analysis: out.analysis,
467
- testCases: out.testCases,
468
- testCaseFiles,
469
- scores,
470
- cost,
471
- };
487
+ return result;
472
488
  }
473
489
  catch (err) {
474
490
  // L1-04 parity with runExploration: write a partial report + a friendly, actionable summary
@@ -547,9 +563,10 @@ export async function runAutomate(input) {
547
563
  await runWriter.writeSuite(s);
548
564
  return s;
549
565
  },
550
- validate: () => validateSuite(runWriter.dir, { storageStatePath: sessionPath, channel: cfg.browser.channel }),
566
+ validate: () => validateSuite(runWriter.dir, { storageStatePath: sessionPath, channel: cfg.browser.channel, workers: cfg.playwrightWorkers }),
551
567
  maxRepair: cfg.maxRepair,
552
568
  onProgress,
569
+ lint: (s) => lintHint(lintSuite(s)), // #57: feed fragile-pattern findings into repair
553
570
  });
554
571
  suite = result.bestSuite;
555
572
  validation = result.bestValidation;