@jeffawe/understudy 0.2.1 → 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.
@@ -22,8 +22,10 @@
22
22
  import { createHash } from 'node:crypto';
23
23
  import { chmod, mkdir, readFile, writeFile, unlink } from 'node:fs/promises';
24
24
  import { existsSync } from 'node:fs';
25
- import { join, resolve } from 'node:path';
26
- export const SESSIONS_DIR = process.env.UNDERSTUDY_SESSIONS_DIR ?? resolve('.understudy/sessions');
25
+ import { join } from 'node:path';
26
+ import { HOME } from '../store/settings.js';
27
+ /** Under ~/.understudy, not the current folder — see recording-store.ts. */
28
+ export const SESSIONS_DIR = process.env.UNDERSTUDY_SESSIONS_DIR ?? join(HOME, 'sessions');
27
29
  /**
28
30
  * How long a saved session is worth trying at all.
29
31
  *
@@ -11,6 +11,12 @@
11
11
  * knows which — it is just a directory.
12
12
  */
13
13
  import type { RawRecording } from './recording.js';
14
+ /**
15
+ * Under ~/.understudy (or UNDERSTUDY_HOME), NOT the current folder. It used to
16
+ * be `./.understudy/recordings`, so the MCP server — started by an agent from
17
+ * inside some repo — wrote recordings there, and the CLI run from anywhere
18
+ * else said "no recordings yet" about a flow saved a minute earlier.
19
+ */
14
20
  export declare const RECORDINGS_DIR: string;
15
21
  export declare function recordingPath(hash: string): string;
16
22
  /**
@@ -13,9 +13,23 @@
13
13
  import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
14
14
  import { existsSync } from 'node:fs';
15
15
  import { join, resolve } from 'node:path';
16
- export const RECORDINGS_DIR = process.env.UNDERSTUDY_RECORDINGS_DIR ?? resolve('.understudy/recordings');
16
+ import { HOME } from '../store/settings.js';
17
+ /**
18
+ * Under ~/.understudy (or UNDERSTUDY_HOME), NOT the current folder. It used to
19
+ * be `./.understudy/recordings`, so the MCP server — started by an agent from
20
+ * inside some repo — wrote recordings there, and the CLI run from anywhere
21
+ * else said "no recordings yet" about a flow saved a minute earlier.
22
+ */
23
+ export const RECORDINGS_DIR = process.env.UNDERSTUDY_RECORDINGS_DIR ?? join(HOME, 'recordings');
24
+ /** Where recordings went before, read (never written) so old hashes still load. */
25
+ const LEGACY_DIR = resolve('.understudy/recordings');
26
+ const legacyDirs = () => (process.env.UNDERSTUDY_RECORDINGS_DIR || LEGACY_DIR === RECORDINGS_DIR ? [] : [LEGACY_DIR]);
17
27
  export function recordingPath(hash) {
18
- return join(RECORDINGS_DIR, `${hash}.json`);
28
+ const path = join(RECORDINGS_DIR, `${hash}.json`);
29
+ if (existsSync(path))
30
+ return path;
31
+ const old = legacyDirs().map((d) => join(d, `${hash}.json`)).find(existsSync);
32
+ return old ?? path;
19
33
  }
20
34
  /**
21
35
  * Write a recording, keyed by hash.
@@ -25,7 +39,7 @@ export function recordingPath(hash) {
25
39
  */
