@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/cli.js CHANGED
@@ -11,22 +11,25 @@ import { parseScript } from '../adapters/recorder/script.js';
11
11
  import { startExtensionRecorder, DEFAULT_PORT, extensionDir, firefoxExtensionDir } from '../adapters/recorder/extension.js';
12
12
  import { listRecordings, loadRecording, saveRecording } from '../core/recording-store.js';
13
13
  import { loadSession, saveSession } from '../core/auth-cache.js';
14
- import { buildRecording } from '../core/recording.js';
14
+ import { buildRecording, rebase } from '../core/recording.js';
15
+ import { checkVariant, dropVariant, promoteVariant, resolveFlow, runsOf, variantDiff } from '../flows/variants.js';
15
16
  import { execute, prove, MissingValuesError } from '../flows/execute.js';
16
17
  import { destructiveControls, remember } from '../memory/notes.js';
18
+ import { commitSteps } from '../flows/destructive.js';
17
19
  import { start, answer, runPlan } from '../plan/planner.js';
18
20
  import { distillRequest, saveDistilled } from '../flows/distill.js';
19
21
  import { readFile, writeFile, mkdir, chmod } from 'node:fs/promises';
20
22
  import { join, resolve as resolvePath } from 'node:path';
21
23
  import { existsSync } from 'node:fs';
22
24
  import { chromium } from 'playwright';
23
- import { emitFlow } from '../flows/emit.js';
25
+ import { emitFlow, envName as emitEnvName } from '../flows/emit.js';
24
26
  import { editFlow, recordingFrom, proveAndSave, proveByRun, proveFlow } from '../flows/save.js';
25
27
  import { acceptPaths, recordRun } from '../flows/runs.js';
26
28
  import { listFindings, triage } from '../flows/findings.js';
27
29
  import { VERSION } from './version.js';
28
- import { recall } from '../memory/recall.js';
30
+ import { recall, stepLine } from '../memory/recall.js';
29
31
  import { setPlaceholders, appPlaceholders } from '../memory/placeholders.js';
32
+ import { setAppTimeout, timeoutFor } from '../store/app-settings.js';
30
33
  import * as store from '../store/db.js';
31
34
  import { valueEnvName, readConfig, writeConfig, loadedFrom, HOME, expandHome, writeEnvValues } from '../store/settings.js';
32
35
  // Piped into `head` and the pipe closed early: stop quietly, like other CLIs.
@@ -44,10 +47,12 @@ USAGE
44
47
  COMMANDS
45
48
  config where settings come from; set them, or point at an env file
46
49
  doctor check the MongoDB connection, vector search and embedder
47
- reembed rebuild every vector with the model now configured
50
+ reembed rebuild every vector with the model now configured, then
51
+ re-fit each app's recall cutoffs from its kept goals
52
+ calibrate <app> fit when recall calls a goal known, for this app and model
48
53
  record <app> capture a flow in your own Chrome, with the extension
49
54
  extension where the Chrome extension is, and how to load it
50
- app <app> an app's settings, e.g. --placeholder email
55
+ app <app> an app's settings, e.g. --placeholder email, --timeout 20000
51
56
  import <app> <file> read an existing Playwright script into a recording
52
57
  recordings [app] list captured recordings
53
58
  save <hash> "<name>" prove a recording by replaying it, then save it as a flow
@@ -66,6 +71,10 @@ COMMANDS
66
71
  distill <app> <flow> print a saved flow's steps for an agent to name and split
67
72
  remember <app> <file> store facts, lessons and findings from a JSON batch
68
73
  emit <app> <flow> print a saved flow as a Playwright or Cypress test
74
+ promote <app> <flow> --variant <name>
75
+ make a variant the main flow, once its branch has merged
76
+ drop <app> <flow> --variant <name>
77
+ delete a variant's copy; that variant uses the main flow again
69
78
 
70
79
  MCP server for agents: understudy-mcp (see REASONER.md).
71
80
 
@@ -90,6 +99,10 @@ REPLAY and SAVE
90
99
  e.g. --value SECRET.password=hunter2 (repeatable)
