@jeffawe/understudy 0.5.1 → 0.6.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.
package/dist/entry/cli.js CHANGED
@@ -6,6 +6,7 @@
6
6
  * Argument parsing is hand-rolled on purpose: the surface is small, and a
7
7
  * parser library would be more code than it saves.
8
8
  */
9
+ import { overridesOf, varsOf, withDefaults } from '../core/vars.js';
9
10
  import { recordLive } from '../adapters/recorder/live.js';
10
11
  import { parseScript } from '../adapters/recorder/script.js';
11
12
  import { startExtensionRecorder, DEFAULT_PORT, extensionDir, firefoxExtensionDir } from '../adapters/recorder/extension.js';
@@ -23,7 +24,8 @@ import { join, resolve as resolvePath } from 'node:path';
23
24
  import { existsSync } from 'node:fs';
24
25
  import { chromium } from 'playwright';
25
26
  import { emitFlow, envName as emitEnvName } from '../flows/emit.js';
26
- import { editFlow, recordingFrom, proveAndSave, proveByRun, proveFlow } from '../flows/save.js';
27
+ import { editFlow, recordingFrom, proveAndSave, proveByRun, proveFlow, slugify } from '../flows/save.js';
28
+ import { extendRecording } from '../flows/extend.js';
27
29
  import { acceptPaths, recordRun } from '../flows/runs.js';
28
30
  import { listFindings, triage } from '../flows/findings.js';
29
31
  import { VERSION } from './version.js';
@@ -64,6 +66,9 @@ COMMANDS
64
66
  edit <app> <flow> --before <n> --step '<json>'
65
67
  add a step to a saved flow: a person's step or a wait, e.g.
66
68
  '{"action":"human","value":"Accept the visit","hints":{"untilText":"Accepted"}}'
69
+ edit <app> <flow> --at <n|id> --set '<json>' (or --remove)
70
+ change a step's fields (null clears one), or remove it;
71
+ a name or value may use {{var}}, with --var var=default
67
72
  findings <app> what looked broken, most severe first
68
73
  recall <app> "<goal>" what memory knows about a goal — nothing runs
69
74
  run <app> "<goal>" find the flow that does the goal, and run it
@@ -105,6 +110,8 @@ REPLAY and SAVE
105
110
  --base-url <url> run against the app at this address, e.g. a preview deploy
106
111
 
107
112
  SAVE
113
+ --extends <flow> it is that flow plus steps of its own: it follows that
114
+ flow's changes (the recording must do all of its steps)
108
115
  --slug <name> the flow's short name (default: made from the name)
109
116
  --intent <text> what the flow is for, if different from its name
110
117
  --force save even though the proving replay failed
@@ -605,6 +612,8 @@ async function executeWithReport(recording, flags, opts) {
605
612
  }
606
613
  if (x.lessons?.fired)
607
614
  console.log(`lessons ${x.lessons.fired} fired, ${x.lessons.helped} on steps that have failed before\n`);
615
+ if (x.unusedValues?.length)
616
+ console.log(`note no step uses ${x.unusedValues.join(', ')} — misspelt? It was ignored\n`);
608
617
  return x.result;
609
618
  }
610
619
  /** `replay <hash>` runs a recording file; `replay <app> <flow>` runs a saved flow and records the run. */
