@jeffawe/understudy 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +171 -2
  3. package/REASONER.md +67 -0
  4. package/build/extension/firefox/background.js +186 -0
  5. package/build/extension/firefox/icons/icon-128.png +0 -0
  6. package/build/extension/firefox/icons/icon-16.png +0 -0
  7. package/build/extension/firefox/icons/icon-32.png +0 -0
  8. package/build/extension/firefox/icons/icon-48.png +0 -0
  9. package/build/extension/firefox/manifest.json +54 -0
  10. package/build/extension/firefox/popup.html +52 -0
  11. package/build/extension/firefox/popup.js +106 -0
  12. package/build/extension/firefox/recorder.js +362 -0
  13. package/dist/adapters/recorder/accname-bundle.d.ts +12 -0
  14. package/dist/adapters/recorder/accname-bundle.js +12 -0
  15. package/dist/adapters/recorder/extension.d.ts +57 -0
  16. package/dist/adapters/recorder/extension.js +146 -0
  17. package/dist/adapters/recorder/injected.d.ts +21 -0
  18. package/dist/adapters/recorder/injected.js +352 -0
  19. package/dist/adapters/recorder/live.d.ts +105 -0
  20. package/dist/adapters/recorder/live.js +317 -0
  21. package/dist/adapters/recorder/script.d.ts +43 -0
  22. package/dist/adapters/recorder/script.js +530 -0
  23. package/dist/adapters/recorder/wire.d.ts +42 -0
  24. package/dist/adapters/recorder/wire.js +51 -0
  25. package/dist/core/auth-cache.d.ts +119 -0
  26. package/dist/core/auth-cache.js +216 -0
  27. package/dist/core/browser.d.ts +47 -0
  28. package/dist/core/browser.js +82 -0
  29. package/dist/core/distill.d.ts +118 -0
  30. package/dist/core/distill.js +197 -0
  31. package/dist/core/fingerprint.d.ts +15 -0
  32. package/dist/core/fingerprint.js +21 -0
  33. package/dist/core/recording-store.d.ts +34 -0
  34. package/dist/core/recording-store.js +64 -0
  35. package/dist/core/recording.d.ts +185 -0
  36. package/dist/core/recording.js +100 -0
  37. package/dist/core/replay.d.ts +307 -0
  38. package/dist/core/replay.js +804 -0
  39. package/dist/core/sig.d.ts +70 -0
  40. package/dist/core/sig.js +0 -0
  41. package/dist/core/trigger.d.ts +18 -0
  42. package/dist/core/trigger.js +35 -0
  43. package/dist/core/types.d.ts +28 -0
  44. package/dist/core/types.js +8 -0
  45. package/dist/core/visual.d.ts +80 -0
  46. package/dist/core/visual.js +111 -0
  47. package/dist/entry/cli.d.ts +9 -0
  48. package/dist/entry/cli.js +1008 -0
  49. package/dist/entry/mcp.d.ts +20 -0
  50. package/dist/entry/mcp.js +288 -0
  51. package/dist/flows/destructive.d.ts +19 -0
  52. package/dist/flows/destructive.js +48 -0
  53. package/dist/flows/distill.d.ts +28 -0
  54. package/dist/flows/distill.js +109 -0
  55. package/dist/flows/drift.d.ts +43 -0
  56. package/dist/flows/drift.js +116 -0
  57. package/dist/flows/emit.d.ts +23 -0
  58. package/dist/flows/emit.js +133 -0
  59. package/dist/flows/execute.d.ts +75 -0
  60. package/dist/flows/execute.js +133 -0
  61. package/dist/flows/findings.d.ts +38 -0
  62. package/dist/flows/findings.js +136 -0
  63. package/dist/flows/runs.d.ts +42 -0
  64. package/dist/flows/runs.js +93 -0
  65. package/dist/flows/save.d.ts +74 -0
  66. package/dist/flows/save.js +171 -0
  67. package/dist/memory/notes.d.ts +89 -0
  68. package/dist/memory/notes.js +163 -0
  69. package/dist/memory/placeholders.d.ts +41 -0
  70. package/dist/memory/placeholders.js +139 -0
  71. package/dist/memory/recall.d.ts +118 -0
  72. package/dist/memory/recall.js +147 -0
  73. package/dist/memory/vocabulary.d.ts +9 -0
  74. package/dist/memory/vocabulary.js +24 -0
  75. package/dist/plan/planner.d.ts +69 -0
  76. package/dist/plan/planner.js +211 -0
  77. package/dist/plan/seams.d.ts +58 -0
  78. package/dist/plan/seams.js +99 -0
  79. package/dist/store/db.d.ts +62 -0
  80. package/dist/store/db.js +183 -0
  81. package/dist/store/embed.d.ts +46 -0
  82. package/dist/store/embed.js +100 -0
  83. package/dist/store/reembed.d.ts +13 -0
  84. package/dist/store/reembed.js +32 -0
  85. package/dist/store/settings.d.ts +67 -0
  86. package/dist/store/settings.js +151 -0
  87. package/dist/store/types.d.ts +220 -0
  88. package/dist/store/types.js +14 -0
  89. package/extension/README.md +79 -0
  90. package/extension/background.js +186 -0
  91. package/extension/icons/icon-128.png +0 -0
  92. package/extension/icons/icon-16.png +0 -0
  93. package/extension/icons/icon-32.png +0 -0
  94. package/extension/icons/icon-48.png +0 -0
  95. package/extension/manifest.json +38 -0
  96. package/extension/popup.html +52 -0
  97. package/extension/popup.js +106 -0
  98. package/extension/recorder.js +362 -0
  99. package/package.json +68 -4
