uwright 0.0.0-stage → 0.1.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.
@@ -0,0 +1,621 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdir } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { openai } from '@ai-sdk/openai';
5
+ import { launch } from '@e2e-dev/core';
6
+ import { createAgent } from '@e2e-dev/core/agent';
7
+ import { surfaceOf, web } from '@e2e-dev/web/engine';
8
+ import { generateText, Output } from 'ai';
9
+ import { ensureBrowserInstalled } from './browser-install.js';
10
+ import { compiledSectionSchema, invocationSuffix, newE2EPlan, stageE2ELock } from './e2e-lock.js';
11
+ import { preflightE2E } from './e2e-preflight.js';
12
+ import { FlowError } from './model.js';
13
+ import { captureNavigation, replayNavigation } from './navigation-action.js';
14
+ import { RunViewer } from './run-viewer.js';
15
+ import { captureLiteralFill, captureSecretFill, replayLiteralFill, replaySecretFill, } from './secret-action.js';
16
+ import { beginTapCapture, captureTap, replayTap } from './tap-action.js';
17
+ import { contextsFor } from './workspace.js';
18
+ const bindingSchema = compiledSectionSchema;
19
+ export function flowPlan(ws, flow, plan) {
20
+ const items = [];
21
+ function append(doc, stack, parentId) {
22
+ const source = path.relative(ws.root, doc.path).split(path.sep).join('/');
23
+ if (stack.includes(source))
24
+ return;
25
+ const suffix = invocationSuffix(parentId);
26
+ const outcome = doc === flow ? 'expected outcome' : 'postconditions';
27
+ for (const section of ['setup', 'steps', outcome, 'teardown']) {
28
+ const binding = plan?.bindings[`${source}:${section}${suffix}`];
29
+ for (const [index, item] of (doc.sections[section] ?? []).entries()) {
30
+ const id = `${parentId ? `${parentId}>` : ''}${source}:${item.line}`;
31
+ const call = binding?.calls.find((candidate) => candidate.step === index + 1);
32
+ const kind = section === outcome || binding?.checks.includes(index + 1)
33
+ ? 'check'
34
+ : call
35
+ ? 'skill'
36
+ : binding
37
+ ? 'action'
38
+ : 'step';
39
+ items.push({ id, parentId, text: item.text, section, kind });
40
+ const skill = call && ws.skills.find((candidate) => candidate.frontmatter.name === call.skill);
41
+ if (skill)
42
+ append(skill, [...stack, source], id);
43
+ }
44
+ }
45
+ }
46
+ append(flow, []);
47
+ return items;
48
+ }
49
+ export async function runE2E(ws, flow, mode, watch) {
50
+ const log = (message) => {
51
+ process.stderr.write(message);
52
+ watch?.log(message);
53
+ };
54
+ if (mode !== 'heal' && mode !== 'strict')
55
+ throw new FlowError('UNSUPPORTED_MODE', 'The e2e runtime supports --mode heal and --mode strict.');
56
+ const strict = mode === 'strict';
57
+ log('Experimental e2e runtime: action recordings are stored in the flow lock; model-call limits apply per operation, not per flow. Traces can contain secrets.\n');
58
+ const secretValues = {};
59
+ const declaredSecrets = new Set();
60
+ for (const doc of [flow, ...ws.skills, ...ws.contexts])
61
+ for (const key of doc.frontmatter.secrets) {
62
+ declaredSecrets.add(key);
63
+ const value = process.env[key];
64
+ if (value)
65
+ secretValues[key] = value;
66
+ }
67
+ const redact = (text) => Object.entries(secretValues).reduce((v, [key, value]) => v.split(value).join(`[REDACTED:${key}]`), text);
68
+ watch?.setRedactor(redact);
69
+ watch?.plan(flowPlan(ws, flow).map((item) => ({ ...item, text: redact(item.text) })), false);
70
+ const runId = randomUUID();
71
+ const tracePath = path.resolve(ws.root, ws.config.artifactsDir, 'traces', `${runId}.zip`);
72
+ await ensureBrowserInstalled(ws.config.target.browser);
73
+ const viewer = new RunViewer(path.resolve(ws.root, ws.config.artifactsDir, 'runs', runId), redact(flow.frontmatter.name ?? path.basename(flow.path)), tracePath);
74
+ await viewer.start();
75
+ log(`Inspect this run: ${viewer.file}\n`);
76
+ const report = {
77
+ passed: true,
78
+ compilerCalls: 0,
79
+ navigationModelCalls: 0,
80
+ judgments: 0,
81
+ skillCalls: [],
82
+ viewer: viewer.file,
83
+ };
84
+ const engine = web({ browser: ws.config.target.browser, viewport: ws.config.target.viewport });
85
+ const host = await launch(engine, {
86
+ app: { url: ws.config.target.baseUrl },
87
+ secrets: secretValues,
88
+ cwd: ws.root,
89
+ headed: !ws.config.target.headless,
90
+ timeout: ws.config.execution.defaultTimeoutMs,
91
+ signal: watch?.signal,
92
+ }).catch(async (error) => {
93
+ await viewer.add({
94
+ source: path.relative(ws.root, flow.path),
95
+ line: 0,
96
+ text: 'Start the browser',
97
+ kind: 'run',
98
+ status: 'failed',
99
+ detail: redact(error instanceof Error ? error.message : String(error)),
100
+ }, async () => {
101
+ throw error;
102
+ });
103
+ await viewer.finish('failed');
104
+ watch?.done(watch.signal.aborted ? 'stopped' : 'failed', viewer.file);
105
+ throw error;
106
+ });
107
+ let tracing = false;
108
+ let succeeded = false;
109
+ let recordings;
110
+ let plan = newE2EPlan(ws, flow);
111
+ const explored = new Set();
112
+ try {
113
+ const session = await host.newSession();
114
+ const surface = surfaceOf(engine);
115
+ if (!surface)
116
+ throw new FlowError('TRACE_UNAVAILABLE', 'Unable to access browser tracing.');
117
+ const browserSurface = surface;
118
+ await surface.context().tracing.start({ screenshots: true, snapshots: true, sources: true });
119
+ tracing = true;
120
+ recordings = await stageE2ELock(ws, flow, Object.values(secretValues));
121
+ plan = await recordings.loadPlan(plan, strict);
122
+ if (strict)
123
+ await preflightE2E(ws, flow, plan, recordings.directory);
124
+ watch?.plan(flowPlan(ws, flow, plan).map((item) => ({ ...item, text: redact(item.text) })));
125
+ await session.app.open(plan.policy.initialPath);
126
+ if (watch) {
127
+ await watch.attach(surface.page());
128
+ await watch.waitForViewer();
129
+ await watch.waitForStart();
130
+ }
131
+ const record = (event) => viewer.add(event, (file) => surface.page().screenshot({ path: file, timeout: 5000 }));
132
+ const agent = createAgent(session, {
133
+ model: openai(ws.config.ai.explorerModel),
134
+ judge: openai(ws.config.ai.judgeModel),
135
+ maxSteps: Math.min(ws.config.ai.maxStepsPerExplore, 100),
136
+ maxModelCalls: Math.min(ws.config.ai.maxModelCallsPerFlow, 100),
137
+ cache: { dir: recordings.directory, mode: strict ? 'read-only' : 'read-write', strict },
138
+ });
139
+ const completed = [];
140
+ async function bind(doc, section, params, invocation) {
141
+ const steps = doc.sections[section] ?? [];
142
+ const available = ws.skills.filter((skill) => skill !== doc);
143
+ if (!steps.length)
144
+ return { bindings: new Map(), checks: new Set() };
145
+ const bindingKey = `${path.relative(ws.root, doc.path).split(path.sep).join('/')}:${section}${invocation}`;
146
+ const safeParams = Object.fromEntries(Object.entries(params).map(([key, value]) => [key, typeof value === 'string' ? value : '[secret]']));
147
+ const prompt = redact(`Identify which numbered steps invoke an available skill and which are checks.
148
+ Return skill calls in calls and step numbers that assert or verify a condition without requesting an action in checks.
149
+ Ordinary actions belong in neither.
150
+ Match by meaning, not exact name.
151
+ Consider the current document and its purpose.
152
+ Bind a skill only when a step requests the whole skill workflow, not an individual action inside it.
153
+ When compiling a skill, its own internal actions are not calls to itself; return a self-call only when a step explicitly invokes the entire same workflow.
154
+ Number steps starting at 1.
155
+ For each required input, bind a literal or a declared secret environment key.
156
+ When a step refers to an available secret key, bind type secret with the key name as value, never as a literal.
157
+ Never include actual secret values.
158
+ Do not invent skill calls.
159
+ Full flow: ${flow.source}
160
+ Completed steps: ${JSON.stringify(completed)}
161
+ Available parameters: ${JSON.stringify(safeParams)}
162
+ Current document: ${JSON.stringify({ name: doc.frontmatter.name, description: doc.frontmatter.description, kind: doc === flow ? 'flow' : 'skill' })}
163
+ Steps: ${JSON.stringify(steps.map((item, i) => ({ step: i + 1, text: item.text })))}
164
+ Skills: ${JSON.stringify(available.map((s) => ({ name: s.frontmatter.name, description: s.frontmatter.description, inputs: s.frontmatter.inputs, secrets: s.frontmatter.secrets })))}
165
+ Available secrets: ${[...declaredSecrets].join(', ')}`);
166
+ function validate(output) {
167
+ const bindings = new Map();
168
+ for (const call of output.calls) {
169
+ if (call.step > steps.length || bindings.has(call.step))
170
+ throw new FlowError('INVALID_SKILL_BINDING', `Invalid skill call at step ${call.step}`);
171
+ const skill = available.find((s) => s.frontmatter.name === call.skill);
172
+ if (!skill)
173
+ throw new FlowError('SKILL_NOT_FOUND', `Unknown skill ${call.skill}`);
174
+ const names = new Set();
175
+ for (const input of call.inputs) {
176
+ if (names.has(input.name) || !skill.frontmatter.inputs.some((def) => def.name === input.name))
177
+ throw new FlowError('INVALID_SKILL_BINDING', `Invalid input ${input.name} for ${call.skill}`);
178
+ names.add(input.name);
179
+ if (input.type === 'secret' && !declaredSecrets.has(input.value))
180
+ throw new FlowError('CONFIG_SECRET_MISSING', `Secret not declared: ${input.value}`);
181
+ if (input.type === 'secret' && !(input.value in secretValues))
182
+ throw new FlowError('CONFIG_SECRET_MISSING', `Missing environment variable ${input.value}`);
183
+ }
184
+ for (const def of skill.frontmatter.inputs)
185
+ if (def.required && def.default === undefined && !names.has(def.name))
186
+ throw new FlowError('SKILL_INPUT_MISSING', `Missing input ${def.name} for ${call.skill}`);
187
+ bindings.set(call.step, call);
188
+ }
189
+ const checks = new Set(output.checks);
190
+ if (checks.size !== output.checks.length)
191
+ throw new FlowError('INVALID_SKILL_BINDING', 'Duplicate check in compiled section');
192
+ for (const step of checks)
193
+ if (step > steps.length || bindings.has(step))
194
+ throw new FlowError('INVALID_SKILL_BINDING', `Invalid check at step ${step}; this section has ${steps.length} steps`);
195
+ return { bindings, checks };
196
+ }
197
+ const locked = plan.bindings[bindingKey];
198
+ if (locked) {
199
+ log(`Locked compilation: ${bindingKey}\n`);
200
+ return validate(locked);
201
+ }
202
+ if (strict)
203
+ throw new FlowError('LOCK_INCOMPLETE', `Missing compiled section ${bindingKey}`, 3);
204
+ let feedback = '';
205
+ for (let attempt = 0; attempt < 3; attempt++) {
206
+ report.compilerCalls++;
207
+ const response = await generateText({
208
+ model: openai(ws.config.ai.compilerModel),
209
+ output: Output.object({ schema: bindingSchema }),
210
+ providerOptions: { openai: { strictJsonSchema: false } },
211
+ prompt: feedback
212
+ ? `${prompt}\nThe prior result was invalid: ${feedback}. Only number the ${steps.length} steps in the current section and use only the available skills; correct the binding.`
213
+ : prompt,
214
+ abortSignal: watch?.signal,
215
+ });
216
+ const output = bindingSchema.parse(response.output);
217
+ if (redact(JSON.stringify(output)) !== JSON.stringify(output))
218
+ throw new FlowError('SECRET_IN_PLAN', 'Compiler returned a secret value');
219
+ try {
220
+ const result = validate(output);
221
+ plan.bindings[bindingKey] = output;
222
+ return result;
223
+ }
224
+ catch (error) {
225
+ if (!(error instanceof FlowError) ||
226
+ !['INVALID_SKILL_BINDING', 'SKILL_NOT_FOUND', 'SKILL_INPUT_MISSING'].includes(error.code) ||
227
+ attempt === 2)
228
+ throw error;
229
+ feedback = redact(`${error.code}: ${error.message}`);
230
+ log(`Compiler correction: ${feedback}\n`);
231
+ }
232
+ }
233
+ throw new FlowError('MODEL_ERROR', 'Compiler returned no valid plan');
234
+ }
235
+ async function execute(doc, params, stack, parentId) {
236
+ const name = doc.frontmatter.name ?? path.basename(doc.path);
237
+ if (stack.includes(name))
238
+ throw new FlowError('SKILL_CIRCULAR_DEPENDENCY', `Skill cycle: ${[...stack, name].join(' -> ')}`);
239
+ const source = path.relative(ws.root, doc.path).split(path.sep).join('/');
240
+ const invocation = invocationSuffix(parentId);
241
+ const scopedParams = { ...params };
242
+ for (const declared of [...contextsFor(ws, doc), doc])
243
+ for (const key of declared.frontmatter.secrets) {
244
+ if (!(key in secretValues))
245
+ throw new FlowError('CONFIG_SECRET_MISSING', `Missing environment variable ${key}`);
246
+ if (!(key in scopedParams))
247
+ scopedParams[key] = host.secret(key);
248
+ }
249
+ const context = [
250
+ ...contextsFor(ws, doc).map((x) => x.source),
251
+ ...(doc.sections.guardrails ?? []).map((x) => x.text),
252
+ ...(doc.sections['context & test data'] ?? []).map((x) => x.text),
253
+ ].join('\n');
254
+ const fullContext = () => redact(`Full authored flow for context only (do not execute later steps early):
255
+ ${flow.source}
256
+ ${doc === flow
257
+ ? ''
258
+ : `Current skill for context:
259
+ ${doc.source}`}
260
+ Successfully completed steps so far:
261
+ ${completed.join('\n')}
262
+ Context and guardrails:
263
+ ${context}`);
264
+ async function executeSection(section) {
265
+ const { bindings, checks } = await bind(doc, section, scopedParams, invocation);
266
+ for (const [i, item] of (doc.sections[section] ?? []).entries()) {
267
+ log(`${source}:${item.line} ${redact(item.text)}\n`);
268
+ const id = `${parentId ? `${parentId}>` : ''}${source}:${item.line}`;
269
+ const call = bindings.get(i + 1);
270
+ const kind = checks.has(i + 1) ? 'check' : call ? 'skill' : 'action';
271
+ await watch?.boundary(redact(item.text), id, parentId, kind, section);
272
+ let detail = kind === 'check' ? 'Model-assisted check' : undefined;
273
+ try {
274
+ if (checks.has(i + 1)) {
275
+ let claim = item.text;
276
+ for (const key of Object.keys(scopedParams))
277
+ claim = claim.split('`' + key + '`').join('{' + key + '}');
278
+ const checkKey = `${source}:${section}:${i + 1}${invocation}`;
279
+ if (strict && !plan.assertions[checkKey])
280
+ throw new FlowError('LOCK_INCOMPLETE', `Missing assertion ${checkKey}`, 3);
281
+ const check = plan.assertions[checkKey] ?? redact(`${fullContext()}\nEvaluate only this current check: ${claim}`);
282
+ await agent.waitFor(check, {
283
+ params: scopedParams,
284
+ vision: plan.policy.checkVision,
285
+ timeout: plan.policy.checkTimeoutMs,
286
+ });
287
+ plan.assertions[checkKey] = check;
288
+ report.judgments++;
289
+ log(`Passed model-assisted check: ${redact(item.text)}\n`);
290
+ }
291
+ else if (call) {
292
+ const skill = ws.skills.find((s) => s.frontmatter.name === call.skill);
293
+ const values = {};
294
+ for (const def of skill.frontmatter.inputs)
295
+ if (def.default !== undefined)
296
+ values[def.name] = def.default;
297
+ for (const input of call.inputs)
298
+ values[input.name] = input.type === 'secret' ? host.secret(input.value) : input.value;
299
+ report.skillCalls.push(call.skill);
300
+ log(`Skill: ${call.skill} (step ${i + 1})\n`);
301
+ await execute(skill, { ...scopedParams, ...values }, [...stack, name], id);
302
+ }
303
+ else {
304
+ let instruction = item.text;
305
+ for (const key of Object.keys(scopedParams))
306
+ instruction = instruction.split('`' + key + '`').join('{' + key + '}');
307
+ instruction = `${fullContext()}\nPerform only this current step; later steps are context, not part of this step: ${instruction}`;
308
+ const actionKey = `${source}:${section}:${i + 1}${invocation}`;
309
+ const locked = plan.actions[actionKey];
310
+ const secretParameter = (secret) => {
311
+ const names = [...item.text.matchAll(/`([^`]+)`/g)]
312
+ .map((match) => match[1])
313
+ .filter((name) => {
314
+ const value = scopedParams[name];
315
+ return value !== undefined && typeof value !== 'string' && value.name === secret;
316
+ });
317
+ return names.length === 1 ? names[0] : undefined;
318
+ };
319
+ if (strict &&
320
+ (!locked?.instruction ||
321
+ (!locked.recordings.length &&
322
+ !locked.secretFill &&
323
+ !locked.literalFill &&
324
+ !locked.tap &&
325
+ !locked.navigation &&
326
+ !locked.stateCheck)))
327
+ throw new FlowError('LOCK_INCOMPLETE', `No recording for ${actionKey}`, 3);
328
+ instruction = locked?.instruction ?? redact(instruction);
329
+ let replayedLocally = false;
330
+ if (locked?.stateCheck &&
331
+ !locked.recordings.length &&
332
+ !locked.secretFill &&
333
+ !locked.literalFill &&
334
+ !locked.tap &&
335
+ !locked.navigation) {
336
+ await agent.waitFor(locked.stateCheck, {
337
+ params: scopedParams,
338
+ vision: plan.policy.checkVision,
339
+ timeout: plan.policy.checkTimeoutMs,
340
+ });
341
+ report.judgments++;
342
+ replayedLocally = true;
343
+ detail = 'Replay: model-assisted state check. Navigation model calls: 0.';
344
+ log(`Step ${i + 1}: locked state check; navigation model calls 0\n`);
345
+ }
346
+ if (locked?.secretFill && !locked.recordings.length) {
347
+ try {
348
+ const parameter = locked.secretFill.parameter ?? secretParameter(locked.secretFill.secret);
349
+ const bound = parameter ? scopedParams[parameter] : undefined;
350
+ if (!parameter || !bound || typeof bound === 'string' || bound.name !== locked.secretFill.secret)
351
+ throw new FlowError('CACHE_STALE', `Secret binding changed for ${actionKey}`, 3);
352
+ locked.secretFill.parameter = parameter;
353
+ await replaySecretFill(browserSurface.page(), locked.secretFill, secretValues);
354
+ replayedLocally = true;
355
+ watch?.action(`replay: fill secret ${locked.secretFill.secret}`, id);
356
+ detail = 'Replay: secret fill. Navigation model calls: 0.';
357
+ log(`Step ${i + 1}: secret-fill replay; navigation model calls 0\n`);
358
+ }
359
+ catch (error) {
360
+ if (strict || !(error instanceof FlowError) || error.code !== 'CACHE_STALE')
361
+ throw error;
362
+ log(`Step ${i + 1}: secret-fill recording is stale; exploring this step\n`);
363
+ }
364
+ }
365
+ if (locked?.literalFill && !locked.recordings.length && !replayedLocally) {
366
+ try {
367
+ await replayLiteralFill(browserSurface.page(), locked.literalFill);
368
+ replayedLocally = true;
369
+ watch?.action('replay: fill recorded value', id);
370
+ detail = 'Replay: recorded fill. Navigation model calls: 0.';
371
+ log(`Step ${i + 1}: recorded fill replay; navigation model calls 0\n`);
372
+ }
373
+ catch (error) {
374
+ if (strict || !(error instanceof FlowError) || error.code !== 'CACHE_STALE')
375
+ throw error;
376
+ log(`Step ${i + 1}: fill recording is stale; exploring this step\n`);
377
+ }
378
+ }
379
+ if (locked?.tap && !locked.recordings.length && !replayedLocally) {
380
+ try {
381
+ await replayTap(browserSurface.page(), locked.tap);
382
+ replayedLocally = true;
383
+ watch?.action(`replay: tap ${locked.tap.role} ${JSON.stringify(locked.tap.name)}`, id);
384
+ detail = 'Replay: recorded click. Navigation model calls: 0.';
385
+ log(`Step ${i + 1}: recorded click replay; navigation model calls 0\n`);
386
+ }
387
+ catch (error) {
388
+ if (strict || !(error instanceof FlowError) || error.code !== 'CACHE_STALE')
389
+ throw error;
390
+ log(`Step ${i + 1}: click recording is stale; exploring this step\n`);
391
+ }
392
+ }
393
+ if (locked?.navigation && !locked.recordings.length && !replayedLocally) {
394
+ await replayNavigation(browserSurface.page(), locked.navigation, ws.config.target.baseUrl, plan.policy.actionTimeoutMs);
395
+ replayedLocally = true;
396
+ watch?.action('replay: recorded navigation', id);
397
+ detail = 'Replay: recorded navigation. Navigation model calls: 0.';
398
+ log(`Step ${i + 1}: recorded navigation replay; navigation model calls 0\n`);
399
+ }
400
+ if (!replayedLocally) {
401
+ let captured;
402
+ let literal;
403
+ let tap;
404
+ let navigation;
405
+ const actionNames = [];
406
+ const allowedLiterals = [...item.text.matchAll(/`([^`]+)`/g)]
407
+ .map((match) => match[1])
408
+ .concat(Object.values(scopedParams).filter((value) => typeof value === 'string'));
409
+ const result = await agent.act(instruction, {
410
+ cacheKey: actionKey,
411
+ params: scopedParams,
412
+ timeout: plan.policy.actionTimeoutMs,
413
+ onBeforeAction: async (event) => {
414
+ if (strict && event.source !== 'replay')
415
+ throw new FlowError('LOCK_REPLAY_MISS', `Locked action cannot be replayed: ${actionKey}`, 3);
416
+ if (!strict && event.source === 'model')
417
+ await beginTapCapture(browserSurface.page()).catch(() => undefined);
418
+ },
419
+ onAction: async (event) => {
420
+ actionNames.push(event.action);
421
+ if (event.action === 'typeSecret') {
422
+ const candidate = await captureSecretFill(browserSurface.page(), secretValues).catch(() => undefined);
423
+ const parameter = candidate && secretParameter(candidate.secret);
424
+ if (candidate && parameter)
425
+ captured = { ...candidate, parameter };
426
+ }
427
+ if (event.action === 'type' || event.action === 'typeText')
428
+ literal = await captureLiteralFill(browserSurface.page(), allowedLiterals, secretValues).catch(() => undefined);
429
+ if (event.action === 'tap' || event.action === 'tapAt')
430
+ tap = await captureTap(browserSurface.page(), event.summary).catch(() => undefined);
431
+ if (event.action === 'navigate')
432
+ navigation = captureNavigation(event.summary, ws.config.target.baseUrl, secretValues, browserSurface.page().url());
433
+ log(`Action ${event.source}: ${redact(event.summary)}\n`);
434
+ watch?.action(redact(`${event.source}: ${event.summary}`), id);
435
+ },
436
+ });
437
+ if (strict && result.modelCalls)
438
+ throw new FlowError('LOCK_REPLAY_MISS', `Locked action required model navigation: ${actionKey}`, 3);
439
+ if (result.cache?.mode !== 'self-finalized')
440
+ explored.add(actionKey);
441
+ let stateCheck;
442
+ if (result.actions === 0) {
443
+ stateCheck = redact(`${fullContext()}
444
+ Verify that the current UI completes this step at this point in the authored flow.
445
+ Later steps have not run. A sign-in screen may be the correct result of opening a protected application before a later sign-in step.
446
+ Do not require later steps to be complete or perform actions.
447
+ Current step: ${item.text}`);
448
+ await agent.waitFor(stateCheck, {
449
+ params: scopedParams,
450
+ vision: plan.policy.checkVision,
451
+ timeout: plan.policy.checkTimeoutMs,
452
+ });
453
+ report.judgments++;
454
+ }
455
+ const entry = result.cache?.entry;
456
+ plan.actions[actionKey] = {
457
+ recordings: entry && /^[a-f0-9]{64}$/.test(entry) ? [`${entry}.json`] : [],
458
+ observedActions: result.actions ?? 0,
459
+ instruction,
460
+ ...(stateCheck ? { stateCheck } : {}),
461
+ ...(actionNames.length === 1 && actionNames[0] === 'typeSecret' && captured
462
+ ? { secretFill: captured }
463
+ : {}),
464
+ ...(actionNames.length === 1 &&
465
+ (actionNames[0] === 'type' || actionNames[0] === 'typeText') &&
466
+ literal
467
+ ? { literalFill: literal }
468
+ : {}),
469
+ ...(actionNames.length === 1 && (actionNames[0] === 'tap' || actionNames[0] === 'tapAt') && tap
470
+ ? { tap }
471
+ : {}),
472
+ ...(actionNames.length === 1 && actionNames[0] === 'navigate' && navigation ? { navigation } : {}),
473
+ };
474
+ report.navigationModelCalls += result.modelCalls;
475
+ detail = `Replay: ${result.cache?.mode ?? 'live'}${result.cache?.reason ? ` (${result.cache.reason})` : ''}. Navigation model calls: ${result.modelCalls}.`;
476
+ log(`Step ${i + 1}: ${result.cache?.mode ?? 'live'}${result.cache?.reason ? ` (${result.cache.reason})` : ''}; navigation model calls ${result.modelCalls}\n`);
477
+ }
478
+ }
479
+ await record({ source, line: item.line, text: redact(item.text), kind, status: 'passed', detail });
480
+ completed.push(`${source}:${item.line} ${redact(item.text)}`);
481
+ watch?.add({
482
+ text: redact(item.text),
483
+ status: 'passed',
484
+ detail: `${source}:${item.line}${detail ? ` · ${detail}` : ''}`,
485
+ }, id);
486
+ }
487
+ catch (error) {
488
+ detail = redact(error instanceof Error ? error.message : String(error));
489
+ await record({ source, line: item.line, text: redact(item.text), kind, status: 'failed', detail });
490
+ watch?.add({ text: redact(item.text), status: 'failed', detail: `${source}:${item.line} · ${detail}` }, id);
491
+ throw new FlowError(error instanceof FlowError ? error.code : 'STEP_FAILED', `${source}:${item.line} ${redact(item.text)}: ${detail}`);
492
+ }
493
+ }
494
+ }
495
+ let primary;
496
+ try {
497
+ await executeSection('setup');
498
+ await executeSection('steps');
499
+ const outcomes = doc === flow ? (doc.sections['expected outcome'] ?? []) : (doc.sections.postconditions ?? []);
500
+ for (const item of outcomes) {
501
+ const id = `${parentId ? `${parentId}>` : ''}${source}:${item.line}`;
502
+ await watch?.boundary(redact(item.text), id, parentId, 'check', doc === flow ? 'expected outcome' : 'postconditions');
503
+ let claim = item.text;
504
+ for (const key of Object.keys(scopedParams))
505
+ claim = claim.split('`' + key + '`').join('{' + key + '}');
506
+ const checkKey = `${source}:${doc === flow ? 'expected outcome' : 'postconditions'}:${item.line}${invocation}`;
507
+ if (strict && !plan.assertions[checkKey])
508
+ throw new FlowError('LOCK_INCOMPLETE', `Missing assertion ${checkKey}`, 3);
509
+ const check = plan.assertions[checkKey] ?? redact(`${fullContext()}\nEvaluate only this current check: ${claim}`);
510
+ try {
511
+ await agent.waitFor(check, {
512
+ params: scopedParams,
513
+ vision: plan.policy.checkVision,
514
+ timeout: plan.policy.checkTimeoutMs,
515
+ });
516
+ plan.assertions[checkKey] = check;
517
+ }
518
+ catch (error) {
519
+ const detail = redact(error instanceof Error ? error.message : String(error));
520
+ await record({ source, line: item.line, text: redact(item.text), kind: 'check', status: 'failed', detail });
521
+ watch?.add({ text: redact(item.text), status: 'failed', detail: `${source}:${item.line} · ${detail}` }, id);
522
+ throw new FlowError('ASSERTION_FAILED', `${source}:${item.line} ${redact(item.text)}: ${detail}`);
523
+ }
524
+ report.judgments++;
525
+ log(`Passed model-assisted check: ${redact(item.text)}\n`);
526
+ await record({ source, line: item.line, text: redact(item.text), kind: 'check', status: 'passed' });
527
+ completed.push(`${source}:${item.line} ${redact(item.text)}`);
528
+ watch?.add({ text: redact(item.text), status: 'passed', detail: `${source}:${item.line} · Model-assisted check` }, id);
529
+ }
530
+ }
531
+ catch (error) {
532
+ primary = error;
533
+ }
534
+ finally {
535
+ try {
536
+ await executeSection('teardown');
537
+ }
538
+ catch (error) {
539
+ log(`Teardown failed: ${redact(error instanceof Error ? error.message : String(error))}\n`);
540
+ }
541
+ }
542
+ if (primary)
543
+ throw primary;
544
+ }
545
+ await execute(flow, {}, []);
546
+ succeeded = true;
547
+ return report;
548
+ }
549
+ catch (error) {
550
+ await viewer.add({
551
+ source: path.relative(ws.root, flow.path),
552
+ line: 0,
553
+ text: 'Run failed',
554
+ kind: 'run',
555
+ status: 'failed',
556
+ detail: redact(error instanceof Error ? error.message : String(error)),
557
+ }, async (file) => {
558
+ const surface = surfaceOf(engine);
559
+ if (!surface)
560
+ throw new Error('No browser surface');
561
+ await surface.page().screenshot({ path: file, timeout: 5000 });
562
+ });
563
+ await viewer.finish('failed');
564
+ watch?.done(watch.signal.aborted ? 'stopped' : 'failed', viewer.file);
565
+ if (error instanceof FlowError)
566
+ throw error;
567
+ const detail = error instanceof Error ? error.message : String(error);
568
+ const code = error instanceof Error && 'code' in error && typeof error.code === 'string' ? error.code : 'E2E_RUNTIME_ERROR';
569
+ throw new FlowError(code, redact(detail), 1);
570
+ }
571
+ finally {
572
+ if (tracing) {
573
+ try {
574
+ await mkdir(path.dirname(tracePath), { recursive: true });
575
+ await surfaceOf(engine).context().tracing.stop({ path: tracePath });
576
+ log(`Trace: ${tracePath}\n`);
577
+ }
578
+ catch (error) {
579
+ log(`Trace could not be saved: ${redact(error instanceof Error ? error.message : String(error))}\n`);
580
+ }
581
+ }
582
+ try {
583
+ await host.close();
584
+ if (succeeded && recordings && !strict) {
585
+ await recordings.savePlan(plan, explored);
586
+ const count = await recordings.publish();
587
+ log(`Recorded ${count} updated e2e lock entries.\n`);
588
+ }
589
+ if (succeeded) {
590
+ await viewer.finish('passed');
591
+ watch?.done('passed', viewer.file);
592
+ }
593
+ }
594
+ catch (error) {
595
+ if (succeeded) {
596
+ const detail = redact(error instanceof Error ? error.message : String(error));
597
+ await viewer.add({
598
+ source: path.relative(ws.root, flow.path),
599
+ line: 0,
600
+ text: 'Lock publication failed',
601
+ kind: 'run',
602
+ status: 'failed',
603
+ detail,
604
+ }, async () => {
605
+ throw new Error('Browser is closed');
606
+ });
607
+ await viewer.finish('failed');
608
+ watch?.done('failed', viewer.file);
609
+ }
610
+ throw error;
611
+ }
612
+ finally {
613
+ try {
614
+ await recordings?.close();
615
+ }
616
+ catch (error) {
617
+ log(`Could not remove staged recordings: ${redact(error instanceof Error ? error.message : String(error))}\n`);
618
+ }
619
+ }
620
+ }
621
+ }
@@ -0,0 +1,30 @@
1
+ import { readdir } from 'node:fs/promises';
2
+ import { newE2EPlan, stageE2ELock } from './e2e-lock.js';
3
+ import { preflightE2E } from './e2e-preflight.js';
4
+ import { FlowError } from './model.js';
5
+ export async function e2eLockStatus(ws, flow) {
6
+ const staged = await stageE2ELock(ws, flow, []);
7
+ try {
8
+ const count = (await readdir(staged.directory)).filter((name) => /^[a-f0-9]{64}\.json$/.test(name)).length;
9
+ try {
10
+ const plan = await staged.loadPlan(newE2EPlan(ws, flow), true);
11
+ await preflightE2E(ws, flow, plan, staged.directory, false);
12
+ return `complete (${count} upstream recordings)`;
13
+ }
14
+ catch (error) {
15
+ if (error instanceof FlowError && error.code === 'LOCK_MISSING_IN_STRICT_MODE')
16
+ return 'missing';
17
+ if (error instanceof FlowError && error.code === 'LOCK_DRIFT_DETECTED')
18
+ return 'stale';
19
+ if (error instanceof FlowError && error.code === 'LOCK_INCOMPLETE')
20
+ return `incomplete: ${error.message}`;
21
+ if (error instanceof FlowError &&
22
+ ['LOCK_INVALID', 'SKILL_NOT_FOUND', 'SKILL_CIRCULAR_DEPENDENCY'].includes(error.code))
23
+ return `invalid: ${error.message}`;
24
+ throw error;
25
+ }
26
+ }
27
+ finally {
28
+ await staged.close();
29
+ }
30
+ }