@@ -636,14 +645,14 @@ async function runSavedFlow(app, slug, flags, how) {
636
645
  console.log(`variant ${variant} has no copy of '${slug}' — running the main flow`);
637
646
  // Up to the commit: the first step that commits something, counting facts.
638
647
  const untilCommit = flags.has('until-commit') && !flags.has('allow-purchases');
639
- const commit = untilCommit ? commitSteps(flow.steps, await destructiveControls(app))[0] : undefined;
648
+ const commit = untilCommit ? commitSteps(withDefaults(flow.steps, { ...flow.vars, ...valuesFromFlags(flags) }), await destructiveControls(app))[0] : undefined;
640
649
  // The safety gate: a destructive flow does something real every time it runs.
641
650
  if (!flags.has('allow-purchases') && !untilCommit) {
642
651
  if (flow.destructive) {
643
652
  fail(`'${slug}' is marked destructive (${flow.destructiveBecause}) — running it may place a real order`, 'pass --until-commit to run up to that step, or --allow-purchases if running it is genuinely fine');
644
653
  }
645
654
  const controls = await destructiveControls(app);
646
- const hit = flow.steps.find((s) => s.name && ['click', 'press', 'dispatch_click'].includes(s.action) && controls.has(s.name.toLowerCase()));
655
+ const hit = withDefaults(flow.steps, { ...flow.vars, ...valuesFromFlags(flags) }).find((s) => s.name && ['click', 'press', 'dispatch_click'].includes(s.action) && controls.has(s.name.toLowerCase()));
647
656
  if (hit)
648
657
  fail(`'${slug}' clicks "${hit.name}", which a fact says commits something real: ${controls.get(hit.name.toLowerCase())}`, 'pass --allow-purchases if that is genuinely fine');
649
658
  }
@@ -658,11 +667,12 @@ async function runSavedFlow(app, slug, flags, how) {
658
667
  console.log(`stopping before step ${commit.index}: ${commit.reason}\n`);
659
668
  const result = await executeWithReport(recording, flags, { useLessons: true, ...(commit ? { stopBefore: recording.events[commit.index].seq } : {}) });
660
669
  printReplay(result);
670
+ const vars = overridesOf(varsOf(flow.steps), flow.vars, valuesFromFlags(flags));
661
671
  const run = await recordRun({
662
672
  app, flow: slug, result, steps: flow.steps, mode: how.mode, ...(how.goal ? { goal: how.goal } : {}), ...(flow.proven === false ? { unproven: true } : {}),
663
- ...(variant ? { variant } : {}),
673
+ ...(variant ? { variant } : {}), vars,
664
674
  });
665
- if (await proveByRun(app, slug, result, 0, variant))
675
+ if (await proveByRun(app, slug, result, 0, variant, vars))
666
676
  console.log(`\nproven '${slug}' passed, so it's no longer marked unproven`);
667
677
  printRunReport(run);
668
678
  if (!result.ok)
@@ -899,10 +909,16 @@ async function cmdSave(positional, flags) {
899
909
  if (!hash || !titleWords.length) {
900
910
  fail('save needs a recording hash and a name', 'understudy save <hash> "log in as a member"');
901
911
  }
902
- const recording = await loadRecording(hash).catch(() => fail(`no recording '${hash}'`, 'understudy recordings'));
912
+ const loaded = await loadRecording(hash).catch(() => fail(`no recording '${hash}'`, 'understudy recordings'));
903
913
  const slug = str(flags.get('slug'));
904
914
  const intent = str(flags.get('intent'));
915
+ const base = str(flags.get('extends'));
916
+ const ext = base
917
+ ? await extendRecording(loaded, base, { slug: slug ?? slugify(titleWords.join(' ')), ...(variantFlag(flags) ? { variant: variantFlag(flags) } : {}) }).catch((e) => fail(e.message))
918
+ : undefined;
919
+ const recording = ext?.recording ?? loaded;
905
920
  await saveAndReport(recording, titleWords.join(' '), {
921
+ ...(ext ? { extends: ext.extends } : {}),
906
922
  values: valuesFromFlags(flags), headed: flags.has('headed'),
907
923
  verify: !flags.has('no-verify'), force: flags.has('force'),
908
924
  ...(slug ? { slug } : {}), ...(intent ? { intent } : {}),
@@ -1108,21 +1124,50 @@ function provenUpToNote(flow) {
1108
1124
  return `PROVEN UP TO step ${flow.provenUpTo}${s?.name ? ` ("${s.name}")` : ''}, its commit — found ready, not pressed. ` +
1109
1125
  'A full run with --allow-purchases proves the rest.';
1110
1126
  }
1111
- /** `edit <app> <flow> --before n --step '{…}'`: add a person's step or a wait to a saved flow. */
1127
+ /**
1128
+ * `edit <app> <flow>`: add a person's step or a wait (--before n --step '{…}'),
1129
+ * change or remove a step (--at n|id --set '{…}' | --remove), set {{var}}
1130
+ * defaults (--var name=value). One call, all checked before anything changes.
1131
+ */
1112
1132
  async function cmdEdit(positional, flags) {
1113
1133
  const app = positional[0] ?? fail('edit needs an app and a flow', `understudy edit myapp book-a-visit --before 3 --step '{"action":"human","value":"…"}'`);
1114
1134
  const slug = positional[1] ?? fail('edit needs a flow', `understudy flows ${app}`);
1115
- const before = Number(str(flags.get('before')) ?? fail('edit needs --before <step index>'));
1116
- const raw = str(flags.get('step')) ?? fail(`edit needs --step '<json>'`);
1117
- let step;
1118
- try {
1119
- step = JSON.parse(raw);
1120
- }
1121
- catch {
1122
- fail(`--step isn't JSON: ${raw}`);
1123
- }
1124
- const flow = await editFlow(app, slug, [{ before, step: step }], variantFlag(flags)).catch((e) => fail(e.message));
1125
- console.log(`added step ${before} to ${app}/${slug} (${flow.steps.length} steps now)`);
1135
+ const json = (flag) => {
1136
+ const raw = str(flags.get(flag));
1137
+ try {
1138
+ return JSON.parse(raw);
1139
+ }
1140
+ catch {
1141
+ return fail(`--${flag} isn't JSON: ${raw}`);
1142
+ }
1143
+ };
1144
+ const change = {};
1145
+ if (flags.has('step')) {
1146
+ const before = Number(str(flags.get('before')) ?? fail('--step needs --before <step index>'));
1147
+ change.add = [{ before, step: json('step') }];
1148
+ }
1149
+ if (flags.has('at')) {
1150
+ const raw = str(flags.get('at')) ?? fail('--at needs a step index or id');
1151
+ const at = /^\d+$/.test(raw) ? Number(raw) : raw;
1152
+ if (flags.has('remove') === flags.has('set'))
1153
+ fail('--at needs --set \'<json>\' or --remove — one of them');
1154
+ change.edit = [flags.has('remove') ? { at, remove: true } : { at, set: json('set') }];
1155
+ }
1156
+ const vars = all(flags, 'var');
1157
+ if (vars.length) {
1158
+ change.vars = Object.fromEntries(vars.map((v) => {
1159
+ const eq = v.indexOf('=');
1160
+ if (eq < 0)
1161
+ fail('--var must be name=value');
1162
+ return [v.slice(0, eq), v.slice(eq + 1)];
1163
+ }));
1164
+ }
1165
+ if (!change.add && !change.edit && !change.vars)
1166
+ fail('edit needs --before/--step, --at with --set or --remove, or --var', `understudy edit ${app} ${slug} --at 3 --set '{"name":"{{bundle}} bundle"}' --var bundle=Family`);
1167
+ const flow = await editFlow(app, slug, change, variantFlag(flags)).catch((e) => fail(e.message));
1168
+ console.log(`edited ${app}/${slug}: ${flow.unprovenBecause?.replace(/^edited: | — .*$/g, '')} (${flow.steps.length} steps now)`);
1169
+ if (flow.vars)
1170
+ console.log(` variables: ${Object.entries(flow.vars).map(([k, v]) => `${k} = ${JSON.stringify(v)}`).join(', ')}`);
1126
1171
  console.log(` UNPROVEN until a run passes — understudy prove ${app} ${slug}`);
1127
1172
  }
1128
1173
  /** `prove <app> <flow>`: prove a saved flow without committing anything. */
package/dist/entry/mcp.js CHANGED
@@ -31,7 +31,8 @@ import { acceptPaths } from '../flows/runs.js';
31
31
  import { collections } from '../store/db.js';
32
32
  import { startExtensionRecorder, extensionDir } from '../adapters/recorder/extension.js';
33
33
  import { saveRecording, loadRecording, recordingPath } from '../core/recording-store.js';
34
- import { editFlow, proveAndSave, proveFlow } from '../flows/save.js';
34
+ import { editFlow, proveAndSave, proveFlow, slugify } from '../flows/save.js';
35
+ import { extendRecording } from '../flows/extend.js';
35
36
  import { dropVariant, promoteVariant } from '../flows/variants.js';
36
37
  import { startSession, step as sessionStep, look as sessionLook, saveSession, closeSession, closeAllSessions } from '../flows/session.js';
37
38
  import { MissingValuesError } from '../flows/execute.js';
@@ -178,6 +179,8 @@ function report(state, out) {
178
179
  ...(executed.lessons?.fired ? { lessons: executed.lessons } : {}),
179
180
  ...(nowProven.length ? { nowProven } : {}),
180
181
  ...(executed.missingValues.length ? { missingValues: executed.missingValues } : {}),
182
+ ...(executed.vars ? { usedValues: executed.vars } : {}),
183
+ ...(executed.unusedValues ? { ignoredValues: `no step uses ${executed.unusedValues.join(', ')} — misspelt? Recall lists the flow's vars` } : {}),
181
184
  ...(executed.staleSession ? { staleSession: executed.staleSession } : {}),
182
185
  };
183
186
  }
@@ -186,7 +189,7 @@ function report(state, out) {
186
189
  const variant = z.string().optional();
187
190
  const baseUrl = z.string().optional();
188
191
  const values = z.record(z.string(), z.string()).optional()
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.');
192
+ .describe('{{var}} values, and login values you fetched ({"SECRET.password":"…"}; else from the user\'s settings). Never stored; never ask for one in chat.');
190
193
  server.registerTool('understudy_recall', {
191
194
  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).',
192
195
  inputSchema: { app: z.string(), goal: z.string(), limit: z.number().int().positive().optional(),
@@ -256,7 +259,7 @@ server.registerTool('understudy_remember', {
256
259
  reached: reached?.map((r) => defined(r)),
257
260
  }))));
258
261
  server.registerTool('understudy_findings', {
259
- description: 'Open findings for an app, most severe first, then most frequent. Pass triage to route them: issue, lesson, noise — or, for a changed path (flow_drift), expected: the app changed on purpose and the new path becomes the normal one. Ask the user before expected.',
262
+ description: 'Open findings, most severe first. triage routes them: issue, lesson, noise, or for a changed path (flow_drift) expected: the app changed on purpose, the new path is normal. Ask the user before expected.',
260
263
  inputSchema: {
261
264
  app: z.string(),
262
265
  triage: z.array(z.object({ fingerprint: z.string(), verdict: z.enum(['issue', 'lesson', 'noise', 'expected']) })).optional(),
@@ -306,8 +309,7 @@ server.registerTool('understudy_record', {
306
309
  server.registerTool('understudy_save', {
307
310
  description: [
308
311
  'Keep a flow, proven by replaying it: the user\'s latest recording, a recording hash, or a Playwright script of a flow you drove.',
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().',
312
+ 'A script is read, not run: literal page actions, locators, expect() and waits; no loops or runtime values.',
311
313
  'Unkept checks come back in droppedAssertions; a call or wait it can\'t replay refuses the save.',
312
314
  'Where only a person can act: human(\'what they do\', { untilText | untilUrl | untilResponse }).',
313
315
  ].join(' '),
@@ -316,6 +318,10 @@ server.registerTool('understudy_save', {
316
318
  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.'),
317
319
  add: z.array(z.object({ before: z.number().int(), step: z.record(z.string(), z.unknown()) })).optional()
318
320
  .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.'),
321
+ edit: z.array(z.object({ at: z.union([z.number().int(), z.string()]), set: z.record(z.string(), z.unknown()).optional(), remove: z.boolean().optional() })).optional()
322
+ .describe('With flow: at (index or id) set fields (null clears; name/value may hold {{var}}), or remove.'),
323
+ vars: z.record(z.string(), z.string().nullable()).optional().describe('With flow: {{var}} defaults.'),
324
+ extends: z.string().optional().describe('A flow this is, plus steps.'),
319
325
  hash: z.string().optional(),
320
326
  script: z.string().optional().describe('Path to a Playwright script of a flow you drove; read passwords from process.env.'),
321
327
  code: z.string().optional().describe('Or the code itself: e.g. the lines Playwright MCP printed for the steps that worked, as they came.'),
@@ -344,10 +350,11 @@ server.registerTool('understudy_save', {
344
350
  ...(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
351
  };
346
352
  }
347
- const edited = a.add?.length ? await editFlow(a.app, a.flow, a.add, a.variant) : undefined;
353
+ const changes = a.add?.length || a.edit?.length || a.vars;
354
+ const edited = changes ? await editFlow(a.app, a.flow, defined({ add: a.add, edit: a.edit?.map((e) => defined(e)), vars: a.vars }), a.variant) : undefined;
348
355
  if (edited && a.verify === false)
349
356
  return { flow: edited.slug, steps: edited.steps.length, unproven: edited.unprovenBecause };
350
- return { ...(edited ? { added: a.add.length } : {}), ...(await proveSaved(a.app, a.flow, a)) };
357
+ return { ...(edited ? { edited: edited.unprovenBecause?.replace(/^edited: | — .*$/g, '') } : {}), ...(await proveSaved(a.app, a.flow, a)) };
351
358
  }
352
359
  if (!a.name)
353
360
  throw new Error('name is required — what the flow does, as someone would ask for it (or pass flow to prove a saved one)');
@@ -383,10 +390,14 @@ server.registerTool('understudy_save', {
383
390
  rec = await loadRecording(hash);
384
391
  }
385
392
  const hash = rec.hash;
393
+ // Another flow plus its own steps: lined up against that flow first.
394
+ const ext = a.extends ? await extendRecording(rec, a.extends, defined({ slug: a.slug ?? slugify(name), variant: a.variant })) : undefined;
395
+ if (ext)
396
+ rec = ext.recording;
386
397
  let out;
387
398
  try {
388
399
  out = await proveAndSave(rec, {
389
- title: name, madeBy,
400
+ title: name, madeBy, ...(ext ? { extends: ext.extends } : {}),
390
401
  ...(a.verify === false ? { verify: false, unproven: a.note ? `saved by an agent without a replay: ${a.note}` : 'saved by an agent without a replay' } : {}),
391
402
  ...(a.values ? { values: a.values } : {}), ...(a.intent ? { intent: a.intent } : {}), ...(a.slug ? { slug: a.slug } : {}),
392
403
  ...(a.variant ? { variant: a.variant } : {}),
@@ -395,7 +406,7 @@ server.registerTool('understudy_save', {
395
406
  catch (e) {
396
407
  // The recording is kept; saving it again by hash needs nothing re-recorded.
397
408
  if (e instanceof MissingValuesError)
398
- return { saved: false, ...missingValues(e, { tool: 'understudy_save', hash, name }) };
409
+ return { saved: false, ...missingValues(e, { tool: 'understudy_save', hash, name, ...(a.extends ? { extends: a.extends } : {}) }) };
399
410
  throw e;
400
411
  }
401
412
  return savedReport(a.app, rec, out, { madeBy, dropped, ...(a.script || a.code ? {} : { droppedUploads: finished.get(a.app)?.droppedUploads ?? 0 }) });
@@ -421,6 +432,7 @@ function savedReport(app, rec, out, extra) {
421
432
  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.' };
422
433
  return {
423
434
  saved: true, flow: out.flow.slug, steps: out.flow.steps.length, madeBy, ...base,
435
+ ...(out.flow.extends ? { extends: out.flow.extends.flow } : {}), ...(out.flow.vars ? { vars: out.flow.vars } : {}),
424
436
  ...(out.flow.proven === false ? {
425
437
  unproven: out.flow.unprovenBecause,
426
438
  proveIt: `when it should pass: understudy_run with subGoals ["${out.flow.slug}"] — a passing run proves it`,
@@ -478,8 +490,8 @@ server.registerTool('understudy_session', {
478
490
  description: [
479
491
  'Explore an app in a browser Understudy drives, and keep what worked as a flow.',
480
492
  '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 as in recall, 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.',
493
+ 'A step is as in recall; a password is valueRef "SECRET.password".',
494
+ 'step returns what changed; look, the page\'s controls. save proves the kept steps in a fresh browser, up to a commit; running a commit needs allowPurchases.',
483
495
  ].join(' '),
484
496
  inputSchema: {
485
497
  do: z.enum(['start', 'step', 'look', 'save', 'close']),
@@ -528,7 +540,7 @@ server.registerTool('understudy_app', {
528
540
  return { app, placeholders: await appPlaceholders(app), timeoutMs: (await timeoutFor(app)) ?? 'default (10000)' };
529
541
  }));
530
542
  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.',
543
+ description: 'Fit when recall calls a goal "known", per app and embedding model: after switching models, or when cutoffs.source is "uncalibrated". Give 2–3 rewordings per flow (not its title) and 5+ goals the app has no flow for; kept for re-fits. Tell the user the before/after.',
532
544
  inputSchema: {
533
545
  app: z.string(),
534
546
  known: z.array(z.object({ flow: z.string().describe('the flow\'s slug'), goals: z.array(z.string()) })).optional(),
@@ -14,7 +14,17 @@
14
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
- const quote = (s) => `'${s.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
17
+ /**
18
+ * A string as code. One holding a flow variable (`{{bundle}} bundle`) becomes a
19
+ * template literal, `` `${bundle} bundle` ``, reading the const the test
20
+ * declares for it — the same shape script import reads back as a variable.
21
+ */
22
+ const quote = (s) => {
23
+ if (!/\{\{\s*[A-Za-z][A-Za-z0-9_]*\s*\}\}/.test(s))
24
+ return `'${s.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
25
+ const body = s.replace(/\\/g, '\\\\').replace(/`/g, '\\`').replace(/\$\{/g, '\\${');
26
+ return `\`${body.replace(/\{\{\s*([A-Za-z][A-Za-z0-9_]*)\s*\}\}/g, '${$1}')}\``;
27
+ };
18
28
  /**
19
29
  * The variable a test reads a login value from: SECRET.password →
20
30
  * UNDERSTUDY_SECRET_PASSWORD, the same one replay reads, so one setting serves
@@ -268,7 +278,16 @@ export function emitFlow(flow, framework = 'playwright-ts') {
268
278
  }
269
279
  const refs = [...required];
270
280
  // Values come from the environment, never the file.
271
- const preamble = refs.length ? refs.map((r) => `const ${envName(r).replace(/^UNDERSTUDY_/, '')} = process.env.${envName(r)} ?? '';`).join('\n') + '\n\n' : '';
281
+ const logins = refs.map((r) => `const ${envName(r).replace(/^UNDERSTUDY_/, '')} = process.env.${envName(r)} ?? '';`);
282
+ // Variables are consts with their defaults: change one to test another value.
283
+ const taken = new Set(['page', 'expect', 'test', 'cy', 'describe', 'it', ...refs.map((r) => envName(r).replace(/^UNDERSTUDY_/, ''))]);
284
+ const vars = Object.entries(flow.vars ?? {});
285
+ for (const [k] of vars) {
286
+ if (taken.has(k) || /^response\d+$/.test(k))
287
+ warnings.push(`variable "${k}" has the name of something the test already uses — rename it in the flow`);
288
+ }
289
+ const consts = vars.map(([k, v]) => `const ${k} = ${quote(v)};`);
290
+ const preamble = [...logins, ...consts].length ? [...logins, ...consts].join('\n') + '\n\n' : '';
272
291
  const header = `// ${flow.intent}\n// Generated by understudy from flow "${flow.app}/${flow.slug}". Regenerate rather than edit.\n\n`;
273
292
  const body = (indent) => lines.map((l) => indent + l).join('\n');
274
293
  const code = pw
@@ -66,6 +66,10 @@ export interface Executed {
66
66
  result: ReplayResult;
67
67
  /** Value references the recording needs that weren't supplied. */
68
68
  missingValues: string[];
69
+ /** Values used for its `{{variables}}` that differ from the defaults (core/vars.ts). */
70
+ vars?: Record<string, string>;
71
+ /** Values passed that no step uses, so nothing used them — usually a misspelt variable. */
72
+ unusedValues?: string[];
69
73
  lessons?: {
70
74
  fired: number;
71
75
  helped: number;
@@ -87,6 +91,8 @@ export declare function restoreSession(recording: RawRecording, values: Record<s
87
91
  savedAt?: string;
88
92
  }>;
89
93
  export declare function execute(recording: RawRecording, opts?: ExecuteOptions): Promise<Executed>;
94
+ /** The recording with no expected page on any step from the first that uses one of `changed`. */
95
+ export declare function unexpectFrom(recording: RawRecording, changed: string[]): RawRecording;
90
96
  export interface Proven extends Executed {
91
97
  /** The recording as it should be saved: with `requiresSession` set, or its unneeded session dropped. */
92
98
  recording: RawRecording;
@@ -11,6 +11,7 @@
11
11
  */
12
12
  import { loadSession, forgetSession, loadSessionById, forgetSessionById } from '../core/auth-cache.js';
13
13
  import { valueRefsOf } from '../core/recording.js';
14
+ import { overridesOf, varsInText, varsOf } from '../core/vars.js';
14
15
  import { replay } from '../core/replay.js';
15
16
  import { foldLessons, lessonsFor } from '../memory/notes.js';
16
17
  import { valuesFromEnv, valueEnvNames, reloadEnvFiles, writableEnvFile } from '../store/settings.js';
@@ -68,7 +69,9 @@ export async function execute(recording, opts = {}) {
68
69
  // (env files re-read, so one just added is seen).
69
70
  reloadEnvFiles();
70
71
  const refs = new Set(valueRefsOf(recording.events));
71
- const values = { ...valuesFromEnv(refs, recording.appSlug), ...(opts.values ?? {}) };
72
+ // {{variables}}: the flow's defaults, unless this run passes its own.
73
+ const used = varsOf(recording.events);
74
+ const values = { ...(recording.vars ?? {}), ...valuesFromEnv(refs, recording.appSlug), ...(opts.values ?? {}) };
72
75
  const missingValues = [...refs].filter((r) => !(r in values));
73
76
  // Checked BEFORE a browser opens: a run that reached the password step
74
77
  // without a password would spend a real login attempt — and some apps lock
@@ -84,7 +87,11 @@ export async function execute(recording, opts = {}) {
84
87
  const headed = Boolean(opts.headed) || forPerson;
85
88
  const onStuck = opts.onStuck;
86
89
  const timeoutMs = opts.timeoutMs ?? (await timeoutFor(app));
87
- const result = await replay(recording, {
90
+ // Other values than the defaults lead to other pages than the ones the flow
91
+ // was proven on: from the first step they change, there's no page to expect.
92
+ const vars = overridesOf(used, recording.vars, values);
93
+ const replayed = Object.keys(vars).length ? unexpectFrom(recording, Object.keys(vars)) : recording;
94
+ const result = await replay(replayed, {
88
95
  values,
89
96
  ...(timeoutMs !== undefined ? { timeoutMs } : {}),
90
97
  ...(storageState ? { storageState } : {}),
@@ -102,7 +109,12 @@ export async function execute(recording, opts = {}) {
102
109
  ...(opts.useLessons ? { lessonsFor: (ctx) => lessonsFor(app, ctx) } : {}),
103
110
  ...(opts.stopBefore !== undefined ? { stopBefore: opts.stopBefore } : {}),
104
111
  });
105
- const out = { result, missingValues, ...(sessionRestoredFrom ? { sessionRestoredFrom } : {}) };
112
+ // A name with no dot is a variable's; one no step uses is most likely misspelt, and was ignored.
113
+ const unusedValues = Object.keys(opts.values ?? {}).filter((k) => !k.includes('.') && !used.includes(k) && !refs.has(k));
114
+ const out = {
115
+ result, missingValues, ...(sessionRestoredFrom ? { sessionRestoredFrom } : {}),
116
+ ...(Object.keys(vars).length ? { vars } : {}), ...(unusedValues.length ? { unusedValues } : {}),
117
+ };
106
118
  // Step 0 of a late-armed recording carries the fingerprint of where it was
107
119
  // armed; landing elsewhere means the session expired.
108
120
  const entry = result.steps.find((s) => s.seq === 0);
@@ -117,6 +129,21 @@ export async function execute(recording, opts = {}) {
117
129
  out.lessons = await foldLessons(app, result.steps, recording.events);
118
130
  return out;
119
131
  }
132
+ /** The recording with no expected page on any step from the first that uses one of `changed`. */
133
+ export function unexpectFrom(recording, changed) {
134
+ const first = recording.events.findIndex((e) => [e.value, e.name].some((t) => varsInText(t).some((v) => changed.includes(v))));
135
+ if (first < 0)
136
+ return recording;
137
+ return {
138
+ ...recording,
139
+ events: recording.events.map((e, i) => {
140
+ if (i < first || e.expectedSig === undefined)
141
+ return e;
142
+ const { expectedSig: _no, ...rest } = e;
143
+ return rest;
144
+ }),
145
+ };
146
+ }
120
147
  /**
121
148
  * Prove a recording before saving it, and work out whether it needs to start
122
149
  * signed in — so nobody has to be asked.
@@ -0,0 +1,81 @@
1
+ /**
2
+ * A flow that extends another: "join-with-bundle, plus the partner's details
3
+ * after it picks the bundle". Its own steps go between that flow's steps,
4
+ * placed after a step's id, so fixing that flow once fixes every flow built
5
+ * on it — rather than one copy to repair per follow-up.
6
+ *
7
+ * The rules that keep it simple:
8
+ *
9
+ * - only ADD. A flow that extends another has all of its steps, in order,
10
+ * unchanged. "Like that one but skip step 5" is a different flow: save it
11
+ * as one. Otherwise reading a flow means working out a diff.
12
+ * - one level. A flow that extends another can't be extended, and can't
13
+ * extend one that does — so one change never ripples through a chain.
14
+ * - the result is stored. `steps` and `vars` are the full flow, rebuilt
15
+ * here whenever the flow it extends changes; everything else reads it like
16
+ * any flow. A rebuilt flow is unproven: nobody has run that version.
17
+ * - an anchor that goes away is never guessed at. The flow keeps its last
18
+ * steps, is marked unproven, and says which steps it lost.
19
+ */
20
+ import type { Flow, FlowExtends, Step } from '../store/types.js';
21
+ import type { RawEvent, RawRecording } from '../core/recording.js';
22
+ /**
23
+ * Pure: is `got` (a recorded step) the base step `base`, whose name or value
24
+ * may hold `{{variables}}`? Returns the values the variables took, or null.
25
+ */
26
+ export declare function sameStep(base: Step, got: Omit<RawEvent, 'seq' | 'ts'>): Record<string, string> | null;
27
+ export interface Aligned {
28
+ /** The new flow's steps: the base's own step objects where they matched, the recording's elsewhere. */
29
+ steps: Step[];
30
+ inherited: string[];
31
+ /** Values the recording gave the base's variables. */
32
+ caught: Record<string, string>;
33
+ problems: string[];
34
+ }
35
+ /**
36
+ * Pure: line a recording up against the flow it extends. Every base step must
37
+ * be in it, in order; whatever else it does is its own. Lined up by longest
38
+ * common run, so a step of its own that looks like a base step can't steal
39
+ * that step's place.
40
+ */
41
+ export declare function alignToBase(base: Pick<Flow, 'slug' | 'steps'>, got: Omit<RawEvent, 'seq' | 'ts'>[]): Aligned;
42
+ /**
43
+ * Pure: the flow rebuilt on the base as it is now — its own steps after the
44
+ * same base steps as before. `lost`: anchors the base no longer has (then
45
+ * nothing is rebuilt). An inherited step the base didn't change keeps the page
46
+ * this flow saw after it, which may differ from the base's own.
47
+ */
48
+ export declare function rebuild(base: Pick<Flow, 'steps' | 'vars'>, flow: Pick<Flow, 'steps'> & {
49
+ extends: FlowExtends;
50
+ }): {
51
+ steps: Step[];
52
+ vars?: Record<string, string>;
53
+ inherited: string[];
54
+ lost: string[];
55
+ };
56
+ /**
57
+ * Turn a recording of the whole path into one that extends `baseSlug`: the
58
+ * base's steps where it does them, its own elsewhere, and the base's variables
59
+ * set to what the recording did. Throws, with every problem, if it can't.
60
+ */
61
+ export declare function extendRecording(rec: RawRecording, baseSlug: string, opts: {
62
+ slug: string;
63
+ variant?: string;
64
+ }): Promise<{
65
+ recording: RawRecording;
66
+ extends: FlowExtends;
67
+ }>;
68
+ /**
69
+ * Pure: after an edit, are this flow's inherited steps all still there, in
70
+ * order, unchanged? An edit may add, change or remove only its own steps.
71
+ */
72
+ export declare function inheritedProblems(before: Step[], after: Step[], ext: FlowExtends): string[];
73
+ /**
74
+ * The flow `slug` changed: rebuild every flow that extends it (each through
75
+ * its own variant). Returns the ones that changed, and the ones that lost an
76
+ * anchor and need saving again.
77
+ */
78
+ export declare function refreshExtenders(app: string, slug: string): Promise<{
79
+ rebuilt: string[];
80
+ lost: string[];
81
+ }>;