@@ -0,0 +1,1008 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * understudy — command line. Agents use the MCP server (entry/mcp.ts) instead;
4
+ * both call the same functions underneath.
5
+ *
6
+ * Argument parsing is hand-rolled on purpose: the surface is small, and a
7
+ * parser library would be more code than it saves.
8
+ */
9
+ import { recordLive } from '../adapters/recorder/live.js';
10
+ import { parseScript } from '../adapters/recorder/script.js';
11
+ import { startExtensionRecorder, DEFAULT_PORT, extensionDir, firefoxExtensionDir } from '../adapters/recorder/extension.js';
12
+ import { listRecordings, loadRecording, saveRecording } from '../core/recording-store.js';
13
+ import { loadSession, saveSession } from '../core/auth-cache.js';
14
+ import { buildRecording } from '../core/recording.js';
15
+ import { execute, prove, MissingValuesError } from '../flows/execute.js';
16
+ import { destructiveControls, remember } from '../memory/notes.js';
17
+ import { start, answer, runPlan } from '../plan/planner.js';
18
+ import { distillRequest, saveDistilled } from '../flows/distill.js';
19
+ import { readFile, writeFile, mkdir, chmod } from 'node:fs/promises';
20
+ import { join, resolve as resolvePath } from 'node:path';
21
+ import { existsSync } from 'node:fs';
22
+ import { chromium } from 'playwright';
23
+ import { emitFlow } from '../flows/emit.js';
24
+ import { recordingFrom, proveAndSave, proveByRun } from '../flows/save.js';
25
+ import { recordRun } from '../flows/runs.js';
26
+ import { recall } from '../memory/recall.js';
27
+ import { setPlaceholders, appPlaceholders } from '../memory/placeholders.js';
28
+ import * as store from '../store/db.js';
29
+ import { valueEnvName, readConfig, writeConfig, loadedFrom, HOME, expandHome, writeEnvValues } from '../store/settings.js';
30
+ const USAGE = `understudy — learn a web app, then test it by intent
31
+
32
+ USAGE
33
+ understudy <command> [options]
34
+
35
+ COMMANDS
36
+ config where settings come from; set them, or point at an env file
37
+ doctor check the MongoDB connection, vector search and embedder
38
+ reembed rebuild every vector with the model now configured
39
+ record <app> capture a flow in your own Chrome, with the extension
40
+ extension where the Chrome extension is, and how to load it
41
+ app <app> an app's settings, e.g. --placeholder email
42
+ import <app> <file> read an existing Playwright script into a recording
43
+ recordings [app] list captured recordings
44
+ save <hash> "<name>" prove a recording by replaying it, then save it as a flow
45
+ flows <app> list an app's saved flows and how each last ran
46
+ replay <hash> re-run a recording file headless
47
+ replay <app> <flow> re-run a saved flow; records the run, drift and findings
48
+ findings <app> what looked broken, most frequent first
49
+ recall <app> "<goal>" what memory knows about a goal — nothing runs
50
+ run <app> "<goal>" find the flow that does the goal, and run it
51
+ answer <runId> <json> answer a question a planned run stopped on
52
+ distill <app> <flow> print a saved flow's steps for an agent to name and split
53
+ remember <app> <file> store facts, lessons and findings from a JSON batch
54
+ emit <app> <flow> print a saved flow as a Playwright or Cypress test
55
+
56
+ MCP server for agents: understudy-mcp (see REASONER.md).
57
+
58
+ RECORD (in your own Chrome — load extension/ unpacked once, see extension/README.md)
59
+ --port <n> port the extension talks to (default 7397)
60
+
61
+ RECORD --new-browser (opt-in: a fresh browser Understudy opens; needs
62
+ "npx playwright install chromium", ~350 MB)
63
+ --url <baseUrl> required the first time you use an app; remembered after
64
+ --max-minutes <n> stop recording after n minutes (default 30)
65
+ --arm-manually drive to the starting point yourself, unrecorded, then
66
+ press Enter to start capturing — e.g. to skip the login
67
+ --value REF=value credentials the saved session is keyed on (repeatable)
68
+ --fresh ignore any saved session and sign in again
69
+
70
+ IMPORT
71
+ --url <baseUrl> resolves goto('/') when the script relies on a baseURL
72
+ --until <n> keep only the first n steps (stop before a real purchase)
73
+
74
+ REPLAY and SAVE
75
+ --value REF=value supply a value the recording deliberately doesn't store,
76
+ e.g. --value SECRET.password=hunter2 (repeatable)
77
+ --headed watch it replay
78
+ --allow-purchases replay a flow marked destructive (refused by default)
79
+
80
+ SAVE
81
+ --slug <name> the flow's short name (default: made from the name)
82
+ --intent <text> what the flow is for, if different from its name
83
+ --force save even though the proving replay failed
84
+
85
+ FINDINGS
86
+ --all include findings already triaged
87
+
88
+ RUN
89
+ --sub-goal <text> plan across several flows, in this order (repeatable)
90
+ --flow <slug> skip matching and run this flow (for an UNSURE match)
91
+ --dry-run say which flow would run, and run nothing
92
+ plus --value, --headed, --allow-purchases as for replay
93
+
94
+ EMIT
95
+ --framework <name> playwright-ts (default) or cypress-js
96
+ --out <file> write to a file instead of printing
97
+
98
+ DISTILL
99
+ --save <file> store the agent's answer (validated first)
100
+
101
+ RECALL
102
+ --limit <n> how many flows and notes to show (default 5)
103
+ --steps list the known flow's steps
104
+
105
+ SETTINGS — from the environment, --env-file <path>, the file saved with
106
+ "understudy config", or ./.env (first wins)
107
+ MONGODB_URI local Community or your Atlas mongodb+srv:// string
108
+ EMBED_URL, EMBED_MODEL, EMBED_KEY, EMBED_DIMS optional embedding model
109
+ UNDERSTUDY_<REF> login values: a recording's SECRET.password reads
110
+ UNDERSTUDY_SECRET_PASSWORD (or pass --value)
111
+ `;
112
+ function parseArgs(argv) {
113
+ const flags = new Map();
114
+ const positional = [];
115
+ for (let i = 0; i < argv.length; i++) {
116
+ const arg = argv[i];
117
+ if (!arg.startsWith('-')) {
118
+ positional.push(arg);
119
+ continue;
120
+ }
121
+ const key = arg.replace(/^--?/, '');
122
+ const next = argv[i + 1];
123
+ const value = next !== undefined && !next.startsWith('-') ? next : true;
124
+ if (typeof value === 'string')
125
+ i++;
126
+ flags.set(key, [...(flags.get(key) ?? []), value]);
127
+ }
128
+ return { flags, positional };
129
+ }
130
+ /** Last string value for a flag. */
131
+ const str = (v) => (v ?? []).filter((x) => typeof x === 'string').at(-1);
132
+ /** Every string value for a repeatable flag. */
133
+ const all = (flags, key) => (flags.get(key) ?? []).filter((x) => typeof x === 'string');
134
+ function fail(message, hint) {
135
+ console.error(`error: ${message}`);
136
+ if (hint)
137
+ console.error(` ${hint}`);
138
+ process.exit(1);
139
+ }
140
+ /** --value REF=value, repeatable → { REF: value }. */
141
+ function valuesFromFlags(flags) {
142
+ const values = {};
143
+ for (const v of all(flags, 'value')) {
144
+ const eq = v.indexOf('=');
145
+ if (eq < 0)
146
+ fail('--value must be REF=value');
147
+ values[v.slice(0, eq)] = v.slice(eq + 1);
148
+ }
149
+ return values;
150
+ }
151
+ // --- apps --------------------------------------------------------------------
152
+ /**
153
+ * An app's base URL, remembered in MongoDB after first use so the app name
154
+ * alone is enough next time. Without MONGODB_URI it simply uses --url.
155
+ */
156
+ async function resolveBaseUrl(slug, flag) {
157
+ if (!process.env.MONGODB_URI) {
158
+ return flag ?? fail(`no base URL for '${slug}'`, 'pass --url (or set MONGODB_URI so it is remembered)');
159
+ }
160
+ const { apps } = await store.collections();
161
+ if (flag) {
162
+ await apps.updateOne({ slug }, { $set: { 'urls.default': flag }, $setOnInsert: { slug, name: slug, createdAt: new Date() } }, { upsert: true });
163
+ return flag;
164
+ }
165
+ const known = (await apps.findOne({ slug }))?.urls.default;
166
+ return known ?? fail(`no base URL for '${slug}'`, 'pass --url the first time you use an app');
167
+ }
168
+ // --- doctor / reembed --------------------------------------------------------
169
+ /**
170
+ * Is everything connected? Connects to MongoDB, creates any missing
171
+ * collections and indexes, checks the embedding model with one real request,
172
+ * and reports whether vector search is ready. Same against local and Atlas.
173
+ */
174
+ async function cmdDoctor() {
175
+ console.log(`MongoDB ${store.describeUri()} (database: ${process.env.MONGODB_DB ?? 'understudy'})`);
176
+ const db = await store.connect();
177
+ console.log(`server ${(await db.admin().serverInfo()).version}`);
178
+ await store.ensureSchema();
179
+ console.log('schema collections and indexes present');
180
+ const { embedderConfig, embed } = await import('../store/embed.js');
181
+ const cfg = embedderConfig();
182
+ if (!cfg) {
183
+ console.log('embedder none configured — search will match names only (set EMBED_KEY for Voyage)');
184
+ }
185
+ else {
186
+ const [v] = await embed(['understudy doctor'], 'query', cfg);
187
+ console.log(`embedder ${cfg.model} at ${new URL(cfg.url).host} — ok, ${v.length} numbers per vector`);
188
+ }
189
+ // Replay needs the headless browser; recording happens in your own Chrome.
190
+ try {
191
+ const b = await chromium.launch({ headless: true });
192
+ await b.close();
193
+ console.log('browser headless Chromium ready (replay)');
194
+ }
195
+ catch {
196
+ console.log('browser headless Chromium MISSING — replay needs it: npx playwright install --only-shell chromium');
197
+ process.exitCode = 1;
198
+ }
199
+ if (!existsSync(chromium.executablePath())) {
200
+ console.log(' (full Chromium not installed — only needed for record --new-browser and --headed)');
201
+ }
202
+ const states = await store.waitForVectorIndexes(60_000).catch(() => store.vectorIndexStates());
203
+ for (const s of states) {
204
+ console.log(`vector ${s.collection.padEnd(6)} ${s.queryable ? 'ready' : `NOT READY (${s.status})`}`);
205
+ }
206
+ if (!states.every((s) => s.queryable)) {
207
+ console.log('\nvector search is not ready yet — a new index can take a minute; run doctor again.');
208
+ process.exitCode = 1;
209
+ }
210
+ }
211
+ async function cmdReembed() {
212
+ const { reembed } = await import('../store/reembed.js');
213
+ const r = await reembed();
214
+ console.log(`re-embedded ${r.flows} flows and ${r.notes} notes with ${r.model}`);
215
+ }
216
+ // --- config ------------------------------------------------------------------
217
+ /**
218
+ * understudy config where settings come from (no secrets shown)
219
+ * understudy config --env-file <path> read settings from this env file from now on
220
+ * understudy config set KEY=value [...] write settings into that env file
221
+ * understudy config --clear forget the saved env file
222
+ */
223
+ async function cmdConfig(positional, flags) {
224
+ const [sub, ...pairs] = positional;
225
+ const cfg = readConfig();
226
+ if (flags.has('clear')) {
227
+ delete cfg.envFile;
228
+ console.log(`saved ${await writeConfig(cfg)} — no env file remembered`);
229
+ return;
230
+ }
231
+ const chosen = str(flags.get('env-file'));
232
+ if (chosen) {
233
+ cfg.envFile = resolvePath(expandHome(chosen));
234
+ console.log(`saved ${await writeConfig(cfg)} — settings will be read from ${cfg.envFile}`);
235
+ if (!existsSync(cfg.envFile))
236
+ console.log(' (that file does not exist yet — create it, or use `understudy config set KEY=value`)');
237
+ }
238
+ if (sub === 'set') {
239
+ if (!pairs.length || pairs.some((p) => !/^[A-Za-z_][A-Za-z0-9_]*=/.test(p))) {
240
+ fail('config set needs KEY=value pairs', 'understudy config set MONGODB_URI="mongodb+srv://…" EMBED_KEY=…');
241
+ }
242
+ const values = Object.fromEntries(pairs.map((p) => [p.slice(0, p.indexOf('=')), p.slice(p.indexOf('=') + 1)]));
243
+ const file = await writeEnvValues(values).catch((e) => fail(e.message));
244
+ console.log(`wrote ${pairs.map((p) => p.slice(0, p.indexOf('='))).join(', ')} to ${file}`);
245
+ return;
246
+ }
247
+ if (sub)
248
+ fail(`unknown: config ${sub}`, 'understudy config [set KEY=value …] [--env-file <path>] [--clear]');
249
+ if (chosen)
250
+ return;
251
+ // Show where everything comes from — never the secrets themselves.
252
+ const shown = (k) => (process.env[k] ? 'set' : 'not set');
253
+ console.log(`config file ${join(HOME, 'config.json')}${existsSync(join(HOME, 'config.json')) ? '' : ' (none yet)'}`);
254
+ console.log(`env file ${cfg.envFile ?? 'none saved — use --env-file <path> or `config set`'}`);
255
+ console.log(`read now ${loadedFrom.length ? loadedFrom.join(', ') : 'no env files (only the environment)'}`);
256
+ console.log(`MONGODB_URI ${process.env.MONGODB_URI ? store.describeUri() : 'not set'}`);
257
+ const defaulted = !process.env.EMBED_URL && !process.env.EMBED_MODEL && process.env.EMBED_KEY;
258
+ console.log(`EMBED_URL ${process.env.EMBED_URL || (defaulted ? 'not set — Voyage, the default' : 'not set (goals match flow names, not meaning)')}`);
259
+ console.log(`EMBED_MODEL ${process.env.EMBED_MODEL || (defaulted ? 'not set — voyage-4-lite, the default' : 'not set')}`);
260
+ console.log(`EMBED_KEY ${shown('EMBED_KEY')}`);
261
+ const logins = Object.keys(process.env).filter((k) => k.startsWith('UNDERSTUDY_') && !['UNDERSTUDY_HOME'].includes(k) && !k.endsWith('_DIR'));
262
+ console.log(`login values ${logins.length ? logins.join(', ') : 'none (a recording\'s SECRET.password reads UNDERSTUDY_SECRET_PASSWORD)'}`);
263
+ }
264
+ // --- record ------------------------------------------------------------------
265
+ /**
266
+ * Wait for Enter in the terminal. Deliberately not anything on the page: an
267
+ * in-page control would itself be recorded as the first step.
268
+ */
269
+ function waitForEnter(prompt) {
270
+ if (!process.stdin.isTTY) {
271
+ fail('--arm-manually needs a terminal to read the Enter keypress from');
272
+ }
273
+ return new Promise((resolve) => {
274
+ console.log(prompt);
275
+ const finish = () => {
276
+ process.stdin.off('data', finish);
277
+ process.stdin.off('end', finish);
278
+ process.stdin.pause();
279
+ resolve();
280
+ };
281
+ process.stdin.resume();
282
+ process.stdin.once('data', finish);
283
+ process.stdin.once('end', finish);
284
+ });
285
+ }
286
+ function printEvents(recording) {
287
+ for (const e of recording.events) {
288
+ 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}`);
290
+ }
291
+ }
292
+ async function cmdRecord(positional, flags) {
293
+ const slug = positional[0] ?? fail('record needs an app name', 'understudy record myapp');
294
+ // The extension is the recorder. The fresh-browser one is opt-in, because it
295
+ // needs Playwright's full Chromium (~350 MB), which isn't installed by default
296
+ // — replay only needs the headless build.
297
+ if (!flags.has('new-browser'))
298
+ return cmdRecordExtension(slug, flags);
299
+ if (!existsSync(chromium.executablePath())) {
300
+ fail("--new-browser needs Playwright's full Chromium (~350 MB), which isn't installed", 'install it with: npx playwright install chromium — or record in your own Chrome with the extension (the default)');
301
+ }
302
+ const baseUrl = await resolveBaseUrl(slug, str(flags.get('url')));
303
+ const values = valuesFromFlags(flags);
304
+ const armManually = flags.has('arm-manually');
305
+ console.log(`recording ${slug} at ${baseUrl}`);
306
+ // A saved session only makes sense when capture starts late: if the login is
307
+ // part of what we're recording, restoring one would skip the very steps the
308
+ // recording exists to capture.
309
+ const cached = armManually && !flags.has('fresh') ? await loadSession(slug, values) : undefined;
310
+ if (cached)
311
+ console.log(`session: restored (saved ${cached.savedAt})`);
312
+ else if (armManually)
313
+ console.log('session: none — sign in yourself before pressing Enter');
314
+ console.log();
315
+ const recording = await recordLive({
316
+ appSlug: slug,
317
+ startUrl: baseUrl,
318
+ ...(cached ? { storageState: cached.storageState } : {}),
319
+ ...(flags.has('max-minutes') ? { maxMinutes: Number(str(flags.get('max-minutes'))) } : {}),
320
+ ...(armManually
321
+ ? {
322
+ armWhen: () => waitForEnter('drive to the point you want to start from — nothing is being recorded yet.\n' +
323
+ 'press Enter here to begin capturing.'),
324
+ // Saved at arm time: this is the state the recording claims to start
325
+ // from, and the steps that follow may well log out of it.
326
+ onArmed: async ({ context, sig }) => {
327
+ console.log(`\narmed at ${sig}\n`);
328
+ const path = await saveSession(context, slug, values, sig);
329
+ if (path)
330
+ console.log(`session saved ${path}`);
331
+ return { sessionSaved: Boolean(path) };
332
+ },
333
+ }
334
+ : {}),
335
+ });
336
+ if (!recording.events.some((e) => e.action !== 'goto')) {
337
+ console.error('\nnothing was recorded — no actions beyond the opening navigation. Not saved.');
338
+ process.exitCode = 2;
339
+ return;
340
+ }
341
+ const { path, existed } = await saveRecording(recording);
342
+ console.log(`\ncaptured ${recording.events.length} events`);
343
+ printEvents(recording);
344
+ const approximate = recording.events.filter((e) => e.resolution === 'unresolved').length;
345
+ if (approximate)
346
+ console.log(`\n${approximate} step(s) have approximate role/name — replay will resolve them.`);
347
+ if (recording.entry?.requiresSession) {
348
+ console.log(`\nthis recording starts from a signed-in browser (${recording.entry.startState}).`);
349
+ console.log(' replay restores the saved session for these --value credentials.');
350
+ }
351
+ console.log(`\nhash ${recording.hash}${existed ? ' (identical recording already existed)' : ''}`);
352
+ console.log(`saved ${path}`);
353
+ }
354
+ /**
355
+ * Record in the Chrome you already have open: this waits for the Understudy
356
+ * extension, which records the tab you start it on (see extension/README.md).
357
+ */
358
+ async function cmdRecordExtension(slug, flags) {
359
+ const port = Number(str(flags.get('port')) ?? DEFAULT_PORT);
360
+ const rec = await startExtensionRecorder({ appSlug: slug, port }).catch((e) => fail(`couldn't listen on port ${port}: ${e.message}`, 'another recording may be waiting — or pass --port and set the same port in the extension'));
361
+ console.log(`waiting for the Understudy extension (${rec.url})`);
362
+ console.log(` in Chrome: go to where the flow starts, click the Understudy icon, then "Record from this page".`);
363
+ console.log(` (extension not loaded yet? understudy extension — it says where it is and how)`);
364
+ console.log(` stop from the extension when you're done (or press Ctrl+C here to stop and keep what was recorded).\n`);
365
+ const onSigint = () => rec.stop();
366
+ process.once('SIGINT', onSigint);
367
+ const out = await rec.done;
368
+ process.off('SIGINT', onSigint);
369
+ if (!out.started || !out.recording.events.some((e) => e.action !== 'goto')) {
370
+ console.error('nothing was recorded — no actions beyond opening the page. Not saved.');
371
+ process.exitCode = 2;
372
+ return;
373
+ }
374
+ const { path, existed } = await saveRecording(out.recording);
375
+ console.log(`captured ${out.recording.events.length} events`);
376
+ printEvents(out.recording);
377
+ if (out.droppedUploads) {
378
+ console.log(`\n${out.droppedUploads} file upload(s) NOT recorded — a page can't say which file was chosen.`);
379
+ console.log(' write that part as a Playwright script and `understudy import` it instead.');
380
+ }
381
+ if (out.saveAs) {
382
+ // Ticked "Save as a flow when I stop": prove and save it now, here.
383
+ console.log(`\nsaving it as "${out.saveAs}" (you ticked "Save as a flow when I stop")\n`);
384
+ await saveAndReport(out.recording, out.saveAs, { values: valuesFromFlags(flags) });
385
+ return;
386
+ }
387
+ if (out.sessionPath) {
388
+ console.log(out.recording.entry?.requiresSession
389
+ ? '\nyou said you were signed in: replay starts from your sign-in (saved locally, 0600).'
390
+ : '\nthe tab\'s sign-in was copied; `save` keeps it only if the flow turns out to need it.');
391
+ }
392
+ console.log(`\nhash ${out.recording.hash}${existed ? ' (identical recording already existed)' : ''}`);
393
+ console.log(`saved ${path}`);
394
+ console.log(`\nnext: understudy save ${out.recording.hash} "<what this flow does>"`);
395
+ }
396
+ /**
397
+ * understudy app <app> the app's settings
398
+ * understudy app <app> --placeholder email keep its email fields as placeholders
399
+ * understudy app <app> --no-placeholders stop doing that for new flows
400
+ */
401
+ async function cmdApp(positional, flags) {
402
+ const app = positional[0] ?? fail('app needs an app name', 'understudy app myapp --placeholder email');
403
+ const kinds = all(flags, 'placeholder');
404
+ if (!kinds.length && !flags.has('no-placeholders')) {
405
+ const current = await appPlaceholders(app);
406
+ console.log(`${app}: placeholders ${current.length ? current.join(', ') : 'passwords only (the default)'}`);
407
+ return;
408
+ }
409
+ const out = await setPlaceholders(app, flags.has('no-placeholders') ? [] : kinds).catch((e) => fail(e.message));
410
+ console.log(`${app}: placeholders ${out.placeholders.length ? out.placeholders.join(', ') + ' (and passwords)' : 'passwords only'}`);
411
+ for (const c of out.converted) {
412
+ console.log(` ${c.placeholder.padEnd(14)} now used by ${c.flows.length} flow(s): ${c.flows.slice(0, 4).join(', ')}${c.flows.length > 4 ? ', …' : ''}`);
413
+ console.log(` ${''.padEnd(14)} value in ${c.valueIn}`);
414
+ }
415
+ if (out.envFile)
416
+ console.log(`moved the address(es) into ${out.envFile} — memory no longer holds them`);
417
+ else if (out.placeholders.includes('email') && !out.converted.length)
418
+ console.log('no email fields with stored addresses in its flows — new ones will be converted when saved');
419
+ }
420
+ /** Where the Chrome extension is, and how to load it — it ships inside the package. */
421
+ function cmdExtension() {
422
+ console.log(`Chrome, Edge, Brave and other Chromium browsers:\n ${extensionDir()}\n`);
423
+ console.log(' 1. open the extensions page (chrome://extensions, edge://extensions, …) and turn on Developer mode');
424
+ console.log(' 2. click "Load unpacked" and choose the folder above');
425
+ console.log(' 3. pin it (puzzle-piece icon) so it is one click away');
426
+ const firefox = firefoxExtensionDir();
427
+ if (existsSync(join(firefox, 'manifest.json'))) {
428
+ console.log(`\nFirefox:\n ${firefox}\n`);
429
+ console.log(' open about:debugging#/runtime/this-firefox → "Load Temporary Add-on…" → choose manifest.json in that folder');
430
+ console.log(' (Firefox removes temporary add-ons when it restarts)');
431
+ }
432
+ console.log('\nSafari: use `understudy record <app> --new-browser` instead (needs: npx playwright install chromium)');
433
+ console.log('\nthen record with: understudy record <app>');
434
+ }
435
+ // --- import ------------------------------------------------------------------
436
+ async function cmdImport(positional, flags) {
437
+ const slug = positional[0] ?? fail('import needs an app name', 'understudy import myapp tests/login.spec.ts');
438
+ const file = positional[1] ?? fail('import needs a script path');
439
+ // A script may rely on a baseURL from playwright.config, so goto('/') has no
440
+ // origin. The app's remembered base URL fills that in.
441
+ const fallback = str(flags.get('url')) ?? (await resolveBaseUrl(slug, undefined).catch(() => undefined));
442
+ const { recording: parsed, warnings } = await parseScript(file, slug, fallback);
443
+ // --until keeps the proven prefix — e.g. everything before a real purchase.
444
+ const until = str(flags.get('until'));
445
+ const recording = until
446
+ ? buildRecording({ source: parsed.source, origin: parsed.origin, appSlug: parsed.appSlug, startUrl: parsed.startUrl }, parsed.events.slice(0, Number(until)))
447
+ : parsed;
448
+ if (until)
449
+ console.log(`kept ${recording.events.length} of ${parsed.events.length} steps (--until ${until})\n`);
450
+ if (!recording.events.length) {
451
+ console.error(`no Playwright actions found in ${file} — expected calls like page.getByRole(...).click()`);
452
+ process.exitCode = 2;
453
+ return;
454
+ }
455
+ console.log(`parsed ${recording.events.length} events from ${file}\n`);
456
+ printEvents(recording);
457
+ // A clean import with warnings is NOT a clean import: each one is a step
458
+ // that was dropped, and replay will fail somewhere after it.
459
+ if (warnings.length) {
460
+ console.log(`\n${warnings.length} call(s) could not be mapped:`);
461
+ for (const w of warnings.slice(0, 10))
462
+ console.log(` ${w}`);
463
+ }
464
+ const { path, existed } = await saveRecording(recording);
465
+ console.log(`\nhash ${recording.hash}${existed ? ' (identical recording already existed)' : ''}`);
466
+ console.log(`saved ${path}`);
467
+ }
468
+ // --- replay ------------------------------------------------------------------
469
+ /**
470
+ * Run a recording with everything around it (saved session, lessons, stale
471
+ * sessions) via flows/execute.ts, and say what's worth knowing as it goes.
472
+ */
473
+ async function executeWithReport(recording, flags, opts) {
474
+ const values = valuesFromFlags(flags);
475
+ const x = await withLoginValues(values, (v) => execute(recording, { values: v, headed: flags.has('headed'), useLessons: opts.useLessons }))
476
+ .catch((e) => fail(e.message));
477
+ if (x.sessionRestoredFrom)
478
+ console.log(`session: restored (saved ${x.sessionRestoredFrom})`);
479
+ if (x.staleSession) {
480
+ console.log('the restored session did not land where it was recorded, and has been discarded.');
481
+ console.log(` expected ${x.staleSession.expected}, saw ${x.staleSession.observed}`);
482
+ console.log(' re-record with --arm-manually to refresh it.\n');
483
+ }
484
+ if (x.lessons?.fired)
485
+ console.log(`lessons ${x.lessons.fired} fired, ${x.lessons.helped} on steps that have failed before\n`);
486
+ return x.result;
487
+ }
488
+ /** `replay <hash>` runs a recording file; `replay <app> <flow>` runs a saved flow and records the run. */
489
+ async function cmdReplay(positional, flags) {
490
+ if (positional.length >= 2)
491
+ return cmdReplayFlow(positional[0], positional[1], flags);
492
+ const hash = positional[0] ?? fail('replay needs a recording hash, or an app and a flow', 'understudy recordings · understudy flows <app>');
493
+ const recording = await loadRecording(hash).catch(() => fail(`no recording '${hash}'`, 'understudy recordings'));
494
+ const result = await executeWithReport(recording, flags, { useLessons: false });
495
+ printReplay(result);
496
+ if (!result.ok)
497
+ process.exitCode = 3;
498
+ }
499
+ async function cmdReplayFlow(app, slug, flags) {
500
+ await runSavedFlow(app, slug, flags, { mode: 'replay' });
501
+ }
502
+ /**
503
+ * Run one saved flow: the safety gate, the replay, and recording the run.
504
+ * Shared by `replay <app> <flow>` and `run <app> "<goal>"`.
505
+ */
506
+ async function runSavedFlow(app, slug, flags, how) {
507
+ const { flows } = await store.collections();
508
+ const flow = await flows.findOne({ app, slug });
509
+ if (!flow)
510
+ fail(`no flow '${slug}' for app '${app}'`, `understudy flows ${app}`);
511
+ // The safety gate: a destructive flow does something real every time it runs.
512
+ if (!flags.has('allow-purchases')) {
513
+ if (flow.destructive) {
514
+ fail(`'${slug}' is marked destructive (${flow.destructiveBecause}) — running it may place a real order`, 'pass --allow-purchases if that is genuinely fine');
515
+ }
516
+ const controls = await destructiveControls(app);
517
+ const hit = flow.steps.find((s) => s.name && ['click', 'press', 'dispatch_click'].includes(s.action) && controls.has(s.name.toLowerCase()));
518
+ if (hit)
519
+ fail(`'${slug}' clicks "${hit.name}", which a fact says commits something real: ${controls.get(hit.name.toLowerCase())}`, 'pass --allow-purchases if that is genuinely fine');
520
+ }
521
+ console.log(`running ${app}/${slug} — ${flow.title}\n`);
522
+ if (flow.proven === false)
523
+ console.log(`note: '${slug}' is UNPROVEN (${flow.unprovenBecause}) — this run will tell.\n`);
524
+ const result = await executeWithReport(recordingFrom(flow), flags, { useLessons: true });
525
+ printReplay(result);
526
+ const run = await recordRun({
527
+ app, flow: slug, result, steps: flow.steps, mode: how.mode, ...(how.goal ? { goal: how.goal } : {}), ...(flow.proven === false ? { unproven: true } : {}),
528
+ });
529
+ if (await proveByRun(app, slug, result))
530
+ console.log(`\nproven '${slug}' passed, so it's no longer marked unproven`);
531
+ printRunReport(run);
532
+ if (!result.ok)
533
+ process.exitCode = 3;
534
+ }
535
+ // --- recall / run ------------------------------------------------------------
536
+ function printRecall(r, showSteps = false) {
537
+ const verdict = { known: 'KNOWN', unsure: 'UNSURE', unknown: "DON'T KNOW" }[r.verdict];
538
+ console.log(`${verdict} — ${r.why} (matched by ${r.method})\n`);
539
+ if (r.flows.length) {
540
+ console.log('flows');
541
+ for (const f of r.flows) {
542
+ const marks = [f.proven === false && 'UNPROVEN', f.destructive && 'DESTRUCTIVE', f.requiresSession && 'needs session', f.kind === 'segment' && 'segment'].filter(Boolean).join(', ');
543
+ console.log(` ${f.score.toFixed(3)} ${f.slug.padEnd(32)} ${f.title}${marks ? ` [${marks}]` : ''}`);
544
+ }
545
+ }
546
+ if (r.notes.length) {
547
+ console.log('\nnotes');
548
+ for (const n of r.notes)
549
+ console.log(` ${n.score.toFixed(3)} ${n.kind.padEnd(6)} ${n.text.slice(0, 100)}`);
550
+ }
551
+ if (r.best && r.steps) {
552
+ console.log(`\n${r.best.slug}: ${r.steps.length} steps${showSteps ? '' : ' (--steps to list them)'}`);
553
+ if (showSteps) {
554
+ for (const s of r.steps) {
555
+ const target = s.role && s.name ? `${s.role} "${s.name}"` : s.testId ? `[test id ${s.testId}]` : s.css ? `[${s.css}]` : '';
556
+ const what = s.placeholder ? `= <${s.placeholder}>` : s.value !== undefined ? `= "${s.value}"` : '';
557
+ console.log(` ${String(s.n).padStart(3)} ${s.action.padEnd(7)} ${target}${s.nth !== undefined ? ` (#${s.nth})` : ''} ${what}`.trimEnd());
558
+ }
559
+ }
560
+ }
561
+ for (const need of r.needs ?? []) {
562
+ console.log(`needs ${need.placeholder} — from ${need.readFrom.join(' or ')}: ${need.set ? 'set' : 'NOT SET'}`);
563
+ }
564
+ }
565
+ /** What memory knows about a goal. A database query: no browser, nothing runs. */
566
+ async function cmdRecall(positional, flags) {
567
+ const [app, ...goalWords] = positional;
568
+ if (!app || !goalWords.length)
569
+ fail('recall needs an app and a goal', 'understudy recall myapp "log in"');
570
+ printRecall(await recall(app, goalWords.join(' '), { withSteps: true, limit: Number(str(flags.get('limit')) ?? 5) }), flags.has('steps'));
571
+ }
572
+ /**
573
+ * Run a goal: find the flow that does it, check it's safe, run it. Only a
574
+ * KNOWN match runs on its own — an unsure one is shown so you can pick, and an
575
+ * unknown one is a cue to record it, never a guess.
576
+ */
577
+ async function cmdRun(positional, flags) {
578
+ const [app, ...goalWords] = positional;
579
+ if (!app || !goalWords.length)
580
+ fail('run needs an app and a goal', 'understudy run myapp "log in"');
581
+ const goal = goalWords.join(' ');
582
+ const picked = str(flags.get('flow'));
583
+ if (picked)
584
+ return runSavedFlow(app, picked, flags, { mode: 'run', goal });
585
+ // Several sub-goals: plan across flows, bridging the seams between them.
586
+ const subGoals = all(flags, 'sub-goal');
587
+ if (subGoals.length) {
588
+ const state = await start({
589
+ app, goal, subGoals,
590
+ ...(flags.has('dry-run') ? { dryRun: true } : {}),
591
+ ...(flags.has('allow-purchases') ? { allowPurchases: true } : {}),
592
+ });
593
+ return reportPlan(state, flags);
594
+ }
595
+ const r = await recall(app, goal);
596
+ printRecall(r);
597
+ if (r.verdict !== 'known' || !r.best) {
598
+ console.log(r.verdict === 'unsure'
599
+ ? `\nnot running — no flow is clearly this goal, and it may not be in memory at all.\n` +
600
+ ` if one of the flows above IS it: understudy run ${app} "${goal}" --flow <slug>\n` +
601
+ ` if none is: understudy record ${app}`
602
+ : `\nnot running — nothing in memory does this. Record it: understudy record ${app}`);
603
+ process.exitCode = 4;
604
+ return;
605
+ }
606
+ if (flags.has('dry-run')) {
607
+ console.log(`\ndry run — would run ${r.best.slug}${r.best.destructive ? ' (DESTRUCTIVE: needs --allow-purchases)' : ''}`);
608
+ return;
609
+ }
610
+ console.log();
611
+ await runSavedFlow(app, r.best.slug, flags, { mode: 'run', goal });
612
+ }
613
+ /** Show where planning got to, and run it if it's complete. */
614
+ async function reportPlan(state, flags) {
615
+ if (state.status === 'waiting') {
616
+ console.log(`run ${state.runId} is waiting for an answer:\n`);
617
+ console.log(JSON.stringify(state.question, null, 1));
618
+ console.log(`\nanswer it: understudy answer ${state.runId} '<json>'`);
619
+ process.exitCode = 5;
620
+ return;
621
+ }
622
+ if (state.status === 'blocked') {
623
+ console.log(`BLOCKED — ${state.why}`);
624
+ if (state.detail)
625
+ console.log(JSON.stringify(state.detail, null, 1));
626
+ process.exitCode = 4;
627
+ return;
628
+ }
629
+ console.log(`plan ${state.plan.join(' → ')}`);
630
+ for (const s of state.seams)
631
+ console.log(`seam before ${s.before}: ${s.how}`);
632
+ if (state.dryRun) {
633
+ console.log('\ndry run — nothing ran');
634
+ return;
635
+ }
636
+ console.log();
637
+ const values = valuesFromFlags(flags);
638
+ const { executed, recorded, nowProven } = await withLoginValues(values, (v) => runPlan(state.runId, { values: v, headed: flags.has('headed') }))
639
+ .catch((e) => fail(e.message));
640
+ if (executed.lessons?.fired)
641
+ console.log(`lessons ${executed.lessons.fired} fired, ${executed.lessons.helped} on steps that have failed before\n`);
642
+ printReplay(executed.result);
643
+ printRunReport(recorded);
644
+ for (const slug of nowProven)
645
+ console.log(`proven '${slug}' passed, so it's no longer marked unproven`);
646
+ if (!executed.result.ok)
647
+ process.exitCode = 3;
648
+ }
649
+ /** Answer a planning question: understudy answer <runId> '{"steps":[…]}' */
650
+ async function cmdAnswer(positional, flags) {
651
+ const [runId, json] = positional;
652
+ if (!runId || !json)
653
+ fail('answer needs a run id and a JSON answer', `understudy answer <runId> '{"subGoals":["…"]}'`);
654
+ let reply;
655
+ try {
656
+ reply = JSON.parse(json);
657
+ }
658
+ catch {
659
+ fail('the answer must be JSON');
660
+ }
661
+ await reportPlan(await answer(runId, reply).catch((e) => fail(e.message)), flags);
662
+ }
663
+ /**
664
+ * distill <app> <flow> print the request for an agent to answer
665
+ * distill <app> <flow> --save <file> store the agent's answer from a JSON file
666
+ */
667
+ async function cmdDistill(positional, flags) {
668
+ const [app, flow] = positional;
669
+ if (!app || !flow)
670
+ fail('distill needs an app and a saved flow', 'understudy distill myapp checkout');
671
+ const file = str(flags.get('save'));
672
+ if (!file) {
673
+ console.log(JSON.stringify(await distillRequest(app, flow).catch((e) => fail(e.message)), null, 1));
674
+ return;
675
+ }
676
+ const saved = await saveDistilled(app, flow, JSON.parse(await readFile(file, 'utf8'))).catch((e) => fail(e.message));
677
+ console.log(`distilled ${app}/${saved.flow}`);
678
+ for (const s of saved.segments)
679
+ console.log(` segment ${s.slug.padEnd(32)} ${s.steps} steps${s.replaced ? ' (replaced the existing one)' : ''}`);
680
+ if (saved.lessons.written || saved.lessons.alreadyKnown)
681
+ console.log(` lessons ${saved.lessons.written} new, ${saved.lessons.alreadyKnown} already known`);
682
+ }
683
+ /** remember <app> <file.json> — a batch of { facts, lessons, findings, reached }. */
684
+ async function cmdRemember(positional) {
685
+ const [app, file] = positional;
686
+ if (!app || !file)
687
+ fail('remember needs an app and a JSON file', 'understudy remember myapp learned.json');
688
+ const r = await remember(app, JSON.parse(await readFile(file, 'utf8'))).catch((e) => fail(e.message));
689
+ console.log(`facts ${r.facts.written} new, ${r.facts.alreadyKnown} already known`);
690
+ console.log(`lessons ${r.lessons.written} new, ${r.lessons.alreadyKnown} already known`);
691
+ console.log(`findings ${r.findings}`);
692
+ console.log(`reached ${r.reached}`);
693
+ }
694
+ function printReplay(result) {
695
+ console.log(`replay ${result.ok ? 'PASSED' : 'FAILED'} in ${(result.durationMs / 1000).toFixed(1)}s\n`);
696
+ for (const s of result.steps) {
697
+ const notes = [
698
+ s.ambiguousByName && `ambiguous: ${s.ambiguousByName.matched} by name, resolved via ${s.ambiguousByName.disambiguatedBy}`,
699
+ s.roleHadNoMatch && `role matched nothing, fell back to ${s.roleHadNoMatch.fellBackTo}`,
700
+ s.roundTripMismatch && `value did not survive: wrote "${s.roundTripMismatch.expected}", read "${s.roundTripMismatch.actual}"`,
701
+ s.error,
702
+ ].filter(Boolean).join('; ');
703
+ console.log(` ${String(s.seq).padStart(2)} ${s.ok ? 'ok ' : 'FAIL'} ${s.action.padEnd(7)} ${(s.sig ?? '').padEnd(28)} ${notes}`);
704
+ }
705
+ console.log(`\npath: ${result.sigSequence.join(' -> ')}`);
706
+ if (result.signals.length) {
707
+ console.log(`\n${result.signals.length} signal(s) captured:`);
708
+ for (const g of result.signals.slice(0, 12)) {
709
+ console.log(` [step ${g.duringStep}] ${g.kind}${g.status ? ' ' + g.status : ''} ${g.text.slice(0, 90)}`);
710
+ }
711
+ }
712
+ }
713
+ /** What recording the run added: drift against earlier runs, and findings. */
714
+ function printRunReport(run) {
715
+ const { drift } = run;
716
+ if (drift.firstRun)
717
+ console.log('\ndrift first passed run — this path is now the baseline');
718
+ else if (!drift.changed)
719
+ console.log('\ndrift same path as recent runs');
720
+ else {
721
+ console.log('\ndrift PATH CHANGED');
722
+ for (const s of drift.added)
723
+ console.log(` new ${s}`);
724
+ for (const s of drift.removed)
725
+ console.log(` gone ${s}`);
726
+ for (const s of drift.stateChanged)
727
+ console.log(` state ${s}`);
728
+ }
729
+ console.log(`findings ${run.findings.length ? `${run.findings.length} raised or seen again (understudy findings <app>)` : 'none'}`);
730
+ console.log(`run ${run.runId.toHexString()}`);
731
+ }
732
+ // --- save / flows / findings -------------------------------------------------
733
+ /** What proving found out about signing in, for a recording made from a tab. */
734
+ function signInNote(recording, signIn) {
735
+ if (!recording.entry?.session)
736
+ return undefined;
737
+ if (recording.entry.requiresSession)
738
+ return 'used, as you said you were signed in when recording';
739
+ if (signIn === 'needed')
740
+ return 'needed — it failed in an empty browser and passed signed in, so it keeps your session';
741
+ return 'not needed — the session copied when you started recording was deleted';
742
+ }
743
+ /**
744
+ * Prove a recording by replaying it, then save it as a flow. A recording that
745
+ * doesn't replay cleanly is refused — memory only holds flows known to work.
746
+ */
747
+ async function cmdSave(positional, flags) {
748
+ const [hash, ...titleWords] = positional;
749
+ if (!hash || !titleWords.length) {
750
+ fail('save needs a recording hash and a name', 'understudy save <hash> "log in as a member"');
751
+ }
752
+ const recording = await loadRecording(hash).catch(() => fail(`no recording '${hash}'`, 'understudy recordings'));
753
+ const slug = str(flags.get('slug'));
754
+ const intent = str(flags.get('intent'));
755
+ await saveAndReport(recording, titleWords.join(' '), {
756
+ values: valuesFromFlags(flags), headed: flags.has('headed'),
757
+ verify: !flags.has('no-verify'), force: flags.has('force'),
758
+ ...(slug ? { slug } : {}), ...(intent ? { intent } : {}),
759
+ });
760
+ }
761
+ /** Ask a yes/no question in the terminal. No terminal (piped, scripted): the answer is no. */
762
+ async function askYesNo(question, byDefault = false) {
763
+ if (!process.stdin.isTTY)
764
+ return false;
765
+ const answer = (await ask(`${question} ${byDefault ? '[Y/n]' : '[y/N]'} `)).trim();
766
+ return answer ? /^y(es)?$/i.test(answer) : byDefault;
767
+ }
768
+ /** Ask for a line in the terminal. */
769
+ async function ask(question) {
770
+ const { createInterface } = await import('node:readline/promises');
771
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
772
+ try {
773
+ return await rl.question(question);
774
+ }
775
+ finally {
776
+ rl.close();
777
+ }
778
+ }
779
+ /** Ask for a line without showing it (a password): each key shows as *. */
780
+ function askHidden(question) {
781
+ const stdin = process.stdin;
782
+ process.stdout.write(question);
783
+ stdin.setRawMode(true);
784
+ stdin.setEncoding('utf8');
785
+ stdin.resume();
786
+ return new Promise((resolve) => {
787
+ let typed = '';
788
+ const done = () => {
789
+ stdin.off('data', onData);
790
+ stdin.setRawMode(false);
791
+ stdin.pause();
792
+ process.stdout.write('\n');
793
+ resolve(typed);
794
+ };
795
+ const onData = (chunk) => {
796
+ for (const ch of chunk) {
797
+ if (ch === '\r' || ch === '\n')
798
+ return done();
799
+ if (ch === '\u0003') { // Ctrl+C
800
+ stdin.setRawMode(false);
801
+ process.stdout.write('\n');
802
+ process.exit(130);
803
+ }
804
+ if (ch === '\u007f' || ch === '\b') {
805
+ if (typed) {
806
+ typed = typed.slice(0, -1);
807
+ process.stdout.write('\b \b');
808
+ }
809
+ continue;
810
+ }
811
+ if (ch < ' ')
812
+ continue;
813
+ typed += ch;
814
+ process.stdout.write('*');
815
+ }
816
+ };
817
+ stdin.on('data', onData);
818
+ });
819
+ }
820
+ /**
821
+ * Run something that needs login values; if some are missing (nothing ran
822
+ * yet), ask for them in the terminal and run it again. Each one can be typed
823
+ * — hidden if it's a secret — or put in the env file, then Enter. Typed
824
+ * values can be saved to the env file so they aren't asked for again.
825
+ * No terminal: the error says where to put them, and nothing is asked.
826
+ */
827
+ async function withLoginValues(values, attempt) {
828
+ for (;;) {
829
+ try {
830
+ return await attempt(values);
831
+ }
832
+ catch (e) {
833
+ if (!(e instanceof MissingValuesError) || !process.stdin.isTTY)
834
+ throw e;
835
+ values = { ...values, ...(await askForValues(e)) };
836
+ }
837
+ }
838
+ }
839
+ async function askForValues(e) {
840
+ console.log(`\n${e.missing.length === 1 ? 'a login value is' : 'login values are'} needed to replay this, and not set — nothing has run yet.`);
841
+ console.log(`type it, or add it to ${e.envFile} and press Enter. (Ctrl+C to stop)\n`);
842
+ const typed = {};
843
+ const toSave = {};
844
+ for (const m of e.missing) {
845
+ const secret = /^SECRET\./i.test(m.placeholder) || /pass|secret|token|key/i.test(m.placeholder);
846
+ const question = ` ${m.placeholder}${secret ? ' (hidden)' : ''}: `;
847
+ const value = secret ? await askHidden(question) : (await ask(question)).trim();
848
+ if (!value)
849
+ continue; // they put it in the env file — the retry re-reads it
850
+ typed[m.placeholder] = value;
851
+ toSave[m.setOneOf[0]] = value;
852
+ }
853
+ if (Object.keys(toSave).length) {
854
+ const keys = Object.keys(toSave).join(', ');
855
+ if (await askYesNo(`\n save ${keys} to ${e.envFile} so you're not asked again?`, true)) {
856
+ const file = await writeEnvValues(toSave).catch((err) => {
857
+ console.log(` couldn't save it: ${err.message} — using it for this run only`);
858
+ });
859
+ if (file)
860
+ console.log(` saved to ${file} (readable only by you)`);
861
+ }
862
+ }
863
+ console.log();
864
+ return typed;
865
+ }
866
+ /**
867
+ * Prove a recording and keep it as a flow, saying what happened. Used by
868
+ * `save`, and by `record` when the extension's "Save as a flow when I stop" is ticked.
869
+ */
870
+ async function saveAndReport(recording, title, opts) {
871
+ if (opts.verify === false)
872
+ console.log('saving without a replay — it will be marked unproven until a run passes\n');
873
+ else
874
+ console.log(`proving ${recording.hash} by replaying it…\n`);
875
+ // No lessons: what gets saved is what the recording does on its own. Proving
876
+ // also works out whether it needs to start signed in (flows/execute.ts: prove).
877
+ let printed = false;
878
+ const out = await withLoginValues(opts.values ?? {}, (values) => proveAndSave(recording, {
879
+ title, ...opts, values,
880
+ keepIfFailed: async (proven) => {
881
+ printReplay(proven.result);
882
+ printed = true;
883
+ console.log('\nthe replay failed, so this would not normally be kept.');
884
+ return askYesNo('keep it anyway, marked unproven (the first run that passes proves it)?');
885
+ },
886
+ })).catch((e) => fail(e.message));
887
+ if (out.proven && !printed)
888
+ printReplay(out.proven.result);
889
+ const note = out.proven ? signInNote(recording, out.proven.signIn) : undefined;
890
+ if (note)
891
+ console.log(`\nsign-in ${note}`);
892
+ if (!out.saved) {
893
+ console.error('\nnot saved — the recording did not replay cleanly' + (recording.entry?.session ? ', signed in or not' : '') + '.');
894
+ console.error(' fix it or re-record; or keep it anyway with --force (or --no-verify to skip the replay), marked unproven.');
895
+ process.exitCode = 3;
896
+ return;
897
+ }
898
+ const { flow } = out;
899
+ for (const c of out.placeholders.converted)
900
+ console.log(`\nemail uses ${c.placeholder} (value in ${c.valueIn}) — this app keeps emails out of memory`);
901
+ console.log(`\nsaved ${flow.app}/${flow.slug} (${flow.steps.length} steps${flow.embedding ? ', searchable by meaning' : ''})`);
902
+ if (flow.proven === false)
903
+ console.log(` UNPROVEN — ${flow.unprovenBecause}. The first run that passes proves it.`);
904
+ if (flow.destructive)
905
+ console.log(` DESTRUCTIVE — ${flow.destructiveBecause}. Replays need --allow-purchases.`);
906
+ if (out.run)
907
+ printRunReport(out.run);
908
+ console.log(`\nreplay it any time: understudy replay ${flow.app} ${flow.slug}`);
909
+ }
910
+ async function cmdFlows(positional) {
911
+ const app = positional[0] ?? fail('flows needs an app name', 'understudy flows myapp');
912
+ const { flows, runs } = await store.collections();
913
+ const rows = await flows.find({ app }, { projection: { embedding: 0, steps: 0 } }).sort({ slug: 1 }).toArray();
914
+ if (!rows.length) {
915
+ console.log(`no flows for '${app}' yet — record one, then \`understudy save <hash> "<name>"\``);
916
+ return;
917
+ }
918
+ for (const f of rows) {
919
+ const last = await runs.find({ app, plan: [f.slug] }).sort({ startedAt: -1 }).limit(1).next();
920
+ const status = last ? `${last.status} ${last.startedAt.toISOString().slice(0, 16).replace('T', ' ')}` : 'never run';
921
+ const marks = [f.proven === false && 'UNPROVEN', f.destructive && 'DESTRUCTIVE', f.requiresSession && 'needs session', f.kind === 'segment' && 'segment', f.madeBy === 'agent' && 'made by an agent']
922
+ .filter(Boolean).join(', ');
923
+ console.log(` ${f.slug.padEnd(32)} ${status.padEnd(24)} ${f.title}${marks ? ` [${marks}]` : ''}`);
924
+ }
925
+ }
926
+ async function cmdFindings(positional, flags) {
927
+ const app = positional[0] ?? fail('findings needs an app name', 'understudy findings myapp');
928
+ 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();
931
+ if (!rows.length) {
932
+ console.log(flags.has('all') ? `no findings for '${app}'` : `no open findings for '${app}' (--all to include triaged ones)`);
933
+ return;
934
+ }
935
+ for (const f of rows) {
936
+ console.log(` ${f.severity.padEnd(6)} ×${String(f.occurrences).padEnd(4)} ${f.kind.padEnd(14)} ${f.statement.slice(0, 110)}${f.evidence?.fromUnprovenFlow ? ' [from an unproven flow — may be the recording]' : ''}`);
937
+ }
938
+ }
939
+ /** emit <app> <flow> — print a saved flow as a Playwright or Cypress test. */
940
+ async function cmdEmit(positional, flags) {
941
+ const [app, slug] = positional;
942
+ if (!app || !slug)
943
+ fail('emit needs an app and a flow', 'understudy emit myapp log-in --framework cypress-js');
944
+ const framework = (str(flags.get('framework')) ?? 'playwright-ts');
945
+ if (framework !== 'playwright-ts' && framework !== 'cypress-js')
946
+ fail('--framework must be playwright-ts or cypress-js');
947
+ const { flows } = await store.collections();
948
+ const flow = await flows.findOne({ app, slug });
949
+ if (!flow)
950
+ fail(`no flow '${slug}' for app '${app}'`, `understudy flows ${app}`);
951
+ const out = emitFlow(flow, framework);
952
+ const file = str(flags.get('out'));
953
+ if (file) {
954
+ await writeFile(file, out.code);
955
+ console.log(`wrote ${file}`);
956
+ }
957
+ else
958
+ console.log(out.code);
959
+ for (const w of out.warnings)
960
+ console.error(`warning: ${w}`);
961
+ if (out.requiredValues.length)
962
+ console.error(`reads from the environment: ${out.requiredValues.map(valueEnvName).join(', ')}`);
963
+ }
964
+ // --- recordings --------------------------------------------------------------
965
+ async function cmdRecordings(positional) {
966
+ const rows = await listRecordings(positional[0]);
967
+ if (!rows.length)
968
+ console.log('no recordings yet — try `understudy record <app>`');
969
+ for (const r of rows) {
970
+ console.log(` ${r.hash} ${r.appSlug.padEnd(14)} ${String(r.events).padStart(3)} events ${r.source.padEnd(6)} ${r.createdAt}`);
971
+ }
972
+ }
973
+ // --- main --------------------------------------------------------------------
974
+ async function main() {
975
+ const { flags, positional } = parseArgs(process.argv.slice(2));
976
+ const [command, ...rest] = positional;
977
+ if (!command || flags.has('help') || flags.has('h')) {
978
+ console.log(USAGE);
979
+ return;
980
+ }
981
+ switch (command) {
982
+ case 'doctor': return cmdDoctor();
983
+ case 'config': return cmdConfig(rest, flags);
984
+ case 'extension': return cmdExtension();
985
+ case 'app': return cmdApp(rest, flags);
986
+ case 'reembed': return cmdReembed();
987
+ case 'record': return cmdRecord(rest, flags);
988
+ case 'import': return cmdImport(rest, flags);
989
+ case 'recordings': return cmdRecordings(rest);
990
+ case 'replay': return cmdReplay(rest, flags);
991
+ case 'save': return cmdSave(rest, flags);
992
+ case 'flows': return cmdFlows(rest);
993
+ case 'findings': return cmdFindings(rest, flags);
994
+ case 'recall': return cmdRecall(rest, flags);
995
+ case 'run': return cmdRun(rest, flags);
996
+ case 'answer': return cmdAnswer(rest, flags);
997
+ case 'distill': return cmdDistill(rest, flags);
998
+ case 'remember': return cmdRemember(rest);
999
+ case 'emit': return cmdEmit(rest, flags);
1000
+ default: fail(`unknown command '${command}'`, 'understudy --help');
1001
+ }
1002
+ }
1003
+ main()
1004
+ .catch((err) => {
1005
+ console.error(`\nfailed: ${err instanceof Error ? err.message : String(err)}`);
1006
+ process.exitCode = 1;
1007
+ })
1008
+ .finally(() => store.close());