@jeffawe/understudy 0.2.2 → 0.2.3

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
@@ -106,13 +106,20 @@ understudy save <hash> "log in as a member" # prove it by replaying, then keep i
106
106
  understudy flows myapp # what it knows how to do
107
107
  understudy replay myapp log-in-as-a-member # run one flow
108
108
  understudy run myapp "sign in" # find the flow for a goal, and run it
109
- understudy findings myapp # what looked broken
109
+ understudy import myapp login.spec.ts # turn a Playwright script into a recording, then save it
110
+ understudy findings myapp # what looked broken, most severe first
110
111
  understudy emit myapp log-in-as-a-member # print it as a Playwright (or Cypress) test
111
112
  understudy app myapp --placeholder email # keep email addresses out of memory (moves them to your env file)
112
113
  ```
113
114
 
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
+
114
120
  An unproven flow is marked as such in `flows` and recall; the first run of
115
- it that passes proves it. `understudy --help` lists everything. A flow that commits something real — a
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
116
123
  purchase, a deletion — is marked destructive and refused unless you pass
117
124
  `--allow-purchases`.
118
125
 
@@ -121,8 +128,11 @@ purchase, a deletion — is marked destructive and refused unless you pass
121
128
  Everything stays with you. Understudy has no server, no account and no
122
129
  telemetry.
123
130
 
124
- - **Recordings** are files on your machine. The Chrome extension sends what it
125
- records only to Understudy on `127.0.0.1`.
131
+ - **Recordings** are files on your machine, in `~/.understudy` (or
132
+ `UNDERSTUDY_HOME`) — the same place whichever folder you, or your agent, run
133
+ it from. The Chrome extension sends what it records only to Understudy on
134
+ `127.0.0.1`. Before 0.2.2 they went in a `.understudy` folder wherever it ran;
135
+ those still load.
126
136
  - **Saved flows, notes and findings** go to the MongoDB you configured.
127
137
  - **Your embedding model** (Voyage by default, if you set a key) receives only
128
138
  the short texts used for search — flow names and descriptions, facts and
@@ -85,9 +85,20 @@ export interface StepOutcome {
85
85
  roleHadNoMatch?: {
86
86
  fellBackTo: string;
87
87
  };
88
+ /** A failed assertion: what it actually found, e.g. the visible text near where the expected text should be. */
89
+ saw?: string;
88
90
  }
91
+ /**
92
+ * The part of a page's text worth showing next to an expected string that
93
+ * wasn't there: a window around the longest run of the expected words that IS
94
+ * there ("Total Transactions 9" for an expected "Total Transactions 10"), or
95
+ * the start of the text if none is. Pure; exported for tests.
96
+ */
97
+ export declare function excerpt(actual: string, expected: string | undefined, width?: number): string;
89
98
  export interface CapturedSignal {
90
99
  kind: 'console' | 'pageerror' | 'requestfailed' | 'http';
100
+ /** console only: console.error or console.warn. Warnings are kept as evidence but aren't findings. */
101
+ level?: 'error' | 'warning';
91
102
  /** Step this happened during — the correlation that makes signals useful. */
92
103
  duringStep: number;
93
104
  text: string;
@@ -25,6 +25,40 @@ import {} from 'playwright';
25
25
  import { openLease } from './browser.js';
26
26
  import { computeSig, urlPattern, waitForAriaStable } from './sig.js';
27
27
  import { acceptBaseline, captureCheckpoint, worthJudging, VISUAL_SEVERE } from './visual.js';
28
+ /** An assertion that failed, carrying what it actually saw. */
29
+ class AssertionFailed extends Error {
30
+ saw;
31
+ constructor(message, saw) {
32
+ super(message);
33
+ this.saw = saw;
34
+ }
35
+ }
36
+ /**
37
+ * The part of a page's text worth showing next to an expected string that
38
+ * wasn't there: a window around the longest run of the expected words that IS
39
+ * there ("Total Transactions 9" for an expected "Total Transactions 10"), or
40
+ * the start of the text if none is. Pure; exported for tests.
41
+ */
42
+ export function excerpt(actual, expected, width = 160) {
43
+ const text = actual.replace(/\s+/g, ' ').trim();
44
+ if (text.length <= width)
45
+ return text;
46
+ const words = (expected ?? '').replace(/\s+/g, ' ').trim().split(' ').filter(Boolean);
47
+ const lower = text.toLowerCase();
48
+ for (let k = words.length; k >= 1; k--) {
49
+ for (let start = 0; start + k <= words.length; start++) {
50
+ const phrase = words.slice(start, start + k).join(' ').toLowerCase();
51
+ if (phrase.length < 3)
52
+ continue;
53
+ const at = lower.indexOf(phrase);
54
+ if (at < 0)
55
+ continue;
56
+ const from = Math.max(0, Math.min(at - Math.floor(width / 3), text.length - width));
57
+ return `${from > 0 ? '…' : ''}${text.slice(from, from + width)}${from + width < text.length ? '…' : ''}`;
58
+ }
59
+ }
60
+ return `${text.slice(0, width)}…`;
61
+ }
28
62
  /** Lesson kinds that mean "this page resolves late" — settle before acting. */
29
63
  const SETTLE_KINDS = new Set(['wait', 'timing']);
30
64
  /** Bodies above this are truncated — a findings fingerprint needs the shape, not the payload. */
@@ -207,7 +241,9 @@ async function checkAssert(page, event, values, timeoutMs) {
207
241
  : squash(actual) === squash(expected);
208
242
  const shown = regex ? `/${expected}/` : `"${expected}"`;
209
243
  /** Poll `read` until `ok`, like expect's retrying; report the last value seen. */
210
- const until = async (read, ok, what) => {
244
+ const until = async (read, ok, what,
245
+ /** What to show as "saw" — e.g. the visible text, not textContent's scripts. */
246
+ shownAs) => {
211
247
  const deadline = Date.now() + timeoutMs;
212
248
  let last = null;
213
249
  for (;;) {
@@ -215,7 +251,10 @@ async function checkAssert(page, event, values, timeoutMs) {
215
251
  if (ok(last))
216
252
  return;
217
253
  if (Date.now() >= deadline) {
218
- throw new Error(`${what}${last === null ? '' : `, got ${typeof last === 'string' ? `"${squash(last).slice(0, 80)}"` : String(last)}`}`);
254
+ const visible = shownAs ? await shownAs().catch(() => null) : null;
255
+ const raw = visible ?? (typeof last === 'string' ? last : null);
256
+ const saw = raw !== null ? `"${excerpt(raw, expected)}"` : last === null ? 'nothing it could read' : String(last);
257
+ throw new AssertionFailed(`${what} — saw ${saw}`, saw);
219
258
  }
220
259
  await page.waitForTimeout(100);
221
260
  }
@@ -236,12 +275,18 @@ async function checkAssert(page, event, values, timeoutMs) {
236
275
  case 'hidden':
237
276
  await target.waitFor({ state: kind, timeout: timeoutMs }).catch(async () => {
238
277
  const count = await locator.count().catch(() => 0);
239
- throw new Error(`expected ${desc} to be ${kind}${kind === 'visible' && count === 0 ? ' — it matched no elements' : ''}`);
278
+ const saw = kind === 'visible'
279
+ ? (count === 0 ? 'it matched no elements' : `it matched ${count} element(s), none visible`)
280
+ : `it is still visible${count > 1 ? ` (${count} match)` : ''}`;
281
+ throw new AssertionFailed(`expected ${desc} to be ${kind} — ${saw}`, saw);
240
282
  });
241
283
  return;
242
284
  case 'text':
243
285
  case 'contains':
244
- return until(() => target.textContent({ timeout: 1000 }), (v) => typeof v === 'string' && matches(v), `expected ${desc} to ${kind === 'text' ? 'have text' : 'contain text'} ${shown}`);
286
+ return until(() => target.textContent({ timeout: 1000 }), (v) => typeof v === 'string' && matches(v), `expected ${desc} to ${kind === 'text' ? 'have text' : 'contain text'} ${shown}`,
287
+ // textContent includes <script> and hidden text (a JSON-LD blob on <body>);
288
+ // show what a person would see.
289
+ () => target.innerText({ timeout: 1000 }));
245
290
  case 'value':
246
291
  return until(() => target.inputValue({ timeout: 1000 }), (v) => typeof v === 'string' && matches(v), `expected ${desc} to have value ${event.valueRef ? `of ${event.valueRef}` : shown}`);
247
292
  case 'checked':
@@ -324,7 +369,7 @@ export async function replay(recording, opts = {}) {
324
369
  page.on('console', (msg) => {
325
370
  if (msg.type() !== 'error' && msg.type() !== 'warning')
326
371
  return;
327
- signals.push({ kind: 'console', duringStep: currentStep, text: msg.text().slice(0, 500) });
372
+ signals.push({ kind: 'console', level: msg.type() === 'error' ? 'error' : 'warning', duringStep: currentStep, text: msg.text().slice(0, 500) });
328
373
  });
329
374
  page.on('pageerror', (err) => {
330
375
  signals.push({ kind: 'pageerror', duringStep: currentStep, text: String(err).slice(0, 500) });
@@ -726,7 +771,15 @@ export async function replay(recording, opts = {}) {
726
771
  // every step regardless. Not comparing them meant execution could walk
727
772
  // into a page the plan had never seen and notice nothing until a locator
728
773
  // happened to miss.
729
- if (event.expectedSig && event.expectedSig !== sig.sig) {
774
+ // A REDIRECT THAT LANDS A BEAT EARLY OR LATE IS NOT AN UNEXPECTED PAGE.
775
+ // Signing in submits, then the app routes to /auth/otp once its API
776
+ // answers — sometimes before this fingerprint, sometimes after. Seeing
777
+ // the page the previous step expected (not there yet) or the one the
778
+ // next step expects (there already) is the same path, a step out of
779
+ // phase. Never for the first step: that one detects a stale session.
780
+ const neighbours = i > 0 ? [walk[i - 1]?.event.expectedSig, walk[i + 1]?.event.expectedSig] : [];
781
+ const inPhase = neighbours.includes(sig.sig);
782
+ if (event.expectedSig && event.expectedSig !== sig.sig && !inPhase) {
730
783
  outcome.unexpectedPage = { expected: event.expectedSig, observed: sig.sig };
731
784
  // THE ESCALATION. An unexpected page is not automatically wrong — an
732
785
  // app may have gained a banner — but continuing blindly is how a run
@@ -751,7 +804,15 @@ export async function replay(recording, opts = {}) {
751
804
  }
752
805
  }
753
806
  catch (err) {
754
- outcome.error = (err instanceof Error ? err.message : String(err)).split('\n')[0].slice(0, 200);
807
+ let message = (err instanceof Error ? err.message : String(err)).split('\n')[0];
808
+ // Playwright's first line ("locator.click: Timeout 5000ms exceeded.") leaves
809
+ // the locator to later lines; say which one, so the step can be found.
810
+ const desc = describeLocator(event);
811
+ if (desc !== '(no locator)' && !message.includes(desc))
812
+ message = `${desc}: ${message}`;
813
+ outcome.error = message.slice(0, 500);
814
+ if (err instanceof AssertionFailed && err.saw)
815
+ outcome.saw = err.saw;
755
816
  }
756
817
  if (outcome.ok || attempt === maxAttempts)
757
818
  break;
package/dist/entry/mcp.js CHANGED
@@ -87,7 +87,7 @@ async function continueRun(state, opts) {
87
87
  runId: state.runId,
88
88
  plan,
89
89
  seams: state.seams,
90
- failedSteps: r.steps.filter((s) => !s.ok).map((s) => ({ seq: s.seq, action: s.action, error: s.error })),
90
+ failedSteps: r.steps.filter((s) => !s.ok).map((s) => ({ seq: s.seq, action: s.action, error: s.error, ...(s.saw ? { saw: s.saw } : {}) })),
91
91
  unexpectedPages: r.steps.filter((s) => s.unexpectedPage).map((s) => ({ seq: s.seq, ...s.unexpectedPage })),
92
92
  path: r.sigSequence,
93
93
  drift: recorded.drift.notCompared ? `not compared: ${recorded.drift.notCompared}`
@@ -269,7 +269,7 @@ server.registerTool('understudy_save', {
269
269
  ...(dropped.length ? { droppedAssertions: dropped, droppedWhy: 'these checks in the script were not kept, so the flow checks less than the script did' } : {}),
270
270
  ...(r ? {
271
271
  passed: r.ok,
272
- failedSteps: r.steps.filter((s) => !s.ok).map((s) => ({ seq: s.seq, action: s.action, error: s.error })),
272
+ failedSteps: r.steps.filter((s) => !s.ok).map((s) => ({ seq: s.seq, action: s.action, error: s.error, ...(s.saw ? { saw: s.saw } : {}) })),
273
273
  signIn: out.proven.signIn,
274
274
  } : { replayed: false }),
275
275
  ...(finished.get(a.app)?.droppedUploads ? { droppedUploads: finished.get(a.app).droppedUploads } : {}),
@@ -13,12 +13,15 @@ export function stable(text) {
13
13
  .replace(/(https?:\/\/[^\s'"?#]+)\?[^\s'"]*/g, '$1')
14
14
  .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, ':uuid')
15
15
  // Not a port: `localhost:3000` is where the app is, not a varying id, and
16
- // replacing it produced `localhost::n`.
17
- .replace(/(?<![\w\]]:)\b\d{3,}\b/g, ':n')
16
+ // replacing it produced `localhost::n`. Not part of a dotted address or
17
+ // version either (127.0.0.1, 1.2.300): replacing those produced `:n.0.0.1`.
18
+ .replace(/(?<![\w\]]:)(?<![\d.])\d{3,}(?!\d|\.\d)/g, ':n')
18
19
  .replace(/\s+/g, ' ')
19
20
  .trim()
20
21
  .slice(0, 300);
21
22
  }
23
+ /** For showing: whitespace squashed and cut, nothing rewritten. */
24
+ const readable = (text) => text.replace(/\s+/g, ' ').trim().slice(0, 300);
22
25
  /** Route shape only: `https://x.com/orders/123?a=b` → `https://x.com/orders/:id`. */
23
26
  export function routeOf(url) {
24
27
  if (!url)
@@ -51,11 +54,14 @@ export function extractFindings(result, goal) {
51
54
  fingerprint: fingerprint(['network_error', s.status, route]),
52
55
  });
53
56
  }
54
- else if (s.kind === 'console' || s.kind === 'pageerror') {
57
+ else if ((s.kind === 'console' && s.level !== 'warning') || s.kind === 'pageerror') {
58
+ // console.warn is framework chatter far more often than a defect (Next.js
59
+ // image-size hints, React dev warnings): kept in the run, not a finding.
55
60
  add({
56
61
  kind: 'console_error',
57
62
  severity: s.kind === 'pageerror' ? 'high' : 'low',
58
- statement: stable(s.text),
63
+ // Shown as it was; only the fingerprint is normalised.
64
+ statement: readable(s.text),
59
65
  evidence: { text: s.text, duringStep: s.duringStep, goal },
60
66
  fingerprint: fingerprint(['console_error', stable(s.text)]),
61
67
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jeffawe/understudy",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "End-to-end tests for your own web apps: record a flow once, and Understudy remembers it, replays it, notices when the app changes, and runs goals you describe in words — on its own or as an MCP server for AI agents.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",