@jeffawe/understudy 0.2.0 → 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.
@@ -20,6 +20,7 @@
20
20
  * of git.
21
21
  */
22
22
  import type { BrowserContext } from 'playwright';
23
+ /** Under ~/.understudy, not the current folder — see recording-store.ts. */
23
24
  export declare const SESSIONS_DIR: string;
24
25
  /** Playwright's storageState payload. Opaque to us — we store and replay it. */
25
26
  export type StorageState = Awaited<ReturnType<BrowserContext['storageState']>>;
@@ -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,
@@ -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,14 +23,23 @@ 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';
29
31
  import { valueEnvName, readConfig, writeConfig, loadedFrom, HOME, expandHome, writeEnvValues } from '../store/settings.js';
32
+ // Piped into `head` and the pipe closed early: stop quietly, like other CLIs.
33
+ process.stdout.on('error', (e) => {
34
+ if (e.code === 'EPIPE')
35
+ process.exit(0);
36
+ throw e;
37
+ });
30
38
  const USAGE = `understudy — learn a web app, then test it by intent
31
39
 
32
40
  USAGE
33
41
  understudy <command> [options]
42
+ understudy --version
34
43
 
35
44
  COMMANDS
36
45
  config where settings come from; set them, or point at an env file
@@ -45,7 +54,7 @@ COMMANDS
45
54
  flows <app> list an app's saved flows and how each last ran
46
55
  replay <hash> re-run a recording file headless
47
56
  replay <app> <flow> re-run a saved flow; records the run, drift and findings
48
- findings <app> what looked broken, most frequent first
57
+ findings <app> what looked broken, most severe first
49
58
  recall <app> "<goal>" what memory knows about a goal — nothing runs
50
59
  run <app> "<goal>" find the flow that does the goal, and run it
51
60
  answer <runId> <json> answer a question a planned run stopped on
@@ -286,7 +295,9 @@ function waitForEnter(prompt) {
286
295
  function printEvents(recording) {
287
296
  for (const e of recording.events) {
288
297
  const value = e.value !== undefined ? ` = "${e.value}"` : e.valueRef ? ` = <${e.valueRef}>` : '';
289
- 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}`);
290
301
  }
291
302
  }
292
303
  async function cmdRecord(positional, flags) {
@@ -419,7 +430,9 @@ async function cmdApp(positional, flags) {
419
430
  }
420
431
  /** Where the Chrome extension is, and how to load it — it ships inside the package. */
421
432
  function cmdExtension() {
422
- console.log(`Chrome, Edge, Brave and other Chromium browsers:\n ${extensionDir()}\n`);
433
+ console.log('Chrome, Edge, Brave and other Chromium browsers — install it from the Chrome Web Store:');
434
+ console.log(' https://chromewebstore.google.com/detail/understudy-recorder/mdobdjogkgimabdpmbmhhcdeoahoapjf\n');
435
+ console.log(`or load it by hand from:\n ${extensionDir()}\n`);
423
436
  console.log(' 1. open the extensions page (chrome://extensions, edge://extensions, …) and turn on Developer mode');
424
437
  console.log(' 2. click "Load unpacked" and choose the folder above');
425
438
  console.log(' 3. pin it (puzzle-piece icon) so it is one click away');
@@ -439,7 +452,7 @@ async function cmdImport(positional, flags) {
439
452
  // A script may rely on a baseURL from playwright.config, so goto('/') has no
440
453
  // origin. The app's remembered base URL fills that in.
441
454
  const fallback = str(flags.get('url')) ?? (await resolveBaseUrl(slug, undefined).catch(() => undefined));
442
- const { recording: parsed, warnings } = await parseScript(file, slug, fallback);
455
+ const { recording: parsed, warnings, dropped } = await parseScript(file, slug, fallback);
443
456
  // --until keeps the proven prefix — e.g. everything before a real purchase.
444
457
  const until = str(flags.get('until'));
445
458
  const recording = until
@@ -461,6 +474,12 @@ async function cmdImport(positional, flags) {
461
474
  for (const w of warnings.slice(0, 10))
462
475
  console.log(` ${w}`);
463
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
+ }
464
483
  const { path, existed } = await saveRecording(recording);
465
484
  console.log(`\nhash ${recording.hash}${existed ? ' (identical recording already existed)' : ''}`);
466
485
  console.log(`saved ${path}`);
@@ -713,8 +732,10 @@ function printReplay(result) {
713
732
  /** What recording the run added: drift against earlier runs, and findings. */
714
733
  function printRunReport(run) {
715
734
  const { drift } = run;
716
- if (drift.firstRun)
717
- 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');
718
739
  else if (!drift.changed)
719
740
  console.log('\ndrift same path as recent runs');
720
741
  else {
@@ -926,8 +947,7 @@ async function cmdFlows(positional) {
926
947
  async function cmdFindings(positional, flags) {
927
948
  const app = positional[0] ?? fail('findings needs an app name', 'understudy findings myapp');
928
949
  const { findings } = await store.collections();
929
- const filter = flags.has('all') ? { app } : { app, status: 'open' };
930
- 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 });
931
951
  if (!rows.length) {
932
952
  console.log(flags.has('all') ? `no findings for '${app}'` : `no open findings for '${app}' (--all to include triaged ones)`);
933
953
  return;
@@ -974,6 +994,10 @@ async function cmdRecordings(positional) {
974
994
  async function main() {
975
995
  const { flags, positional } = parseArgs(process.argv.slice(2));
976
996
  const [command, ...rest] = positional;
997
+ if (flags.has('version') || flags.has('v') || command === 'version') {
998
+ console.log(VERSION);
999
+ return;
1000
+ }
977
1001
  if (!command || flags.has('help') || flags.has('h')) {
978
1002
  console.log(USAGE);
979
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[];