@jeffawe/understudy 0.2.1 → 0.2.2

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.
@@ -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,
@@ -304,4 +304,15 @@ export interface HandoffRecord {
304
304
  steps: number;
305
305
  url: string;
306
306
  }
307
+ /**
308
+ * A step's locator as Playwright code, for error messages. "matched no
309
+ * elements" without saying WHICH locator sent people reading the source to find
310
+ * out what had been stored.
311
+ */
312
+ export declare function describeLocator(event: RawEvent): string;
313
+ /**
314
+ * A Playwright URL glob as a regex: `**` is anything, `*` anything but `/`.
315
+ * A glob with no scheme matches anywhere in the URL, as a path would.
316
+ */
317
+ export declare function urlGlob(glob: string): RegExp;
307
318
  export declare function replay(recording: RawRecording, opts?: ReplayOptions): Promise<ReplayResult>;
@@ -76,7 +76,24 @@ function locatorFor(root, event) {
76
76
  });
77
77
  }
78
78
  else if (event.name) {
79
- locator = base.getByText(name, event.exact ? { exact: true } : {});
79
+ // The lookup the source used. `getByPlaceholder('Email')` replayed as
80
+ // getByText can never match: an input has no text of its own.
81
+ const opts = event.exact ? { exact: true } : {};
82
+ switch (event.hints?.by) {
83
+ case 'placeholder':
84
+ locator = base.getByPlaceholder(name, opts);
85
+ break;
86
+ case 'label':
87
+ locator = base.getByLabel(name, opts);
88
+ break;
89
+ case 'title':
90
+ locator = base.getByTitle(name, opts);
91
+ break;
92
+ case 'alt':
93
+ locator = base.getByAltText(name, opts);
94
+ break;
95
+ default: locator = base.getByText(name, opts);
96
+ }
80
97
  }
