@jeffawe/understudy 0.3.0 → 0.5.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 (42) hide show
  1. package/CHANGELOG.md +127 -0
  2. package/README.md +69 -160
  3. package/REASONER.md +76 -86
  4. package/dist/adapters/recorder/script.d.ts +25 -2
  5. package/dist/adapters/recorder/script.js +126 -31
  6. package/dist/core/outline.d.ts +43 -0
  7. package/dist/core/outline.js +121 -0
  8. package/dist/core/recording.d.ts +19 -1
  9. package/dist/core/recording.js +38 -2
  10. package/dist/core/replay.d.ts +62 -1
  11. package/dist/core/replay.js +162 -106
  12. package/dist/entry/cli.js +185 -30
  13. package/dist/entry/mcp.d.ts +2 -0
  14. package/dist/entry/mcp.js +128 -23
  15. package/dist/flows/destructive.js +1 -1
  16. package/dist/flows/distill.js +11 -6
  17. package/dist/flows/emit.d.ts +7 -0
  18. package/dist/flows/emit.js +26 -10
  19. package/dist/flows/execute.d.ts +12 -0
  20. package/dist/flows/execute.js +23 -16
  21. package/dist/flows/runs.d.ts +2 -0
  22. package/dist/flows/runs.js +7 -3
  23. package/dist/flows/save.d.ts +5 -2
  24. package/dist/flows/save.js +38 -23
  25. package/dist/flows/session.d.ts +176 -0
  26. package/dist/flows/session.js +383 -0
  27. package/dist/flows/variants.d.ts +81 -0
  28. package/dist/flows/variants.js +139 -0
  29. package/dist/memory/calibrate.d.ts +114 -0
  30. package/dist/memory/calibrate.js +260 -0
  31. package/dist/memory/pages.d.ts +34 -0
  32. package/dist/memory/pages.js +60 -0
  33. package/dist/memory/recall.d.ts +87 -25
  34. package/dist/memory/recall.js +242 -45
  35. package/dist/plan/planner.d.ts +11 -1
  36. package/dist/plan/planner.js +36 -19
  37. package/dist/store/app-settings.d.ts +26 -0
  38. package/dist/store/app-settings.js +49 -0
  39. package/dist/store/db.js +8 -1
  40. package/dist/store/reembed.js +18 -7
  41. package/dist/store/types.d.ts +50 -0
  42. package/package.json +3 -2
package/dist/entry/mcp.js CHANGED
@@ -14,6 +14,8 @@
14
14
  * understudy_record wait for the user to record a flow in their Chrome
15
15
  * understudy_save prove a recording by replaying it, then keep it as a flow (or prove a saved one)
16
16
  * understudy_app an app's settings — e.g. keep email fields as placeholders
17
+ * understudy_calibrate fit when recall calls a goal known, for one app and embedding model
18
+ * understudy_session explore in a browser Understudy drives; keep what worked as a flow
17
19
  *
18
20
  * Long-lived: reconnect (/mcp) after changing the source.
19
21
  */
@@ -30,9 +32,14 @@ import { collections } from '../store/db.js';
30
32
  import { startExtensionRecorder, extensionDir } from '../adapters/recorder/extension.js';
31
33
  import { saveRecording, loadRecording, recordingPath } from '../core/recording-store.js';
32
34
  import { editFlow, proveAndSave, proveFlow } from '../flows/save.js';
35
+ import { dropVariant, promoteVariant } from '../flows/variants.js';
36
+ import { startSession, step as sessionStep, look as sessionLook, saveSession, closeSession, closeAllSessions } from '../flows/session.js';
33
37
  import { MissingValuesError } from '../flows/execute.js';
34
- import { parseScript } from '../adapters/recorder/script.js';
38
+ import { parseScript, parseScriptSource } from '../adapters/recorder/script.js';
39
+ import { join } from 'node:path';
35
40
  import { setPlaceholders, appPlaceholders } from '../memory/placeholders.js';
41
+ import { setAppTimeout, timeoutFor } from '../store/app-settings.js';
42
+ import { calibrate } from '../memory/calibrate.js';
36
43
  import { VERSION } from './version.js';
37
44
  /**
38
45
  * Sent to the agent when it connects. EVERY session pays for this, used or not,
@@ -149,7 +156,7 @@ async function continueRun(state, opts) {
149
156
  }
150
157
  /** What a finished run tells the agent. */