91
100
  --headed watch it replay
92
101
  --allow-purchases replay a flow marked destructive (refused by default)
102
+ --until-commit run a destructive flow up to its commit step: checked, never pressed
103
+ --variant <name> a branch or deploy: use (or save) its copy of each flow, never
104
+ the main one — also for run, recall, prove, edit and emit
105
+ --base-url <url> run against the app at this address, e.g. a preview deploy
93
106
 
94
107
  SAVE
95
108
  --slug <name> the flow's short name (default: made from the name)
@@ -111,6 +124,13 @@ EMIT
111
124
  --framework <name> playwright-ts (default) or cypress-js
112
125
  --out <file> write to a file instead of printing
113
126
 
127
+ CALIBRATE
128
+ --goals <file> goals to fit on, kept for next time (reembed re-fits from them):
129
+ {"known": {"<flow-slug>": ["how someone would ask", …]},
130
+ "unknown": ["a goal that sounds like the app but isn't in it", …]}
131
+ --template print a goals file to fill in, listing the app's flows
132
+ --dry-run fit and show, keep nothing
133
+
114
134
  DISTILL
115
135
  --save <file> store the agent's answer (validated first)
116
136
 
@@ -228,6 +248,70 @@ async function cmdReembed() {
228
248
  const { reembed } = await import('../store/reembed.js');
229
249
  const r = await reembed();
230
250
  console.log(`re-embedded ${r.flows} flows and ${r.notes} notes with ${r.model}`);
251
+ // A new model scores on a new scale: re-fit the cutoffs wherever there are goals to fit on.
252
+ const { recalibrateAll } = await import('../memory/calibrate.js');
253
+ const { refitted, withoutGoals } = await recalibrateAll();
254
+ for (const c of refitted) {
255
+ console.log(`calibrated ${c.app}: ${c.saved ? `${cutoffLine(c.after)} — ${c.after.correct}/${c.total} goals right` : `not saved — ${c.notes.join('; ')}`}`);
256
+ }
257
+ for (const app of withoutGoals)
258
+ console.log(`not calibrated ${app}: no goals kept — run: understudy calibrate ${app} --template`);
259
+ }
260
+ const cutoffLine = (c) => `strong ${c.strong.toFixed(3)}, good ${c.good.toFixed(3)} + margin ${c.margin.toFixed(3)}`;
261
+ /**
262
+ * understudy calibrate <app> [--goals file] [--dry-run] fit recall's cutoffs
263
+ * understudy calibrate <app> --template a goals file to fill in
264
+ */
265
+ async function cmdCalibrate(positional, flags) {
266
+ const [app] = positional;
267
+ if (!app)
268
+ fail('calibrate needs an app', 'understudy calibrate myapp --goals goals.json');
269
+ const { calibrate } = await import('../memory/calibrate.js');
270
+ if (flags.has('template')) {
271
+ const { flows } = await store.collections();
272
+ const list = await flows.find({ app }, { projection: { slug: 1, title: 1 } }).toArray();
273
+ if (!list.length)
274
+ fail(`no flows for '${app}'`);
275
+ const known = Object.fromEntries(list.map((f) => [f.slug, [`<another way to say: ${f.title}>`]]));
276
+ console.log(JSON.stringify({ known, unknown: ['<a goal that sounds like this app, but that it has no flow for>'] }, null, 2));
277
+ return;
278
+ }
279
+ let goals;
280
+ const file = str(flags.get('goals'));
281
+ if (file) {
282
+ let raw;
283
+ try {
284
+ raw = JSON.parse(await readFile(file, 'utf8'));
285
+ }
286
+ catch (e) {
287
+ fail(`can't read ${file}: ${e.message}`);
288
+ }
289
+ const placeholder = (g) => /^<.*>$/.test(g.trim());
290
+ goals = {
291
+ known: Object.entries(raw.known ?? {}).flatMap(([flow, gs]) => (gs ?? []).filter((g) => !placeholder(g)).map((goal) => ({ flow, goal }))),
292
+ unknown: (raw.unknown ?? []).filter((g) => !placeholder(g)),
293
+ };
294
+ }
295
+ const c = await calibrate(app, { ...(goals ? { goals } : {}), ...(flags.has('dry-run') ? { dryRun: true } : {}) });
296
+ console.log(`${c.app} with ${c.model}: ${c.flows} flows, ${c.total} goals — ${c.goals.known} known + ${c.goals.fromRuns} from runs, ${c.goals.unknown} unknown + ${c.goals.leftOut} by leaving a flow out\n`);
297
+ console.log(`before ${cutoffLine(c.before)} (${c.before.source}) ${c.before.correct}/${c.total} right`);
298
+ console.log(`fitted ${cutoffLine(c.after)} ${c.after.correct}/${c.total} right`);
299
+ if (c.mistakes.length) {
300
+ console.log('\nstill wrong with the fitted cutoffs');
301
+ for (const m of c.mistakes) {
302
+ console.log(` ${m.verdict === 'known' ? 'called known' : 'missed '} ${m.score.toFixed(3)}${m.next !== undefined ? ` (next ${m.next.toFixed(3)})` : ''} "${m.goal}" → ${m.top ?? '-'}${m.expected ? `, wanted ${m.expected}` : ''}`);
303
+ }
304
+ }
305
+ if (c.misranked.length) {
306
+ console.log(`\n${c.model} ranked another flow first for ${c.misranked.length} known goal(s) — no cutoff fixes that:`);
307
+ for (const m of c.misranked)
308
+ console.log(` "${m.goal}" → ${m.top}, wanted ${m.expected}`);
309
+ }
310
+ for (const n of c.notes)
311
+ console.log(`\nnote: ${n}`);
312
+ console.log(c.saved ? '\nsaved — recall uses these cutoffs for this app with this model' : flags.has('dry-run') ? '\ndry run — nothing kept' : '\nnot saved (goals kept) — add more and run again');
313
+ if (!c.saved && !flags.has('dry-run'))
314
+ process.exitCode = 1;
231
315
  }
