@jeffawe/understudy 0.4.0 → 0.5.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 (40) hide show
  1. package/CHANGELOG.md +127 -0
  2. package/README.md +69 -172
  3. package/REASONER.md +76 -86
  4. package/dist/adapters/recorder/script.d.ts +25 -2
  5. package/dist/adapters/recorder/script.js +126 -31
  6. package/dist/core/outline.d.ts +43 -0
  7. package/dist/core/outline.js +121 -0
  8. package/dist/core/recording.d.ts +19 -1
  9. package/dist/core/recording.js +38 -2
  10. package/dist/core/replay.d.ts +62 -1
  11. package/dist/core/replay.js +162 -106
  12. package/dist/entry/cli.js +110 -29
  13. package/dist/entry/mcp.d.ts +1 -0
  14. package/dist/entry/mcp.js +114 -23
  15. package/dist/flows/destructive.js +1 -1
  16. package/dist/flows/distill.js +11 -6
  17. package/dist/flows/emit.d.ts +7 -0
  18. package/dist/flows/emit.js +26 -10
  19. package/dist/flows/execute.d.ts +12 -0
  20. package/dist/flows/execute.js +23 -16
  21. package/dist/flows/runs.d.ts +2 -0
  22. package/dist/flows/runs.js +7 -3
  23. package/dist/flows/save.d.ts +5 -2
  24. package/dist/flows/save.js +38 -23
  25. package/dist/flows/session.d.ts +176 -0
  26. package/dist/flows/session.js +383 -0
  27. package/dist/flows/variants.d.ts +81 -0
  28. package/dist/flows/variants.js +139 -0
  29. package/dist/memory/calibrate.js +3 -1
  30. package/dist/memory/pages.d.ts +34 -0
  31. package/dist/memory/pages.js +60 -0
  32. package/dist/memory/recall.d.ts +56 -2
  33. package/dist/memory/recall.js +194 -30
  34. package/dist/plan/planner.d.ts +11 -1
  35. package/dist/plan/planner.js +36 -19
  36. package/dist/store/app-settings.d.ts +26 -0
  37. package/dist/store/app-settings.js +49 -0
  38. package/dist/store/db.js +8 -1
  39. package/dist/store/types.d.ts +18 -0
  40. package/package.json +3 -2
@@ -16,7 +16,7 @@
16
16
  * state { use: "buy-a-bundle" } — run that flow first — or { holds: true }
17
17
  */
18
18
  import type { Run, Step } from '../store/types.js';
19
- import type { RawRecording } from '../core/recording.js';
19
+ import { type RawRecording } from '../core/recording.js';
20
20
  import { type ExecuteOptions } from '../flows/execute.js';