151
158
  function report(state, out) {
152
- const { executed, recorded, plan, nowProven } = out;
159
+ const { executed, recorded, plan, nowProven, commit } = out;
153
160
  const r = executed.result;
154
161
  const byPerson = r.steps.filter((s) => s.viaHuman || s.viaHandoff);
155
162
  return {
@@ -157,6 +164,7 @@ function report(state, out) {
157
164
  runId: state.runId,
158
165
  plan,
159
166
  seams: state.seams,
167
+ ...(commit && r.stoppedBefore !== undefined ? { stoppedBefore: `step ${commit.index}, ${commit.reason}: its control was there and ready, and was not pressed — nothing after it ran` } : {}),
160
168
  failedSteps: r.steps.filter((s) => !s.ok).map((s) => ({ seq: s.seq, action: s.action, error: s.error, ...(s.saw ? { saw: s.saw } : {}) })),
161
169
  ...(byPerson.length ? { doneByAPerson: byPerson.map((s) => ({ seq: s.seq, how: s.viaHuman ? `human step, ${s.viaHuman === 'page' ? 'the page showed it done' : 'they said it was done'}` : 'a failed step they did by hand' })) } : {}),
162
170
  unexpectedPages: r.steps.filter((s) => s.unexpectedPage).map((s) => ({ seq: s.seq, ...s.unexpectedPage })),
@@ -173,12 +181,17 @@ function report(state, out) {
173
181
  ...(executed.staleSession ? { staleSession: executed.staleSession } : {}),
174
182
  };
175
183
  }
184
+ /** A branch or deploy's copy of flows, beside the main ones. */
185
+ /** Described once, on recall; REASONER.md says the rest. */
186
+ const variant = z.string().optional();
187
+ const baseUrl = z.string().optional();
176
188
  const values = z.record(z.string(), z.string()).optional()
177
189
  .describe('Login values you fetched yourself, e.g. {"SECRET.password":"…"}; otherwise read from the user\'s settings. Never stored. Never ask the user to paste one into chat.');
178
190
  server.registerTool('understudy_recall', {
179
191
  description: 'Call first: what memory knows about a goal — closest flows, notes, a verdict. Free; nothing runs. A known flow comes with its steps and needed login values: run it with understudy_run or drive it yourself, and tell the user which. Unknown: the user records it (understudy_record), or you drive it and save the script (understudy_save).',
180
- inputSchema: { app: z.string(), goal: z.string(), limit: z.number().int().positive().optional() },
181
- }, ({ app, goal, limit }) => wrap(() => recall(app, goal, { withSteps: true, ...(limit ? { limit } : {}) })));
192
+ inputSchema: { app: z.string(), goal: z.string(), limit: z.number().int().positive().optional(),
193
+ variant: variant.describe('A branch: its copies of flows.') },
194
+ }, ({ app, goal, limit, variant: v }) => wrap(() => recall(app, goal, { withSteps: true, ...(limit ? { limit } : {}), ...(v ? { variant: v } : {}) })));
182
195
  server.registerTool('understudy_run', {
183
196
  description: 'Plan a goal and run it headless (visible when a step needs a person). Start with dryRun. Returns a question for understudy_answer, "blocked" with why, or the result.',
184
197
  inputSchema: {
@@ -186,7 +199,8 @@ server.registerTool('understudy_run', {
186
199
  subGoals: z.array(z.string()).optional().describe('Skip the decompose question.'),
187
200
  dryRun: z.boolean().optional().describe('Plan only; open no browser.'),
188
201
  allowPurchases: z.boolean().optional(),
189
- values, headed: z.boolean().optional(),
202
+ stopBeforeCommit: z.boolean().optional(),
203
+ variant, baseUrl, values, headed: z.boolean().optional(),
190
204
  },
191
205
  }, (a) => wrap(async () => {
192
206
  const state = await start({
@@ -194,6 +208,8 @@ server.registerTool('understudy_run', {
194
208
  ...(a.subGoals ? { subGoals: a.subGoals } : {}),
195
209
  ...(a.dryRun ? { dryRun: true } : {}),
196
210
  ...(a.allowPurchases ? { allowPurchases: true } : {}),
211
+ ...(a.stopBeforeCommit ? { stopBeforeCommit: true } : {}),
212
+ ...(a.variant ? { variant: a.variant } : {}), ...(a.baseUrl ? { baseUrl: a.baseUrl } : {}),
197
213
  });
198
214
  if (a.values)
199
215
  valuesByRun.set(state.runId, a.values);
@@ -290,26 +306,45 @@ server.registerTool('understudy_record', {
290
306
  server.registerTool('understudy_save', {
291
307
  description: [
292
308
  'Keep a flow, proven by replaying it: the user\'s latest recording, a recording hash, or a Playwright script of a flow you drove.',
293
- 'A script is read, not run — literal page calls only: no loops, no values computed at runtime (a code from an email is a human step).',
294
- 'Understood: goto, click, dblclick, fill, type, press, check, uncheck, selectOption, setInputFiles, scrollIntoViewIfNeeded; getBy* locators, locator(css), frameLocator, filter({hasText}), first/last/nth;',
295
- 'inline expect(page | locator) checks of URL, title, visible, hidden, text, value, checked; page.waitForURL, waitForSelector, waitForResponse.',
296
- 'Other checks come back in droppedAssertions; calls that change the steps (evaluate, hover, route…) refuse the save.',
309
+ 'A script is read, not run: literal page calls only, no loops or runtime values.',
310
+ 'Understood: goto, click, fill, type, press, check, uncheck, selectOption, setInputFiles, scrollIntoViewIfNeeded; getBy*, locator(css), frameLocator, filter({hasText}), first/last/nth; inline expect() of URL, title, visible, hidden, text, value, checked; waitForURL, waitForSelector, waitForResponse, locator.waitFor().',
311
+ 'Unkept checks come back in droppedAssertions; a call or wait it can\'t replay refuses the save.',
297
312
  'Where only a person can act: human(\'what they do\', { untilText | untilUrl | untilResponse }).',
298
313
  ].join(' '),
299
314
  inputSchema: {
300
315
  app: z.string(), name: z.string().optional().describe('What the flow does, as someone would ask for it. Needed unless flow is given.'),
301
316
  flow: z.string().optional().describe('A saved flow to prove where it stands (e.g. one kept with verify false), instead of saving a new one.'),
302
317
  add: z.array(z.object({ before: z.number().int(), step: z.record(z.string(), z.unknown()) })).optional()
303
- .describe('With flow: steps to add first, each before step n. {"action":"human","value":"what they do","hints":{"untilText":"…"}}, {"action":"wait_response","value":"/api/visits","hints":{"method":"POST","status":201,"field":"commission.amount","above":0}}, {"action":"assert","role":"checkbox","name":"…","hints":{"assert":"checked"}}; also wait_url, wait_text.'),
318
+ .describe('With flow: steps to add, each before step n: human {value, hints:{untilText|untilUrl|untilResponse}}, wait_response {value:"/api/x", hints:{method,status,field,equals|above}}, assert {role,name,hints:{assert:"checked"}}, wait_url, wait_text.'),
304
319
  hash: z.string().optional(),
305
320
  script: z.string().optional().describe('Path to a Playwright script of a flow you drove; read passwords from process.env.'),
321
+ code: z.string().optional().describe('Or the code itself: e.g. the lines Playwright MCP printed for the steps that worked, as they came.'),
306
322
  intent: z.string().optional(), slug: z.string().optional(), values,
307
- verify: z.boolean().optional().describe('A flow that commits something real (a purchase, a submission) is replayed only up to that step, which is checked and never pressed. false: keep it without replaying at all; saved as unproven until a run passes.'),
323
+ variant: variant.describe('Save as this branch\'s copy; the main flow is untouched.'),
324
+ promote: z.boolean().optional().describe('With flow and variant: make the variant the main flow (the branch merged).'),
325
+ drop: z.boolean().optional().describe('With flow and variant: delete the copy; the variant uses the main flow again.'),
326
+ verify: z.boolean().optional().describe('A commit step (a purchase) is replayed only up to, never pressed. false: keep it with no replay, unproven until a run passes.'),
308
327
  note: z.string().optional().describe('With verify false: why, e.g. what you checked yourself.'),
309
328
  },
310
329
  }, (a) => wrap(async () => {
311
330
  if (a.flow) {
312
- const edited = a.add?.length ? await editFlow(a.app, a.flow, a.add) : undefined;
331
+ if (a.drop && a.promote)
332
+ throw new Error('drop or promote, not both');
333
+ if (a.drop) {
334
+ if (!a.variant)
335
+ throw new Error('drop needs the variant whose copy to delete');
336
+ return dropVariant(a.app, a.flow, a.variant);
337
+ }
338
+ if (a.promote) {
339
+ if (!a.variant)
340
+ throw new Error('promote needs the variant to make the main flow');
341
+ const p = await promoteVariant(a.app, a.flow, a.variant);
342
+ return {
343
+ ...p,
344
+ ...(p.staleSegments.length ? { note: `segments cut from the old main flow still hold its old steps: ${p.staleSegments.join(', ')} — distill '${p.flow}' again (ask the user first)` } : {}),
345
+ };
346
+ }
347
+ const edited = a.add?.length ? await editFlow(a.app, a.flow, a.add, a.variant) : undefined;
313
348
  if (edited && a.verify === false)
314
349
  return { flow: edited.slug, steps: edited.steps.length, unproven: edited.unprovenBecause };
315
350
  return { ...(edited ? { added: a.add.length } : {}), ...(await proveSaved(a.app, a.flow, a)) };
@@ -320,13 +355,18 @@ server.registerTool('understudy_save', {
320
355
  let rec;
321
356
  let madeBy = 'user';
322
357
  let dropped = [];
323
- if (a.script) {
324
- // A flow the agent drove: read its script into steps, exactly like `understudy import`.
358
+ if (a.script && a.code)
359
+ throw new Error('pass script (a path) or code (the code itself), not both');
360
+ if (a.script || a.code) {
361
+ // A flow the agent drove: read its code into steps, exactly like `understudy import`.
325
362
  const { apps } = await collections();
326
363
  const base = (await apps.findOne({ slug: a.app }))?.urls.default;
327
- const parsed = await parseScript(a.script, a.app, base);
364
+ // Inline code has no file: uploads are looked up from where the server runs.
365
+ const parsed = a.script
366
+ ? await parseScript(a.script, a.app, base)
367
+ : parseScriptSource(a.code, join(process.cwd(), 'inline-code.ts'), a.app, base);
328
368
  if (!parsed.recording.events.length)
329
- throw new Error(`no Playwright actions found in ${a.script} — expected calls like page.getByRole(...).click()`);
369
+ throw new Error(`no Playwright actions found in ${a.script ?? 'the code'} — expected calls like page.getByRole(...).click()`);
330
370
  if (parsed.warnings.length)
331
371
  throw new Error(`these calls in the script can't be replayed, so it wasn't kept — rewrite them as plain Playwright actions:\n- ${parsed.warnings.slice(0, 10).join('\n- ')}`);
332
372
  rec = parsed.recording;
@@ -339,7 +379,7 @@ server.registerTool('understudy_save', {
339
379
  throw new Error('the user is still recording — ask them to click "Stop" in the extension first');
340
380
  const hash = a.hash ?? finished.get(a.app)?.hash;
341
381
  if (!hash)
342
- throw new Error(`no finished recording for "${a.app}" — start one with understudy_record, pass a hash, or pass a script`);
382
+ throw new Error(`no finished recording for "${a.app}" — start one with understudy_record, pass a hash, or pass script or code`);
343
383
  rec = await loadRecording(hash);
344
384
  }
345
385
  const hash = rec.hash;
@@ -349,6 +389,7 @@ server.registerTool('understudy_save', {
349
389
  title: name, madeBy,
350
390
  ...(a.verify === false ? { verify: false, unproven: a.note ? `saved by an agent without a replay: ${a.note}` : 'saved by an agent without a replay' } : {}),
351
391
  ...(a.values ? { values: a.values } : {}), ...(a.intent ? { intent: a.intent } : {}), ...(a.slug ? { slug: a.slug } : {}),
392
+ ...(a.variant ? { variant: a.variant } : {}),
352
393
  });
353
394
  }
354
395
  catch (e) {
@@ -357,6 +398,12 @@ server.registerTool('understudy_save', {
357
398
  return { saved: false, ...missingValues(e, { tool: 'understudy_save', hash, name }) };
358
399
  throw e;
359
400
  }
401
+ return savedReport(a.app, rec, out, { madeBy, dropped, ...(a.script || a.code ? {} : { droppedUploads: finished.get(a.app)?.droppedUploads ?? 0 }) });
402
+ }));
403
+ /** What a save tells the agent — for `understudy_save` and a session's save alike. */
404
+ function savedReport(app, rec, out, extra) {
405
+ const { madeBy, dropped = [] } = extra;
406
+ const hash = rec.hash;
360
407
  const r = out.proven?.result;
361
408
  const base = {
362
409
  recording: hash,
@@ -368,7 +415,7 @@ server.registerTool('understudy_save', {
368
415
  failedSteps: r.steps.filter((s) => !s.ok).map((s) => ({ seq: s.seq, action: s.action, error: s.error, ...(s.saw ? { saw: s.saw } : {}) })),
369
416
  signIn: out.proven.signIn,
370
417
  } : { replayed: false }),
371
- ...(finished.get(a.app)?.droppedUploads ? { droppedUploads: finished.get(a.app).droppedUploads } : {}),
418
+ ...(extra.droppedUploads ? { droppedUploads: extra.droppedUploads } : {}),
372
419
  };
373
420
  if (!out.saved)
374
421
  return { saved: false, ...base, why: 'it did not replay cleanly, so it was not kept. Fix the step, or pass verify: false to keep it unproven.' };
@@ -384,10 +431,10 @@ server.registerTool('understudy_save', {
384
431
  ...(out.run ? { findings: out.run.findings.map((f) => f.statement) } : {}),
385
432
  ...(out.placeholders.converted.length ? { placeholders: out.placeholders.converted } : {}),
386
433
  };
387
- }));
434
+ }
388
435
  /** understudy_save with `flow`: prove a saved flow — up to its commit, if it has one. Records the run. */
389
436
  async function proveSaved(app, slug, a) {
390
- const out = await proveFlow(app, slug, a.values ? { values: a.values } : {});
437
+ const out = await proveFlow(app, slug, { ...(a.values ? { values: a.values } : {}), ...(a.variant ? { variant: a.variant } : {}) });
391
438
  const r = out.result;
392
439
  return {
393
440
  flow: out.flow.slug, passed: r.ok, newlyProven: out.newlyProven,
@@ -427,15 +474,73 @@ function provenUpTo(flow) {
427
474
  stoppedBefore: `step ${flow.provenUpTo}${s?.name ? ` ("${s.name}")` : ''}, its commit: the control was there and ready, and was not pressed — nothing after it has run`,
428
475
  };
429
476
  }
477
+ server.registerTool('understudy_session', {
478
+ description: [
479
+ 'Explore an app in a browser Understudy drives, and keep what worked as a flow.',
480
+ 'do: start {app, url} or {app, flow, upTo} (runs a saved flow first; to repair one, it stops where it fails), step {step}, look {within?}, save {name, keep?}, close.',
481
+ 'A step is a stored step, e.g. {"action":"click","role":"button","name":"Next"}; a password is valueRef "SECRET.password".',
482
+ 'step returns what changed; look, the page\'s controls (no field values). save proves the kept steps in a fresh browser, up to a commit. A commit step needs allowPurchases.',
483
+ ].join(' '),
484
+ inputSchema: {
485
+ do: z.enum(['start', 'step', 'look', 'save', 'close']),
486
+ session: z.string().optional(), app: z.string().optional(),
487
+ url: z.string().optional(), flow: z.string().optional(),
488
+ upTo: z.number().int().min(0).optional(),
489
+ headed: z.boolean().optional(), allowPurchases: z.boolean().optional(), variant, baseUrl: z.string().optional(),
490
+ values: z.record(z.string(), z.string()).optional().describe('Login values, as for run.'),
491
+ step: z.record(z.string(), z.unknown()).optional(),
492
+ within: z.string().optional(), name: z.string().optional(),
493
+ keep: z.array(z.number().int().min(0)).optional().describe('Session step numbers, in order. Default: every step that worked.'),
494
+ intent: z.string().optional(), slug: z.string().optional(),
495
+ },
496
+ }, (a) => wrap(async () => {
497
+ const need = (v, what) => {
498
+ if (v === undefined)
499
+ throw new Error(`${a.do} needs ${what}`);
500
+ return v;
501
+ };
502
+ switch (a.do) {
503
+ case 'start':
504
+ return startSession(defined({
505
+ app: need(a.app, 'app'), url: a.url, flow: a.flow, upTo: a.upTo, headed: a.headed, values: a.values, allowPurchases: a.allowPurchases,
506
+ variant: a.variant, baseUrl: a.baseUrl,
507
+ }));
508
+ case 'step': return sessionStep(need(a.session, 'session'), need(a.step, 'step'));
509
+ case 'look': return sessionLook(need(a.session, 'session'), a.within);
510
+ case 'save': {
511
+ const { recording: rec, out, suggestions } = await saveSession(need(a.session, 'session'), defined({ name: need(a.name, 'name'), keep: a.keep, intent: a.intent, slug: a.slug, variant: a.variant }));
512
+ return { ...savedReport(rec.appSlug, rec, out, { madeBy: 'agent' }), ...(suggestions ? { suggestions } : {}) };
513
+ }
514
+ case 'close': return closeSession(need(a.session, 'session'));
515
+ }
516
+ }));
430
517
  server.registerTool('understudy_app', {
431
518
  description: 'An app\'s settings. placeholders ["email"] keeps email addresses out of memory: they become placeholders, and the values move to the user\'s env file.',
432
519
  inputSchema: {
433
520
  app: z.string(),
434
521
  placeholders: z.array(z.enum(['email'])).optional().describe('[] turns it off for new flows.'),
522
+ timeoutMs: z.number().int().nullable().optional(),
435
523
  },
436
- }, ({ app, placeholders }) => wrap(async () => {
524
+ }, ({ app, placeholders, timeoutMs }) => wrap(async () => {
525
+ const set = timeoutMs !== undefined ? await setAppTimeout(app, timeoutMs) : undefined;
437
526
  if (placeholders)
438
- return setPlaceholders(app, placeholders);
439
- return { app, placeholders: await appPlaceholders(app) };
527
+ return { ...(await setPlaceholders(app, placeholders)), ...(set ? { timeoutMs: set.timeoutMs ?? 'default' } : {}) };
528
+ return { app, placeholders: await appPlaceholders(app), timeoutMs: (await timeoutFor(app)) ?? 'default (10000)' };
440
529
  }));
530
+ server.registerTool('understudy_calibrate', {
531
+ description: 'Fit when recall calls a goal "known", for this app and embedding model — needed after switching models, or when recall calls the wrong things known (its `cutoffs.source` says "uncalibrated"). Give 2–3 rewordings per flow (not its own title) and 5+ goals that sound like the app but that it has no flow for; they are kept, so later calls and `understudy reembed` re-fit from them. Tell the user the before/after and any mistakes.',
532
+ inputSchema: {
533
+ app: z.string(),
534
+ known: z.array(z.object({ flow: z.string().describe('the flow\'s slug'), goals: z.array(z.string()) })).optional(),
535
+ unknown: z.array(z.string()).optional(),
536
+ dryRun: z.boolean().optional().describe('fit and report, keep nothing'),
537
+ },
538
+ }, ({ app, known, unknown, dryRun }) => wrap(() => calibrate(app, {
539
+ goals: { known: (known ?? []).flatMap((k) => k.goals.map((goal) => ({ flow: k.flow, goal }))), unknown: unknown ?? [] },
540
+ ...(dryRun ? { dryRun } : {}),
541
+ })));
542
+ // Each open session is a browser: close them when the client goes.
543
+ for (const signal of ['SIGINT', 'SIGTERM'])
544
+ process.once(signal, () => { void closeAllSessions().finally(() => process.exit(0)); });
545
+ process.stdin.once('end', () => { void closeAllSessions(); });
441
546
  await server.connect(new StdioServerTransport());
@@ -12,7 +12,7 @@
12
12
  * boundaries, facts, other destructive flows). They return with the safety
13
13
  * gate in phase 3 — see `git show legacy-cockroach:src/core/destructive.ts`.
14
14
  */
15
- const COMMIT_WORDS = /\b(pay|purchase|buy|place order|order now|checkout|check out|confirm|delete|remove account|reset|deactivate|destroy|publish|subscribe|charge|submit order)\b/i;
15
+ const COMMIT_WORDS = /\b(pay|purchase|buy|book|place order|order now|checkout|check out|confirm|delete|remove account|reset|deactivate|destroy|publish|subscribe|charge|submit order)\b/i;
16
16
  const PAYMENT_HOSTS = /(^|\.)(stripe|paypal|braintree|adyen|checkout|squareup|klarna|worldpay|authorize)\.(com|net|io)$/i;
17
17
  /**
18
18
  * Only these actions can commit anything. Typing into "Confirm password" or
@@ -9,6 +9,7 @@
9
9
  * No replay here: a saved flow was proven when it was saved (or by a run since —
10
10
  * unproven ones are refused), so its steps and the page each one reached are on record.
11
11
  */
12
+ import { MAIN } from './variants.js';
12
13
  import { buildDistillRequest, validateDistilled } from '../core/distill.js';
13
14
  import { collections, ensureSchema } from '../store/db.js';
14
15
  import { embed, embedderConfig } from '../store/embed.js';
@@ -18,9 +19,13 @@ import { flowDestructiveReason } from './destructive.js';
18
19
  import { recordingFrom } from './save.js';
19
20
  async function loadFlow(app, slug) {
20
21
  const { flows } = await collections();
21
- const flow = await flows.findOne({ app, slug });
22
- if (!flow)
23
- throw new Error(`no flow '${slug}' for app '${app}'`);
22
+ const flow = await flows.findOne({ app, slug, ...MAIN });
23
+ if (!flow) {
24
+ const copy = await flows.findOne({ app, slug }, { projection: { variant: 1 } });
25
+ throw new Error(copy?.variant
26
+ ? `'${slug}' exists only as variant "${copy.variant}" — segments are cut from main flows; promote it first (understudy_save { flow, variant, promote: true })`
27
+ : `no flow '${slug}' for app '${app}'`);
28
+ }
24
29
  if (flow.kind !== 'recording')
25
30
  throw new Error(`'${slug}' is a segment — distill the recording it came from (${flow.from?.flow})`);
26
31
  // Distilling trusts every step to have passed; an unproven one may not have,
@@ -52,7 +57,7 @@ export async function saveDistilled(app, slug, answer) {
52
57
  const parentText = searchTextOf(flow.title, d.intent, d.outcome);
53
58
  // One request embeds the parent and every segment.
54
59
  const vectors = embedderConfig() ? await embed([parentText, ...segmentDocs.map((s) => s.searchText)], 'document') : [];
55
- await c.flows.updateOne({ app, slug }, {
60
+ await c.flows.updateOne({ app, slug, ...MAIN }, {
56
61
  $set: {
57
62
  intent: d.intent, outcome: d.outcome, preconditions: d.preconditions,
58
63
  requires: d.requires ?? [], establishes: d.establishes ?? [],
@@ -64,7 +69,7 @@ export async function saveDistilled(app, slug, answer) {
64
69
  for (const [i, seg] of segmentDocs.entries()) {
65
70
  // Reusing an existing slug REPLACES that segment: segments belong to the
66
71
  // app, so the same block from a new recording merges instead of competing.
67
- const existed = await c.flows.findOne({ app, slug: seg.slug }, { projection: { kind: 1 } });
72
+ const existed = await c.flows.findOne({ app, slug: seg.slug, ...MAIN }, { projection: { kind: 1 } });
68
73
  if (existed && existed.kind !== 'segment')
69
74
  throw new Error(`"${seg.slug}" is already a recorded flow's slug — pick another for the segment`);
70
75
  const unset = {};
@@ -72,7 +77,7 @@ export async function saveDistilled(app, slug, answer) {
72
77
  unset.embedding = '';
73
78
  if (!seg.destructiveBecause)
74
79
  unset.destructiveBecause = '';
75
- await c.flows.updateOne({ app, slug: seg.slug }, { $set: { ...seg, ...(vectors[i + 1] ? { embedding: vectors[i + 1] } : {}), updatedAt: now }, $setOnInsert: { createdAt: now }, ...(Object.keys(unset).length ? { $unset: unset } : {}) }, { upsert: true });
80
+ await c.flows.updateOne({ app, slug: seg.slug, ...MAIN }, { $set: { ...seg, ...(vectors[i + 1] ? { embedding: vectors[i + 1] } : {}), updatedAt: now }, $setOnInsert: { createdAt: now }, ...(Object.keys(unset).length ? { $unset: unset } : {}) }, { upsert: true });
76
81
  saved.push({ slug: seg.slug, steps: seg.steps.length, replaced: Boolean(existed) });
77
82
  }
78
83
  const lessons = d.candidateLessons?.length
@@ -20,4 +20,11 @@ export interface Emitted {
20
20
  /** Value references the test reads from the environment. */
21
21
  requiredValues: string[];
22
22
  }
23
+ /**
24
+ * The variable a test reads a login value from: SECRET.password →
25
+ * UNDERSTUDY_SECRET_PASSWORD, the same one replay reads, so one setting serves
26
+ * both. `ENV.X` came from a script that read `process.env.X`, so the test reads
27
+ * X — the variable that script's author actually set.
28
+ */
29
+ export declare const envName: (ref: string) => string;
23
30
  export declare function emitFlow(flow: Flow, framework?: Framework): Emitted;
@@ -11,12 +11,17 @@
11
11
  *
12
12
  * Ported from the old emit.ts; it now reads the flow document directly.
13
13
  */
14
- import { forced, humanUntil, responseCheckOf, valueRefsOf } from '../core/recording.js';
14
+ import { forced, humanUntil, literalValue, responseCheckOf, valueRefsOf } from '../core/recording.js';
15
15
  import { urlGlob } from '../core/replay.js';
16
16
  import { valueEnvName } from '../store/settings.js';
17
17
  const quote = (s) => `'${s.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
18
- /** SECRET.password → UNDERSTUDY_SECRET_PASSWORD: the same variable replay reads, so one setting serves both. */
19
- const envName = valueEnvName;
18
+ /**
19
+ * The variable a test reads a login value from: SECRET.password →
20
+ * UNDERSTUDY_SECRET_PASSWORD, the same one replay reads, so one setting serves
21
+ * both. `ENV.X` came from a script that read `process.env.X`, so the test reads
22
+ * X — the variable that script's author actually set.
23
+ */
24
+ export const envName = (ref) => (ref.startsWith('ENV.') ? ref.slice(4) : valueEnvName(ref));
20
25
  const describe = (s) => `${s.action} ${s.role ?? ''} ${s.name ?? s.testId ?? s.css ?? ''}`.replace(/\s+/g, ' ').trim();
21
26
  /**
22
27
  * Narrowing replay applies after finding the element, in the same order:
@@ -49,16 +54,22 @@ const matcher = (s, flag, flags) => s.hints?.[flag] ? `/${s.value ?? ''}/${Strin
49
54
  function assertion(s, loc, value, pw, warn) {
50
55
  const kind = String(s.hints?.assert ?? 'visible');
51
56
  const expected = s.valueRef ? value : matcher(s, 'valueRegex', 'valueFlags');
57
+ // A step that may wait longer than the default says so in the test too.
58
+ const opt = typeof s.hints?.timeoutMs === 'number' ? `{ timeout: ${s.hints.timeoutMs} }` : '';
52
59
  if (pw) {
53
60
  switch (kind) {
54
61
  case 'title': return `await expect(page).toHaveTitle(${expected});`;
55
- case 'visible': return `await expect(${loc}).toBeVisible();`;
56
- case 'hidden': return `await expect(${loc}).toBeHidden();`;
62
+ case 'visible': return `await expect(${loc}).toBeVisible(${opt});`;
63
+ case 'hidden': return `await expect(${loc}).toBeHidden(${opt});`;
57
64
  case 'text': return `await expect(${loc}).toHaveText(${expected});`;
58
65
  case 'contains': return `await expect(${loc}).toContainText(${expected});`;
59
66
  case 'value': return `await expect(${loc}).toHaveValue(${expected});`;
60
- case 'checked': return `await expect(${loc}).toBeChecked();`;
61
- case 'unchecked': return `await expect(${loc}).not.toBeChecked();`;
67
+ case 'checked': return `await expect(${loc}).toBeChecked(${opt});`;
68
+ case 'unchecked': return `await expect(${loc}).not.toBeChecked(${opt});`;
69
+ case 'enabled': return `await expect(${loc}).toBeEnabled(${opt});`;
70
+ case 'disabled': return `await expect(${loc}).toBeDisabled(${opt});`;
71
+ case 'editable': return `await expect(${loc}).toBeEditable(${opt});`;
72
+ case 'focused': return `await expect(${loc}).toBeFocused(${opt});`;
62
73
  }
63
74
  }
64
75
  else {
@@ -74,6 +85,10 @@ function assertion(s, loc, value, pw, warn) {
74
85
  case 'value': return `${loc}.should('have.value', ${v});`;
75
86
  case 'checked': return `${loc}.should('be.checked');`;
76
87
  case 'unchecked': return `${loc}.should('not.be.checked');`;
88
+ case 'enabled': return `${loc}.should('be.enabled');`;
89
+ case 'disabled': return `${loc}.should('be.disabled');`;
90
+ case 'editable': return `${loc}.should('not.be.disabled').and('not.have.attr', 'readonly');`;
91
+ case 'focused': return `${loc}.should('have.focus');`;
77
92
  }
78
93
  }
79
94
  warn(`"${describe(s)}" is an assertion of a kind this output doesn't know (${kind}); skipped`);
@@ -81,7 +96,8 @@ function assertion(s, loc, value, pw, warn) {
81
96
  }
82
97
  /** `r => r.url().includes('/api/visits') && r.request().method() === 'POST' && r.status() === 201` */
83
98
  function responsePredicate(c) {
84
- const url = c.url.includes('*') ? `/${urlGlob(c.url).source}/.test(r.url())` : `r.url().includes(${quote(c.url)})`;
99
+ const url = c.regexFlags !== undefined ? `/${c.url}/${c.regexFlags}.test(r.url())`
100
+ : c.url.includes('*') ? `/${urlGlob(c.url).source}/.test(r.url())` : `r.url().includes(${quote(c.url)})`;
85
101
  return `(r) => ${[url, c.method && `r.request().method() === ${quote(c.method)}`, c.status !== undefined && `r.status() === ${c.status}`].filter(Boolean).join(' && ')}`;
86
102
  }
87
103
  /** `body.items[0].id` as optional chaining, so a missing field fails the expect, not the line. */
@@ -93,7 +109,7 @@ function playwrightResponseCheck(c, name) {
93
109
  return [`expect(${v})${c.equals !== undefined ? `.toBe(${JSON.stringify(c.equals)})` : c.above !== undefined ? `.toBeGreaterThan(${c.above})` : '.toBeDefined()'};`];
94
110
  }
95
111
  function cypressIntercept(c, name) {
96
- const url = c.url.includes('*') ? quote(c.url) : `new RegExp(${quote(c.url.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))})`;
112
+ const url = c.regexFlags !== undefined ? `/${c.url}/${c.regexFlags}` : c.url.includes('*') ? quote(c.url) : `new RegExp(${quote(c.url.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))})`;
97
113
  return `cy.intercept({ ${c.method ? `method: ${quote(c.method)}, ` : ''}url: ${url} }).as(${quote(name)});`;
98
114
  }
99
115
  function cypressResponseCheck(c, name) {
@@ -154,7 +170,7 @@ export function emitFlow(flow, framework = 'playwright-ts') {
154
170
  const pageLevel = ['goto', 'wait_url', 'wait_text', 'wait_response', 'human'].includes(s.action) || (s.action === 'assert' && s.hints?.assert === 'title');
155
171
  const loc = pageLevel ? '' : narrow(s, pw ? playwrightLocator(s, warn) : cypressLocator(s, warn), pw, warn);
156
172
  const ref = valueRefsOf([s])[0];
157
- const value = ref ? (required.add(ref), envName(ref).replace(/^UNDERSTUDY_/, '')) : quote(s.value ?? (s.action === 'goto' ? s.url : ''));
173
+ const value = ref ? (required.add(ref), envName(ref).replace(/^UNDERSTUDY_/, '')) : quote(literalValue(s) ?? (s.action === 'goto' ? s.url : ''));
158
174
  // Both frameworks spell it the same way.
159
175
  const force = forced(s) ? '{ force: true }' : '';
160
176
  switch (s.action) {
@@ -9,6 +9,7 @@
9
9
  * the MCP server. Throws with a readable message instead of printing, so each
10
10
  * caller decides how to show it.
11
11
  */
12
+ import { type StorageState } from '../core/auth-cache.js';
12
13
  import { type RawRecording } from '../core/recording.js';
13
14
  import { type ReplayOptions, type ReplayResult } from '../core/replay.js';
14
15
  /** A login value a recording needs, and where it may be set. */
@@ -50,6 +51,8 @@ export interface ExecuteOptions {
50
51
  onStuck?: (stuck: StuckStep) => Promise<'done' | 'abort'>;
51
52
  /** Read the last page into `result.endChecks`, after a full pass. */
52
53
  endChecks?: boolean;
54
+ /** How long a step may wait. Default: the app's setting, else UNDERSTUDY_TIMEOUT_MS, else replay's 10 s. */
55
+ timeoutMs?: number;
53
56
  }
54
57
  /** A step that failed, put to a person who can see the browser. */
55
58
  export interface StuckStep {
@@ -74,6 +77,15 @@ export interface Executed {
74
77
  };
75
78
  sessionRestoredFrom?: string;
76
79
  }
80
+ /**
81
+ * The saved session a recording that starts signed in needs. A late-armed
82
+ * recording starts signed in; a cold browser would land on a login page and
83
+ * fail somewhere confusing, so a missing one is an error, said plainly.
84
+ */
85
+ export declare function restoreSession(recording: RawRecording, values: Record<string, string>): Promise<{
86
+ storageState?: StorageState;
87
+ savedAt?: string;
88
+ }>;
77
89
  export declare function execute(recording: RawRecording, opts?: ExecuteOptions): Promise<Executed>;
78
90
  export interface Proven extends Executed {
79
91
  /** The recording as it should be saved: with `requiresSession` set, or its unneeded session dropped. */
@@ -14,6 +14,7 @@ import { valueRefsOf } from '../core/recording.js';
14
14
  import { replay } from '../core/replay.js';
15
15
  import { foldLessons, lessonsFor } from '../memory/notes.js';
16
16
  import { valuesFromEnv, valueEnvNames, reloadEnvFiles, writableEnvFile } from '../store/settings.js';
17
+ import { timeoutFor } from '../store/app-settings.js';
17
18
  /**
18
19
  * Thrown before any browser opens when login values are missing, so a caller
19
20
  * can ask for them (the terminal) or say where to put them (MCP), then retry.
@@ -39,6 +40,25 @@ export function missingValuesFor(recording, given = {}) {
39
40
  const found = { ...valuesFromEnv(refs, recording.appSlug), ...given };
40
41
  return [...refs].filter((r) => !(r in found)).map((r) => ({ placeholder: r, setOneOf: valueEnvNames(r, recording.appSlug) }));
41
42
  }
43
+ /**
44
+ * The saved session a recording that starts signed in needs. A late-armed
45
+ * recording starts signed in; a cold browser would land on a login page and
46
+ * fail somewhere confusing, so a missing one is an error, said plainly.
47
+ */
48
+ export async function restoreSession(recording, values) {
49
+ if (!recording.entry?.requiresSession)
50
+ return {};
51
+ const sessionId = recording.entry.session;
52
+ const cached = sessionId ? await loadSessionById(recording.appSlug, sessionId) : await loadSession(recording.appSlug, values);
53
+ if (!cached) {
54
+ throw new Error(sessionId
55
+ ? `this starts from the signed-in tab it was recorded in, and that saved session (${sessionId}) is gone or older ` +
56
+ 'than 12 hours — record it again from the extension, or start the plan with a flow that logs in'
57
+ : 'this starts from a signed-in browser, and no saved session matches these credentials — pass the same ' +
58
+ '--value credentials it was recorded with, re-record with --arm-manually, or start the plan with a flow that logs in');
59
+ }
60
+ return { storageState: cached.storageState, savedAt: cached.savedAt };
61
+ }
42
62
  export async function execute(recording, opts = {}) {
43
63
  if (recording.entry?.prelude?.length) {
44
64
  throw new Error(`this starts after other flows (${recording.entry.prelude.join(' -> ')}), and preludes are parked in the rewrite — ` +
@@ -56,30 +76,17 @@ export async function execute(recording, opts = {}) {
56
76
  if (missingValues.length) {
57
77
  throw new MissingValuesError(missingValues.map((r) => ({ placeholder: r, setOneOf: valueEnvNames(r, recording.appSlug) })));
58
78
  }
59
- // A late-armed recording starts signed in; a cold browser would land on a
60
- // login page and fail somewhere confusing.
61
- let storageState;
62
- let sessionRestoredFrom;
79
+ const { storageState, savedAt: sessionRestoredFrom } = await restoreSession(recording, values);
63
80
  const sessionId = recording.entry?.session;
64
- if (recording.entry?.requiresSession) {
65
- const cached = sessionId ? await loadSessionById(recording.appSlug, sessionId) : await loadSession(recording.appSlug, values);
66
- if (!cached) {
67
- throw new Error(sessionId
68
- ? `this starts from the signed-in tab it was recorded in, and that saved session (${sessionId}) is gone or older ` +
69
- 'than 12 hours — record it again from the extension, or start the plan with a flow that logs in'
70
- : 'this starts from a signed-in browser, and no saved session matches these credentials — pass the same ' +
71
- '--value credentials it was recorded with, re-record with --arm-manually, or start the plan with a flow that logs in');
72
- }
73
- storageState = cached.storageState;
74
- sessionRestoredFrom = cached.savedAt;
75
- }
76
81
  const app = recording.appSlug;
77
82
  // A person's step needs a browser they can see — unless told otherwise (CI).
78
83
  const forPerson = Boolean(opts.onHuman) && recording.events.some((e) => e.action === 'human') && process.env.UNDERSTUDY_HEADLESS !== '1';
79
84
  const headed = Boolean(opts.headed) || forPerson;
80
85
  const onStuck = opts.onStuck;
86
+ const timeoutMs = opts.timeoutMs ?? (await timeoutFor(app));
81
87
  const result = await replay(recording, {
82
88
  values,
89
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
83
90
  ...(storageState ? { storageState } : {}),
84
91
  ...(headed ? { headless: false } : {}),
85
92
  ...(opts.onHuman ? { onHuman: opts.onHuman } : {}),
@@ -28,6 +28,8 @@ export declare function recordRun(opts: {
28
28
  steps: Step[];
29
29
  /** 'replay' when a flow was named; 'run' when it was found from a goal. */
30
30
  mode?: 'replay' | 'run';
31
+ /** Run with this variant's flows. Its history is compared with its own runs only. */
32
+ variant?: string;
31
33
  /** What was asked for. Defaults to the flow's slug. */
32
34
  goal?: string;
33
35
  /** The flows run, in order, when it was more than one. Defaults to [flow]. */
@@ -12,6 +12,7 @@ import { collections } from '../store/db.js';
12
12
  import { compareToHistory, driftFinding } from './drift.js';
13
13
  import { extractFindings, saveFindings } from './findings.js';
14
14
  import { stepFingerprint } from '../core/fingerprint.js';
15
+ import { resolveFlow, runsOf } from './variants.js';
15
16
  /** `/inventory.html#bf3dd322` → `/inventory.html` */
16
17
  const pageOf = (sig) => sig.slice(0, sig.lastIndexOf('#')) || sig;
17
18
  /** How many recent passed runs drift compares with. */
@@ -24,7 +25,7 @@ export async function recordRun(opts) {
24
25
  // 1. Drift, against the most recent passed runs of this flow — however it
25
26
  // was started, it walked the same steps.
26
27
  const history = await c.runs
27
- .find({ app, plan, mode: { $in: ['replay', 'run'] }, status: 'passed', stoppedBefore: { $exists: false }, accepted: { $ne: false }, ...(opts.runId ? { _id: { $ne: opts.runId } } : {}) }, { projection: { sigSequence: 1 } })
28
+ .find({ app, plan, ...runsOf(opts.variant), mode: { $in: ['replay', 'run'] }, status: 'passed', stoppedBefore: { $exists: false }, accepted: { $ne: false }, ...(opts.runId ? { _id: { $ne: opts.runId } } : {}) }, { projection: { sigSequence: 1 } })
28
29
  .sort({ startedAt: -1 })
29
30
  .limit(LOOKBACK)
30
31
  .toArray();
@@ -55,7 +56,9 @@ export async function recordRun(opts) {
55
56
  continue;
56
57
  const step = steps[outcome.seq];
57
58
  const via = step?.role && step.name ? { role: step.role, name: step.name } : undefined;
58
- await c.pages.updateOne({ app, sig }, { $set: { lastSeen: now }, $setOnInsert: { app, sig, urlPattern: pageOf(sig), links: [], firstSeen: now } }, { upsert: true });
59
+ await c.pages.updateOne({ app, sig },
60
+ // What it looked like, kept so the next visit can say what changed.
61
+ { $set: { lastSeen: now, ...(outcome.outline ? { outline: outcome.outline, outlineAt: now } : {}) }, $setOnInsert: { app, sig, urlPattern: pageOf(sig), links: [], firstSeen: now } }, { upsert: true });
59
62
  // A link belongs to the page it leaves FROM: "on prev, clicking `via` leads to sig".
60
63
  if (prev && prev !== sig && via) {
61
64
  await c.pages.updateOne({ app, sig: prev }, { $addToSet: { links: { to: sig, via } } });
@@ -69,6 +72,7 @@ export async function recordRun(opts) {
69
72
  app,
70
73
  goal: opts.goal ?? flow,
71
74
  mode: opts.mode ?? 'replay',
75
+ ...(opts.variant ? { variant: opts.variant } : {}),
72
76
  status: result.ok ? 'passed' : 'failed',
73
77
  plan,
74
78
  steps: result.steps.map((s) => {
@@ -115,7 +119,7 @@ export async function acceptPaths(app, fingerprints) {
115
119
  const newest = pending.at(-1);
116
120
  const updated = [];
117
121
  for (const [i, slug] of newest.plan.entries()) {
118
- const flow = await c.flows.findOne({ app, slug });
122
+ const flow = await resolveFlow(app, slug, newest.variant);
119
123
  if (!flow)
120
124
  continue;
121
125
  const start = newest.starts?.[i] ?? 0;