@plune-ai/cairn 0.3.4 → 0.4.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 (110) hide show
  1. package/README.md +20 -7
  2. package/dist/agent/graph.d.ts +24 -530
  3. package/dist/agent/graph.d.ts.map +1 -1
  4. package/dist/agent/graph.js +144 -207
  5. package/dist/agent/graph.js.map +1 -1
  6. package/dist/agent/index.d.ts +2 -2
  7. package/dist/agent/index.d.ts.map +1 -1
  8. package/dist/agent/index.js +260 -201
  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/cli/index.d.ts.map +1 -1
  19. package/dist/cli/index.js +20 -10
  20. package/dist/cli/index.js.map +1 -1
  21. package/dist/codegen/lint.d.ts +11 -0
  22. package/dist/codegen/lint.d.ts.map +1 -0
  23. package/dist/codegen/lint.js +37 -0
  24. package/dist/codegen/lint.js.map +1 -0
  25. package/dist/config/index.d.ts.map +1 -1
  26. package/dist/config/index.js +7 -0
  27. package/dist/config/index.js.map +1 -1
  28. package/dist/config/schema.d.ts +2 -0
  29. package/dist/config/schema.d.ts.map +1 -1
  30. package/dist/core/index.d.ts +2 -0
  31. package/dist/core/index.d.ts.map +1 -1
  32. package/dist/core/index.js +1 -0
  33. package/dist/core/index.js.map +1 -1
  34. package/dist/core/modalities/explore.d.ts.map +1 -1
  35. package/dist/core/modalities/explore.js +8 -4
  36. package/dist/core/modalities/explore.js.map +1 -1
  37. package/dist/core/modality.d.ts +4 -0
  38. package/dist/core/modality.d.ts.map +1 -1
  39. package/dist/core/modality.js +1 -0
  40. package/dist/core/modality.js.map +1 -1
  41. package/dist/core/progress.d.ts +13 -0
  42. package/dist/core/progress.d.ts.map +1 -0
  43. package/dist/core/progress.js +63 -0
  44. package/dist/core/progress.js.map +1 -0
  45. package/dist/core/registry.js +1 -1
  46. package/dist/core/registry.js.map +1 -1
  47. package/dist/design/dedup.d.ts +14 -0
  48. package/dist/design/dedup.d.ts.map +1 -0
  49. package/dist/design/dedup.js +64 -0
  50. package/dist/design/dedup.js.map +1 -0
  51. package/dist/design/index.d.ts.map +1 -1
  52. package/dist/design/index.js +3 -1
  53. package/dist/design/index.js.map +1 -1
  54. package/dist/eval/scorers.d.ts.map +1 -1
  55. package/dist/eval/scorers.js +33 -0
  56. package/dist/eval/scorers.js.map +1 -1
  57. package/dist/index.d.ts +4 -2
  58. package/dist/index.d.ts.map +1 -1
  59. package/dist/index.js +2 -1
  60. package/dist/index.js.map +1 -1
  61. package/dist/llm/routing.d.ts +5 -1
  62. package/dist/llm/routing.d.ts.map +1 -1
  63. package/dist/llm/routing.js +7 -2
  64. package/dist/llm/routing.js.map +1 -1
  65. package/dist/llm/structured.d.ts +1 -1
  66. package/dist/llm/structured.d.ts.map +1 -1
  67. package/dist/llm/structured.js +2 -2
  68. package/dist/llm/structured.js.map +1 -1
  69. package/dist/prompts/local/qa-playwright-ts-writer.d.ts +1 -1
  70. package/dist/prompts/local/qa-playwright-ts-writer.d.ts.map +1 -1
  71. package/dist/prompts/local/qa-playwright-ts-writer.js +1 -0
  72. package/dist/prompts/local/qa-playwright-ts-writer.js.map +1 -1
  73. package/dist/prompts/local/qa-testcase-from-ui.d.ts +1 -1
  74. package/dist/prompts/local/qa-testcase-from-ui.d.ts.map +1 -1
  75. package/dist/prompts/local/qa-testcase-from-ui.js +2 -1
  76. package/dist/prompts/local/qa-testcase-from-ui.js.map +1 -1
  77. package/dist/telemetry/index.d.ts +6 -0
  78. package/dist/telemetry/index.d.ts.map +1 -1
  79. package/dist/telemetry/index.js +15 -2
  80. package/dist/telemetry/index.js.map +1 -1
  81. package/dist/tui/App.d.ts.map +1 -1
  82. package/dist/tui/App.js +17 -7
  83. package/dist/tui/App.js.map +1 -1
  84. package/dist/tui/hooks/use-runner.d.ts.map +1 -1
  85. package/dist/tui/hooks/use-runner.js +4 -2
  86. package/dist/tui/hooks/use-runner.js.map +1 -1
  87. package/dist/tui/index.d.ts.map +1 -1
  88. package/dist/tui/index.js +18 -3
  89. package/dist/tui/index.js.map +1 -1
  90. package/dist/tui/keys.d.ts +29 -0
  91. package/dist/tui/keys.d.ts.map +1 -0
  92. package/dist/tui/keys.js +27 -0
  93. package/dist/tui/keys.js.map +1 -0
  94. package/dist/tui/router-context.d.ts +6 -1
  95. package/dist/tui/router-context.d.ts.map +1 -1
  96. package/dist/tui/router-context.js.map +1 -1
  97. package/dist/tui/screens/form-screen.d.ts.map +1 -1
  98. package/dist/tui/screens/form-screen.js +55 -5
  99. package/dist/tui/screens/form-screen.js.map +1 -1
  100. package/dist/tui/types.d.ts +3 -0
  101. package/dist/tui/types.d.ts.map +1 -1
  102. package/dist/validate/index.d.ts +4 -0
  103. package/dist/validate/index.d.ts.map +1 -1
  104. package/dist/validate/index.js +7 -2
  105. package/dist/validate/index.js.map +1 -1
  106. package/dist/validate/runner.d.ts +5 -1
  107. package/dist/validate/runner.d.ts.map +1 -1
  108. package/dist/validate/runner.js +7 -4
  109. package/dist/validate/runner.js.map +1 -1
  110. package/package.json +8 -8