26
40
  export async function saveRecording(rec) {
27
41
  await mkdir(RECORDINGS_DIR, { recursive: true });
28
- const path = recordingPath(rec.hash);
42
+ const path = join(RECORDINGS_DIR, `${rec.hash}.json`);
29
43
  const existed = existsSync(path);
30
44
  await writeFile(path, JSON.stringify(rec, null, 2), 'utf8');
31
45
  return { path, existed };
@@ -39,15 +53,24 @@ export async function loadRecording(hashOrPath) {
39
53
  return parsed;
40
54
  }
41
55
  export async function listRecordings(appSlug) {
42
- if (!existsSync(RECORDINGS_DIR))
43
- return [];
44
- const files = (await readdir(RECORDINGS_DIR)).filter((f) => f.endsWith('.json'));
56
+ const files = [];
57
+ for (const dir of [RECORDINGS_DIR, ...legacyDirs()]) {
58
+ if (!existsSync(dir))
59
+ continue;
60
+ for (const f of await readdir(dir))
61
+ if (f.endsWith('.json'))
62
+ files.push(join(dir, f));
63
+ }
45
64
  const out = [];
65
+ const seen = new Set();
46
66
  for (const file of files) {
47
67
  try {
48
- const rec = await loadRecording(join(RECORDINGS_DIR, file));
68
+ const rec = await loadRecording(file);
49
69
  if (appSlug && rec.appSlug !== appSlug)
50
70
  continue;
71
+ if (seen.has(rec.hash))
72
+ continue;
73
+ seen.add(rec.hash);
51
74
  out.push({
52
75
  hash: rec.hash,
53
76
  appSlug: rec.appSlug,
@@ -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;
@@ -304,4 +315,15 @@ export interface HandoffRecord {
304
315
  steps: number;
305
316
  url: string;
306
317
  }
318
+ /**
319
+ * A step's locator as Playwright code, for error messages. "matched no
320
+ * elements" without saying WHICH locator sent people reading the source to find
321
+ * out what had been stored.
322
+ */
323
+ export declare function describeLocator(event: RawEvent): string;
324
+ /**
325
+ * A Playwright URL glob as a regex: `**` is anything, `*` anything but `/`.
326
+ * A glob with no scheme matches anywhere in the URL, as a path would.
327
+ */
328
+ export declare function urlGlob(glob: string): RegExp;
307
329
  export declare function replay(recording: RawRecording, opts?: ReplayOptions): Promise<ReplayResult>;
@@ -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. */
@@ -76,7 +110,24 @@ function locatorFor(root, event) {
76
110
  });
77
111
  }
78
112
  else if (event.name) {
79
- locator = base.getByText(name, event.exact ? { exact: true } : {});
113
+ // The lookup the source used. `getByPlaceholder('Email')` replayed as
114
+ // getByText can never match: an input has no text of its own.
115
+ const opts = event.exact ? { exact: true } : {};
116
+ switch (event.hints?.by) {
117
+ case 'placeholder':
118
+ locator = base.getByPlaceholder(name, opts);
119
+ break;
120
+ case 'label':
121
+ locator = base.getByLabel(name, opts);
122
+ break;
123
+ case 'title':
124
+ locator = base.getByTitle(name, opts);
125
+ break;
126
+ case 'alt':
127
+ locator = base.getByAltText(name, opts);
128
+ break;
129
+ default: locator = base.getByText(name, opts);
130
+ }
80
131
  }
81
132
  else if (event.role) {
82
133
  locator = base.getByRole(event.role);
@@ -116,6 +167,135 @@ function locatorFor(root, event) {
116
167
  locator = nth < 0 ? locator.last() : locator.nth(nth);
117
168
  return locator;
118
169
  }
170
+ const NAME_LOOKUP_CALL = {
171
+ placeholder: 'getByPlaceholder', label: 'getByLabel', title: 'getByTitle', alt: 'getByAltText',
172
+ };
173
+ /**
174
+ * A step's locator as Playwright code, for error messages. "matched no
175
+ * elements" without saying WHICH locator sent people reading the source to find
176
+ * out what had been stored.
177
+ */
178
+ export function describeLocator(event) {
179
+ const q = (s) => `'${s.replace(/'/g, "\\'")}'`;
180
+ const name = event.name !== undefined
181
+ ? (event.hints?.nameRegex ? `/${event.name}/${String(event.hints.nameFlags ?? '')}` : q(event.name))
182
+ : undefined;
183
+ const exact = event.exact ? ', exact: true' : '';
184
+ let out;
185
+ if (event.role && name)
186
+ out = `getByRole(${q(event.role)}, { name: ${name}${exact} })`;
187
+ else if (name)
188
+ out = `${NAME_LOOKUP_CALL[String(event.hints?.by)] ?? 'getByText'}(${name}${exact ? ', { exact: true }' : ''})`;
189
+ else if (event.role)
190
+ out = `getByRole(${q(event.role)})`;
191
+ else if (event.css)
192
+ out = `locator(${q(event.css)})`;
193
+ else if (event.testId)
194
+ out = `locator('[${event.testIdAttr ?? 'data-testid'}="${event.testId}"]')`;
195
+ else
196
+ return '(no locator)';
197
+ const scope = Array.isArray(event.hints?.scope) ? event.hints.scope.map((s) => `${s} >> `).join('') : '';
198
+ const hasText = typeof event.hints?.hasText === 'string' ? `.filter({ hasText: ${q(event.hints.hasText)} })` : '';
199
+ const nth = typeof event.hints?.nth === 'number' ? (event.hints.nth < 0 ? '.last()' : `.nth(${event.hints.nth})`) : '';
200
+ const frame = event.frameHint ? `frame *${event.frameHint} >> ` : '';
201
+ return `${frame}${scope}${out}${hasText}${nth}`;
202
+ }
203
+ /**
204
+ * A Playwright URL glob as a regex: `**` is anything, `*` anything but `/`.
205
+ * A glob with no scheme matches anywhere in the URL, as a path would.
206
+ */
207
+ export function urlGlob(glob) {
208
+ let re = '';
209
+ for (let i = 0; i < glob.length; i++) {
210
+ const c = glob[i];
211
+ if (c === '*' && glob[i + 1] === '*') {
212
+ re += '.*';
213
+ i++;
214
+ }
215
+ else if (c === '*')
216
+ re += '[^/]*';
217
+ else if (c === '?')
218
+ re += '.';
219
+ else
220
+ re += c.replace(/[.+^${}()|[\]\\/]/g, '\\$&');
221
+ }
222
+ return new RegExp(`${/^[a-z]+:/i.test(glob) || glob.startsWith('*') ? '^' : ''}${re}$`);
223
+ }
224
+ /** Whitespace-normalised, as Playwright's text assertions compare. */
225
+ const squash = (s) => s.replace(/\s+/g, ' ').trim();
226
+ /**
227
+ * Check an `assert` step, waiting up to the timeout for it to come true — the
228
+ * same patience Playwright's own `expect` has. Kinds: see script.ts AssertKind.
229
+ */
230
+ async function checkAssert(page, event, values, timeoutMs) {
231
+ const kind = String(event.hints?.assert ?? 'visible');
232
+ const expected = valueFor(event, values);
233
+ const valued = ['text', 'contains', 'value', 'title'].includes(kind);
234
+ if (valued && expected === undefined) {
235
+ throw new Error(`assert ${kind} has no expected value${event.valueRef ? ` — set ${event.valueRef}` : ''}`);
236
+ }
237
+ const regex = event.hints?.valueRegex ? new RegExp(expected, String(event.hints.valueFlags ?? '')) : undefined;
238
+ const matches = (actual) => regex ? regex.test(actual)
239
+ : kind === 'contains' ? squash(actual).includes(squash(expected))
240
+ : kind === 'value' ? actual === expected
241
+ : squash(actual) === squash(expected);
242
+ const shown = regex ? `/${expected}/` : `"${expected}"`;
243
+ /** Poll `read` until `ok`, like expect's retrying; report the last value seen. */
244
+ const until = async (read, ok, what,
245
+ /** What to show as "saw" — e.g. the visible text, not textContent's scripts. */
246
+ shownAs) => {
247
+ const deadline = Date.now() + timeoutMs;
248
+ let last = null;
249
+ for (;;) {
250
+ last = await read().catch(() => null);
251
+ if (ok(last))
252
+ return;
253
+ if (Date.now() >= deadline) {
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);
258
+ }
259
+ await page.waitForTimeout(100);
260
+ }
261
+ };
262
+ if (kind === 'title') {
263
+ return until(() => page.title(), (v) => typeof v === 'string' && matches(v), `expected the page title to be ${shown}`);
264
+ }
265
+ const root = event.frameHint
266
+ ? (page.frames().find((f) => f.url().includes(event.frameHint) || f.name().endsWith(event.frameHint)) ?? page)
267
+ : page;
268
+ const locator = locatorFor(root, event);
269
+ if (!locator)
270
+ throw new Error('assert step has no usable locator (no role, name, css or testId)');
271
+ const target = locator.first();
272
+ const desc = describeLocator(event);
273
+ switch (kind) {
274
+ case 'visible':
275
+ case 'hidden':
276
+ await target.waitFor({ state: kind, timeout: timeoutMs }).catch(async () => {
277
+ const count = await locator.count().catch(() => 0);
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);
282
+ });
283
+ return;
284
+ case 'text':
285
+ case 'contains':
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 }));
290
+ case 'value':
291
+ return until(() => target.inputValue({ timeout: 1000 }), (v) => typeof v === 'string' && matches(v), `expected ${desc} to have value ${event.valueRef ? `of ${event.valueRef}` : shown}`);
292
+ case 'checked':
293
+ case 'unchecked':
294
+ return until(() => target.isChecked({ timeout: 1000 }), (v) => v === (kind === 'checked'), `expected ${desc} to be ${kind}`);
295
+ default:
296
+ throw new Error(`replay does not implement assert '${kind}'`);
297
+ }
298
+ }
119
299
  /**
120
300
  * Wait until the URL has stopped changing.
121
301
  *
@@ -189,7 +369,7 @@ export async function replay(recording, opts = {}) {
189
369
  page.on('console', (msg) => {
190
370
  if (msg.type() !== 'error' && msg.type() !== 'warning')
191
371
  return;
192
- 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) });
193
373
  });
194
374
  page.on('pageerror', (err) => {
195
375
  signals.push({ kind: 'pageerror', duringStep: currentStep, text: String(err).slice(0, 500) });
@@ -306,14 +486,28 @@ export async function replay(recording, opts = {}) {
306
486
  throw new Error(`${event.action} has no value to wait for`);
307
487
  if (event.action === 'wait_url') {
308
488
  // Substring, not equality: recordings carry concrete URLs while the
309
- // thing worth waiting for is the route.
310
- await page.waitForURL((u) => u.href.includes(expected), { timeout: timeoutMs });
489
+ // thing worth waiting for is the route. A script's own
490
+ // `waitForURL('**/dashboard')` or `toHaveURL(/done/)` keeps its
491
+ // glob or regex meaning.
492
+ const pattern = event.hints?.urlRegex
493
+ ? new RegExp(expected, String(event.hints.urlFlags ?? ''))
494
+ : expected.includes('*') ? urlGlob(expected) : undefined;
495
+ await page
496
+ .waitForURL((u) => (pattern ? pattern.test(u.href) : u.href.includes(expected)), { timeout: timeoutMs })
497
+ .catch(() => {
498
+ throw new Error(`the URL never matched ${pattern ? String(pattern) : `"${expected}"`} (it is ${page.url()})`);
499
+ });
311
500
  }