21
21
  export interface PlanRequest {
22
22
  app: string;
@@ -25,6 +25,15 @@ export interface PlanRequest {
25
25
  subGoals?: string[];
26
26
  dryRun?: boolean;
27
27
  allowPurchases?: boolean;
28
+ /**
29
+ * A plan that commits something real runs up to its first commit step, whose
30
+ * control is checked and never pressed — the whole form, without the booking.
31
+ */
32
+ stopBeforeCommit?: boolean;
33
+ /** Use this variant's copy of each flow, where it has one (flows/variants.ts). */
34
+ variant?: string;
35
+ /** Run the app at this address — a branch's preview deploy — instead of the one the flows were saved on. */
36
+ baseUrl?: string;
28
37
  }
29
38
  export type PlanState = {
30
39
  status: 'waiting';
@@ -66,6 +75,7 @@ export declare function recordingForPlan(runId: string): Promise<{
66
75
  * outcome written onto the same run document.
67
76
  */
68
77
  export declare function runPlan(runId: string, opts?: Pick<ExecuteOptions, 'values' | 'headed' | 'onHuman' | 'onStuck'>): Promise<{
78
+ commit?: import("../flows/destructive.js").CommitStep;
69
79
  executed: import("../flows/execute.js").Executed;
70
80
  recorded: import("../flows/runs.js").RecordedRun;
71
81
  plan: string[];
@@ -20,7 +20,10 @@ import { collections } from '../store/db.js';
20
20
  import { recall } from '../memory/recall.js';
21
21
  import { vocabulary } from '../memory/vocabulary.js';
22
22
  import { destructiveControls } from '../memory/notes.js';
23
+ import { commitSteps } from '../flows/destructive.js';
23
24
  import { resolveSeam, acceptSeamAnswer } from './seams.js';
25
+ import { rebase } from '../core/recording.js';
26
+ import { checkVariant, pickVariant, resolveFlow } from '../flows/variants.js';
24
27
  import { execute } from '../flows/execute.js';
25
28
  import { recordRun } from '../flows/runs.js';
26
29
  import { proveByRun } from '../flows/save.js';
@@ -62,13 +65,18 @@ const SEAM_HOW = [
62
65
  export async function start(req) {
63
66
  const { runs } = await collections();
64
67
  const now = new Date();
68
+ const variant = checkVariant(req.variant);
69
+ if (req.baseUrl !== undefined && !/^https?:\/\/[^/]/.test(req.baseUrl))
70
+ throw new Error(`baseUrl must be an http(s) address, not "${req.baseUrl}"`);
65
71
  const run = {
66
- app: req.app, goal: req.goal, mode: 'run', status: 'waiting', plan: [], steps: [], sigSequence: [],
72
+ app: req.app, goal: req.goal, mode: 'run', status: 'waiting', ...(variant ? { variant } : {}), plan: [], steps: [], sigSequence: [],
67
73
  events: [], findings: [], durationMs: 0, startedAt: now,
68
74
  planning: {
69
75
  ...(req.subGoals?.length ? { subGoals: req.subGoals } : {}),
70
76
  ...(req.dryRun ? { dryRun: true } : {}),
71
77
  ...(req.allowPurchases ? { allowPurchases: true } : {}),
78
+ ...(req.stopBeforeCommit ? { stopBeforeCommit: true } : {}),
79
+ ...(req.baseUrl ? { baseUrl: req.baseUrl } : {}),
72
80
  },
73
81
  };
74
82
  const { insertedId } = await runs.insertOne(run);
@@ -98,7 +106,7 @@ export async function answer(runId, reply) {
98
106
  planning.states = { ...planning.states, [state]: { holds: true } };
99
107
  }
100
108
  else if (typeof r?.use === 'string') {
101
- if (!(await flows.findOne({ app: run.app, slug: r.use, establishes: state }))) {
109
+ if (!(await resolveFlow(run.app, r.use, run.variant))?.establishes?.includes(state)) {
102
110
  throw new Error(`"${r.use}" isn't a flow that establishes "${state}" — pick one from establishedBy, or answer { "holds": true }`);
103
111
  }
104
112
  planning.states = { ...planning.states, [state]: { use: r.use } };
@@ -110,8 +118,8 @@ export async function answer(runId, reply) {
110
118
  else if (q.kind === 'seam') {
111
119
  const i = q.before;
112
120
  const [from, to] = await Promise.all([
113
- flows.findOne({ app: run.app, slug: planning.bound[i - 1] }),
114
- flows.findOne({ app: run.app, slug: planning.bound[i] }),
121
+ resolveFlow(run.app, planning.bound[i - 1], run.variant),
122
+ resolveFlow(run.app, planning.bound[i], run.variant),
115
123
  ]);
116
124
  const accepted = await acceptSeamAnswer(run.app, from, to, reply);
117
125
  if ('problems' in accepted)
@@ -151,7 +159,7 @@ async function advance(run) {
151
159
  if (!planning.bound) {
152
160
  const bound = [];
153
161
  for (const sub of planning.subGoals) {
154
- const r = await recall(run.app, sub);
162
+ const r = await recall(run.app, sub, run.variant ? { variant: run.variant } : {});
155
163
  if (r.verdict !== 'known' || !r.best) {
156
164
  const close = r.flows.slice(0, 3).map((f) => ({ slug: f.slug, title: f.title, score: Number(f.score.toFixed(3)) }));
157
165
  return block(run, `no flow clearly does "${sub}" (${r.why}) — rephrase it in the app's words, or record it`, { subGoal: sub, closest: close });
@@ -163,7 +171,7 @@ async function advance(run) {
163
171
  planning.bound = bound;
164
172
  }
165
173
  const load = async () => {
166
- const found = await Promise.all(planning.bound.map((slug) => flows.findOne({ app: run.app, slug })));
174
+ const found = await Promise.all(planning.bound.map((slug) => resolveFlow(run.app, slug, run.variant)));
167
175
  return found.some((f) => !f) ? undefined : found;
168
176
  };
169
177
  let chain = await load();
@@ -187,25 +195,26 @@ async function advance(run) {
187
195
  return block(run, `"${chosen.use}" no longer exists — plan again`);
188
196
  continue;
189
197
  }
190
- const makers = await flows
191
- .find({ app: run.app, establishes: need.state }, { projection: { slug: 1, title: 1, destructive: 1, proven: 1 } })
192
- .toArray();
198
+ const makers = pickVariant(await flows
199
+ .find({ app: run.app, establishes: need.state }, { projection: { slug: 1, variant: 1, title: 1, destructive: 1, proven: 1 } })
200
+ .toArray(), run.variant);
193
201
  return ask(run, {
194
202
  kind: 'state', state: need.state, neededBy: need.neededBy,
195
203
  establishedBy: makers.map((f) => ({ slug: f.slug, title: f.title, ...(f.destructive ? { destructive: true } : {}), ...(f.proven === false ? { unproven: true } : {}) })),
196
204
  how: STATE_HOW,
197
205
  });
198
206
  }
199
- // 3. Safety: refuse anything that commits something real, unless allowed.
200
- if (!planning.allowPurchases) {
207
+ // 3. Safety: refuse anything that commits something real, unless allowed —
208
+ // or unless the run stops before it (see runPlan).
209
+ if (!planning.allowPurchases && !planning.stopBeforeCommit) {
201
210
  const risky = chain.find((f) => f.destructive);
202
211
  if (risky)
203
- return block(run, `${risky.slug} is destructive (${risky.destructiveBecause}) — allow purchases to run it`);
212
+ return block(run, `${risky.slug} is destructive (${risky.destructiveBecause}) — stop before the commit to run everything up to it, or allow purchases to run it`);
204
213
  const controls = await destructiveControls(run.app);
205
214
  for (const f of chain) {
206
215
  const hit = f.steps.find((s) => s.name && ['click', 'press', 'dispatch_click'].includes(s.action) && controls.has(s.name.toLowerCase()));
207
216
  if (hit)
208
- return block(run, `${f.slug} clicks "${hit.name}", which a fact says commits something real: ${controls.get(hit.name.toLowerCase())}`);
217
+ return block(run, `${f.slug} clicks "${hit.name}", which a fact says commits something real: ${controls.get(hit.name.toLowerCase())} — stop before the commit, or allow purchases`);
209
218
  }
210
219
  }
211
220
  // 4. The first flow must be able to start from a cold browser (or a saved session).
@@ -244,7 +253,7 @@ export async function recordingForPlan(runId) {
244
253
  const run = await runs.findOne({ _id: new ObjectId(runId) });
245
254
  if (!run || run.status !== 'planned')
246
255
  throw new Error(`run ${runId} isn't planned (it is ${run?.status ?? 'missing'})`);
247
- const chain = (await Promise.all(run.plan.map((slug) => flows.findOne({ app: run.app, slug }))));
256
+ const chain = (await Promise.all(run.plan.map((slug) => resolveFlow(run.app, slug, run.variant))));
248
257
  const first = chain[0];
249
258
  const steps = [];
250
259
  const starts = [];
@@ -258,7 +267,7 @@ export async function recordingForPlan(runId) {
258
267
  starts.push(steps.length);
259
268
  steps.push(...flow.steps);
260
269
  });
261
- const recording = {
270
+ const built = {
262
271
  version: 1, source: 'import', origin: `plan:${run.plan.join('+')}`, appSlug: run.app,
263
272
  startUrl: first.startUrl, createdAt: new Date().toISOString(), hash: `plan-${runId}`,
264
273
  ...(first.requiresSession
@@ -266,6 +275,7 @@ export async function recordingForPlan(runId) {
266
275
  : {}),
267
276
  events: steps.map((s, seq) => ({ ...s, seq, ts: seq })),
268
277
  };
278
+ const recording = run.planning?.baseUrl ? rebase(built, run.planning.baseUrl) : built;
269
279
  return { run, recording, steps, starts, unproven: chain.some((f) => f.proven === false) };
270
280
  }
271
281
  /**
@@ -274,16 +284,23 @@ export async function recordingForPlan(runId) {
274
284
  */
275
285
  export async function runPlan(runId, opts = {}) {
276
286
  const { run, recording, steps, starts, unproven } = await recordingForPlan(runId);
277
- const executed = await execute(recording, { ...opts, useLessons: true });
287
+ // Up to the commit: the first step that commits something, counting facts.
288
+ // Not a human step — unlike proving a save, a run has someone to ask.
289
+ const commit = run.planning?.stopBeforeCommit && !run.planning.allowPurchases
290
+ ? commitSteps(steps, await destructiveControls(run.app))[0]
291
+ : undefined;
292
+ const executed = await execute(recording, {
293
+ ...opts, useLessons: true, ...(commit ? { stopBefore: recording.events[commit.index].seq } : {}),
294
+ });
278
295
  const recorded = await recordRun({
279
- app: run.app, flow: run.plan.join('+'), plan: run.plan, goal: run.goal, mode: 'run',
296
+ app: run.app, flow: run.plan.join('+'), plan: run.plan, goal: run.goal, mode: 'run', ...(run.variant ? { variant: run.variant } : {}),
280
297
  result: executed.result, steps, runId: run._id, starts, ...(unproven ? { unproven: true } : {}),
281
298
  });
282
299
  // Each unproven flow in a plan that passed is proven now.
283
300
  const nowProven = [];
284
301
  for (const [i, slug] of run.plan.entries()) {
285
- if (await proveByRun(run.app, slug, executed.result, starts[i]))
302
+ if (await proveByRun(run.app, slug, executed.result, starts[i], run.variant))
286
303
  nowProven.push(slug);
287
304
  }
288
- return { executed, recorded, plan: run.plan, nowProven };
305
+ return { executed, recorded, plan: run.plan, nowProven, ...(commit ? { commit } : {}) };
289
306
  }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Per-app settings that change how its flows run, beyond placeholders
3
+ * (memory/placeholders.ts): today, how long a step may wait.
4
+ *
5
+ * Replay waits 10 s for each step's element, URL or response. An app that is
6
+ * slow on purpose (a login that takes 15 s to become usable) needs longer, and
7
+ * one fixed number for every app means either slow failures or flaky passes.
8
+ * So: UNDERSTUDY_TIMEOUT_MS for all of them, overridden per app.
9
+ */
10
+ export declare const TIMEOUT_LIMITS: {
11
+ readonly min: 1000;
12
+ readonly max: 600000;
13
+ };
14
+ /** UNDERSTUDY_TIMEOUT_MS, if set. */
15
+ export declare function envTimeoutMs(): number | undefined;
16
+ /**
17
+ * How long a step of this app may wait: the app's own setting, else
18
+ * UNDERSTUDY_TIMEOUT_MS, else undefined (replay's default). Without a database
19
+ * (replaying a recording file) only the environment counts.
20
+ */
21
+ export declare function timeoutFor(app: string): Promise<number | undefined>;
22
+ /** Set (or, with null, clear) how long a step of this app may wait. */
23
+ export declare function setAppTimeout(app: string, ms: number | null): Promise<{
24
+ app: string;
25
+ timeoutMs?: number;
26
+ }>;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Per-app settings that change how its flows run, beyond placeholders
3
+ * (memory/placeholders.ts): today, how long a step may wait.
4
+ *
5
+ * Replay waits 10 s for each step's element, URL or response. An app that is
6
+ * slow on purpose (a login that takes 15 s to become usable) needs longer, and
7
+ * one fixed number for every app means either slow failures or flaky passes.
8
+ * So: UNDERSTUDY_TIMEOUT_MS for all of them, overridden per app.
9
+ */
10
+ import { collections } from './db.js';
11
+ export const TIMEOUT_LIMITS = { min: 1000, max: 600_000 };
12
+ function check(ms, from) {
13
+ if (!Number.isInteger(ms) || ms < TIMEOUT_LIMITS.min || ms > TIMEOUT_LIMITS.max) {
14
+ throw new Error(`${from} must be a whole number of milliseconds from ${TIMEOUT_LIMITS.min} to ${TIMEOUT_LIMITS.max}, not ${ms}`);
15
+ }
16
+ return ms;
17
+ }
18
+ /** UNDERSTUDY_TIMEOUT_MS, if set. */
19
+ export function envTimeoutMs() {
20
+ const raw = process.env.UNDERSTUDY_TIMEOUT_MS?.trim();
21
+ return raw ? check(Number(raw), 'UNDERSTUDY_TIMEOUT_MS') : undefined;
22
+ }
23
+ /**
24
+ * How long a step of this app may wait: the app's own setting, else
25
+ * UNDERSTUDY_TIMEOUT_MS, else undefined (replay's default). Without a database
26
+ * (replaying a recording file) only the environment counts.
27
+ */
28
+ export async function timeoutFor(app) {
29
+ let own;
30
+ if (process.env.MONGODB_URI) {
31
+ // A database that can't be reached doesn't stop a replay over a setting.
32
+ own = await collections()
33
+ .then(({ apps }) => apps.findOne({ slug: app }, { projection: { timeoutMs: 1 } }))
34
+ .then((a) => a?.timeoutMs)
35
+ .catch(() => undefined);
36
+ }
37
+ return own ?? envTimeoutMs();
38
+ }
39
+ /** Set (or, with null, clear) how long a step of this app may wait. */
40
+ export async function setAppTimeout(app, ms) {
41
+ const { apps } = await collections();
42
+ if (ms === null) {
43
+ await apps.updateOne({ slug: app }, { $unset: { timeoutMs: '' } });
44
+ return { app };
45
+ }
46
+ check(ms, 'timeoutMs');
47
+ await apps.updateOne({ slug: app }, { $set: { timeoutMs: ms }, $setOnInsert: { slug: app, name: app, urls: {}, createdAt: new Date() } }, { upsert: true });
48
+ return { app, timeoutMs: ms };
49
+ }
package/dist/store/db.js CHANGED
@@ -55,7 +55,9 @@ export async function collections() {
55
55
  /** Ordinary indexes: the lookups every command does. */
56
56
  const INDEXES = {
57
57
  apps: [{ key: { slug: 1 }, unique: true }],
58
- flows: [{ key: { app: 1, slug: 1 }, unique: true }],
58
+ // A variant is its own flow under the same name. A main flow has no `variant`,
59
+ // which the index treats as null: one main flow per name, and one per variant.
60
+ flows: [{ key: { app: 1, slug: 1, variant: 1 }, unique: true }],
59
61
  pages: [{ key: { app: 1, sig: 1 }, unique: true }],
60
62
  notes: [{ key: { app: 1, kind: 1 } }],
61
63
  findings: [{ key: { app: 1, fingerprint: 1 }, unique: true }, { key: { app: 1, status: 1 } }],
@@ -112,6 +114,11 @@ export async function ensureSchema() {
112
114
  const d = await connect();
113
115
  const dims = await checkEmbedder();
114
116
  const existing = new Set((await d.listCollections({}, { nameOnly: true }).toArray()).map((c) => c.name));
117
+ // Before variants, a name was unique per app on its own; that index would
118
+ // refuse a variant of an existing flow.
119
+ if (existing.has('flows') && await d.collection('flows').indexExists('app_1_slug_1')) {
120
+ await d.collection('flows').dropIndex('app_1_slug_1');
121
+ }
115
122
  for (const [name, indexes] of Object.entries(INDEXES)) {
116
123
  // A search index can only be created on a collection that exists.
117
124
  if (!existing.has(name))
@@ -10,6 +10,7 @@
10
10
  *
11
11
  * Steps live inside their flow, because you never want one without the other.
12
12
  */
13
+ import type { Control } from '../core/outline.js';
13
14
  import type { ObjectId } from 'mongodb';
14
15
  import type { RawEvent } from '../core/recording.js';
15
16
  export type Precondition = 'authenticated' | 'not authenticated';
@@ -33,6 +34,8 @@ export interface App {
33
34
  * value moves to the user's env file. See memory/placeholders.ts.
34
35
  */
35
36
  placeholders?: PlaceholderKind[];
37
+ /** How long one step may wait, in ms — overrides UNDERSTUDY_TIMEOUT_MS. See store/app-settings.ts. */
38
+ timeoutMs?: number;
36
39
  /**
37
40
  * Goals to fit recall's known/unknown cutoffs from (`understudy calibrate`).
38
41
  * Kept so `reembed` can re-fit them for a new model without asking again.
@@ -71,6 +74,12 @@ export interface Flow {
71
74
  _id?: ObjectId;
72
75
  app: string;
73
76
  slug: string;
77
+ /**
78
+ * Set on a copy of a flow made for one version of the app — a branch, a
79
+ * preview deploy — so testing it never replaces the main flow. Absent on the
80
+ * main flow, never null. See flows/variants.ts.
81
+ */
82
+ variant?: string;
74
83
  title: string;
75
84
  /** What the flow is FOR, phrased the way someone would ask for it. */
76
85
  intent: string;
@@ -156,6 +165,9 @@ export interface Page {
156
165
  name: string;
157
166
  };
158
167
  }[];
168
+ /** Its controls when last seen — roles, names, states, options; never field values. */
169
+ outline?: Control[];
170
+ outlineAt?: Date;
159
171
  firstSeen: Date;
160
172
  lastSeen: Date;
161
173
  }
@@ -230,6 +242,8 @@ export interface Run {
230
242
  * attributed: an agent reached the goal by other means and reported it.
231
243
  */
232
244
  mode: 'run' | 'replay' | 'attributed';
245
+ /** Run with this variant's flows, where it has them. Its history is its own. */
246
+ variant?: string;
233
247
  /**
234
248
  * The run stopped, as asked, before this step — the flow's commit — rather
235
249
  * than doing it. Its path is partial, so it is never drift history.
@@ -290,6 +304,10 @@ export interface Run {
290
304
  }>;
291
305
  dryRun?: boolean;
292
306
  allowPurchases?: boolean;
307
+ /** Run up to the first commit step, check its control, and stop there. */
308
+ stopBeforeCommit?: boolean;
309
+ /** Run the app at this address instead of the one the flows were saved on. */
310
+ baseUrl?: string;
293
311
  };
294
312
  startedAt: Date;
295
313
  endedAt?: Date;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jeffawe/understudy",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "End-to-end tests for your own web apps: record a flow once, and Understudy remembers it, replays it, notices when the app changes, and runs goals you describe in words — on its own or as an MCP server for AI agents.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -33,7 +33,8 @@
33
33
  "dist",
34
34
  "extension",
35
35
  "build/extension/firefox",
36
- "REASONER.md"
36
+ "REASONER.md",
37
+ "CHANGELOG.md"
37
38
  ],
38
39
  "publishConfig": {
39
40
  "access": "public"