81
98
  else if (event.role) {
82
99
  locator = base.getByRole(event.role);
@@ -116,6 +133,124 @@ function locatorFor(root, event) {
116
133
  locator = nth < 0 ? locator.last() : locator.nth(nth);
117
134
  return locator;
118
135
  }
136
+ const NAME_LOOKUP_CALL = {
137
+ placeholder: 'getByPlaceholder', label: 'getByLabel', title: 'getByTitle', alt: 'getByAltText',
138
+ };
139
+ /**
140
+ * A step's locator as Playwright code, for error messages. "matched no
141
+ * elements" without saying WHICH locator sent people reading the source to find
142
+ * out what had been stored.
143
+ */
144
+ export function describeLocator(event) {
145
+ const q = (s) => `'${s.replace(/'/g, "\\'")}'`;
146
+ const name = event.name !== undefined
147
+ ? (event.hints?.nameRegex ? `/${event.name}/${String(event.hints.nameFlags ?? '')}` : q(event.name))
148
+ : undefined;
149
+ const exact = event.exact ? ', exact: true' : '';
150
+ let out;
151
+ if (event.role && name)
152
+ out = `getByRole(${q(event.role)}, { name: ${name}${exact} })`;
153
+ else if (name)
154
+ out = `${NAME_LOOKUP_CALL[String(event.hints?.by)] ?? 'getByText'}(${name}${exact ? ', { exact: true }' : ''})`;
155
+ else if (event.role)
156
+ out = `getByRole(${q(event.role)})`;
157
+ else if (event.css)
158
+ out = `locator(${q(event.css)})`;
159
+ else if (event.testId)
160
+ out = `locator('[${event.testIdAttr ?? 'data-testid'}="${event.testId}"]')`;
161
+ else
162
+ return '(no locator)';
163
+ const scope = Array.isArray(event.hints?.scope) ? event.hints.scope.map((s) => `${s} >> `).join('') : '';
164
+ const hasText = typeof event.hints?.hasText === 'string' ? `.filter({ hasText: ${q(event.hints.hasText)} })` : '';
165
+ const nth = typeof event.hints?.nth === 'number' ? (event.hints.nth < 0 ? '.last()' : `.nth(${event.hints.nth})`) : '';
166
+ const frame = event.frameHint ? `frame *${event.frameHint} >> ` : '';
167
+ return `${frame}${scope}${out}${hasText}${nth}`;
168
+ }
169
+ /**
170
+ * A Playwright URL glob as a regex: `**` is anything, `*` anything but `/`.
171
+ * A glob with no scheme matches anywhere in the URL, as a path would.
172
+ */
173
+ export function urlGlob(glob) {
174
+ let re = '';
175
+ for (let i = 0; i < glob.length; i++) {
176
+ const c = glob[i];
177
+ if (c === '*' && glob[i + 1] === '*') {
178
+ re += '.*';
179
+ i++;
180
+ }
181
+ else if (c === '*')
182
+ re += '[^/]*';
183
+ else if (c === '?')
184
+ re += '.';
185
+ else
186
+ re += c.replace(/[.+^${}()|[\]\\/]/g, '\\$&');
187
+ }
188
+ return new RegExp(`${/^[a-z]+:/i.test(glob) || glob.startsWith('*') ? '^' : ''}${re}$`);
189
+ }
190
+ /** Whitespace-normalised, as Playwright's text assertions compare. */
191
+ const squash = (s) => s.replace(/\s+/g, ' ').trim();
192
+ /**
193
+ * Check an `assert` step, waiting up to the timeout for it to come true — the
194
+ * same patience Playwright's own `expect` has. Kinds: see script.ts AssertKind.
195
+ */
196
+ async function checkAssert(page, event, values, timeoutMs) {
197
+ const kind = String(event.hints?.assert ?? 'visible');
198
+ const expected = valueFor(event, values);
199
+ const valued = ['text', 'contains', 'value', 'title'].includes(kind);
200
+ if (valued && expected === undefined) {
201
+ throw new Error(`assert ${kind} has no expected value${event.valueRef ? ` — set ${event.valueRef}` : ''}`);
202
+ }
203
+ const regex = event.hints?.valueRegex ? new RegExp(expected, String(event.hints.valueFlags ?? '')) : undefined;
204
+ const matches = (actual) => regex ? regex.test(actual)
205
+ : kind === 'contains' ? squash(actual).includes(squash(expected))
206
+ : kind === 'value' ? actual === expected
207
+ : squash(actual) === squash(expected);
208
+ const shown = regex ? `/${expected}/` : `"${expected}"`;
209
+ /** Poll `read` until `ok`, like expect's retrying; report the last value seen. */
210
+ const until = async (read, ok, what) => {
211
+ const deadline = Date.now() + timeoutMs;
212
+ let last = null;
213
+ for (;;) {
214
+ last = await read().catch(() => null);
215
+ if (ok(last))
216
+ return;
217
+ if (Date.now() >= deadline) {
218
+ throw new Error(`${what}${last === null ? '' : `, got ${typeof last === 'string' ? `"${squash(last).slice(0, 80)}"` : String(last)}`}`);
219
+ }
220
+ await page.waitForTimeout(100);
221
+ }
222
+ };
223
+ if (kind === 'title') {
224
+ return until(() => page.title(), (v) => typeof v === 'string' && matches(v), `expected the page title to be ${shown}`);
225
+ }
226
+ const root = event.frameHint
227
+ ? (page.frames().find((f) => f.url().includes(event.frameHint) || f.name().endsWith(event.frameHint)) ?? page)
228
+ : page;
229
+ const locator = locatorFor(root, event);
230
+ if (!locator)
231
+ throw new Error('assert step has no usable locator (no role, name, css or testId)');
232
+ const target = locator.first();
233
+ const desc = describeLocator(event);
234
+ switch (kind) {
235
+ case 'visible':
236
+ case 'hidden':
237
+ await target.waitFor({ state: kind, timeout: timeoutMs }).catch(async () => {
238
+ const count = await locator.count().catch(() => 0);
239
+ throw new Error(`expected ${desc} to be ${kind}${kind === 'visible' && count === 0 ? ' — it matched no elements' : ''}`);
240
+ });
241
+ return;
242
+ case 'text':
243
+ 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}`);
245
+ case 'value':
246
+ return until(() => target.inputValue({ timeout: 1000 }), (v) => typeof v === 'string' && matches(v), `expected ${desc} to have value ${event.valueRef ? `of ${event.valueRef}` : shown}`);
247
+ case 'checked':
248
+ case 'unchecked':
249
+ return until(() => target.isChecked({ timeout: 1000 }), (v) => v === (kind === 'checked'), `expected ${desc} to be ${kind}`);
250
+ default:
251
+ throw new Error(`replay does not implement assert '${kind}'`);
252
+ }
253
+ }
119
254
  /**
120
255
  * Wait until the URL has stopped changing.
121
256
  *
@@ -306,14 +441,28 @@ export async function replay(recording, opts = {}) {
306
441
  throw new Error(`${event.action} has no value to wait for`);
307
442
  if (event.action === 'wait_url') {
308
443
  // 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 });
444
+ // thing worth waiting for is the route. A script's own
445
+ // `waitForURL('**/dashboard')` or `toHaveURL(/done/)` keeps its
446
+ // glob or regex meaning.
447
+ const pattern = event.hints?.urlRegex
448
+ ? new RegExp(expected, String(event.hints.urlFlags ?? ''))
449
+ : expected.includes('*') ? urlGlob(expected) : undefined;
450
+ await page
451
+ .waitForURL((u) => (pattern ? pattern.test(u.href) : u.href.includes(expected)), { timeout: timeoutMs })
452
+ .catch(() => {
453
+ throw new Error(`the URL never matched ${pattern ? String(pattern) : `"${expected}"`} (it is ${page.url()})`);
454
+ });
311
455
  }
312
456
  else {
313
457
  await page.getByText(expected).first().waitFor({ state: 'visible', timeout: timeoutMs });
314
458
  }
315
459
  outcome.ok = true;
316
460
  }
461
+ else if (event.action === 'assert') {
462
+ // A check, not an action: nothing is dispatched, so a retry is safe.
463
+ await checkAssert(page, event, values, timeoutMs);
464
+ outcome.ok = true;
465
+ }
317
466
  else if (event.action === 'snapshot') {
318
467
  // A checkpoint addresses no element — it is a moment, not a target.
319
468
  // Settle first for the same reason sig() does: a picture taken
@@ -452,7 +601,7 @@ export async function replay(recording, opts = {}) {
452
601
  }
453
602
  }
454
603
  if (outcome.matched === 0)
455
- throw new Error('locator matched no elements');
604
+ throw new Error(`locator ${describeLocator(event)} matched no elements`);
456
605
  const target = outcome.matched > 1 ? locator.first() : locator;
457
606
  // Past this line the app may have been changed. Everything above is
458
607
  // addressing, which is safe to try again; nothing below is.
@@ -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) }] });
@@ -89,9 +90,10 @@ async function continueRun(state, opts) {
89
90
  failedSteps: r.steps.filter((s) => !s.ok).map((s) => ({ seq: s.seq, action: s.action, error: s.error })),
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,6 +264,9 @@ 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
272
  failedSteps: r.steps.filter((s) => !s.ok).map((s) => ({ seq: s.seq, action: s.action, error: s.error })),
@@ -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;
@@ -0,0 +1,16 @@
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
+ import { readFileSync } from 'node:fs';
9
+ export const VERSION = (() => {
10
+ try {
11
+ return JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version;
12
+ }
13
+ catch {
14
+ return 'unknown';
15
+ }
16
+ })();
@@ -22,6 +22,12 @@ export interface DriftStep {
22
22
  export interface Drift {
23
23
  /** No earlier passed run to compare with — not drift, just the first time. */
24
24
  firstRun: boolean;
25
+ /**
26
+ * Why there was no comparison at all, when there wasn't one. A FAILED run
27
+ * stops early, so its path isn't compared — and it used to be reported as
28
+ * "first run", which read as "the passing run a minute ago never happened".
29
+ */
30
+ notCompared?: string;
25
31
  changed: boolean;
26
32
  /** Pages no recent run has ever visited. The interesting case. */
27
33
  added: string[];
@@ -37,6 +37,46 @@ function narrow(s, loc, pw, warn) {
37
37
  loc += h.nth < 0 ? '.last()' : pw ? `.nth(${h.nth})` : `.eq(${h.nth})`;
38
38
  return loc;
39
39
  }
40
+ /** hints.by → the Playwright lookup that found the name (script.ts NameLookup). */
41
+ const NAME_LOOKUP = {
42
+ placeholder: 'getByPlaceholder', label: 'getByLabel', title: 'getByTitle', alt: 'getByAltText',
43
+ };
44
+ /** A text matcher as source: a regex stays a regex. */
45
+ const matcher = (s, flag, flags) => s.hints?.[flag] ? `/${s.value ?? ''}/${String(s.hints[flags] ?? '')}` : quote(s.value ?? '');
46
+ /** An assert step as `expect(...)`, or a Cypress `should`. */
47
+ function assertion(s, loc, value, pw, warn) {
48
+ const kind = String(s.hints?.assert ?? 'visible');
49
+ const expected = s.valueRef ? value : matcher(s, 'valueRegex', 'valueFlags');
50
+ if (pw) {
51
+ switch (kind) {
52
+ case 'title': return `await expect(page).toHaveTitle(${expected});`;
53
+ case 'visible': return `await expect(${loc}).toBeVisible();`;
54
+ case 'hidden': return `await expect(${loc}).toBeHidden();`;
55
+ case 'text': return `await expect(${loc}).toHaveText(${expected});`;
56
+ case 'contains': return `await expect(${loc}).toContainText(${expected});`;
57
+ case 'value': return `await expect(${loc}).toHaveValue(${expected});`;
58
+ case 'checked': return `await expect(${loc}).toBeChecked();`;
59
+ case 'unchecked': return `await expect(${loc}).not.toBeChecked();`;
60
+ }
61
+ }
62
+ else {
63
+ if (s.hints?.valueRegex)
64
+ warn(`"${describe(s)}" checks a regex, which this Cypress output emits as a substring`);
65
+ const v = s.valueRef ? value : quote(s.value ?? '');
66
+ switch (kind) {
67
+ case 'title': return `cy.title().should('eq', ${v});`;
68
+ case 'visible': return `${loc}.should('be.visible');`;
69
+ case 'hidden': return `${loc}.should('not.be.visible');`;
70
+ case 'text': return `${loc}.invoke('text').should('eq', ${v});`;
71
+ case 'contains': return `${loc}.should('contain.text', ${v});`;
72
+ case 'value': return `${loc}.should('have.value', ${v});`;
73
+ case 'checked': return `${loc}.should('be.checked');`;
74
+ case 'unchecked': return `${loc}.should('not.be.checked');`;
75
+ }
76
+ }
77
+ warn(`"${describe(s)}" is an assertion of a kind this output doesn't know (${kind}); skipped`);
78
+ return `// TODO: assert ${kind}`;
79
+ }
40
80
  /** Best locator first — the same order replay tries, so the code fails where replay would. */
41
81
  function playwrightLocator(s, warn) {
42
82
  const scope = s.frameHint ? `page.frameLocator(${quote(`[id$="${s.frameHint}"]`)})` : 'page';
@@ -46,7 +86,7 @@ function playwrightLocator(s, warn) {
46
86
  if (s.testId)
47
87
  return `${scope}.locator(${quote(`[${s.testIdAttr ?? 'data-testid'}="${s.testId}"]`)})`;
48
88
  if (s.name)
49
- return `${scope}.getByText(${quote(s.name)})`;
89
+ return `${scope}.${NAME_LOOKUP[String(s.hints?.by)] ?? 'getByText'}(${quote(s.name)}${s.exact ? ', { exact: true }' : ''})`;
50
90
  if (s.css) {
51
91
  warn(`"${describe(s)}" is addressed only by CSS — it breaks on any markup change`);
52
92
  return `${scope}.locator(${quote(s.css)})`;
@@ -80,9 +120,10 @@ export function emitFlow(flow, framework = 'playwright-ts') {
80
120
  warnings.push('this flow starts signed in; the generated test starts signed out — add a login first');
81
121
  const lines = [];
82
122
  for (const s of flow.steps) {
83
- if (s.action === 'snapshot' || s.action === 'assert')
123
+ if (s.action === 'snapshot')
84
124
  continue;
85
- const loc = s.action === 'goto' ? '' : narrow(s, pw ? playwrightLocator(s, warn) : cypressLocator(s, warn), pw, warn);
125
+ const pageLevel = s.action === 'goto' || s.action === 'wait_url' || s.action === 'wait_text' || (s.action === 'assert' && s.hints?.assert === 'title');
126
+ const loc = pageLevel ? '' : narrow(s, pw ? playwrightLocator(s, warn) : cypressLocator(s, warn), pw, warn);
86
127
  const value = s.valueRef ? (required.add(s.valueRef), envName(s.valueRef).replace(/^UNDERSTUDY_/, '')) : quote(s.value ?? (s.action === 'goto' ? s.url : ''));
87
128
  switch (s.action) {
88
129
  case 'goto':
@@ -113,7 +154,12 @@ export function emitFlow(flow, framework = 'playwright-ts') {
113
154
  lines.push(pw ? `await ${loc}.scrollIntoViewIfNeeded();` : `${loc}.scrollIntoView();`);
114
155
  break;
115
156
  case 'wait_url':
116
- lines.push(pw ? `await page.waitForURL(new RegExp(${quote(s.value ?? '')}));` : `cy.url().should('include', ${value});`);
157
+ lines.push(pw
158
+ ? `await page.waitForURL(${s.hints?.urlRegex ? matcher(s, 'urlRegex', 'urlFlags') : s.value?.includes('*') ? quote(s.value) : `(u) => u.href.includes(${value})`});`
159
+ : `cy.url().should('${s.hints?.urlRegex ? 'match' : 'include'}', ${s.hints?.urlRegex ? matcher(s, 'urlRegex', 'urlFlags') : value});`);
160
+ break;
161
+ case 'assert':
162
+ lines.push(assertion(s, loc, value, pw, warn));
117
163
  break;
118
164
  case 'wait_text':
119
165
  lines.push(pw ? `await page.getByText(${value}).waitFor();` : `cy.contains(${value});`);
@@ -127,7 +173,7 @@ export function emitFlow(flow, framework = 'playwright-ts') {
127
173
  const header = `// ${flow.intent}\n// Generated by understudy from flow "${flow.app}/${flow.slug}". Regenerate rather than edit.\n\n`;
128
174
  const body = (indent) => lines.map((l) => indent + l).join('\n');
129
175
  const code = pw
130
- ? `import { test } from '@playwright/test';\n\n${header}${preamble}test(${quote(flow.title)}, async ({ page }) => {\n${body(' ')}\n});\n`
176
+ ? `import { test${lines.some((l) => l.includes('expect(')) ? ', expect' : ''} } from '@playwright/test';\n\n${header}${preamble}test(${quote(flow.title)}, async ({ page }) => {\n${body(' ')}\n});\n`
131
177
  : `${header}${preamble}describe(${quote(flow.title)}, () => {\n it(${quote(flow.title)}, () => {\n${body(' ')}\n });\n});\n`;
132
178
  return { framework, code, warnings, requiredValues: refs };
133
179
  }
@@ -21,6 +21,17 @@ export declare function extractFindings(result: Pick<ReplayResult, 'signals' | '
21
21
  * occurrence. A finding someone already triaged keeps its status.
22
22
  */
23
23
  export declare function saveFindings(coll: Collection<Finding>, app: string, drafts: FindingDraft[], at?: Date): Promise<void>;
24
+ /**
25
+ * Findings for an app, MOST SEVERE FIRST, then most frequent, then newest.
26
+ *
27
+ * Frequency alone put eight framework image warnings above the one real
28
+ * regression: a noisy console fires on every page, a broken route once.
29
+ * Sorted here rather than in the query because severity is a word, not a rank.
30
+ */
31
+ export declare function listFindings(coll: Collection<Finding>, app: string, opts?: {
32
+ all?: boolean;
33
+ limit?: number;
34
+ }): Promise<Finding[]>;
24
35
  export type Verdict = 'issue' | 'lesson' | 'noise';
25
36
  /**
26
37
  * Route open findings. issue: the app is wrong and someone should fix it.