232
316
  // --- config ------------------------------------------------------------------
233
317
  /**
@@ -415,13 +499,22 @@ async function cmdRecordExtension(slug, flags) {
415
499
  * understudy app <app> the app's settings
416
500
  * understudy app <app> --placeholder email keep its email fields as placeholders
417
501
  * understudy app <app> --no-placeholders stop doing that for new flows
502
+ * understudy app <app> --timeout <ms|default> how long a step may wait
418
503
  */
419
504
  async function cmdApp(positional, flags) {
420
505
  const app = positional[0] ?? fail('app needs an app name', 'understudy app myapp --placeholder email');
506
+ const timeout = str(flags.get('timeout'));
507
+ if (timeout !== undefined) {
508
+ const out = await setAppTimeout(app, timeout === 'default' ? null : Number(timeout)).catch((e) => fail(e.message));
509
+ console.log(`${app}: a step may wait ${out.timeoutMs ? `${out.timeoutMs} ms` : 'the default (UNDERSTUDY_TIMEOUT_MS, else 10000 ms)'}`);
510
+ }
421
511
  const kinds = all(flags, 'placeholder');
422
512
  if (!kinds.length && !flags.has('no-placeholders')) {
513
+ if (timeout !== undefined)
514
+ return;
423
515
  const current = await appPlaceholders(app);
424
516
  console.log(`${app}: placeholders ${current.length ? current.join(', ') : 'passwords only (the default)'}`);
517
+ console.log(`${app}: a step may wait ${(await timeoutFor(app)) ?? 10000} ms`);
425
518
  return;
426
519
  }
427
520
  const out = await setPlaceholders(app, flags.has('no-placeholders') ? [] : kinds).catch((e) => fail(e.message));
@@ -498,7 +591,10 @@ async function cmdImport(positional, flags) {
498
591
  */
499
592
  async function executeWithReport(recording, flags, opts) {
500
593
  const values = valuesFromFlags(flags);
501
- const x = await withLoginValues(values, (v) => execute(recording, { values: v, headed: flags.has('headed'), useLessons: opts.useLessons, ...personAtTerminal() }))
594
+ const x = await withLoginValues(values, (v) => execute(recording, {
595
+ values: v, headed: flags.has('headed'), useLessons: opts.useLessons, ...personAtTerminal(),
596
+ ...(opts.stopBefore !== undefined ? { stopBefore: opts.stopBefore } : {}),
597
+ }))
502
598
  .catch((e) => fail(e.message));
503
599
  if (x.sessionRestoredFrom)
504
600
  console.log(`session: restored (saved ${x.sessionRestoredFrom})`);
@@ -530,14 +626,21 @@ async function cmdReplayFlow(app, slug, flags) {
530
626
  * Shared by `replay <app> <flow>` and `run <app> "<goal>"`.
531
627
  */
532
628
  async function runSavedFlow(app, slug, flags, how) {
533
- const { flows } = await store.collections();
534
- const flow = await flows.findOne({ app, slug });
629
+ const variant = variantFlag(flags);
630
+ const flow = await resolveFlow(app, slug, variant);
535
631
  if (!flow)
536
632
  fail(`no flow '${slug}' for app '${app}'`, `understudy flows ${app}`);
633
+ if (flow.variant)
634
+ console.log(`variant ${flow.variant}'s copy of '${slug}'`);
635
+ else if (variant)
636
+ console.log(`variant ${variant} has no copy of '${slug}' — running the main flow`);
637
+ // Up to the commit: the first step that commits something, counting facts.
638
+ const untilCommit = flags.has('until-commit') && !flags.has('allow-purchases');
639
+ const commit = untilCommit ? commitSteps(flow.steps, await destructiveControls(app))[0] : undefined;
537
640
  // The safety gate: a destructive flow does something real every time it runs.
538
- if (!flags.has('allow-purchases')) {
641
+ if (!flags.has('allow-purchases') && !untilCommit) {
539
642
  if (flow.destructive) {
540
- fail(`'${slug}' is marked destructive (${flow.destructiveBecause}) — running it may place a real order`, 'pass --allow-purchases if that is genuinely fine');
643
+ 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');
541
644
  }
542
645
  const controls = await destructiveControls(app);
543
646
  const hit = flow.steps.find((s) => s.name && ['click', 'press', 'dispatch_click'].includes(s.action) && controls.has(s.name.toLowerCase()));
@@ -547,12 +650,19 @@ async function runSavedFlow(app, slug, flags, how) {
547
650
  console.log(`running ${app}/${slug} — ${flow.title}\n`);
548
651
  if (flow.proven === false)
549
652
  console.log(`note: '${slug}' is UNPROVEN (${flow.unprovenBecause}) — this run will tell.\n`);
550
- const result = await executeWithReport(recordingFrom(flow), flags, { useLessons: true });
653
+ const baseUrl = str(flags.get('base-url'));
654
+ const recording = baseUrl ? rebase(recordingFrom(flow), baseUrl) : recordingFrom(flow);
655
+ if (baseUrl)
656
+ console.log(`against ${new URL(recording.startUrl).origin} (saved on ${new URL(flow.startUrl).origin})\n`);
657
+ if (commit)
658
+ console.log(`stopping before step ${commit.index}: ${commit.reason}\n`);
659
+ const result = await executeWithReport(recording, flags, { useLessons: true, ...(commit ? { stopBefore: recording.events[commit.index].seq } : {}) });
551
660
  printReplay(result);
552
661
  const run = await recordRun({
553
662
  app, flow: slug, result, steps: flow.steps, mode: how.mode, ...(how.goal ? { goal: how.goal } : {}), ...(flow.proven === false ? { unproven: true } : {}),
663
+ ...(variant ? { variant } : {}),
554
664
  });
555
- if (await proveByRun(app, slug, result))
665
+ if (await proveByRun(app, slug, result, 0, variant))
556
666
  console.log(`\nproven '${slug}' passed, so it's no longer marked unproven`);
557
667
  printRunReport(run);
558
668
  if (!result.ok)
@@ -565,7 +675,8 @@ function printRecall(r, showSteps = false) {
565
675
  if (r.flows.length) {
566
676
  console.log('flows');
567
677
  for (const f of r.flows) {
568
- const marks = [f.proven === false && 'UNPROVEN', f.destructive && 'DESTRUCTIVE', f.requiresSession && 'needs session', f.kind === 'segment' && 'segment'].filter(Boolean).join(', ');
678
+ const failedLast = f.lastFailed && (!f.lastPassed || f.lastFailed.at > f.lastPassed);
679
+ const marks = [f.variants?.length && `variants: ${f.variants.join(', ')}`, f.proven === false && 'UNPROVEN', failedLast && 'LAST RUN FAILED', f.pathNotAccepted && 'path not accepted', f.destructive && 'DESTRUCTIVE', f.requiresSession && 'needs session', f.kind === 'segment' && 'segment'].filter(Boolean).join(', ');
569
680
  console.log(` ${f.score.toFixed(3)} ${f.slug.padEnd(32)} ${f.title}${marks ? ` [${marks}]` : ''}`);
570
681
  }
571
682
  }
@@ -577,13 +688,15 @@ function printRecall(r, showSteps = false) {
577
688
  if (r.best && r.steps) {
578
689
  console.log(`\n${r.best.slug}: ${r.steps.length} steps${showSteps ? '' : ' (--steps to list them)'}`);
579
690
  if (showSteps) {
580
- for (const s of r.steps) {
581
- const target = s.role && s.name ? `${s.role} "${s.name}"` : s.testId ? `[test id ${s.testId}]` : s.css ? `[${s.css}]` : '';
582
- const what = s.placeholder ? `= <${s.placeholder}>` : s.value !== undefined ? `= "${s.value}"` : '';
583
- console.log(` ${String(s.n).padStart(3)} ${s.action.padEnd(7)} ${target}${s.nth !== undefined ? ` (#${s.nth})` : ''} ${what}`.trimEnd());
584
- }
691
+ for (const s of r.steps)
692
+ console.log(` ${stepLine(s)}`);
585
693
  }
586
694
  }
695
+ if (r.differsFromMain?.length) {
696
+ console.log(`\n${r.best.slug} @${r.best.variant}, against the main flow:`);
697
+ for (const line of r.differsFromMain)
698
+ console.log(` ${line}`);
699
+ }
587
700
  for (const need of r.needs ?? []) {
588
701
  console.log(`needs ${need.placeholder} — from ${need.readFrom.join(' or ')}: ${need.set ? 'set' : 'NOT SET'}`);
589
702
  }
@@ -593,7 +706,8 @@ async function cmdRecall(positional, flags) {
593
706
  const [app, ...goalWords] = positional;
594
707
  if (!app || !goalWords.length)
595
708
  fail('recall needs an app and a goal', 'understudy recall myapp "log in"');
596
- printRecall(await recall(app, goalWords.join(' '), { withSteps: true, limit: Number(str(flags.get('limit')) ?? 5) }), flags.has('steps'));
709
+ const variant = variantFlag(flags);
710
+ printRecall(await recall(app, goalWords.join(' '), { withSteps: true, limit: Number(str(flags.get('limit')) ?? 5), ...(variant ? { variant } : {}) }), flags.has('steps'));
597
711
  }
598
712
  /**
599
713
  * Run a goal: find the flow that does it, check it's safe, run it. Only a
@@ -615,10 +729,13 @@ async function cmdRun(positional, flags) {
615
729
  app, goal, subGoals,
616
730
  ...(flags.has('dry-run') ? { dryRun: true } : {}),
617
731
  ...(flags.has('allow-purchases') ? { allowPurchases: true } : {}),
732
+ ...(flags.has('until-commit') ? { stopBeforeCommit: true } : {}),
733
+ ...(variantFlag(flags) ? { variant: variantFlag(flags) } : {}),
734
+ ...(str(flags.get('base-url')) ? { baseUrl: str(flags.get('base-url')) } : {}),
618
735
  });
619
736
  return reportPlan(state, flags);
620
737
  }
621
- const r = await recall(app, goal);
738
+ const r = await recall(app, goal, variantFlag(flags) ? { variant: variantFlag(flags) } : {});
622
739
  printRecall(r);
623
740
  if (r.verdict !== 'known' || !r.best) {
624
741
  console.log(r.verdict === 'unsure'
@@ -661,11 +778,13 @@ async function reportPlan(state, flags) {
661
778
  }
662
779
  console.log();
663
780
  const values = valuesFromFlags(flags);
664
- const { executed, recorded, nowProven } = await withLoginValues(values, (v) => runPlan(state.runId, { values: v, headed: flags.has('headed'), ...personAtTerminal() }))
781
+ const { executed, recorded, nowProven, commit } = await withLoginValues(values, (v) => runPlan(state.runId, { values: v, headed: flags.has('headed'), ...personAtTerminal() }))
665
782
  .catch((e) => fail(e.message));
666
783
  if (executed.lessons?.fired)
667
784
  console.log(`lessons ${executed.lessons.fired} fired, ${executed.lessons.helped} on steps that have failed before\n`);
668
785
  printReplay(executed.result);
786
+ if (commit && executed.result.stoppedBefore !== undefined)
787
+ console.log(`stopped before step ${commit.index} (${commit.reason}) — checked, not pressed`);
669
788
  printRunReport(recorded);
670
789
  for (const slug of nowProven)
671
790
  console.log(`proven '${slug}' passed, so it's no longer marked unproven`);
@@ -787,8 +906,18 @@ async function cmdSave(positional, flags) {
787
906
  values: valuesFromFlags(flags), headed: flags.has('headed'),
788
907
  verify: !flags.has('no-verify'), force: flags.has('force'),
789
908
  ...(slug ? { slug } : {}), ...(intent ? { intent } : {}),
909
+ ...(variantFlag(flags) ? { variant: variantFlag(flags) } : {}),
790
910
  });
791
911
  }
912
+ /** --variant, checked. */
913
+ const variantFlag = (flags) => {
914
+ try {
915
+ return checkVariant(str(flags.get('variant')));
916
+ }
917
+ catch (e) {
918
+ return fail(e.message);
919
+ }
920
+ };
792
921
  /** Ask a yes/no question in the terminal. No terminal (piped, scripted): the answer is no. */
793
922
  async function askYesNo(question, byDefault = false) {
794
923
  if (!process.stdin.isTTY)
@@ -957,7 +1086,7 @@ async function saveAndReport(recording, title, opts) {
957
1086
  if (flow.proven === false)
958
1087
  console.log(` UNPROVEN — ${flow.unprovenBecause}. The first run that passes proves it.`);
959
1088
  if (flow.destructive)
960
- console.log(` DESTRUCTIVE — ${flow.destructiveBecause}. Replays need --allow-purchases.`);
1089
+ console.log(` DESTRUCTIVE — ${flow.destructiveBecause}. Replays need --until-commit (up to it) or --allow-purchases.`);
961
1090
  const upTo = provenUpToNote(flow);
962
1091
  if (upTo)
963
1092
  console.log(` ${upTo}`);
@@ -992,7 +1121,7 @@ async function cmdEdit(positional, flags) {
992
1121
  catch {
993
1122
  fail(`--step isn't JSON: ${raw}`);
994
1123
  }
995
- const flow = await editFlow(app, slug, [{ before, step: step }]).catch((e) => fail(e.message));
1124
+ const flow = await editFlow(app, slug, [{ before, step: step }], variantFlag(flags)).catch((e) => fail(e.message));
996
1125
  console.log(`added step ${before} to ${app}/${slug} (${flow.steps.length} steps now)`);
997
1126
  console.log(` UNPROVEN until a run passes — understudy prove ${app} ${slug}`);
998
1127
  }
@@ -1000,7 +1129,7 @@ async function cmdEdit(positional, flags) {
1000
1129
  async function cmdProve(positional, flags) {
1001
1130
  const app = positional[0] ?? fail('prove needs an app and a flow', 'understudy prove myapp book-a-visit');
1002
1131
  const slug = positional[1] ?? fail('prove needs a flow', `understudy flows ${app}`);
1003
- const out = await withLoginValues(valuesFromFlags(flags), (values) => proveFlow(app, slug, { values, headed: flags.has('headed') }))
1132
+ const out = await withLoginValues(valuesFromFlags(flags), (values) => proveFlow(app, slug, { values, headed: flags.has('headed'), ...(variantFlag(flags) ? { variant: variantFlag(flags) } : {}) }))
1004
1133
  .catch((e) => fail(e.message));
1005
1134
  if (out.commit)
1006
1135
  console.log(`stopping before step ${out.commit.index}: ${out.commit.reason}\n`);
@@ -1017,17 +1146,21 @@ async function cmdProve(positional, flags) {
1017
1146
  async function cmdFlows(positional) {
1018
1147
  const app = positional[0] ?? fail('flows needs an app name', 'understudy flows myapp');
1019
1148
  const { flows, runs } = await store.collections();
1020
- const rows = await flows.find({ app }, { projection: { embedding: 0, steps: 0 } }).sort({ slug: 1 }).toArray();
1149
+ const rows = await flows.find({ app }, { projection: { embedding: 0, steps: 0 } }).sort({ slug: 1, variant: 1 }).toArray();
1021
1150
  if (!rows.length) {
1022
1151
  console.log(`no flows for '${app}' yet — record one, then \`understudy save <hash> "<name>"\``);
1023
1152
  return;
1024
1153
  }
1025
1154
  for (const f of rows) {
1026
- const last = await runs.find({ app, plan: [f.slug] }).sort({ startedAt: -1 }).limit(1).next();
1155
+ const last = await runs.find({ app, plan: [f.slug], ...runsOf(f.variant) }).sort({ startedAt: -1 }).limit(1).next();
1027
1156
  const status = last ? `${last.status} ${last.startedAt.toISOString().slice(0, 16).replace('T', ' ')}` : 'never run';
1028
1157
  const marks = [f.proven === false && 'UNPROVEN', f.provenUpTo !== undefined && `proven to step ${f.provenUpTo}`, f.destructive && 'DESTRUCTIVE', f.requiresSession && 'needs session', f.kind === 'segment' && 'segment', f.madeBy === 'agent' && 'made by an agent']
1029
1158
  .filter(Boolean).join(', ');
1030
- console.log(` ${f.slug.padEnd(32)} ${status.padEnd(24)} ${f.title}${marks ? ` [${marks}]` : ''}`);
1159
+ const name = f.variant ? `${f.slug} @${f.variant}` : f.slug;
1160
+ console.log(` ${name.padEnd(32)} ${status.padEnd(24)} ${f.title}${marks ? ` [${marks}]` : ''}`);
1161
+ if (f.variant)
1162
+ for (const line of (await variantDiff(app, f.slug, f.variant)).slice(0, 6))
1163
+ console.log(` ${line}`);
1031
1164
  }
1032
1165
  }
1033
1166
  async function cmdFindings(positional, flags) {
@@ -1056,6 +1189,26 @@ async function cmdFindings(positional, flags) {
1056
1189
  console.log(` ${f.fingerprint} ${f.severity.padEnd(6)} ×${String(f.occurrences).padEnd(4)} ${f.kind.padEnd(14)} ${f.statement.slice(0, 110)}${f.evidence?.fromUnprovenFlow ? ' [from an unproven flow — may be the recording]' : ''}`);
1057
1190
  }
1058
1191
  }
1192
+ /** promote <app> <flow> --variant <name> — the branch merged: its copy becomes the main flow. */
1193
+ async function cmdPromote(positional, flags) {
1194
+ const [app, slug] = positional;
1195
+ if (!app || !slug)
1196
+ fail('promote needs an app and a flow', 'understudy promote myapp book-a-visit --variant feature/new-intake');
1197
+ const variant = variantFlag(flags) ?? fail('promote needs --variant <name>: the copy to make the main flow');
1198
+ const out = await promoteVariant(app, slug, variant).catch((e) => fail(e.message));
1199
+ console.log(`promoted ${app}/${slug} @${variant} — it is the main flow now${out.replaced ? ', replacing the old one' : ''}`);
1200
+ if (out.staleSegments.length)
1201
+ console.log(` segments cut from the old flow still hold its old steps: ${out.staleSegments.join(', ')} — distill ${slug} again`);
1202
+ }
1203
+ /** drop <app> <flow> --variant <name> — delete a variant's copy of a flow. */
1204
+ async function cmdDrop(positional, flags) {
1205
+ const [app, slug] = positional;
1206
+ if (!app || !slug)
1207
+ fail('drop needs an app and a flow', 'understudy drop myapp book-a-visit --variant feature/new-intake');
1208
+ const variant = variantFlag(flags) ?? fail('drop needs --variant <name>: the copy to delete (the main flow is never dropped this way)');
1209
+ await dropVariant(app, slug, variant).catch((e) => fail(e.message));
1210
+ console.log(`dropped ${app}/${slug} @${variant} — runs with ${variant} use the main flow again`);
1211
+ }
1059
1212
  /** emit <app> <flow> — print a saved flow as a Playwright or Cypress test. */
1060
1213
  async function cmdEmit(positional, flags) {
1061
1214
  const [app, slug] = positional;
@@ -1064,8 +1217,7 @@ async function cmdEmit(positional, flags) {
1064
1217
  const framework = (str(flags.get('framework')) ?? 'playwright-ts');
1065
1218
  if (framework !== 'playwright-ts' && framework !== 'cypress-js')
1066
1219
  fail('--framework must be playwright-ts or cypress-js');
1067
- const { flows } = await store.collections();
1068
- const flow = await flows.findOne({ app, slug });
1220
+ const flow = await resolveFlow(app, slug, variantFlag(flags));
1069
1221
  if (!flow)
1070
1222
  fail(`no flow '${slug}' for app '${app}'`, `understudy flows ${app}`);
1071
1223
  const out = emitFlow(flow, framework);
@@ -1079,7 +1231,7 @@ async function cmdEmit(positional, flags) {
1079
1231
  for (const w of out.warnings)
1080
1232
  console.error(`warning: ${w}`);
1081
1233
  if (out.requiredValues.length)
1082
- console.error(`reads from the environment: ${out.requiredValues.map(valueEnvName).join(', ')}`);
1234
+ console.error(`reads from the environment: ${out.requiredValues.map(emitEnvName).join(', ')}`);
1083
1235
  }
1084
1236
  // --- recordings --------------------------------------------------------------
1085
1237
  async function cmdRecordings(positional) {
@@ -1108,6 +1260,7 @@ async function main() {
1108
1260
  case 'extension': return cmdExtension();
1109
1261
  case 'app': return cmdApp(rest, flags);
1110
1262
  case 'reembed': return cmdReembed();
1263
+ case 'calibrate': return cmdCalibrate(rest, flags);
1111
1264
  case 'record': return cmdRecord(rest, flags);
1112
1265
  case 'import': return cmdImport(rest, flags);
1113
1266
  case 'recordings': return cmdRecordings(rest);
@@ -1123,6 +1276,8 @@ async function main() {
1123
1276
  case 'distill': return cmdDistill(rest, flags);
1124
1277
  case 'remember': return cmdRemember(rest);
1125
1278
  case 'emit': return cmdEmit(rest, flags);
1279
+ case 'promote': return cmdPromote(rest, flags);
1280
+ case 'drop': return cmdDrop(rest, flags);
1126
1281
  default: fail(`unknown command '${command}'`, 'understudy --help');
1127
1282
  }
1128
1283
  }
@@ -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
  */