@@ -11,6 +11,7 @@ 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";
@@ -19,11 +20,11 @@ import { ingestChecklist, formatChecklist, coverageScore, styleDirective } from
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();
@@ -93,7 +94,7 @@ export async function runExploration(input) {
93
94
  const analyzeTier = router.tierFor("worker", visionTier);
94
95
  const designTier = router.tierFor("reasoner", cfg.models.reasoning);
95
96
  const codegenTier = router.tierFor("worker", cfg.models.bulk);
96
- const graph = buildExploreGraph({
97
+ const deps = {
97
98
  gateway,
98
99
  prompts,
99
100
  analyzeInvoke: router.invoke("worker", analyzeTier),
@@ -106,7 +107,7 @@ export async function runExploration(input) {
106
107
  styleText,
107
108
  languageText,
108
109
  runWriter,
109
- validate: (runDir) => validateSuite(runDir, { storageStatePath: sessionPath, channel: cfg.browser.channel }),
110
+ validate: (runDir) => validateSuite(runDir, { storageStatePath: sessionPath, channel: cfg.browser.channel, workers: cfg.playwrightWorkers }),
110
111
  maxRepair: cfg.maxRepair,
111
112
  onProgress,
112
113
  // #38: persist study + snapshots the moment observe succeeds, so a mid-run kill still leaves
@@ -122,156 +123,169 @@ export async function runExploration(input) {
122
123
  // durability is best-effort
123
124
  }
124
125
  },
126
+ // Durability: persist the ATC/MTC case docs the moment they are designed, so a kill during the long
127
+ // codegen/validate phase still leaves the cases on disk (best-effort). suiteFromUrl(studyUrl)
128
+ // matches the final write below → identical files, no duplicates.
129
+ onTestCases: async (testCases, verified, studyUrl) => {
130
+ try {
131
+ const { docs } = buildTestCaseDocs(testCases, verified, suiteFromUrl(studyUrl), checklistItems.length > 0);
132
+ await runWriter.writeTestCases(docs);
133
+ }
134
+ catch {
135
+ // durability is best-effort
136
+ }
137
+ },
125
138
  // L1-05: a session was supplied → fail fast if the first page is a login screen (expired session).
126
139
  expectAuthenticated: Boolean(input.sessionName || input.sessionFile),
127
140
  sessionName: input.sessionName,
128
- });
141
+ };
129
142
  try {
130
- const out = await graph.invoke({ url: input.url, runId }, {
131
- callbacks: telemetry.callbackHandler ? [telemetry.callbackHandler] : [],
132
- runName: "exploration",
133
- metadata: { runId, backend: cfg.browser.backend, profile: cfg.llmProfile },
134
- });
135
- if (!out.study || !out.analysis)
136
- throw new Error("The graph did not return study/analysis.");
137
- // (Expired-session detection now fails fast inside the graph's identifyElements node — L1-05.)
138
- // keep-best: final = the BEST suite/validation across all attempts (repair could not make it worse).
139
- const suite = out.bestSuite ?? out.suite;
140
- const validation = out.bestValidation ?? out.validation;
141
- if (out.bestSuite)
142
- await runWriter.writeSuite(out.bestSuite); // restore the best code on disk
143
- // Phase 4: study prior runs of this URL + collect the best (collect-best).
144
- const runsBase = resolve(input.runsBaseDir ?? resolve(process.cwd(), "runs"));
145
- const priorRuns = (await collectPriorRuns(runsBase, out.study.url)).filter((r) => r.runId !== runId);
146
- const currentPassed = (validation?.results ?? [])
147
- .filter((r) => r.status === "passed")
148
- .map((r) => r.test);
149
- const allTimePassing = unionPassedTitles([
150
- ...priorRuns,
151
- { runId, url: out.study.url, greenRatio: validation?.greenRatio ?? 0, passedTests: currentPassed },
152
- ]);
153
- const bestPriorGreen = priorRuns[0]?.greenRatio;
154
- onProgress(`collect — prior runs for URL: ${priorRuns.length}` +
155
- (bestPriorGreen !== undefined ? `; best so far: ${Math.round(bestPriorGreen * 100)}%` : "") +
156
- `; stable cases total (all-time): ${allTimePassing.length}`);
157
- // B1: run metrics — deterministic scorers + LLM-judge (SDK-side).
158
- onProgress("score — scoring (scorers + LLM-judge)…");
159
- const scores = deterministicScores({
160
- study: out.study,
161
- verified: out.verified,
162
- testCases: out.testCases,
163
- suite,
164
- validation,
165
- });
166
- try {
167
- scores.push(...(await judgeTestCases(out.testCases, out.analysis.pageSemantics, router.invoke("judge", cfg.models.judge), prompts)));
168
- }
169
- catch {
170
- // the judge is not critical for the run
171
- }
172
- if (checklistItems.length > 0) {
143
+ // Task 2: wrap in a root trace so nested LangChain CallbackHandler generations attach to ONE trace.
144
+ // Fix 2: the entire post-graph evaluation (scores + judges + pilot + score-attach) runs INSIDE
145
+ // the callback so judge/pilot LLM calls fire the handler while the root span is still active.
146
+ const result = await telemetry.runInTrace("exploration", { runId, backend: cfg.browser.backend, profile: cfg.llmProfile }, async () => {
147
+ const out = await runExploreGraph(deps, { url: input.url, runId });
148
+ // (Expired-session detection now fails fast inside the graph's identifyElements node — L1-05.)
149
+ // keep-best: final = the BEST suite/validation across all attempts (repair could not make it worse).
150
+ const suite = out.bestSuite ?? out.suite;
151
+ const validation = out.bestValidation ?? out.validation;
152
+ if (out.bestSuite)
153
+ await runWriter.writeSuite(out.bestSuite); // restore the best code on disk
154
+ // Phase 4: study prior runs of this URL + collect the best (collect-best).
155
+ const runsBase = resolve(input.runsBaseDir ?? resolve(process.cwd(), "runs"));
156
+ const priorRuns = (await collectPriorRuns(runsBase, out.study.url)).filter((r) => r.runId !== runId);
157
+ const currentPassed = (validation?.results ?? [])
158
+ .filter((r) => r.status === "passed")
159
+ .map((r) => r.test);
160
+ const allTimePassing = unionPassedTitles([
161
+ ...priorRuns,
162
+ { runId, url: out.study.url, greenRatio: validation?.greenRatio ?? 0, passedTests: currentPassed },
163
+ ]);
164
+ const bestPriorGreen = priorRuns[0]?.greenRatio;
165
+ onProgress(`collect — prior runs for URL: ${priorRuns.length}` +
166
+ (bestPriorGreen !== undefined ? `; best so far: ${Math.round(bestPriorGreen * 100)}%` : "") +
167
+ `; stable cases total (all-time): ${allTimePassing.length}`);
168
+ // B1: run metrics — deterministic scorers + LLM-judge (SDK-side).
169
+ onProgress("score — scoring (scorers + LLM-judge)…");
170
+ const scores = deterministicScores({
171
+ study: out.study,
172
+ verified: out.verified,
173
+ testCases: out.testCases,
174
+ suite,
175
+ validation,
176
+ });
173
177
  try {
174
- const cov = await judgeChecklistCoverage(checklistItems, out.testCases, router.invoke("judge", cfg.models.judge), prompts);
175
- scores.push({ name: "checklist_coverage", value: cov.value, comment: cov.comment });
178
+ scores.push(...(await judgeTestCases(out.testCases, out.analysis.pageSemantics, router.invoke("judge", cfg.models.judge), prompts)));
176
179
  }
177
180
  catch {
178
- // fallback: token-based coverage (offline / judge unavailable)
179
- scores.push({ name: "checklist_coverage", value: coverageScore(checklistItems, out.testCases) });
181
+ // the judge is not critical for the run
180
182
  }
181
- }
182
- onProgress(`score — ${scores.length} metrics`);
183
- // Best-effort: write scores to Langfuse against the trace (requires a self-hosted instance).
184
- const traceId = telemetry.callbackHandler?.last_trace_id;
185
- if (telemetry.enabled && telemetry.client && traceId) {
186
- try {
187
- for (const sc of scores) {
188
- telemetry.client.score.create({
189
- traceId,
190
- name: sc.name,
191
- value: sc.value,
192
- comment: sc.comment,
193
- dataType: "NUMERIC",
194
- });
183
+ if (checklistItems.length > 0) {
184
+ try {
185
+ const cov = await judgeChecklistCoverage(checklistItems, out.testCases, router.invoke("judge", cfg.models.judge), prompts);
186
+ scores.push({ name: "checklist_coverage", value: cov.value, comment: cov.comment });
187
+ }
188
+ catch {
189
+ // fallback: token-based coverage (offline / judge unavailable)
190
+ scores.push({ name: "checklist_coverage", value: coverageScore(checklistItems, out.testCases) });
195
191
  }
196
192
  }
193
+ onProgress(`score — ${scores.length} metrics`);
194
+ // Best-effort: write scores to Langfuse against the trace (requires a self-hosted instance).
195
+ // The trace is still active here (inside runInTrace) so last_trace_id is set.
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
+ });
207
+ }
208
+ }
209
+ catch {
210
+ // best-effort
211
+ }
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
+ }
197
222
  catch {
198
- // best-effort
223
+ // pilot is not critical
199
224
  }
200
- }
201
- // Pilot supervisor: a holistic verdict for the run (idea from explorbot).
202
- let pilot;
203
- try {
204
- pilot = await pilotReview(out.analysis.pageSemantics, validation, out.testCases,
205
- // L1-01: Pilot verdict now runs on the strong `reasoner` role (was the cheap `judge` tier) —
206
- // intended behavior change toward a "smart judge". See ADR-0011.
207
- router.invoke("reasoner", router.tierFor("reasoner", cfg.models.reasoning)), prompts);
208
- onProgress(`pilot — verdict: ${pilot.verdict} — ${pilot.reason}`);
209
- }
210
- catch {
211
- // pilot is not critical
212
- }
213
- const cost = router.ledger.report(); // L1-01: per-role cost + tokens for this run
214
- const budgetReport = { used: budget.spent, max: budget.max }; // L1-04 (Box 3)
215
- const stoppedEarly = Boolean(out.stoppedEarly); // L1-04 (Box 2)
216
- // #39: also emit ATC/MTC case docs (.md) — explore now produces the human-readable cases like
217
- // design, so manual MTC cases are visible deliverables (not just buried inside report.md).
218
- const caseSuite = suiteFromUrl(out.study.url);
219
- const caseDocs = buildTestCaseDocs(out.testCases, out.verified, caseSuite, checklistItems.length > 0);
220
- const testCaseFiles = await runWriter.writeTestCases(caseDocs.docs);
221
- onProgress(`explore — wrote ${testCaseFiles.length} cases: ${caseDocs.autoN} ATC, ${caseDocs.manualN} MTC → testcases/`);
222
- await runWriter.writeStudy(out.study);
223
- if (out.study.screenshotB64)
224
- await runWriter.writeScreenshot(out.study.screenshotB64);
225
- await runWriter.writeAria(out.study.ariaYaml);
226
- await runWriter.writeReport({
227
- runId,
228
- url: out.study.url,
229
- pageSemantics: out.analysis.pageSemantics,
230
- testCases: out.testCases,
231
- validation,
232
- scores,
233
- pilot,
234
- cost,
235
- budget: budgetReport,
236
- stoppedEarly,
237
- history: {
238
- priorRuns: priorRuns.length,
239
- bestPriorGreen: bestPriorGreen ?? null,
240
- allTimePassing,
241
- },
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
+ },
254
+ });
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
+ };
242
287
  });