312
501
  else {
313
502
  await page.getByText(expected).first().waitFor({ state: 'visible', timeout: timeoutMs });
314
503
  }
315
504
  outcome.ok = true;
316
505
  }
506
+ else if (event.action === 'assert') {
507
+ // A check, not an action: nothing is dispatched, so a retry is safe.
508
+ await checkAssert(page, event, values, timeoutMs);
509
+ outcome.ok = true;
510
+ }
317
511
  else if (event.action === 'snapshot') {
318
512
  // A checkpoint addresses no element — it is a moment, not a target.
319
513
  // Settle first for the same reason sig() does: a picture taken
@@ -452,7 +646,7 @@ export async function replay(recording, opts = {}) {
452
646
  }
453
647
  }
454
648
  if (outcome.matched === 0)
455
- throw new Error('locator matched no elements');
649
+ throw new Error(`locator ${describeLocator(event)} matched no elements`);
456
650
  const target = outcome.matched > 1 ? locator.first() : locator;
457
651
  // Past this line the app may have been changed. Everything above is
458
652
  // addressing, which is safe to try again; nothing below is.
@@ -577,7 +771,15 @@ export async function replay(recording, opts = {}) {
577
771
  // every step regardless. Not comparing them meant execution could walk
578
772
  // into a page the plan had never seen and notice nothing until a locator
579
773
  // happened to miss.
580
- 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) {
581
783
  outcome.unexpectedPage = { expected: event.expectedSig, observed: sig.sig };
582
784
  // THE ESCALATION. An unexpected page is not automatically wrong — an
583
785
  // app may have gained a banner — but continuing blindly is how a run
@@ -602,7 +804,15 @@ export async function replay(recording, opts = {}) {
602
804
  }
603
805
  }
