@jeffawe/understudy 0.2.3 → 0.4.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/README.md CHANGED
@@ -1,10 +1,20 @@
1
1
  # Understudy
2
2
 
3
+ ![Understudy — record a flow once, replay it as a test](https://understudy.jeffawe.dev/og.png)
4
+
5
+ [![npm](https://img.shields.io/npm/v/@jeffawe/understudy)](https://www.npmjs.com/package/@jeffawe/understudy)
6
+
3
7
  End-to-end tests for your own web apps, without clicking through every flow by
4
8
  hand. Record a flow once; Understudy remembers it, replays it as a test, notices
5
9
  when the app changes, and can run goals you describe in words — including goals
6
10
  that need pieces of several recordings.
7
11
 
12
+ It's an npm package, [`@jeffawe/understudy`](https://www.npmjs.com/package/@jeffawe/understudy):
13
+
14
+ ```sh
15
+ npm install -g @jeffawe/understudy
16
+ ```
17
+
8
18
  It works on its own from the command line, and it plugs into an AI agent
9
19
  (Claude Code, Codex, Cursor) over MCP. The agent is optional; with one,
10
20
  Understudy never calls a model itself — the agent is the model.
@@ -20,20 +30,43 @@ record → save → replay / run → findings
20
30
  are never stored: a password field is kept as
21
31
  a reference like `SECRET.password`, and you supply the value when replaying.
22
32
  - **save** — the recording is replayed headless first. It is kept only if every
23
- step passes, so memory only holds flows known to work.
33
+ step passes, so memory only holds flows known to work. A flow that buys or
34
+ submits something is replayed only up to that step: the button is checked,
35
+ never pressed. Don't want a replay at all? `--no-verify` keeps it as
36
+ unproven until a run passes.
24
37
  - **replay / run** — `replay` runs a flow by name; `run` finds the flow that
25
38
  does a goal you describe ("go to my basket") and runs it. Matching is by
26
39
  meaning if you configure an embedding model, by name if you don't.
27
40
  - **findings** — every run checks for console errors, failed requests, error
28
41
  responses, values that didn't stick, and whether the flow took a different
29
42
  path through the app than last time. Each problem is reported once, with a
30
- count, not once per run.
43
+ count, not once per run. A run that passes on a changed path is flagged until
44
+ you say the change is meant to be there — then that path is the normal one.
31
45
 
32
46
  With an agent attached it also splits recordings into reusable segments (a
33
47
  login cut out of a checkout, say), plans a goal across segments of different
34
48
  recordings, and writes down what it learns as facts and lessons that apply to
35
49
  every future run.
36
50
 
51
+ ## More than clicks
52
+
53
+ A flow is a list of steps. Besides clicking and typing, a step can:
54
+
55
+ - **wait for a person** — something only you can do, like accepting a visit in
56
+ another system or typing a code from your phone. The run pauses, asks, and
57
+ carries on when you say it's done (or when the page shows it).
58
+ - **wait for the server** — a response, its status, and one field of its JSON:
59
+ "`POST /api/visits` returned 201 and `commission.amount` is above 0".
60
+ - **check how it ended** — after a save, Understudy offers what the last page
61
+ showed (headings, ticked boxes, status messages) as checks. You choose which
62
+ mean "it ended right".
63
+ - **need an app state** — "member has an active bundle". A plan runs the flow
64
+ that makes it true first, or takes your word that it already is.
65
+
66
+ These come from a Playwright script (`page.waitForResponse`,
67
+ `human('what to do', { untilText: '…' })`), or can be added to a flow you've
68
+ already saved with `understudy edit`.
69
+
37
70
  ## Set up (about five minutes)
38
71
 
39
72
  You need **Node 22+** and a **MongoDB** with vector search — a free
@@ -91,10 +124,22 @@ ollama pull mxbai-embed-large
91
124
  understudy config set EMBED_URL=http://localhost:11434/v1/embeddings EMBED_MODEL=mxbai-embed-large EMBED_DIMS=1024
92
125
  ```
93
126
 
94
- Two things to know: one database holds one model's vectors, so switching later
95
- means `understudy reembed`; and the line between "a flow I know" and "close,
96
- but not it" was calibrated on Voyage — other models score differently, so check
97
- a few goals with `understudy recall` first.
127
+ Two things to know. One database holds one model's vectors, so switching later
128
+ means `understudy reembed`. And the line between "a flow I know" and "close,
129
+ but not it" was set for Voyage. Other models score on their own scale: with
130
+ the cutoffs set for Voyage, mxbai-embed-large called 12 of 14 goals an app didn't have
131
+ "known", so the wrong flow would have run. Fit the line to your app and model:
132
+
133
+ ```bash
134
+ understudy calibrate myapp --template > goals.json # every flow, to reword
135
+ # fill in 2–3 ways someone would ask for each flow, and 5+ goals that sound
136
+ # like the app but that it has no flow for
137
+ understudy calibrate myapp --goals goals.json
138
+ ```
139
+
140
+ The goals are kept, so after any later `understudy reembed` the line is re-fit
141
+ for the new model on its own. `recall` says when it's using cutoffs that
142
+ weren't fitted for the model you have.
98
143
 
99
144
  ## Use it
100
145
 
@@ -107,21 +152,21 @@ understudy flows myapp # what it knows how to do
107
152
  understudy replay myapp log-in-as-a-member # run one flow
108
153
  understudy run myapp "sign in" # find the flow for a goal, and run it
109
154
  understudy import myapp login.spec.ts # turn a Playwright script into a recording, then save it
155
+ understudy prove myapp book-a-visit # prove a saved flow without buying anything
156
+ understudy edit myapp book-a-visit --before 3 --step '{"action":"human","value":"Accept the visit"}'
157
+ # add a person's step, a wait or a check to a saved flow
110
158
  understudy findings myapp # what looked broken, most severe first
159
+ understudy findings myapp --triage <id>=expected
160
+ # a changed path is meant to be there: make it the normal one
111
161
  understudy emit myapp log-in-as-a-member # print it as a Playwright (or Cypress) test
112
162
  understudy app myapp --placeholder email # keep email addresses out of memory (moves them to your env file)
113
163
  ```
114
164
 
115
- An imported script keeps its checks — `expect(...).toBeVisible()`,
116
- `toHaveText`, `toHaveURL`, `waitForURL` and the like — so a replay fails when
117
- the page is wrong, not just when a button is missing. A check it can't replay is
118
- listed when you import, never dropped silently.
119
-
120
165
  An unproven flow is marked as such in `flows` and recall; the first run of
121
- it that passes proves it. `understudy --help` lists everything, and
122
- `understudy --version` says which one you have. A flow that commits something real — a
123
- purchase, a deletion — is marked destructive and refused unless you pass
124
- `--allow-purchases`.
166
+ it that passes proves it. A flow that commits something real — a purchase, a
167
+ deletion — is marked destructive: saving and `prove` stop just before that
168
+ step, and a full run needs `--allow-purchases`. `understudy --help` lists
169
+ everything, and `understudy --version` says which one you have.
125
170
 
126
171
  ## Where your data goes
127
172
 
@@ -161,10 +206,15 @@ claude mcp add understudy -- npx -y -p @jeffawe/understudy understudy-mcp --env-
161
206
  ```
162
207
 
163
208
  Ten tools: `recall`, `run`, `answer`, `record`, `save`, `distill`,
164
- `save_distilled`, `remember`, `findings`, `app`. The server tells the agent how to use
165
- them when it connects; [REASONER.md](REASONER.md) is the full version — how to
166
- split a goal, when to answer a question and when to say "I don't know", and
167
- what to write down.
209
+ `save_distilled`, `remember`, `findings`, `app`. Each tool says how to use it,
210
+ and a run's questions say how to answer them, so the server's own instructions
211
+ are one line — an agent pays only for the tools it uses.
212
+ [REASONER.md](REASONER.md) is the long version — how to split a goal, when to
213
+ answer a question and when to say "I don't know", and what to write down.
214
+
215
+ Mid-run, the agent may ask you to do a step only a person can do, or whether a
216
+ changed path in your app is meant to be there. Answer it in the chat; it
217
+ records your answer.
168
218
 
169
219
  ## Learn more
170
220
 
package/REASONER.md CHANGED
@@ -17,7 +17,7 @@ remembers. You supply the judgement; it never calls a model.
17
17
  - **Destructive flows** (purchases, deletions) are refused unless
18
18
  `allowPurchases`. Start runs with `dryRun: true`.
19
19
 
20
- ## The two questions a run can ask
20
+ ## The questions a run can ask
21
21
 
22
22
  Runs plan before any browser opens.
23
23
 
@@ -29,6 +29,18 @@ Runs plan before any browser opens.
29
29
  - **seam** → `{"steps": [one click or goto]}` to get from one flow to the next,
30
30
  or `{"steps": []}` **unless you actually know** — an answer is saved and
31
31
  reused forever.
32
+ - **state** → a flow needs an app state ("member-has-active-bundle") nothing
33
+ before it makes true: `{"use": "<slug>"}` from `establishedBy` to run it
34
+ first, or `{"holds": true}` if it's already true for the account. Ask the
35
+ user rather than guess; it lasts for this run only.
36
+
37
+ Then, mid-run, with the browser open:
38
+
39
+ - **human** → a step only a person can do. Tell the user `ask`; answer
40
+ `{"done": true}` when they say so (the run checks `doneWhen` itself, and
41
+ carries on once the page shows it), or `{"abort": "why"}`.
42
+ - **handoff** → a step failed in a visible browser (`headed`). Same answers;
43
+ they do just that step by hand.
32
44
 
33
45
  ## Growing memory
34
46
 
@@ -42,7 +54,8 @@ Runs plan before any browser opens.
42
54
  - **Distilling** names a flow and splits it into reusable segments. **Ask the
43
55
  user before each one**; any flow may be distilled. Refer to steps by index
44
56
  only; preconditions are exactly `"authenticated"` or `"not authenticated"`;
45
- reuse existing segment slugs rather than inventing synonyms.
57
+ other app state goes in `requires` / `establishes` (kebab-case, reusing
58
+ `vocabulary.states`); reuse existing segment slugs rather than inventing synonyms.
46
59
  - **Learned something?** Keep a list and put it to the user at a natural pause,
47
60
  then write the approved items in one `understudy_remember`:
48
61
  a **fact** changes plans ("order history is at `/past-invoices`");
@@ -51,14 +64,28 @@ Runs plan before any browser opens.
51
64
  a **finding** says the app is broken.
52
65
  Reached a goal without `understudy_run`? Record it there as `reached`.
53
66
  - **Findings**: `understudy_findings` lists what looked broken; triage each as
54
- `issue`, `lesson` or `noise`.
67
+ `issue`, `lesson` or `noise`. A run that passed on a changed path isn't
68
+ history until its `flow_drift` finding is triaged `expected` — ask the user.
69
+ - **End checks**: a save offers checks of how the flow ended (headings, ticked
70
+ boxes, status messages). Ask the user which mean "it ended right"; add
71
+ those with `understudy_save { flow, add }`.
55
72
  - **Emails out of memory**: `understudy_app` with `placeholders: ["email"]`
56
73
  makes email fields placeholders and moves the addresses to the user's env file.
57
74
 
58
75
  ## Traps
59
76
 
60
77
  - **File uploads can't be recorded** — write a Playwright script instead.
61
- - **Don't save anything irreversible** (a real order): saving replays it.
78
+ - **A step only a person can do** (approval elsewhere, a code on a phone):
79
+ in a saved script, `human('what they do', { untilText | untilUrl | untilResponse })`.
80
+ - **What only the server shows** (a commission recorded): `page.waitForResponse`
81
+ in a script, or a `wait_response` step with `field` and `equals` / `above`.
82
+ - **An older flow missing one of these:** `understudy_save` with `flow` and `add`.
83
+ - **Purchases aren't replayed by saving.** A flow with a commit step ("Pay
84
+ now", "Confirm & Submit") is proven only up to it: the control is checked,
85
+ never pressed. Anything irreversible the words don't reveal still runs —
86
+ say so with a fact (`marksDestructive`) first — or save it without
87
+ replaying at all (`verify: false`, with a `note`). `understudy_save` with
88
+ `flow` proves one saved that way later, up to its commit.
62
89
  - **Logins are often rate-limited**; a missing login value stops a run before
63
90
  it opens a browser, so check `needs` from recall first. The answer names the
64
91
  env file line to add: ask the user to add it, then call again.
@@ -321,6 +321,63 @@ function readArgument(arg) {
321
321
  return { valueRef: arg.getText() };
322
322
  return { valueRef: arg.getText().slice(0, 80) };
323
323
  }
324
+ /**
325
+ * Actions whose FIRST argument is the value (`fill('x')`, `press('Enter')`).
326
+ * Every other action's first argument is its options object.
327
+ */
328
+ const VALUE_FIRST = new Set(['fill', 'type', 'press', 'selectOption', 'setInputFiles']);
329
+ /**
330
+ * Options that change nothing replay needs to know: it has its own timeouts
331
+ * and settles the page after every step.
332
+ */
333
+ const IGNORABLE_OPTIONS = new Set(['timeout', 'noWaitAfter', 'delay', 'trial', 'strict']);
334
+ /**
335
+ * Read an action's options — `click({ force: true })`, `fill(x, { force: true })`.
336
+ *
337
+ * THIS USED TO BE READ AS A VALUE. `check({ force: true })` became
338
+ * `valueRef: '{ force: true }'`, so replay never forced the click (it can't
339
+ * reach a checkbox hidden under its styled label without it) and every run
340
+ * demanded a login value called "{ force: true }". `force` is kept; an option
341
+ * the IR can't express (a right click, a modifier key) is reported.
342
+ */
343
+ function readActionOptions(arg, method) {
344
+ if (!arg)
345
+ return { unsupported: [] };
346
+ if (!ts.isObjectLiteralExpression(arg))
347
+ return { unsupported: [`${method}() options that aren't written inline`] };
348
+ const out = { unsupported: [] };
349
+ for (const prop of arg.properties) {
350
+ const key = prop.name && (ts.isIdentifier(prop.name) || ts.isStringLiteral(prop.name)) ? prop.name.text : undefined;
351
+ if (!key || !ts.isPropertyAssignment(prop)) {
352
+ out.unsupported.push(`${method}() options that aren't plain properties`);
353
+ continue;
354
+ }
355
+ if (key === 'force') {
356
+ if (prop.initializer.kind === ts.SyntaxKind.TrueKeyword)
357
+ out.force = true;
358
+ else if (prop.initializer.kind !== ts.SyntaxKind.FalseKeyword)
359
+ out.unsupported.push(`${method}({ force }) with a non-literal value`);
360
+ }
361
+ else if (!IGNORABLE_OPTIONS.has(key)) {
362
+ out.unsupported.push(`${method}({ ${key} })`);
363
+ }
364
+ }
365
+ return out;
366
+ }
367
+ /**
368
+ * `selectOption({ label: 'Large' })` / `({ value: 'l' })` → 'Large' / 'l'.
369
+ * Replay's selectOption(string) matches an option's value or its label.
370
+ */
371
+ function selectedOption(arg) {
372
+ if (!arg || !ts.isObjectLiteralExpression(arg) || arg.properties.length !== 1)
373
+ return undefined;
374
+ const prop = arg.properties[0];
375
+ if (!ts.isPropertyAssignment(prop) || !ts.isIdentifier(prop.name))
376
+ return undefined;
377
+ if (prop.name.text !== 'label' && prop.name.text !== 'value')
378
+ return undefined;
379
+ return text(prop.initializer);
380
+ }
324
381
  /** `process.env.X`, `process.env.X!`, `process.env['X']`, `process.env.X ?? ''` → 'X'. */
325
382
  function envVariable(arg) {
326
383
  let e = arg;
@@ -480,8 +537,10 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
480
537
  const events = [];
481
538
  const warnings = [];
482
539
  const dropped = [];
483
- // A static read cannot know which page it is on, so the last goto stands in.
484
- // Anything before the first goto is attributed to the fallback URL.
540
+ // A static read cannot know which page it is on, so the last goto (or literal
541
+ // URL wait) stands in. Anything before the first goto is attributed to the
542
+ // fallback URL. It is a guess: the first replay that passes replaces it with
543
+ // the page each step actually ran on (flows/save.ts, stepsFrom).
485
544
  let currentUrl = fallbackUrl ?? '';
486
545
  let startUrl = fallbackUrl ?? '';
487
546
  const snippet = (node) => node.getText().replace(/\s+/g, ' ').slice(0, 80);
@@ -500,7 +559,31 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
500
559
  resolution: 'script-literal',
501
560
  ...(match.regex ? { hints: { urlRegex: true, urlFlags: match.flags } } : {}),
502
561
  });
562
+ // A wait for a plain address says which page the steps after it are on —
563
+ // the best a static read can do. A regex or a glob names no single page.
564
+ // Only an address that is one: a bare word like 'dashboard' is a substring
565
+ // replay looks for, not a path to resolve.
566
+ const plain = !match.regex && !match.source.includes('*');
567
+ if (plain && /^https?:\/\//.test(match.source))
568
+ currentUrl = match.source;
569
+ else if (plain && match.source.startsWith('/') && fallbackUrl)
570
+ currentUrl = absolute(match.source, fallbackUrl);
503
571
  };
572
+ /** A `wait_response` step from what waitForResponse() was given. */
573
+ const pushWaitResponse = (arg, node) => {
574
+ const { check, why } = responseWaitFrom(arg);
575
+ if (!check)
576
+ return drop(`${why ?? 'waitForResponse()'}, not kept`, node);
577
+ const { url, ...rest } = check;
578
+ events.push({
579
+ seq: events.length, ts: events.length, action: 'wait_response', value: url,
580
+ url: currentUrl, resolution: 'script-literal', ...(Object.keys(rest).length ? { hints: rest } : {}),
581
+ });
582
+ };
583
+ // `const answer = page.waitForResponse(...)`, the click, then `await answer`:
584
+ // Playwright's way of not missing a fast response. The wait belongs where it
585
+ // is AWAITED — after the click — not where it was set up.
586
+ const deferred = new Map();
504
587
  /** An `assert` step on an element (or, for `title`, the page). */
505
588
  const pushAssert = (t, kind, arg, node) => {
506
589
  const needsValue = kind === 'text' || kind === 'contains' || kind === 'value' || kind === 'title';
@@ -575,6 +658,17 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
575
658
  pushAssert(t, kind, arg, node);
576
659
  };
577
660
  const visit = (node) => {
661
+ if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer && ts.isCallExpression(node.initializer)
662
+ && ts.isPropertyAccessExpression(node.initializer.expression) && node.initializer.expression.name.text === 'waitForResponse') {
663
+ deferred.set(node.name.text, node.initializer);
664
+ return;
665
+ }
666
+ if (ts.isAwaitExpression(node) && ts.isIdentifier(node.expression) && deferred.has(node.expression.text)) {
667
+ const call = deferred.get(node.expression.text);
668
+ deferred.delete(node.expression.text);
669
+ pushWaitResponse(call.arguments[0], call);
670
+ return;
671
+ }
578
672
  // `Promise.all([page.waitForURL(x), page.click(y)])` — the wait is written
579
673
  // first but happens after the click it waits on. Replay is sequential, so
580
674
  // the actions go first and the waits after them.
@@ -603,6 +697,34 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
603
697
  : ts.isIdentifier(node.expression)
604
698
  ? node.expression.text
605
699
  : undefined;
700
+ // A PERSON'S STEP: `human('Approve the visit in the provider portal',
701
+ // { untilText: 'Visit accepted' })`. Not Playwright — a marker an agent
702
+ // writes where it had to ask someone. Read, never run.
703
+ if (callee === 'human' && ts.isIdentifier(node.expression)) {
704
+ const instruction = node.arguments[0] ? text(node.arguments[0]) : undefined;
705
+ if (!instruction) {
706
+ warnings.push(`human() needs what the person must do, as a literal string: ${snippet(node)}`);
707
+ }
708
+ else {
709
+ const until = readUntil(node.arguments[1]);
710
+ for (const u of until.unsupported)
711
+ warnings.push(`human({ ${u} }) cannot be represented: ${snippet(node)}`);
712
+ events.push({
713
+ seq: events.length,
714
+ ts: events.length,
715
+ action: 'human',
716
+ value: instruction,
717
+ url: currentUrl,
718
+ resolution: 'script-literal',
719
+ ...(until.url || until.text || until.response
720
+ ? { hints: { ...(until.url ? { untilUrl: until.url } : {}), ...(until.text ? { untilText: until.text } : {}), ...(until.response ? { untilResponse: until.response } : {}) } }
721
+ : {}),
722
+ });
723
+ if (until.url?.startsWith('/') && fallbackUrl && !until.url.includes('*'))
724
+ currentUrl = absolute(until.url, fallbackUrl);
725
+ }
726
+ return;
727
+ }
606
728
  if (callee && SNAPSHOT_CALLS.has(callee)) {
607
729
  // The label is the first string literal in the arguments, wherever it
608
730
  // sits — `toHaveScreenshot('x.png')` has it first, `checkpoint(page,
@@ -670,6 +792,9 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
670
792
  pushAssert({ rooted: true, bare: false, merged: { css } }, kind, undefined, node);
671
793
  }
672
794
  }
