@jeffawe/understudy 0.0.0-stage → 0.2.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 (99) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +166 -2
  3. package/REASONER.md +67 -0
  4. package/build/extension/firefox/background.js +186 -0
  5. package/build/extension/firefox/icons/icon-128.png +0 -0
  6. package/build/extension/firefox/icons/icon-16.png +0 -0
  7. package/build/extension/firefox/icons/icon-32.png +0 -0
  8. package/build/extension/firefox/icons/icon-48.png +0 -0
  9. package/build/extension/firefox/manifest.json +54 -0
  10. package/build/extension/firefox/popup.html +52 -0
  11. package/build/extension/firefox/popup.js +106 -0
  12. package/build/extension/firefox/recorder.js +362 -0
  13. package/dist/adapters/recorder/accname-bundle.d.ts +12 -0
  14. package/dist/adapters/recorder/accname-bundle.js +12 -0
  15. package/dist/adapters/recorder/extension.d.ts +57 -0
  16. package/dist/adapters/recorder/extension.js +146 -0
  17. package/dist/adapters/recorder/injected.d.ts +21 -0
  18. package/dist/adapters/recorder/injected.js +352 -0
  19. package/dist/adapters/recorder/live.d.ts +105 -0
  20. package/dist/adapters/recorder/live.js +317 -0
  21. package/dist/adapters/recorder/script.d.ts +43 -0
  22. package/dist/adapters/recorder/script.js +530 -0
  23. package/dist/adapters/recorder/wire.d.ts +42 -0
  24. package/dist/adapters/recorder/wire.js +51 -0
  25. package/dist/core/auth-cache.d.ts +119 -0
  26. package/dist/core/auth-cache.js +216 -0
  27. package/dist/core/browser.d.ts +47 -0
  28. package/dist/core/browser.js +82 -0
  29. package/dist/core/distill.d.ts +118 -0
  30. package/dist/core/distill.js +197 -0
  31. package/dist/core/fingerprint.d.ts +15 -0
  32. package/dist/core/fingerprint.js +21 -0
  33. package/dist/core/recording-store.d.ts +34 -0
  34. package/dist/core/recording-store.js +64 -0
  35. package/dist/core/recording.d.ts +185 -0
  36. package/dist/core/recording.js +100 -0
  37. package/dist/core/replay.d.ts +307 -0
  38. package/dist/core/replay.js +804 -0
  39. package/dist/core/sig.d.ts +70 -0
  40. package/dist/core/sig.js +0 -0
  41. package/dist/core/trigger.d.ts +18 -0
  42. package/dist/core/trigger.js +35 -0
  43. package/dist/core/types.d.ts +28 -0
  44. package/dist/core/types.js +8 -0
  45. package/dist/core/visual.d.ts +80 -0
  46. package/dist/core/visual.js +111 -0
  47. package/dist/entry/cli.d.ts +9 -0
  48. package/dist/entry/cli.js +1016 -0
  49. package/dist/entry/mcp.d.ts +20 -0
  50. package/dist/entry/mcp.js +288 -0
  51. package/dist/flows/destructive.d.ts +19 -0
  52. package/dist/flows/destructive.js +48 -0
  53. package/dist/flows/distill.d.ts +28 -0
  54. package/dist/flows/distill.js +109 -0
  55. package/dist/flows/drift.d.ts +43 -0
  56. package/dist/flows/drift.js +116 -0
  57. package/dist/flows/emit.d.ts +23 -0
  58. package/dist/flows/emit.js +133 -0
  59. package/dist/flows/execute.d.ts +75 -0
  60. package/dist/flows/execute.js +133 -0
  61. package/dist/flows/findings.d.ts +38 -0
  62. package/dist/flows/findings.js +136 -0
  63. package/dist/flows/runs.d.ts +42 -0
  64. package/dist/flows/runs.js +93 -0
  65. package/dist/flows/save.d.ts +74 -0
  66. package/dist/flows/save.js +171 -0
  67. package/dist/memory/notes.d.ts +89 -0
  68. package/dist/memory/notes.js +163 -0
  69. package/dist/memory/placeholders.d.ts +41 -0
  70. package/dist/memory/placeholders.js +139 -0
  71. package/dist/memory/recall.d.ts +118 -0
  72. package/dist/memory/recall.js +147 -0
  73. package/dist/memory/vocabulary.d.ts +9 -0
  74. package/dist/memory/vocabulary.js +24 -0
  75. package/dist/plan/planner.d.ts +69 -0
  76. package/dist/plan/planner.js +211 -0
  77. package/dist/plan/seams.d.ts +58 -0
  78. package/dist/plan/seams.js +99 -0
  79. package/dist/store/db.d.ts +62 -0
  80. package/dist/store/db.js +183 -0
  81. package/dist/store/embed.d.ts +46 -0
  82. package/dist/store/embed.js +100 -0
  83. package/dist/store/reembed.d.ts +13 -0
  84. package/dist/store/reembed.js +32 -0
  85. package/dist/store/settings.d.ts +67 -0
  86. package/dist/store/settings.js +151 -0
  87. package/dist/store/types.d.ts +220 -0
  88. package/dist/store/types.js +14 -0
  89. package/extension/README.md +76 -0
  90. package/extension/background.js +186 -0
  91. package/extension/icons/icon-128.png +0 -0
  92. package/extension/icons/icon-16.png +0 -0
  93. package/extension/icons/icon-32.png +0 -0
  94. package/extension/icons/icon-48.png +0 -0
  95. package/extension/manifest.json +38 -0
  96. package/extension/popup.html +52 -0
  97. package/extension/popup.js +106 -0
  98. package/extension/recorder.js +362 -0
  99. package/package.json +68 -4