604
806
  catch (err) {
605
- 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;
606
816
  }
607
817
  if (outcome.ok || attempt === maxAttempts)
608
818
  break;
@@ -29,11 +29,12 @@
29
29
  */
30
30
  import { mkdir, readFile, writeFile } from 'node:fs/promises';
31
31
  import { existsSync } from 'node:fs';
32
- import { dirname, join, resolve } from 'node:path';
32
+ import { dirname, join } from 'node:path';
33
33
  import { PNG } from 'pngjs';
34
34
  import pixelmatch from 'pixelmatch';
35
+ import { HOME } from '../store/settings.js';
35
36
  /** Gitignored: these are large, machine-local, and regenerable. */
36
- export const SHOTS_DIR = process.env.UNDERSTUDY_SHOTS_DIR ?? resolve('.understudy/shots');
37
+ export const SHOTS_DIR = process.env.UNDERSTUDY_SHOTS_DIR ?? join(HOME, 'shots');
37
38
  /**
38
39
  * Below this fraction of changed pixels, say nothing.
39
40
  *
package/dist/entry/cli.js CHANGED
@@ -23,6 +23,8 @@ import { chromium } from 'playwright';
23
23
  import { emitFlow } from '../flows/emit.js';
24
24
  import { recordingFrom, proveAndSave, proveByRun } from '../flows/save.js';
25
25
  import { recordRun } from '../flows/runs.js';
26
+ import { listFindings } from '../flows/findings.js';
27
+ import { VERSION } from './version.js';
26
28
  import { recall } from '../memory/recall.js';
27
29
  import { setPlaceholders, appPlaceholders } from '../memory/placeholders.js';
28
30
  import * as store from '../store/db.js';
@@ -37,6 +39,7 @@ const USAGE = `understudy — learn a web app, then test it by intent
37
39
 
38
40
  USAGE
39
41
  understudy <command> [options]
42
+ understudy --version
40
43
 
41
44
  COMMANDS
42
45
  config where settings come from; set them, or point at an env file
@@ -51,7 +54,7 @@ COMMANDS
51
54
  flows <app> list an app's saved flows and how each last ran
52
55
  replay <hash> re-run a recording file headless
53
56
  replay <app> <flow> re-run a saved flow; records the run, drift and findings
54
- findings <app> what looked broken, most frequent first
57
+ findings <app> what looked broken, most severe first
55
58
  recall <app> "<goal>" what memory knows about a goal — nothing runs
56
59
  run <app> "<goal>" find the flow that does the goal, and run it
57
60
  answer <runId> <json> answer a question a planned run stopped on
@@ -292,7 +295,9 @@ function waitForEnter(prompt) {
292
295
  function printEvents(recording) {
293
296
  for (const e of recording.events) {
294
297
  const value = e.value !== undefined ? ` = "${e.value}"` : e.valueRef ? ` = <${e.valueRef}>` : '';
295
- console.log(` ${String(e.seq).padStart(2)} ${e.action.padEnd(7)} ${(e.role ?? '').padEnd(9)} ${e.name ?? ''}${value}`);
298
+ const check = e.action === 'assert' ? ` (${String(e.hints?.assert ?? 'visible')})` : '';
299
+ const by = typeof e.hints?.by === 'string' ? `[${e.hints.by}] ` : '';
300
+ console.log(` ${String(e.seq).padStart(2)} ${e.action.padEnd(7)} ${(e.role ?? '').padEnd(9)} ${by}${e.name ?? e.testId ?? e.css ?? ''}${value}${check}`);
296
301
  }
297
302
  }
298
303
  async function cmdRecord(positional, flags) {
@@ -447,7 +452,7 @@ async function cmdImport(positional, flags) {
447
452
  // A script may rely on a baseURL from playwright.config, so goto('/') has no
448
453
  // origin. The app's remembered base URL fills that in.
449
454
  const fallback = str(flags.get('url')) ?? (await resolveBaseUrl(slug, undefined).catch(() => undefined));
450
- const { recording: parsed, warnings } = await parseScript(file, slug, fallback);
455
+ const { recording: parsed, warnings, dropped } = await parseScript(file, slug, fallback);
451
456
  // --until keeps the proven prefix — e.g. everything before a real purchase.
452
457
  const until = str(flags.get('until'));
453
458
  const recording = until
@@ -469,6 +474,12 @@ async function cmdImport(positional, flags) {
469
474
  for (const w of warnings.slice(0, 10))
470
475
  console.log(` ${w}`);
471
476
  }
477
+ // Not fatal — the flow still replays — but it checks less than the script.
478
+ if (dropped.length) {
479
+ console.log(`\n${dropped.length} assertion(s) not kept:`);
480
+ for (const d of dropped.slice(0, 10))
481
+ console.log(` ${d}`);
482
+ }
472
483
  const { path, existed } = await saveRecording(recording);
473
484
  console.log(`\nhash ${recording.hash}${existed ? ' (identical recording already existed)' : ''}`);
474
485
  console.log(`saved ${path}`);
@@ -721,8 +732,10 @@ function printReplay(result) {
721
732
  /** What recording the run added: drift against earlier runs, and findings. */