795
+ else if (method === 'waitForResponse') {
796
+ pushWaitResponse(node.arguments[0], node);
797
+ }
673
798
  else if (!SETTLING_WAITS.has(method)) {
674
799
  drop(`${method}() is not kept (replay can't wait on network events)`, node);
675
800
  }
@@ -712,7 +837,22 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
712
837
  warnings.push(`unaddressable ${action}: ${snippet(node)}`);
713
838
  }
714
839
  else {
715
- const raw = readArgument(node.arguments[0]);
840
+ const takesValue = VALUE_FIRST.has(method);
841
+ const options = readActionOptions(node.arguments[takesValue ? 1 : 0], method);
842
+ for (const o of options.unsupported)
843
+ warnings.push(`${o} cannot be represented, ignored: ${snippet(node)}`);
844
+ let raw = {};
845
+ if (takesValue) {
846
+ const first = node.arguments[0];
847
+ const option = method === 'selectOption' ? selectedOption(first) : undefined;
848
+ if (option !== undefined)
849
+ raw = { value: option };
850
+ else if (first && (ts.isObjectLiteralExpression(first) || ts.isArrayLiteralExpression(first))) {
851
+ warnings.push(`${method}() with ${ts.isArrayLiteralExpression(first) ? 'several values' : 'an options object'} cannot be represented: ${snippet(node)}`);
852
+ }
853
+ else
854
+ raw = readArgument(first);
855
+ }
716
856
  const fieldHint = merged.name?.source || merged.testId || merged.css || 'field';
717
857
  const secretSignal = [merged.name?.source, merged.css, merged.testId].filter(Boolean).join(' ');
718
858
  // A literal password in a committed test still must not reach the
@@ -733,7 +873,7 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
733
873
  ...where(merged),
734
874
  url: currentUrl,
735
875
  resolution: 'script-literal',
736
- ...hintsOf(t),
876
+ ...hintsOf(t, options.force ? { force: true } : {}),
737
877
  });