@@ -0,0 +1,804 @@
1
+ /**
2
+ * Replay — re-run a RawRecording headless, and watch everything.
3
+ *
4
+ * Three jobs, and only the first is obvious:
5
+ *
6
+ * 1. VERIFY. A recording that will not reproduce must never become memory.
7
+ * PLAN.md's rule: won't replay → `needs_review`, never promoted. Bad
8
+ * memory is worse than no memory, because the agent acts on it confidently.
9
+ *
10
+ * 2. ENRICH. Per-step page fingerprint, console errors, network responses with
11
+ * bodies. All of it captured unconditionally and with no model involved,
12
+ * which is what makes findings detection free and what gives flow-drift its
13
+ * baseline.
14
+ *
15
+ * 3. CONFIRM ADDRESSING. Names are computed in-page at capture, but a name
16
+ * that resolved then may not resolve now. Replay is where a locator is
17
+ * proven to still find exactly one element.
18
+ *
19
+ * THE STEP WALKER HERE IS THE EXECUTOR'S STEP WALKER. Running a recording and
20
+ * running a bound plan are the same operation — resolve a locator, act, compute
21
+ * sig(), compare, capture. This is not scaffolding for the recorder; it is the
22
+ * first half of the thing that runs tests.
23
+ */
24
+ import {} from 'playwright';
25
+ import { openLease } from './browser.js';
26
+ import { computeSig, urlPattern, waitForAriaStable } from './sig.js';
27
+ import { acceptBaseline, captureCheckpoint, worthJudging, VISUAL_SEVERE } from './visual.js';
28
+ /** Lesson kinds that mean "this page resolves late" — settle before acting. */
29
+ const SETTLE_KINDS = new Set(['wait', 'timing']);
30
+ /** Bodies above this are truncated — a findings fingerprint needs the shape, not the payload. */
31
+ const MAX_BODY = 4000;
32
+ /**
33
+ * Build a locator from an IR step, best addressing first.
34
+ *
35
+ * Order matters and mirrors fragility: a test id is stable by contract,
36
+ * role+name is stable by meaning, raw CSS is the last resort because it breaks
37
+ * on any markup change. `hints.nth` is applied last — it is positional, which
38
+ * is exactly the brittleness this project exists to reduce, so it is only ever
39
+ * a narrowing of something already selected.
40
+ */
41
+ function locatorFor(root, event) {
42
+ let locator;
43
+ // APPLY THE SCOPE. The parser splits a chain into scope + target on purpose —
44
+ // `page.getByRole('navigation').getByText('Login')` addresses "Login" INSIDE
45
+ // the navigation landmark — and then this function used to ignore the scope
46
+ // entirely, searching the whole page instead. Mostly that passed by luck with
47
+ // an ambiguous match; for a relative target like `locator('xpath=..')` it
48
+ // resolves from the document root and matches nothing at all.
49
+ const scope = event.hints?.scope;
50
+ let base = root;
51
+ if (Array.isArray(scope)) {
52
+ for (const raw of scope) {
53
+ if (typeof raw !== 'string')
54
+ continue;
55
+ const value = raw.slice(raw.indexOf('=') + 1);
56
+ if (!value)
57
+ continue;
58
+ if (raw.startsWith('role='))
59
+ base = base.getByRole(value);
60
+ else if (raw.startsWith('css='))
61
+ base = base.locator(value);
62
+ else if (raw.startsWith('name='))
63
+ base = base.getByText(value);
64
+ }
65
+ }
66
+ // A name written as a regex in the source stays a regex here. `event.name`
67
+ // holds the SOURCE, which for something like `Version 2\.5` is not the
68
+ // accessible name and would match nothing as a literal.
69
+ const name = event.hints?.nameRegex
70
+ ? new RegExp(event.name, String(event.hints.nameFlags ?? ''))
71
+ : event.name;
72
+ if (event.role && event.name) {
73
+ locator = base.getByRole(event.role, {
74
+ name,
75
+ ...(event.exact ? { exact: true } : {}),
76
+ });
77
+ }
78
+ else if (event.name) {
79
+ locator = base.getByText(name, event.exact ? { exact: true } : {});
80
+ }
81
+ else if (event.role) {
82
+ locator = base.getByRole(event.role);
83
+ }
84
+ else if (event.css) {
85
+ locator = base.locator(event.css);
86
+ }
87
+ // Test id is a FALLBACK, not the first choice: role+name is what the whole
88
+ // system keys on (selector dedupe, sig(), binding), so replay should prove
89
+ // that addressing works rather than quietly succeeding by another route.
90
+ //
91
+ // Built as an explicit attribute selector rather than getByTestId, which
92
+ // only consults `data-testid` unless reconfigured globally — saucedemo uses
93
+ // `data-test`, so every step resolved to nothing until this was recorded.
94
+ if (!locator && event.testId) {
95
+ const attr = event.testIdAttr ?? 'data-testid';
96
+ locator = base.locator(`[${attr}="${event.testId.replace(/"/g, '\\"')}"]`);
97
+ }
98
+ if (!locator && event.css)
99
+ locator = base.locator(event.css);
100
+ if (!locator)
101
+ return undefined;
102
+ // FILTER BEFORE NTH — that is the order the source wrote them in, and the
103
+ // two do not commute. `locator('label').filter({hasText:/^No$/}).nth(1)` is
104
+ // "the second label saying No"; applying nth first would give "the second
105
+ // label on the page, if it happens to say No".
106
+ const hasText = event.hints?.hasText;
107
+ if (hasText !== undefined) {
108
+ locator = locator.filter({
109
+ hasText: event.hints?.hasTextRegex
110
+ ? new RegExp(hasText, String(event.hints.hasTextFlags ?? ''))
111
+ : hasText,
112
+ });
113
+ }
114
+ const nth = event.hints?.nth ?? undefined;
115
+ if (nth !== undefined)
116
+ locator = nth < 0 ? locator.last() : locator.nth(nth);
117
+ return locator;
118
+ }
119
+ /**
120
+ * Wait until the URL has stopped changing.
121
+ *
122
+ * Deliberately polling rather than `waitForLoadState`: these are client-side
123
+ * route changes, so there is no document load to wait on — the URL simply
124
+ * changes a few hundred milliseconds after the action that caused it. Requiring
125
+ * a quiet period rather than a single reading is what distinguishes "settled"
126
+ * from "has not started yet".
127
+ */
128
+ async function waitForUrlSettled(page, opts = {}, quietMs = 400, budgetMs = 5000) {
129
+ const deadline = Date.now() + budgetMs;
130
+ let last = page.url();
131
+ let unchangedSince = Date.now();
132
+ // A NAVIGATION HAS TO BE GIVEN TIME TO START.
133
+ //
134
+ // "Unchanged for 400ms" is trivially true in the instant after a click, so
135
+ // without this the function returned before the redirect began and the sig
136
+ // was taken on the page being LEFT. That is not theoretical: it put
137
+ // `/auth/otp` in as the end state of the login segment, and because segments
138
+ // dedupe by slug that wrong boundary overwrote a correct one and broke a
139
+ // composition that had been working.
140
+ //
141
+ // Only for actions that can navigate — adding a second to every fill would
142
+ // cost a minute on a sixty-step recording for nothing.
143
+ const graceUntil = opts.mayNavigate ? Date.now() + 1200 : 0;
144
+ while (Date.now() < deadline) {
145
+ await page.waitForTimeout(50);
146
+ const now = page.url();
147
+ if (now !== last) {
148
+ last = now;
149
+ unchangedSince = Date.now();
150
+ }
151
+ else if (Date.now() - unchangedSince >= quietMs && Date.now() >= graceUntil) {
152
+ return;
153
+ }
154
+ }
155
+ }
156
+ /** Actions that can trigger a navigation, and therefore need the grace above. */
157
+ const NAVIGATING_ACTIONS = new Set(['click', 'press', 'goto', 'select']);
158
+ /** Resolve a step's value, whether literal or a reference. */
159
+ function valueFor(event, values) {
160
+ if (event.value !== undefined)
161
+ return event.value;
162
+ if (event.valueRef === undefined)
163
+ return undefined;
164
+ return values[event.valueRef];
165
+ }
166
+ export async function replay(recording, opts = {}) {
167
+ const { values = {}, headless = true, timeoutMs = 10_000, captureBodies = true, visualCheck, onDecision, lessonsFor, storageState, prelude, onHandoff, budget, } = opts;
168
+ const maxAttempts = Math.max(1, budget?.stepAttempts ?? 1);
169
+ const handoffs = [];
170
+ const escalations = [];
171
+ const visualChecks = [];
172
+ // OWNERSHIP IS THE CALLER'S, NOT THE LEASE'S. A lease handed in belongs to
173
+ // whoever opened it and may well be replayed into again — closing it here
174
+ // would tear down the context a prelude just walked, one line before the
175
+ // recorder was going to capture from it.
176
+ const ownsLease = !opts.lease;
177
+ const lease = opts.lease ?? await openLease({ headless, ...(storageState ? { storageState } : {}) });
178
+ const page = lease.page;
179
+ const steps = [];
180
+ const sigSequence = [];
181
+ const signals = [];
182
+ const startedAt = Date.now();
183
+ // `currentStep` is what turns a pile of console noise into evidence: it is
184
+ // the correlation between a signal and the intent that was executing when it
185
+ // fired. A 500 is interesting; a 500 *during checkout* is a finding.
186
+ let currentStep = -1;
187
+ /** Route of the page we are on, so a lesson can be scoped to one page. */
188
+ let lastPattern;
189
+ page.on('console', (msg) => {
190
+ if (msg.type() !== 'error' && msg.type() !== 'warning')
191
+ return;
192
+ signals.push({ kind: 'console', duringStep: currentStep, text: msg.text().slice(0, 500) });
193
+ });
194
+ page.on('pageerror', (err) => {
195
+ signals.push({ kind: 'pageerror', duringStep: currentStep, text: String(err).slice(0, 500) });
196
+ });
197
+ page.on('requestfailed', (req) => {
198
+ signals.push({
199
+ kind: 'requestfailed',
200
+ duringStep: currentStep,
201
+ text: req.failure()?.errorText ?? 'request failed',
202
+ url: req.url(),
203
+ });
204
+ });
205
+ page.on('response', async (res) => {
206
+ const status = res.status();
207
+ const contentType = res.headers()['content-type'] ?? '';
208
+ const interesting = status >= 400 || contentType.includes('application/json');
209
+ if (!interesting)
210
+ return;
211
+ let body;
212
+ if (captureBodies && status >= 400) {
213
+ // Bodies can fail to read on redirects and aborted requests; a missing
214
+ // body should never take down the replay.
215
+ body = await res.text().then((t) => t.slice(0, MAX_BODY)).catch(() => undefined);
216
+ }
217
+ signals.push({
218
+ kind: 'http',
219
+ duringStep: currentStep,
220
+ text: `${res.request().method()} ${status}`,
221
+ url: res.url(),
222
+ status,
223
+ ...(body ? { body } : {}),
224
+ });
225
+ });
226
+ // The prelude is walked through the SAME step walker — a prelude step that
227
+ // silently behaved differently from a recorded one would be a second executor,
228
+ // which is the thing this file exists not to have.
229
+ const walk = [
230
+ ...(prelude ?? []).map((event) => ({ event, isPrelude: true })),
231
+ ...recording.events.map((event) => ({ event, isPrelude: false })),
232
+ ];
233
+ const preludeSteps = [];
234
+ let preludeFailed = false;
235
+ for (let i = 0; i < walk.length; i++) {
236
+ const { event, isPrelude } = walk[i];
237
+ currentStep = event.seq;
238
+ // Checked per step, so the wall-clock limit is honoured even on a run that
239
+ // never asks a question.
240
+ const budgetSpent = budget?.exceeded?.();
241
+ /** Set the instant an action goes out, so a retry cannot double-submit. */
242
+ let dispatched = false;
243
+ const stepStart = Date.now();
244
+ const outcome = { seq: event.seq, action: event.action, ok: false, durationMs: 0 };
245
+ // WHAT HAVE WE LEARNED ABOUT THIS STEP? Consulted BEFORE acting, because a
246
+ // lesson's whole purpose is "do Y first".
247
+ let applied = [];
248
+ if (lessonsFor) {
249
+ // For a goto the relevant page is the one being navigated TO — there is
250
+ // no previous page on the first step, and a lesson about a landing page
251
+ // would never fire if we only ever looked backwards.
252
+ const contextPattern = event.action === 'goto' && (event.value ?? event.url)
253
+ ? urlPattern(event.value ?? event.url)
254
+ : lastPattern;
255
+ applied = await lessonsFor({
256
+ ...(contextPattern ? { url_pattern: contextPattern } : {}),
257
+ action: event.action,
258
+ ...(event.role ? { role: event.role } : {}),
259
+ ...(event.name ? { name: event.name } : {}),
260
+ }).catch(() => []);
261
+ if (applied.length) {
262
+ outcome.lessonsApplied = applied.map((l) => ({ lessonId: l.lessonId, kind: l.kind, title: l.title }));
263
+ }
264
+ // A `wait` or `timing` lesson exists because something on this page
265
+ // resolves late. Settling before the action is the cheapest possible
266
+ // form of "do Y first".
267
+ //
268
+ // `timing` is included because that is what a distiller naturally calls
269
+ // it: the OTP lesson ("the code is validated asynchronously after the
270
+ // last digit, clicking Sign in immediately submits stale state") was
271
+ // written as `timing`, matched the step perfectly, and then did nothing
272
+ // — the lesson was right and the handler was too narrow to act on it.
273
+ if (applied.some((l) => SETTLE_KINDS.has(l.kind))) {
274
+ await waitForAriaStable(page, 2000).catch(() => { });
275
+ }
276
+ }
277
+ // THE ATTEMPT LOOP IS PURE CONTROL FLOW, not a reasoner round trip.
278
+ // Retrying by asking would make every retry human-speed, which is the
279
+ // opposite of the point — the budget exists to REDUCE escalations.
280
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
281
+ outcome.ok = false;
282
+ delete outcome.error;
283
+ try {
284
+ // AN UNRESOLVED SEAM MEANS "I DO NOT KNOW HOW TO GET FROM HERE TO
285
+ // THERE". Executing through it would start the next segment from a
286
+ // state it was never recorded in — a plan quietly doing the wrong thing
287
+ // rather than failing. Refusing here, with a browser open, is what lets
288
+ // a human record the bridge instead of the run simply dying.
289
+ const gap = event.hints?.seamGapBefore;
290
+ if (gap) {
291
+ throw new Error(`unresolved seam ${gap.from} -> ${gap.to}${gap.detail ? ` (${gap.detail})` : ''}`);
292
+ }
293
+ if (event.action === 'goto') {
294
+ const url = valueFor(event, values) ?? event.url;
295
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: timeoutMs });
296
+ outcome.ok = true;
297
+ }
298
+ else if (event.action === 'wait_url' || event.action === 'wait_text') {
299
+ // BOTH ARE PURE WAITS, so they are implemented here rather than left
300
+ // to escalate. Handing a human a browser and asking them to record a
301
+ // *wait* would be an absurd use of the handoff, and these are five
302
+ // lines. `dispatch_click` genuinely needs a decision and still
303
+ // escalates.
304
+ const expected = valueFor(event, values) ?? '';
305
+ if (!expected)
306
+ throw new Error(`${event.action} has no value to wait for`);
307
+ if (event.action === 'wait_url') {
308
+ // Substring, not equality: recordings carry concrete URLs while the
309
+ // thing worth waiting for is the route.
310
+ await page.waitForURL((u) => u.href.includes(expected), { timeout: timeoutMs });
311
+ }
312
+ else {
313
+ await page.getByText(expected).first().waitFor({ state: 'visible', timeout: timeoutMs });
314
+ }
315
+ outcome.ok = true;
316
+ }
317
+ else if (event.action === 'snapshot') {
318
+ // A checkpoint addresses no element — it is a moment, not a target.
319
+ // Settle first for the same reason sig() does: a picture taken
320
+ // mid-transition shows a layout that never existed, and would fail
321
+ // against every baseline including one taken from itself.
322
+ await waitForUrlSettled(page, { mayNavigate: true });
323
+ await waitForAriaStable(page, 1500);
324
+ if (visualCheck) {
325
+ const check = await captureCheckpoint(page, {
326
+ appSlug: visualCheck.appSlug,
327
+ runId: visualCheck.runId,
328
+ seq: event.seq,
329
+ label: event.value ?? `step-${event.seq}`,
330
+ });
331
+ visualChecks.push(check);
332
+ outcome.visual = check;
333
+ // SEVERE MEANS STOP. A third of the page changing is not a moved
334
+ // button; it is a blank render or an error screen, and sig() can
335
+ // miss both because landmarks survive. Driving the remaining steps
336
+ // into that produces cascading noise, not information.
337
+ if (!check.isNew && (check.ratio ?? 0) >= VISUAL_SEVERE) {
338
+ outcome.ok = false;
339
+ outcome.error =
340
+ `visual checkpoint "${check.label}" changed by ` +
341
+ `${((check.ratio ?? 0) * 100).toFixed(1)}% — stopping rather than running on`;
342
+ }
343
+ else {
344
+ outcome.ok = true;
345
+ }
346
+ }
347
+ else {
348
+ // Visual checking is opt-in: without a reasoner able to look at an
349
+ // image there is nobody to judge the result, and an unjudged diff is
350
+ // just a file on disk.
351
+ outcome.ok = true;
352
+ }
353
+ }
354
+ else {
355
+ // frame_hint is matched by SUFFIX, never exactly — iframe ids are
356
+ // routinely generated per session, and an exact match would fail on
357
+ // every run but the one that recorded it.
358
+ const root = event.frameHint
359
+ ? (page.frames().find((f) => f.url().includes(event.frameHint) || f.name().endsWith(event.frameHint)) ?? page)
360
+ : page;
361
+ let locator = locatorFor(root, event);
362
+ if (!locator)
363
+ throw new Error('step has no usable locator (no role, name, css or testId)');
364
+ // WAIT BEFORE COUNTING. `count()` is an instant poll — it does not
365
+ // auto-wait the way click()/fill() do. Against a server-rendered page
366
+ // that is invisible; against a client-rendered app the element simply
367
+ // has not been created yet, so every step failed in milliseconds with
368
+ // "locator matched no elements" and the 10s step timeout below never
369
+ // came into play.
370
+ //
371
+ // Waiting for `attached` rather than `visible` on purpose: a step may
372
+ // legitimately target something present but not visible (the sr-only
373
+ // radio inputs in these intake forms are exactly that).
374
+ await locator
375
+ .first()
376
+ .waitFor({ state: 'attached', timeout: timeoutMs })
377
+ .catch(() => {
378
+ // Genuinely absent. Fall through — count() reports 0 and the
379
+ // existing "matched no elements" error is still the right one.
380
+ });
381
+ // Count second: a locator matching several elements is a latent flake,
382
+ // and knowing that is worth more than the step passing by luck.
383
+ outcome.matched = await locator.count();
384
+ // ROLE CAN MATCH NOTHING BY DESIGN, NOT JUST BY DRIFT.
385
+ //
386
+ // getByRole() excludes elements with no real ARIA semantics — a plain
387
+ // div/span used as a click target (no button, no link, no aria-*) is
388
+ // "generic" and Playwright's role engine will never surface it, no
389
+ // matter how accurately the name was captured live. That is not page
390
+ // drift to report and give up on; a test id or raw css captured on the
391
+ // same step addresses the same element a different way, and this is
392
+ // exactly the "last resort" locatorFor's own docstring describes but
393
+ // never actually reached for. Only tried when the primary attempt used
394
+ // role — a locator already built from testId or css failing means the
395
+ // element is actually gone, and retrying it here would be pointless.
396
+ if (outcome.matched === 0 && event.role) {
397
+ const attr = event.testIdAttr ?? 'data-testid';
398
+ // Tried in order of how much each is worth trusting, and the visible
399
+ // TEXT is the one that survives a redesign: a css path captured
400
+ // before class-name escaping shipped can be syntactically invalid
401
+ // (Tailwind's `hover:` and `[16px]`), and re-escaping it after the
402
+ // fact cannot be done safely — splitting `py-3.5` on the dot that
403
+ // separates classes produces two classes that were never there. Text
404
+ // needs no such repair, and for a div-as-button the accessible name
405
+ // IS what the user clicked on.
406
+ const candidates = [
407
+ ...(event.testId
408
+ ? [{ how: attr, locator: root.locator(`[${attr}="${event.testId.replace(/"/g, '\\"')}"]`) }]
409
+ : []),
410
+ ...(event.css ? [{ how: 'css', locator: root.locator(event.css) }] : []),
411
+ ...(event.name ? [{ how: 'text', locator: root.getByText(event.name, { exact: true }) }] : []),
412
+ ];
413
+ for (const candidate of candidates) {
414
+ await candidate.locator
415
+ .first()
416
+ .waitFor({ state: 'attached', timeout: timeoutMs })
417
+ // An invalid selector throws here rather than reporting nothing,
418
+ // and that must not abort the replay — the next candidate is
419
+ // exactly what it should fall through to.
420
+ .catch(() => { });
421
+ const count = await candidate.locator.count().catch(() => 0);
422
+ if (count > 0) {
423
+ outcome.roleHadNoMatch = { fellBackTo: candidate.how };
424
+ locator = candidate.locator;
425
+ outcome.matched = count;
426
+ break;
427
+ }
428
+ }
429
+ }
430
+ // AMBIGUITY IS NOT SUCCESS.
431
+ //
432
+ // "Add to cart" is the accessible name of six different buttons on
433
+ // saucedemo. Falling back to .first() makes the step pass by luck and
434
+ // records a locator that will pick a different product the moment the
435
+ // list reorders. When a more specific addressing was captured, use it
436
+ // to disambiguate — and remember that role+name alone was insufficient,
437
+ // because that is exactly what `selectors.fragility` needs to know.
438
+ if (outcome.matched > 1 && (event.testId || event.css)) {
439
+ const attr = event.testIdAttr ?? 'data-testid';
440
+ const specific = event.testId
441
+ ? root.locator(`[${attr}="${event.testId.replace(/"/g, '\\"')}"]`)
442
+ : root.locator(event.css);
443
+ // Guarded for the same reason the fallback chain above is: an
444
+ // unescaped Tailwind class path throws instead of matching nothing,
445
+ // and failing to disambiguate is not a reason to fail the step —
446
+ // it just means the ambiguity stands and gets reported.
447
+ const specificCount = await specific.count().catch(() => 0);
448
+ if (specificCount === 1) {
449
+ outcome.ambiguousByName = { matched: outcome.matched, disambiguatedBy: event.testId ? attr : 'css' };
450
+ locator = specific;
451
+ outcome.matched = 1;
452
+ }
453
+ }
454
+ if (outcome.matched === 0)
455
+ throw new Error('locator matched no elements');
456
+ const target = outcome.matched > 1 ? locator.first() : locator;
457
+ // Past this line the app may have been changed. Everything above is
458
+ // addressing, which is safe to try again; nothing below is.
459
+ dispatched = true;
460
+ switch (event.action) {
461
+ case 'click':
462
+ await target.click({ timeout: timeoutMs });
463
+ break;
464
+ case 'fill': {
465
+ const value = valueFor(event, values);
466
+ if (value === undefined) {
467
+ throw new Error(`no value for ${event.valueRef ?? 'field'} — pass it via --value ${event.valueRef}=…`);
468
+ }
469
+ await target.fill(value, { timeout: timeoutMs });
470
+ // ROUND-TRIP ASSERTION, generated rather than written by hand: the
471
+ // IR knows what went into which field, so it can check the value
472
+ // survived. Fields that silently reformat or reject input are a
473
+ // real defect class and this is free to detect.
474
+ const actual = await target.inputValue({ timeout: 2000 }).catch(() => undefined);
475
+ if (actual !== undefined && actual !== value) {
476
+ outcome.roundTripMismatch = { expected: value, actual };
477
+ }
478
+ break;
479
+ }
480
+ case 'press':
481
+ await target.press(valueFor(event, values) ?? 'Enter', { timeout: timeoutMs });
482
+ break;
483
+ case 'check':
484
+ await target.check({ timeout: timeoutMs });
485
+ break;
486
+ case 'uncheck':
487
+ await target.uncheck({ timeout: timeoutMs });
488
+ break;
489
+ case 'select': {
490
+ const value = valueFor(event, values);
491
+ if (value === undefined)
492
+ throw new Error('select step has no value');
493
+ await target.selectOption(value, { timeout: timeoutMs });
494
+ break;
495
+ }
496
+ case 'upload': {
497
+ const value = valueFor(event, values);
498
+ if (value === undefined)
499
+ throw new Error('upload step has no file path');
500
+ // A multi-file input is stored newline-joined, because the IR's
501
+ // value is a single string and a newline cannot occur in the
502
+ // hash-prefixed names the recorder writes.
503
+ const files = value.includes('\n') ? value.split('\n') : value;
504
+ await target.setInputFiles(files, { timeout: timeoutMs });
505
+ break;
506
+ }
507
+ case 'scroll_container': {
508
+ // TWO PHRASINGS, because scroll gates come in two shapes and the
509
+ // IR should be able to say which one it means.
510
+ //
511
+ // value 'bottom'/'top' — the TARGET IS THE PANE. Set its own
512
+ // scrollTop. This is the "scroll the summary to the end"
513
+ // gate, where the thing to scroll has no landmark inside it
514
+ // worth addressing and is reached by CSS.
515
+ // no value — the TARGET IS CONTENT INSIDE the pane.
516
+ // Ask Playwright to bring it into view and let it work out
517
+ // which ancestor actually scrolls. Preferred where a real
518
+ // element marks the end of the content, because it survives
519
+ // the pane's class names changing.
520
+ const where = valueFor(event, values);
521
+ if (where === 'bottom' || where === 'top') {
522
+ // Typed structurally rather than as `Element`: this project's
523
+ // tsconfig has no DOM lib, and the two properties used are the
524
+ // whole contract.
525
+ await target.evaluate((el, edge) => {
526
+ el.scrollTop = edge === 'bottom' ? el.scrollHeight : 0;
527
+ }, where);
528
+ }
529
+ else {
530
+ await target.scrollIntoViewIfNeeded({ timeout: timeoutMs });
531
+ }
532
+ // The gate is driven by a scroll LISTENER, and listeners are
533
+ // routinely throttled to an animation frame or debounced. Setting
534
+ // scrollTop and clicking in the same tick lands the click while the
535
+ // control is still disabled — which fails as "element is not
536
+ // enabled", pointing at the button rather than at the scroll that
537
+ // never registered. Two frames is enough for rAF-based handlers
538
+ // and costs nothing on flows that don't need it.
539
+ await page.waitForTimeout(120);
540
+ break;
541
+ }
542
+ default:
543
+ throw new Error(`replay does not implement action '${event.action}'`);
544
+ }
545
+ outcome.ok = true;
546
+ }
547
+ // Settle before fingerprinting: a sig taken mid-transition describes a
548
+ // state that never existed. Same lesson as explore.
549
+ //
550
+ // THE URL HAS TO SETTLE FIRST, and the aria budget alone does not
551
+ // guarantee it. A click that signs in returns quickly, then the client
552
+ // router pushes a new route a beat later — so the fingerprint was taken
553
+ // on the page being LEFT. That is not a cosmetic error: the sig after a
554
+ // segment's last step becomes its `end_state`, so the redirect got
555
+ // attributed to the NEXT segment and every state boundary shifted by one
556
+ // transition. The planner then rejects the semantically right segment
557
+ // ("starts at /overview, execution is at /auth/otp") and binds its
558
+ // neighbour instead.
559
+ await waitForUrlSettled(page, { mayNavigate: NAVIGATING_ACTIONS.has(event.action) });
560
+ await waitForAriaStable(page, 1500);
561
+ const sig = await computeSig(page);
562
+ outcome.sig = sig.sig;
563
+ lastPattern = sig.urlPattern;
564
+ // PRELUDE SIGS ARE NOT PART OF THE FLOW'S PATH. `sigSequence[0]` becomes
565
+ // the flow's `start_state` at ingest and `[last]` its `end_state`, so
566
+ // letting the prelude in shifts the whole boundary — and the consecutive-
567
+ // dedupe just below would additionally SWALLOW the recording's real first
568
+ // sig whenever it equals the prelude's last, silently, which is exactly
569
+ // the off-by-one the comment above is about.
570
+ if (!isPrelude && sigSequence[sigSequence.length - 1] !== sig.sig) {
571
+ sigSequence.push(sig.sig);
572
+ }
573
+ // AM I WHERE I EXPECTED TO BE?
574
+ //
575
+ // Both sides of this comparison already existed and were being discarded:
576
+ // the step recorded the sig it produced, and we compute the sig after
577
+ // every step regardless. Not comparing them meant execution could walk
578
+ // into a page the plan had never seen and notice nothing until a locator
579
+ // happened to miss.
580
+ if (event.expectedSig && event.expectedSig !== sig.sig) {
581
+ outcome.unexpectedPage = { expected: event.expectedSig, observed: sig.sig };
582
+ // THE ESCALATION. An unexpected page is not automatically wrong — an
583
+ // app may have gained a banner — but continuing blindly is how a run
584
+ // does something nobody asked for. Deterministic code cannot judge it,
585
+ // so it asks. With nobody to ask, it records and carries on.
586
+ if (onDecision) {
587
+ const question = {
588
+ step: event.seq,
589
+ action: event.action,
590
+ target: event.name ?? event.testId ?? event.css,
591
+ expected: event.expectedSig,
592
+ observed: sig.sig,
593
+ semantic: `after ${event.action} on "${event.name ?? '?'}"`,
594
+ };
595
+ const answer = await onDecision({ kind: 'unexpected_page', context: question });
596
+ escalations.push({ step: event.seq, kind: 'unexpected_page', question, answer });
597
+ if (answer.action === 'abort') {
598
+ outcome.error = `aborted by reasoner: ${String(answer.reason ?? 'unexpected page')}`;
599
+ outcome.ok = false;
600
+ }
601
+ }
602
+ }
603
+ }
604
+ catch (err) {
605
+ outcome.error = (err instanceof Error ? err.message : String(err)).split('\n')[0].slice(0, 200);
606
+ }
607
+ if (outcome.ok || attempt === maxAttempts)
608
+ break;
609
+ // A RETRY IS ONLY SAFE BEFORE THE ACTION WENT OUT. Re-clicking a button
610
+ // that navigated and then failed its fingerprint check submits twice.
611
+ // Retries are for ADDRESSING failures — "locator matched no elements", an
612
+ // attach timeout — which are the ones that actually heal on a second look.
613
+ if (dispatched)
614
+ break;
615
+ // A refusal is not a flake. Retrying an unresolved seam just waits.
616
+ if (event.hints?.seamGapBefore)
617
+ break;
618
+ // Without settling, attempt 2 fails identically in zero milliseconds and
619
+ // the whole loop is theatre.
620
+ await waitForAriaStable(page, 1500).catch(() => { });
621
+ outcome.attempts = attempt + 1;
622
+ }
623
+ // A step that FAILED is the other place judgement is needed: a missing
624
+ // element may be rot to heal or a genuine gap to ask about, and only the
625
+ // selector's health tells them apart.
626
+ if (!outcome.ok && onDecision && outcome.error && !outcome.error.startsWith('aborted by reasoner')) {
627
+ const question = {
628
+ step: event.seq,
629
+ action: event.action,
630
+ target: event.name ?? event.testId ?? event.css,
631
+ error: outcome.error,
632
+ matched: outcome.matched,
633
+ };
634
+ const answer = await onDecision({ kind: 'step_failed', context: question });
635
+ escalations.push({ step: event.seq, kind: 'step_failed', question, answer });
636
+ if (answer.action === 'continue') {
637
+ outcome.ok = true;
638
+ outcome.error = `${outcome.error} (continued by reasoner)`;
639
+ }
640
+ }
641
+ // THE HANDOFF. The executor has run out of ways to do this itself, so it
642
+ // asks a human to do the piece it cannot and carries on from wherever they
643
+ // got to. A prelude step is excluded: the prelude is how we reached the
644
+ // starting line, and a human patching it would be patching the wrong thing.
645
+ if (!outcome.ok && onHandoff && !isPrelude) {
646
+ const trigger = outcome.error?.includes('does not implement action')
647
+ ? 'unimplemented_action'
648
+ : event.hints?.seamGapBefore
649
+ ? 'unresolved_seam'
650
+ : budgetSpent
651
+ ? 'budget'
652
+ : 'step_attempts';
653
+ const here = await computeSig(page).catch(() => ({ sig: '(unknown)' }));
654
+ const request = {
655
+ trigger,
656
+ seq: event.seq,
657
+ reason: budgetSpent ?? outcome.error ?? 'step failed',
658
+ url: page.url(),
659
+ sig: here.sig,
660
+ ...(event.expectedSig ? { expectedSig: event.expectedSig } : {}),
661
+ storageState: await lease.context.storageState(),
662
+ failed: {
663
+ action: event.action,
664
+ ...(event.name ?? event.testId ?? event.css
665
+ ? { target: event.name ?? event.testId ?? event.css }
666
+ : {}),
667
+ error: outcome.error ?? 'step failed',
668
+ attempts: outcome.attempts ?? 1,
669
+ },
670
+ };
671
+ const handed = await onHandoff(request);
672
+ if (handed.action === 'adopt') {
673
+ // ADOPT, DO NOT RE-DRIVE. The handoff window shared this run's
674
+ // server-side session, so the work is already done over there. Replaying
675
+ // the captured steps here would walk a flow that has already moved on —
676
+ // locators gone, side effects applied twice.
677
+ if (handed.storageState)
678
+ await lease.reseed(handed.storageState);
679
+ await page.goto(handed.url, { waitUntil: 'domcontentloaded', timeout: timeoutMs }).catch(() => { });
680
+ await waitForUrlSettled(page, { mayNavigate: true });
681
+ await waitForAriaStable(page, 1500);
682
+ const landed = await computeSig(page);
683
+ // A handoff can take ten minutes, which is long enough for the session
684
+ // it was seeded from to expire. Verifying rather than assuming turns
685
+ // that into an ordinary escalation instead of a confusing failure later.
686
+ if (handed.sig && handed.sig !== landed.sig) {
687
+ outcome.error =
688
+ `handoff landed on ${landed.sig}, not the ${handed.sig} it reported`;
689
+ outcome.ok = false;
690
+ }
691
+ else {
692
+ outcome.ok = true;
693
+ outcome.viaHandoff = true;
694
+ delete outcome.error;
695
+ if (sigSequence[sigSequence.length - 1] !== landed.sig)
696
+ sigSequence.push(landed.sig);
697
+ outcome.sig = landed.sig;
698
+ lastPattern = landed.urlPattern;
699
+ }
700
+ handoffs.push({
701
+ seq: event.seq,
702
+ trigger,
703
+ reason: request.reason,
704
+ ...(handed.recordingHash ? { recordingHash: handed.recordingHash } : {}),
705
+ steps: handed.steps.length,
706
+ url: handed.url,
707
+ });
708
+ // A SEAM HANDOFF IS DIFFERENT FROM EVERY OTHER ONE. What the human
709
+ // recorded is the BRIDGE — how to get from the previous segment's end
710
+ // to this segment's start. This step is the destination's first step
711
+ // and has still not run. Clearing the marker and re-entering the same
712
+ // index runs it, now from the right place; marking it done would skip
713
+ // a real step and quietly shorten the flow.
714
+ if (outcome.ok && trigger === 'unresolved_seam') {
715
+ delete event.hints.seamGapBefore;
716
+ i--;
717
+ continue;
718
+ }
719
+ }
720
+ else if (handed.action === 'abort') {
721
+ outcome.error = `aborted at handoff: ${handed.reason ?? 'declined'}`;
722
+ }
723
+ // 'skip' leaves the failure exactly as it was — the run stops below.
724
+ }
725
+ outcome.durationMs = Date.now() - stepStart;
726
+ (isPrelude ? preludeSteps : steps).push(outcome);
727
+ // Stop at the first failure. Every later step assumes state this one was
728
+ // supposed to produce, so continuing yields cascading noise rather than
729
+ // more information.
730
+ if (!outcome.ok) {
731
+ preludeFailed = isPrelude;
732
+ break;
733
+ }
734
+ }
735
+ // THE VISUAL VERDICT, ONCE, AT THE END.
736
+ //
737
+ // Deliberately not per-checkpoint: a visual diff is a quality signal, not a
738
+ // safety one, so there is nothing to protect by stopping. Suspending mid-run
739
+ // would hold an open browser while a human-speed judge thinks, and a run
740
+ // cannot survive its process dying. Batching also lets the judge read the
741
+ // whole story — a diff at step 12 often only makes sense given step 40.
742
+ //
743
+ // The severe case already aborted above, where stopping did buy something.
744
+ const judgeable = worthJudging(visualChecks);
745
+ if (judgeable.length && onDecision) {
746
+ const question = {
747
+ checkpoints: judgeable.map((c) => ({
748
+ label: c.label,
749
+ step: c.seq,
750
+ changedFraction: Number((c.ratio ?? 0).toFixed(4)),
751
+ ...(c.resized ? { resized: true } : {}),
752
+ baselineImage: c.baselinePath,
753
+ currentImage: c.currentPath,
754
+ ...(c.diffPath ? { diffImage: c.diffPath } : {}),
755
+ })),
756
+ expects: {
757
+ verdicts: '[{ label, verdict: "regression" | "expected" | "noise", why }]',
758
+ note: 'OPEN THE IMAGE FILES before answering — the paths above are real files on ' +
759
+ 'disk and the changed fraction alone cannot tell a moved timestamp from a ' +
760
+ 'missing button. regression -> recorded as a finding; expected -> the current ' +
761
+ 'shot becomes the new baseline so it stops firing; noise -> ignored, baseline kept.',
762
+ },
763
+ };
764
+ const answer = await onDecision({
765
+ kind: 'visual_diff',
766
+ context: question,
767
+ }).catch(() => ({}));
768
+ escalations.push({ step: -1, kind: 'visual_diff', question, answer });
769
+ // ACCEPTING A BASELINE IS THE POINT. Without it an intentional redesign
770
+ // fires on every run forever, which is exactly how visual testing gets
771
+ // switched off.
772
+ const verdicts = Array.isArray(answer.verdicts) ? answer.verdicts : [];
773
+ for (const raw of verdicts) {
774
+ const v = raw;
775
+ if (v.verdict !== 'expected')
776
+ continue;
777
+ const check = judgeable.find((c) => c.label === v.label);
778
+ if (check)
779
+ await acceptBaseline(check).catch(() => { });
780
+ }
781
+ }
782
+ if (ownsLease)
783
+ await lease.close();
784
+ const failed = steps.filter((s) => !s.ok);
785
+ // A prelude that did not replay means the recording's own steps NEVER RAN.
786
+ // Calling that `needsReview` would quarantine a recording nothing was learned
787
+ // about, so it is reported as its own condition and `ok` is simply false.
788
+ const preludeOk = !preludeFailed;
789
+ return {
790
+ hash: recording.hash,
791
+ ...(prelude?.length ? { preludeSteps, preludeOk } : {}),
792
+ ok: preludeOk && failed.length === 0 && steps.length === recording.events.length,
793
+ // The gate. Anything that did not fully reproduce is quarantined from
794
+ // memory rather than partially ingested.
795
+ needsReview: preludeOk && (failed.length > 0 || steps.length !== recording.events.length),
796
+ steps,
797
+ sigSequence,
798
+ signals,
799
+ durationMs: Date.now() - startedAt,
800
+ escalations,
801
+ visualChecks,
802
+ handoffs,
803
+ };
804
+ }