722
733
  function printRunReport(run) {
723
734
  const { drift } = run;
724
- if (drift.firstRun)
725
- console.log('\ndrift first passed run — this path is now the baseline');
735
+ if (drift.notCompared)
736
+ console.log(`\ndrift not compared — ${drift.notCompared}`);
737
+ else if (drift.firstRun)
738
+ console.log('\ndrift first passed run of this plan — this path is now the baseline');
726
739
  else if (!drift.changed)
727
740
  console.log('\ndrift same path as recent runs');
728
741
  else {
@@ -934,8 +947,7 @@ async function cmdFlows(positional) {
934
947
  async function cmdFindings(positional, flags) {
935
948
  const app = positional[0] ?? fail('findings needs an app name', 'understudy findings myapp');
936
949
  const { findings } = await store.collections();
937
- const filter = flags.has('all') ? { app } : { app, status: 'open' };
938
- const rows = await findings.find(filter).sort({ occurrences: -1, lastSeen: -1 }).limit(50).toArray();
950
+ const rows = await listFindings(findings, app, { all: flags.has('all'), limit: 50 });
939
951
  if (!rows.length) {
940
952
  console.log(flags.has('all') ? `no findings for '${app}'` : `no open findings for '${app}' (--all to include triaged ones)`);
941
953
  return;
@@ -982,6 +994,10 @@ async function cmdRecordings(positional) {
982
994
  async function main() {
983
995
  const { flags, positional } = parseArgs(process.argv.slice(2));
984
996
  const [command, ...rest] = positional;
997
+ if (flags.has('version') || flags.has('v') || command === 'version') {
998
+ console.log(VERSION);
999
+ return;
1000
+ }
985
1001
  if (!command || flags.has('help') || flags.has('h')) {
986
1002
  console.log(USAGE);
987
1003
  return;
package/dist/entry/mcp.js CHANGED
@@ -24,14 +24,15 @@ import { recall } from '../memory/recall.js';
24
24
  import { remember } from '../memory/notes.js';
25
25
  import { start, answer, runPlan } from '../plan/planner.js';
26
26
  import { distillRequest, saveDistilled } from '../flows/distill.js';
27
- import { triage } from '../flows/findings.js';
27
+ import { triage, listFindings } from '../flows/findings.js';
28
28
  import { collections } from '../store/db.js';
29
29
  import { startExtensionRecorder, extensionDir } from '../adapters/recorder/extension.js';
30
- import { saveRecording, loadRecording } from '../core/recording-store.js';
30
+ import { saveRecording, loadRecording, recordingPath } from '../core/recording-store.js';
31
31
  import { proveAndSave } from '../flows/save.js';
32
32
  import { MissingValuesError } from '../flows/execute.js';
33
33
  import { parseScript } from '../adapters/recorder/script.js';
34
34
  import { setPlaceholders, appPlaceholders } from '../memory/placeholders.js';
35
+ import { VERSION } from './version.js';
35
36
  /**
36
37
  * Sent to the agent when it connects — its copy of the contract, since an
37
38
  * agent that installed Understudy from npm never sees REASONER.md. Kept short:
@@ -44,7 +45,7 @@ const INSTRUCTIONS = `Understudy remembers the user's web-app flows and runs the
44
45
  - No flow for it? understudy_record (the user records) then understudy_save — or save a Playwright script of what you drove (understudy_save with script). Save what's worth testing again.
45
46
  - Ask the user before each distill. Gather facts, lessons and findings, get approval, then one understudy_remember.
46
47
  Full guide: REASONER.md in the package.`;
47
- const server = new McpServer({ name: 'understudy', version: '0.2.0' }, { instructions: INSTRUCTIONS });
48
+ const server = new McpServer({ name: 'understudy', version: VERSION }, { instructions: INSTRUCTIONS });
48
49
  /** Credentials passed to `run`, kept in memory (never stored) until the run executes. */
49
50
  const valuesByRun = new Map();
50
51
  const ok = (data) => ({ content: [{ type: 'text', text: JSON.stringify(data, null, 1) }] });
@@ -86,12 +87,13 @@ async function continueRun(state, opts) {
86
87
  runId: state.runId,
87
88
  plan,
88
89
  seams: state.seams,
89
- 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 } : {}) })),
90
91
  unexpectedPages: r.steps.filter((s) => s.unexpectedPage).map((s) => ({ seq: s.seq, ...s.unexpectedPage })),
91
92
  path: r.sigSequence,
92
- drift: recorded.drift.firstRun ? 'first run' : recorded.drift.changed
93
- ? { added: recorded.drift.added, removed: recorded.drift.removed, stateChanged: recorded.drift.stateChanged }
94
- : 'same path',
93
+ drift: recorded.drift.notCompared ? `not compared: ${recorded.drift.notCompared}`
94
+ : recorded.drift.firstRun ? 'first passed run of this plan — now the baseline' : recorded.drift.changed
95
+ ? { added: recorded.drift.added, removed: recorded.drift.removed, stateChanged: recorded.drift.stateChanged }
96
+ : 'same path',
95
97
  findings: recorded.findings.map((f) => ({ kind: f.kind, severity: f.severity, statement: f.statement })),
96
98
  ...(executed.lessons?.fired ? { lessons: executed.lessons } : {}),
97
99
  ...(nowProven.length ? { nowProven } : {}),
@@ -157,7 +159,7 @@ server.registerTool('understudy_remember', {
157
159
  reached: reached?.map((r) => defined(r)),
158
160
  }))));
159
161
  server.registerTool('understudy_findings', {
160
- description: 'Open findings for an app, most frequent first. Pass triage to route them: issue, lesson or noise.',
162
+ description: 'Open findings for an app, most severe first, then most frequent. Pass triage to route them: issue, lesson or noise.',
161
163
  inputSchema: {
162
164
  app: z.string(),
163
165
  triage: z.array(z.object({ fingerprint: z.string(), verdict: z.enum(['issue', 'lesson', 'noise']) })).optional(),
@@ -166,7 +168,7 @@ server.registerTool('understudy_findings', {
166
168
  }, ({ app, triage: items, all }) => wrap(async () => {
167
169
  const { findings } = await collections();
168
170
  const routed = items?.length ? await triage(findings, app, items) : undefined;
169
- const rows = await findings.find(all ? { app } : { app, status: 'open' }).sort({ occurrences: -1, lastSeen: -1 }).limit(40).toArray();
171
+ const rows = await listFindings(findings, app, { ...(all ? { all } : {}), limit: 40 });
170
172
  return {
171
173
  ...(routed ? { triaged: routed } : {}),
172
174
  findings: rows.map((f) => ({ fingerprint: f.fingerprint, kind: f.kind, severity: f.severity, occurrences: f.occurrences, status: f.status, statement: f.statement })),
@@ -203,7 +205,13 @@ server.registerTool('understudy_record', {
203
205
  };
204
206
  }));
205
207
  server.registerTool('understudy_save', {
206
- description: 'Prove a flow by replaying it, and keep it only if every step passes: the user\'s latest recording, a recording hash, or a script of a flow you drove.',
208
+ description: [
209
+ 'Prove a flow by replaying it, and keep it only if every step passes: the user\'s latest recording, a recording hash, or a script of a flow you drove.',
210
+ 'A script is READ, not run: only literal page calls are kept, so no loops, no values computed at runtime, no reading logs or emails mid-flow.',
211
+ 'Kept: goto, click, dblclick, fill, type, press, check, uncheck, selectOption, setInputFiles, scrollIntoViewIfNeeded; locators getByRole, getByText, getByLabel, getByPlaceholder, getByTitle, getByAltText, getByTestId, locator(css), frameLocator, filter({hasText}), first/last/nth;',
212
+ 'assertions expect(page).toHaveURL/toHaveTitle, expect(locator).toBeVisible/toBeHidden/toHaveText/toContainText/toHaveValue/toBeChecked (and .not on visible/hidden/checked), page.waitForURL, page.waitForSelector.',
213
+ 'Write locators inline in expect(...), not via a variable. Other assertions come back in droppedAssertions; calls that would change the steps (evaluate, hover, route…) refuse the save.',
214
+ ].join(' '),
207
215
  inputSchema: {
208
216
  app: z.string(), name: z.string().describe('What the flow does, as someone would ask for it.'),
209
217
  hash: z.string().optional(),
@@ -215,6 +223,7 @@ server.registerTool('understudy_save', {
215
223
  }, (a) => wrap(async () => {
216
224
  let rec;
217
225
  let madeBy = 'user';
226
+ let dropped = [];
218
227
  if (a.script) {
219
228
  // A flow the agent drove: read its script into steps, exactly like `understudy import`.
220
229
  const { apps } = await collections();
@@ -225,6 +234,7 @@ server.registerTool('understudy_save', {
225
234
  if (parsed.warnings.length)
226
235
  throw new Error(`these calls in the script can't be replayed, so it wasn't kept — rewrite them as plain Playwright actions:\n- ${parsed.warnings.slice(0, 10).join('\n- ')}`);
227
236
  rec = parsed.recording;
237
+ dropped = parsed.dropped;
228
238
  await saveRecording(rec);
229
239
  madeBy = 'agent';
230
240
  }
@@ -254,9 +264,12 @@ server.registerTool('understudy_save', {
254
264
  const r = out.proven?.result;
255
265
  const base = {
256
266
  recording: hash,
267
+ // Where the steps it read are, so a failure can be checked against them.
268
+ recordingFile: recordingPath(hash),
269
+ ...(dropped.length ? { droppedAssertions: dropped, droppedWhy: 'these checks in the script were not kept, so the flow checks less than the script did' } : {}),
257
270
  ...(r ? {
258
271
  passed: r.ok,
259
- 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 } : {}) })),
260
273
  signIn: out.proven.signIn,
261
274
  } : { replayed: false }),
262
275
  ...(finished.get(a.app)?.droppedUploads ? { droppedUploads: finished.get(a.app).droppedUploads } : {}),
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The package's version, read from package.json — so the CLI's --version and
3
+ * the MCP server's handshake can't drift from what npm installed (the server
4
+ * said 0.2.0 while the package was 0.2.1).
5
+ *
6
+ * package.json is two folders up from both src/entry and dist/entry.
7
+ */
8
+ export declare const VERSION: string;