738
878
  }
739
879
  }
@@ -742,12 +882,74 @@ export async function parseScript(filePath, appSlug, fallbackUrl) {
742
882
  ts.forEachChild(node, visit);
743
883
  };
744
884
  visit(sourceFile);
885
+ for (const [name, call] of deferred)
886
+ drop(`waitForResponse() kept in "${name}" but never awaited, not kept`, call);
745
887
  return {
746
888
  recording: buildRecording({ source: 'script', origin: filePath, appSlug, startUrl }, events.map((e, i) => ({ ...e, seq: i }))),
747
889
  warnings,
748
890
  dropped,
749
891
  };
750
892
  }
893
+ /**
894
+ * What `waitForResponse(x)` waits for. A string or glob is the address; a
895
+ * predicate is read for the three things it usually tests —
896
+ * `r.url().includes('/api/visits') && r.status() === 201 && r.request().method() === 'POST'`.
897
+ * Read from source text, so anything cleverer is reported rather than guessed.
898
+ */
899
+ function responseWaitFrom(arg) {
900
+ if (!arg)
901
+ return { why: 'waitForResponse() with nothing to wait for' };
902
+ const literal = text(arg);
903
+ if (literal)
904
+ return { check: { url: literal } };
905
+ if (ts.isRegularExpressionLiteral(arg))
906
+ return { why: 'waitForResponse(/regex/) — write the address as a string or glob' };
907
+ if (!ts.isArrowFunction(arg) && !ts.isFunctionExpression(arg))
908
+ return { why: 'waitForResponse() with a predicate held in a variable' };
909
+ const body = arg.body.getText();
910
+ const url = body.match(/\.url\(\)\s*(?:\.(?:includes|endsWith|startsWith)\(\s*|===?\s*)['"`]([^'"`]+)['"`]/)?.[1];
911
+ if (!url)
912
+ return { why: 'waitForResponse() predicate with no literal address in it (r.url().includes(\'…\'))' };
913
+ const status = body.match(/\.status\(\)\s*===?\s*(\d{3})/)?.[1];
914
+ const method = body.match(/\.method\(\)\s*===?\s*['"`]([A-Za-z]+)['"`]/)?.[1];
915
+ return { check: { url, ...(status ? { status: Number(status) } : {}), ...(method ? { method: method.toUpperCase() } : {}) } };
916
+ }
917
+ /** `{ untilUrl: '/done', untilText: 'Accepted' }`, literals only. */
918
+ function readUntil(node) {
919
+ const out = { unsupported: [] };
920
+ if (!node)
921
+ return out;
922
+ if (!ts.isObjectLiteralExpression(node))
923
+ return { unsupported: ['options not written inline'] };
924
+ for (const prop of node.properties) {
925
+ const key = prop.name && ts.isIdentifier(prop.name) ? prop.name.text : '?';
926
+ const value = ts.isPropertyAssignment(prop) ? text(prop.initializer) : undefined;
927
+ if (key === 'untilUrl' && value)
928
+ out.url = value;
929
+ else if (key === 'untilText' && value)
930
+ out.text = value;
931
+ else if (key === 'untilResponse' && value)
932
+ out.response = value;
933
+ else if (key === 'untilResponse' && ts.isPropertyAssignment(prop) && ts.isObjectLiteralExpression(prop.initializer)) {
934
+ // { url, method, status, field, equals | above } — literal values only.
935
+ const o = {};
936
+ for (const q of prop.initializer.properties) {
937
+ if (!ts.isPropertyAssignment(q) || !ts.isIdentifier(q.name))
938
+ continue;
939
+ const v = q.initializer;
940
+ o[q.name.text] = ts.isNumericLiteral(v) ? Number(v.text)
941
+ : v.kind === ts.SyntaxKind.TrueKeyword ? true : v.kind === ts.SyntaxKind.FalseKeyword ? false : text(v);
942
+ }
943
+ if (typeof o.url === 'string')
944
+ out.response = o;
945
+ else
946
+ out.unsupported.push('untilResponse without a literal url');
947
+ }
948
+ else
949
+ out.unsupported.push(key);
950
+ }
951
+ return out;
952
+ }
751
953
  /** `{ state: 'hidden' }` → 'hidden'. */
752
954
  function readState(node) {
753
955
  if (!node || !ts.isObjectLiteralExpression(node))
@@ -29,13 +29,19 @@ export interface Vocabulary {
29
29
  steps: number;
30
30
  preconditions: string[];
31
31
  outcome: string | null;
32
+ requires?: string[];
33
+ establishes?: string[];
32
34
  }>;
33
35
  /** Whole recorded flows, for coarser matches. */
34
36
  flows: Array<{
35
37
  slug: string;
36
38
  title: string;
37
39
  intent: string;
40
+ requires?: string[];
41
+ establishes?: string[];
38
42
  }>;
43
+ /** App states already named by some flow's requires/establishes — reuse these words. */
44
+ states?: string[];
39
45
  /** What is known to be true about the app, phrased as the corpus phrases it. */
40
46
  facts: string[];
41
47
  }
@@ -74,6 +80,8 @@ export interface Distilled {
74
80
  intent: string;
75
81
  preconditions: string[];
76
82
  outcome: string;
83
+ requires?: string[];
84
+ establishes?: string[];
77
85
  segments: Array<{
78
86
  slug: string;
79
87
  title: string;
@@ -82,6 +90,8 @@ export interface Distilled {
82
90
  stepRange: [number, number];
83
91
  preconditions?: string[];
84
92
  outcome?: string;
93
+ requires?: string[];
94
+ establishes?: string[];
85
95
  }>;
86
96
  candidateLessons?: Array<{
87
97
  kind: string;
@@ -102,6 +112,8 @@ export interface Distilled {
102
112
  * the model, or it can end up named, segmented, and bound like a real one.
103
113
  */
104
114
  export declare function buildDistillRequest(recording: RawRecording, replayResult: ReplayResult, vocabulary?: Vocabulary): DistillRequest;
115
+ /** A state name: kebab-case, short enough to be a name rather than a sentence. */
116
+ export declare const STATE_NAME: RegExp;
105
117
  export interface ValidationResult {
106
118
  ok: boolean;
107
119
  errors: string[];
@@ -22,6 +22,8 @@ const SCHEMA = {
22
22
  intent: { type: 'string', description: 'What this whole flow is FOR, in the user\'s language. Not a list of steps.' },
23
23
  preconditions: { type: 'array', items: { type: 'string', enum: ['authenticated', 'not authenticated'] }, description: 'Exactly "authenticated" or "not authenticated" — nothing else. Empty if neither matters.' },
24
24
  outcome: { type: 'string', description: 'The state the app is in afterwards.' },
25
+ requires: { type: 'array', items: { type: 'string', pattern: '^[a-z0-9]+(-[a-z0-9]+)*$' }, description: 'App states that must already be true for this to work, kebab-case ("member-has-active-bundle"). Reuse vocabulary.states.' },
26
+ establishes: { type: 'array', items: { type: 'string', pattern: '^[a-z0-9]+(-[a-z0-9]+)*$' }, description: 'App states this makes true, in the same words a flow that needs them would use.' },
25
27
  segments: {
26
28
  type: 'array',
27
29
  description: 'Reusable chunks. A segment belongs to the APP, not to this recording — a login block cut from a checkout recording must be reusable by every future flow.',
@@ -35,6 +37,8 @@ const SCHEMA = {
35
37
  stepRange: { type: 'array', items: { type: 'integer' }, minItems: 2, maxItems: 2, description: '[start, end) indices into the steps given. Never invent steps.' },
36
38
  preconditions: { type: 'array', items: { type: 'string', enum: ['authenticated', 'not authenticated'] } },
37
39
  outcome: { type: 'string' },
40
+ requires: { type: 'array', items: { type: 'string' } },
41
+ establishes: { type: 'array', items: { type: 'string' } },
38
42
  },
39
43
  },
40
44
  },
@@ -50,38 +54,11 @@ const SCHEMA = {
50
54
  },
51
55
  },
52
56
  };
53
- const INSTRUCTIONS = `You are distilling a VERIFIED browser recording into reusable memory.
54
-
55
- The steps below were captured from a real session and every one of them was
56
- replayed successfully. They are ground truth.
57
-
58
- YOUR JOB IS TO ANNOTATE AND PARTITION, NOT TO AUTHOR.
59
- · Do NOT restate, reorder, or invent steps. Reference them by index only.
60
- · Segments are [start, end) ranges over the step list given.
61
- · Segments should cut on MEANINGFUL boundaries — a change of page state
62
- (see sigAfter) is usually one.
63
-
64
- What matters most:
65
- · intent — what this flow is FOR, phrased the way someone would ASK for it
66
- ("log in as a standard user"), never a description of the mechanics
67
- ("fill two textboxes and click a button").
68
- · segments — a segment belongs to the APP, not to this recording. A login
69
- block cut out of a checkout recording must be reusable by every future
70
- flow, so name and scope it accordingly.
71
- · preconditions — EXACTLY "authenticated" or "not authenticated", or empty.
72
- Not "authenticated as a member": the planner checks whole strings, so any
73
- other wording silently never matches.
74
-
75
- USE THE APP'S EXISTING VOCABULARY.
76
- The request includes every segment this app already has. If a block of steps
77
- here does the same thing as one of those, REUSE its exact slug and phrasing
78
- rather than inventing a synonym. "Sign in to the app" and "Authenticate as a
79
- member" as two separate segments is a corpus defect: they compete for the same
80
- bind slot, and a planner searching for one will not find the other.
81
- Only invent new wording when the thing genuinely is new.
82
-
83
- Only report a lesson or a correction if the recording actually shows one.
84
- Inventing them is worse than leaving the arrays empty.`;
57
+ const INSTRUCTIONS = `Name this recording and cut it into reusable segments. Every step below replayed; refer to steps by index only — never add, change or reorder them.
58
+ - intent: what it is FOR, as someone would ask ("log in as a member"), not the mechanics.
59
+ - segments: [start, end) ranges, cut where the page changes (sigAfter). A segment belongs to the app: if one in vocabulary does the same thing, reuse its slug.
60
+ - preconditions: exactly "authenticated" or "not authenticated", or none. Other app state goes in requires / establishes, kebab-case, reusing vocabulary.states.
61
+ - candidateLessons, corrections: only if the recording shows one. Empty beats invented.`;
85
62
  /**
86
63
  * Build the payload handed to whoever is distilling.
87
64
  *
@@ -113,6 +90,8 @@ export function buildDistillRequest(recording, replayResult, vocabulary = { segm
113
90
  schema: SCHEMA,
114
91
  };
115
92
  }
93
+ /** A state name: kebab-case, short enough to be a name rather than a sentence. */
94
+ export const STATE_NAME = /^(?=.{2,60}$)[a-z0-9]+(-[a-z0-9]+)*$/;
116
95
  /**
117
96
  * Validate a distillation before ANY of it is written.
118
97
  *
@@ -143,6 +122,18 @@ export function validateDistilled(input, stepCount) {
143
122
  push('preconditions must be an array');
144
123
  else
145
124
  preconditionProblem('preconditions', d.preconditions);
125
+ const stateProblem = (at, v) => {
126
+ if (v === undefined)
127
+ return;
128
+ if (!Array.isArray(v))
129
+ return push(`${at} must be an array of state names`);
130
+ for (const x of v) {
131
+ if (typeof x !== 'string' || !STATE_NAME.test(x))
132
+ push(`${at}: "${String(x)}" must be a kebab-case state name, e.g. "member-has-active-bundle"`);
133
+ }
134
+ };
135
+ stateProblem('requires', d.requires);
136
+ stateProblem('establishes', d.establishes);
146
137
  if (!Array.isArray(d.segments)) {
147
138
  push('segments must be an array');
148
139
  return { ok: false, errors };
@@ -166,6 +157,8 @@ export function validateDistilled(input, stepCount) {
166
157
  // honest: a range outside the verified steps would let the model reference
167
158
  // something that was never recorded or never replayed.
168
159
  preconditionProblem(`${at}.preconditions`, s.preconditions);
160
+ stateProblem(`${at}.requires`, s.requires);
161
+ stateProblem(`${at}.establishes`, s.establishes);
169
162
  const range = s.stepRange;
170
163
  if (!Array.isArray(range) || range.length !== 2 || !range.every((n) => Number.isInteger(n))) {
171
164
  push(`${at}.stepRange must be [start, end) integers`);