243
- await runWriter.writeReportMd(renderReportMd({
244
- runId,
245
- url: out.study.url,
246
- backend: cfg.browser.backend,
247
- profile: cfg.llmProfile,
248
- pageSemantics: out.analysis.pageSemantics,
249
- elements: out.study.elements,
250
- testCases: out.testCases,
251
- validation,
252
- scores,
253
- consoleErrors: out.study.consoleErrors,
254
- cost,
255
- budget: budgetReport,
256
- stoppedEarly,
257
- }));
258
- const green = validation ? `${Math.round(validation.greenRatio * 100)}%` : "—";
259
- await runWriter.writeLog([...logLines, "", `summary: green=${green} testCases=${out.testCases.length} runId=${runId}`].join("\n"));
260
- return {
261
- runId,
262
- runDir: runWriter.dir,
263
- study: out.study,
264
- analysis: out.analysis,
265
- testCases: out.testCases,
266
- suite,
267
- validation,
268
- scores,
269
- pilot,
270
- cost,
271
- budget: budgetReport,
272
- stoppedEarly,
273
- testCaseFiles,
274
- };
288
+ return result;
275
289
  }
276
290
  catch (err) {
277
291
  // L1-04 (Box 1/3/4): the single failure path — write a partial report + a readable, actionable
@@ -312,12 +326,17 @@ export async function runDesign(input) {
312
326
  ensureBrowsersInstalled({ channel: cfg.browser.channel });
313
327
  const keys = { anthropicApiKey: cfg.anthropicApiKey, openrouterApiKey: cfg.openrouterApiKey, groqApiKey: cfg.groqApiKey };
314
328
  const budget = new CallBudget(80); // cost-guardrail: safeguard (normally ~6-10 calls/run)
315
- const router = new RoleRouter(cfg, keys, budget); // L1-01: per-role routing + cost ledger
316
329
  const logLines = [];
330
+ // Parity with runExploration (#38): buffer progress into run.log, flushed incrementally so a
331
+ // mid-run kill leaves the log on disk. `persistLog` is wired once the run dir exists.
332
+ let persistLog = () => undefined; // no-op until the run dir exists
317
333
  const onProgress = (event) => {
318
334
  logLines.push(`${new Date().toISOString()} ${event}`);
319
335
  input.onProgress?.(event);
336
+ persistLog();
320
337
  };
338
+ const telemetry = await initTelemetry(cfg);
339
+ const router = new RoleRouter(cfg, keys, budget, undefined, undefined, undefined, telemetry.callbackHandler ? [telemetry.callbackHandler] : undefined); // L1-01: per-role routing + cost ledger
321
340
  let storageState;
322
341
  const sessionStore = new SessionStore(resolve(input.sessionsDir ?? ".auth"));
323
342
  if (input.sessionFile)
@@ -331,11 +350,12 @@ export async function runDesign(input) {
331
350
  channel: cfg.browser.channel,
332
351
  headless: !input.headed,
333
352
  });
334
- const telemetry = await initTelemetry(cfg);
335
353
  const prompts = new PromptRegistry();
336
354
  const artifacts = new ArtifactStore(resolve(input.runsBaseDir ?? resolve(process.cwd(), "runs")));
337
355
  const runId = randomUUID();
338
356
  const runWriter = await artifacts.openRun(runId);
357
+ // #38: now that the run dir exists, flush run.log on every progress event (best-effort).
358
+ persistLog = () => void runWriter.writeLog(logLines.join("\n")).catch(() => undefined);
339
359
  const checklistItems = input.checklistText ? ingestChecklist(input.checklistText) : [];
340
360
  const knowledgeText = await loadKnowledge(resolve(input.knowledgeDir ?? "knowledge"), input.url);
341
361
  const experienceText = formatExperience(unionPassedTitles((await collectPriorRuns(resolve(input.runsBaseDir ?? resolve(process.cwd(), "runs")), input.url)).filter((r) => r.runId !== runId)));
@@ -346,7 +366,7 @@ export async function runDesign(input) {
346
366
  const analyzeTier = router.tierFor("worker", visionTier);
347
367
  const designTier = router.tierFor("reasoner", cfg.models.reasoning);
348
368
  const codegenTier = router.tierFor("worker", cfg.models.bulk);
349
- const graph = buildExploreGraph({
369
+ const designDeps = {
350
370
  gateway,
351
371
  prompts,
352
372
  analyzeInvoke: router.invoke("worker", analyzeTier),
@@ -362,71 +382,109 @@ export async function runDesign(input) {
362
382
  validate: () => Promise.resolve({ results: [], greenRatio: 0, flakyCount: 0 }),
363
383
  maxRepair: 0,
364
384
  onProgress,
385
+ // #38 parity with explore: persist study + snapshots the moment observe succeeds, so a mid-run
386
+ // kill still leaves the page study/screenshot/ARIA on disk (best-effort — never break the run).
387
+ onStudy: async (study) => {
388
+ try {
389
+ await runWriter.writeStudy(study);
390
+ if (study.screenshotB64)
391
+ await runWriter.writeScreenshot(study.screenshotB64);
392
+ await runWriter.writeAria(study.ariaYaml);
393
+ }
394
+ catch {
395
+ // durability is best-effort
396
+ }
397
+ },
398
+ // Durability: design's loss window is small (END right after designTestCases), but still real — flush
399
+ // the case docs the instant they are designed so an interrupt before the final write keeps them.
400
+ onTestCases: async (testCases, verified, studyUrl) => {
401
+ try {
402
+ const { docs } = buildTestCaseDocs(testCases, verified, suiteFromUrl(studyUrl), checklistItems.length > 0);
403
+ await runWriter.writeTestCases(docs);
404
+ }
405
+ catch {
406
+ // durability is best-effort
407
+ }
408
+ },
365
409
  codeless: true,
366
410
  // L1-05: a session was supplied → fail fast if the first page is a login screen (expired session).
367
411
  expectAuthenticated: Boolean(input.sessionName || input.sessionFile),
368
412
  sessionName: input.sessionName,
369
- });
413
+ };
370
414
  try {
371
- const out = await graph.invoke({ url: input.url, runId }, {
372
- callbacks: telemetry.callbackHandler ? [telemetry.callbackHandler] : [],
373
- runName: "design",
374
- metadata: { runId, backend: cfg.browser.backend, profile: cfg.llmProfile, mode: "design" },
375
- });
376
- if (!out.study || !out.analysis)
377
- throw new Error("The graph did not return study/analysis.");
378
- // (Expired-session detection now fails fast inside the graph's identifyElements node — L1-05.)
379
- const suite = suiteFromUrl(out.study.url);
380
- const { docs, autoN, manualN } = buildTestCaseDocs(out.testCases, out.verified, suite, checklistItems.length > 0);
381
- const testCaseFiles = await runWriter.writeTestCases(docs);
382
- onProgress(`design — wrote ${testCaseFiles.length} cases: ${autoN} auto/ATC, ${manualN} manual/MTC (${suite}) → testcases/`);
383
- const scores = deterministicScores({
384
- study: out.study,
385
- verified: out.verified,
386
- testCases: out.testCases,
387
- });
388
- try {
389
- scores.push(...(await judgeTestCases(out.testCases, out.analysis.pageSemantics, router.invoke("judge", cfg.models.judge), prompts)));
390
- }
391
- catch {
392
- // judge optional
393
- }
394
- if (checklistItems.length > 0) {
415
+ // Task 2: wrap in a root trace so nested LangChain CallbackHandler generations attach to ONE trace.
416
+ // Fix 2: the entire post-graph evaluation (scores + judges + score-attach) runs INSIDE
417
+ // the callback so judge LLM calls fire the handler while the root span is still active.
418
+ const result = await telemetry.runInTrace("design", { runId, backend: cfg.browser.backend, profile: cfg.llmProfile, mode: "design" }, async () => {
419
+ const out = await runExploreGraph(designDeps, { url: input.url, runId });
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
+ });
395
430
  try {
396
- const cov = await judgeChecklistCoverage(checklistItems, out.testCases, router.invoke("judge", cfg.models.judge), prompts);
397
- scores.push({ name: "checklist_coverage", value: cov.value, comment: cov.comment });
431
+ scores.push(...(await judgeTestCases(out.testCases, out.analysis.pageSemantics, router.invoke("judge", cfg.models.judge), prompts)));
398
432
  }
399
433
  catch {
400
- scores.push({ name: "checklist_coverage", value: coverageScore(checklistItems, out.testCases) });
434
+ // judge optional
401
435
  }
402
- }
403
- await runWriter.writeStudy(out.study);
404
- if (out.study.screenshotB64)
405
- await runWriter.writeScreenshot(out.study.screenshotB64);
406
- await runWriter.writeAria(out.study.ariaYaml);
407
- const cost = router.ledger.report(); // L1-01: per-role cost + tokens for this run
408
- await runWriter.writeReport({
409
- runId,
410
- url: out.study.url,
411
- mode: "design",
412
- suite,
413
- pageSemantics: out.analysis.pageSemantics,
414
- testCases: out.testCases,
415
- testCaseFiles,
416
- scores,
417
- cost,
436
+ if (checklistItems.length > 0) {
437
+ 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 });
440
+ }
441
+ catch {
442
+ scores.push({ name: "checklist_coverage", value: coverageScore(checklistItems, out.testCases) });
443
+ }
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,
460
+ });
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
+ };
418
472
  });
419
- await runWriter.writeLog([...logLines, "", `summary: mode=design testCases=${out.testCases.length} suite=${suite} runId=${runId}`].join("\n"));
420
- return {
473
+ return result;
474
+ }
475
+ catch (err) {
476
+ // L1-04 parity with runExploration: write a partial report + a friendly, actionable summary
477
+ // instead of leaking a raw traceback. Study/snapshots/log/cases were already persisted
478
+ // incrementally (onStudy/persistLog/onTestCases), so the partial run is still useful on disk.
479
+ throw await finalizeFailure(runWriter, {
421
480
  runId,
422
- runDir: runWriter.dir,
423
- study: out.study,
424
- analysis: out.analysis,
425
- testCases: out.testCases,
426
- testCaseFiles,
427
- scores,
428
- cost,
429
- };
481
+ url: input.url,
482
+ error: err,
483
+ cost: router.ledger.report(),
484
+ budget: { used: budget.spent, max: budget.max },
485
+ sessionName: input.sessionName,
486
+ onProgress,
487
+ });
430
488
  }
431
489
  finally {
432
490
  await gateway.close();
@@ -491,9 +549,10 @@ export async function runAutomate(input) {
491
549
  await runWriter.writeSuite(s);
492
550
  return s;
493
551
  },
494
- validate: () => validateSuite(runWriter.dir, { storageStatePath: sessionPath, channel: cfg.browser.channel }),
552
+ validate: () => validateSuite(runWriter.dir, { storageStatePath: sessionPath, channel: cfg.browser.channel, workers: cfg.playwrightWorkers }),
495
553
  maxRepair: cfg.maxRepair,
496
554
  onProgress,
555
+ lint: (s) => lintHint(lintSuite(s)), // #57: feed fragile-pattern findings into repair
497
556
  });
498
557
  suite = result.bestSuite;
499
558
  validation = result.bestValidation;