@jeffawe/understudy 0.3.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 (42) hide show
  1. package/CHANGELOG.md +127 -0
  2. package/README.md +69 -160
  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 +185 -30
  13. package/dist/entry/mcp.d.ts +2 -0
  14. package/dist/entry/mcp.js +128 -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.d.ts +114 -0
  30. package/dist/memory/calibrate.js +260 -0
  31. package/dist/memory/pages.d.ts +34 -0
  32. package/dist/memory/pages.js +60 -0
  33. package/dist/memory/recall.d.ts +87 -25
  34. package/dist/memory/recall.js +242 -45
  35. package/dist/plan/planner.d.ts +11 -1
  36. package/dist/plan/planner.js +36 -19
  37. package/dist/store/app-settings.d.ts +26 -0
  38. package/dist/store/app-settings.js +49 -0
  39. package/dist/store/db.js +8 -1
  40. package/dist/store/reembed.js +18 -7
  41. package/dist/store/types.d.ts +50 -0
  42. package/package.json +3 -2
@@ -15,16 +15,80 @@
15
15
  * Either way, a goal that IS a flow's name or slug matches exactly.
16
16
  */
17
17
  import { collections, vectorSearch } from '../store/db.js';
18
- import { embed, embedderConfig } from '../store/embed.js';
18
+ import { checkVariant, pickVariant, resolveFlow, runsOf, variantDiff } from '../flows/variants.js';
19
+ import { flowPagesChanged } from './pages.js';
20
+ import { embed, embedderConfig, VOYAGE_DEFAULT } from '../store/embed.js';
19
21
  import { valuesFromEnv, valueEnvNames } from '../store/settings.js';
20
- import { valueRefsOf } from '../core/recording.js';
22
+ import { describeResponse, forced, humanUntil, literalValue, responseCheckOf, valueRefsOf } from '../core/recording.js';
23
+ /** Hints that aren't for whoever drives the step: `nth` has its own field, the others are bookkeeping. */
24
+ const NOT_BRIEF = new Set(['nth', 'inputType', 'seamGapBefore', 'unparsedChainStep']);
21
25
  /**
22
- * When a match by MEANING is good enough to act on. Calibrated 2026-11-18 on
23
- * a real 28-flow corpus with voyage-4-lite (15 known goals, 14 plausible
24
- * unknown ones): no single score separates them, because a
26
+ * Pure: a stored step as an agent gets it. Short — css is left out when there's
27
+ * a better way to find the element — but nothing that changes which element is
28
+ * meant, or what counts as passing, may be dropped.
29
+ */
30
+ export function briefStep(s, n) {
31
+ const nth = typeof s.hints?.nth === 'number' ? s.hints.nth : undefined;
32
+ const addressed = Boolean(s.role && s.name);
33
+ const hints = Object.fromEntries(Object.entries(s.hints ?? {}).filter(([k]) => !NOT_BRIEF.has(k)));
34
+ // Older flows carry `{ force: true }` as a click's valueRef; it is not a login value.
35
+ if (forced(s))
36
+ hints.force = true;
37
+ const placeholder = valueRefsOf([s])[0];
38
+ return {
39
+ n, action: s.action,
40
+ ...(s.role ? { role: s.role } : {}), ...(s.name ? { name: s.name } : {}),
41
+ ...(s.exact ? { exact: true } : {}),
42
+ ...(s.testId ? { testId: s.testId, ...(s.testIdAttr ? { testIdAttr: s.testIdAttr } : {}) } : {}),
43
+ ...(!addressed && !s.testId && s.css ? { css: s.css } : {}),
44
+ ...(s.frameHint ? { frameHint: s.frameHint } : {}),
45
+ ...(nth !== undefined ? { nth } : {}),
46
+ ...(placeholder ? { placeholder } : literalValue(s) !== undefined ? { value: literalValue(s) } : s.action === 'goto' ? { value: s.url } : {}),
47
+ ...(Object.keys(hints).length ? { hints } : {}),
48
+ };
49
+ }
50
+ /** Pure: a brief step as one line for a person (`recall --steps`), leaving nothing in it out. */
51
+ export function stepLine(s) {
52
+ const h = s.hints ?? {};
53
+ const text = (v, regex, flags) => (regex ? `/${String(v)}/${String(flags ?? '')}` : `"${String(v)}"`);
54
+ const name = s.name === undefined ? undefined : text(s.name, h.nameRegex, h.nameFlags);
55
+ const target = [
56
+ s.role,
57
+ // With no role, say what the name is looked up as: a placeholder, a label, plain text…
58
+ name !== undefined && (s.role ? name : `${String(h.by ?? 'text')} ${name}`),
59
+ s.testId && `[${s.testIdAttr ?? 'test id'} ${s.testId}]`,
60
+ s.css && `[${s.css}]`,
61
+ h.hasText !== undefined && `with text ${text(h.hasText, h.hasTextRegex, h.hasTextFlags)}`,
62
+ Array.isArray(h.scope) && `inside ${h.scope.join(' >> ')}`,
63
+ s.frameHint && `in frame ${s.frameHint}`,
64
+ s.nth !== undefined && `(#${s.nth})`,
65
+ s.exact && '(exact)',
66
+ h.force === true && '(forced)',
67
+ typeof h.timeoutMs === 'number' && `(waits up to ${h.timeoutMs / 1000}s)`,
68
+ ];
69
+ const response = s.action === 'wait_response' ? responseCheckOf(s.value, h) : undefined;
70
+ const until = s.action === 'human' ? humanUntil(s) : undefined;
71
+ const expects = [
72
+ s.action === 'assert' && String(h.assert ?? 'visible'),
73
+ s.placeholder ? `= <${s.placeholder}>`
74
+ : response ? describeResponse(response)
75
+ : s.value !== undefined && `= ${text(s.value, h.valueRegex ?? h.urlRegex, h.valueFlags ?? h.urlFlags)}`,
76
+ until?.url && `until the address matches "${until.url}"`,
77
+ until?.text && `until the page shows "${until.text}"`,
78
+ until?.response && `until ${describeResponse(until.response)}`,
79
+ ];
80
+ return [`${String(s.n).padStart(3)} ${s.action.padEnd(7)}`, ...target, ...expects].filter(Boolean).join(' ').trimEnd();
81
+ }
82
+ /**
83
+ * When a match by MEANING is good enough to act on — the built-in cutoffs, for
84
+ * voyage-4-lite. Set by hand 2026-11-18 on a real 28-flow corpus (15 known
85
+ * goals, 14 plausible unknown ones): no single score separates them, because a
25
86
  * goal the app doesn't have still lands near something. What does separate
26
- * them is how far the top match is ahead of the runner-up. A different
27
- * embedding model needs recalibrating.
87
+ * them is how far the top match is ahead of the runner-up.
88
+ *
89
+ * Other models score on other scales (mxbai-embed-large puts unrelated goals
90
+ * at 0.72–0.80), so `understudy calibrate` fits these per app and model, and
91
+ * recall uses the fitted ones when there are any (see cutoffsFor).
28
92
  */
29
93
  export const MEANING = {
30
94
  /** At or above this, the top flow is the answer. */
@@ -36,24 +100,46 @@ export const MEANING = {
36
100
  };
37
101
  /** The same rule for word matching, where a score is the share of the goal's words a flow contains. */
38
102
  export const WORDS = { strong: 1, good: 0.6, margin: 0.2 };
103
+ /**
104
+ * Pure: is the top flow the answer? The whole rule, in one place — judge
105
+ * explains it, calibrate fits it. With only one flow there's no runner-up to
106
+ * beat, so only a strong match counts.
107
+ */
108
+ export function isKnown(top, second, rule) {
109
+ if (top >= rule.strong)
110
+ return true;
111
+ return top >= rule.good && second !== undefined && top - second >= rule.margin;
112
+ }
39
113
  /** Pure: the verdict for a ranked list of scores. Exported for tests. */
40
114
  export function judge(scores, rule) {
41
115
  const [top, second] = scores;
42
116
  if (top === undefined)
43
117
  return { verdict: 'unknown', why: 'this app has no flows yet' };
44
118
  const f = (n) => n.toFixed(2);
45
- if (top >= rule.strong)
46
- return { verdict: 'known', why: `strong match (${f(top)})` };
119
+ if (isKnown(top, second, rule)) {
120
+ return { verdict: 'known', why: top >= rule.strong ? `strong match (${f(top)})` : `good match (${f(top)}), clearly ahead of the next (${f(second)})` };
121
+ }
47
122
  if (top >= rule.good) {
48
- // With only one flow there's no runner-up to beat, so only a strong match counts.
49
123
  if (second === undefined)
50
124
  return { verdict: 'unsure', why: `good match (${f(top)}), but only one flow to compare with` };
51
- if (top - second >= rule.margin)
52
- return { verdict: 'known', why: `good match (${f(top)}), clearly ahead of the next (${f(second)})` };
53
125
  return { verdict: 'unsure', why: `good match (${f(top)}), but the next is close (${f(second)})` };
54
126
  }
55
127
  return { verdict: 'unknown', why: `nothing matches well (best ${f(top)})` };
56
128
  }
129
+ /**
130
+ * Which cutoffs recall uses with this model: fitted for this app; else fitted
131
+ * for another app with the same model (better than another model's numbers);
132
+ * else the built-in ones, which were set for voyage-4-lite.
133
+ */
134
+ export async function cutoffsFor(app, cfg) {
135
+ const { apps } = await collections();
136
+ const same = { 'cutoffs.model': cfg.model, 'cutoffs.dims': cfg.dims };
137
+ const own = await apps.findOne({ slug: app, ...same }, { projection: { cutoffs: 1 } });
138
+ const fitted = own?.cutoffs ?? (await apps.findOne(same, { sort: { 'cutoffs.fittedAt': -1 }, projection: { cutoffs: 1 } }))?.cutoffs;
139
+ if (fitted)
140
+ return { strong: fitted.strong, good: fitted.good, margin: fitted.margin, source: own ? 'this app' : 'another app' };
141
+ return { ...MEANING, source: cfg.model === VOYAGE_DEFAULT.model ? 'built-in' : 'uncalibrated' };
142
+ }
57
143
  const STOP = new Set(['a', 'an', 'the', 'to', 'my', 'of', 'for', 'and', 'in', 'on', 'as', 'i', 'me', 'it', 'is', 'with', 'at', 'up', 'out']);
58
144
  const words = (s) => new Set(s.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w && !STOP.has(w)));
59
145
  /** Share of the goal's words that appear in the flow's name, slug or intent. */
@@ -69,7 +155,7 @@ export function wordScore(goal, flow) {
69
155
  return hit / g.size;
70
156
  }
71
157
  const toMatch = (f, score) => ({
72
- slug: f.slug, title: f.title, kind: f.kind, madeBy: f.madeBy ?? 'user', proven: f.proven !== false,
158
+ slug: f.slug, ...(f.variant ? { variant: f.variant } : {}), title: f.title, kind: f.kind, madeBy: f.madeBy ?? 'user', proven: f.proven !== false,
73
159
  ...(f.proven === false && f.unprovenBecause ? { unprovenBecause: f.unprovenBecause } : {}),
74
160
  ...(f.provenUpTo !== undefined ? { provenUpTo: f.provenUpTo } : {}),
75
161
  ...(f.requires?.length ? { requires: f.requires } : {}), ...(f.establishes?.length ? { establishes: f.establishes } : {}), score,
@@ -85,26 +171,110 @@ const TIE = 0.005;
85
171
  export function rank(matches) {
86
172
  return [...matches].sort((a, b) => (Math.abs(a.score - b.score) <= TIE ? Number(b.proven) - Number(a.proven) || Number(b.madeBy === 'user') - Number(a.madeBy === 'user') || b.score - a.score : b.score - a.score));
87
173
  }
88
- /** The verdict's reason, plus a warning when the flow it picked may not work. */
89
- const withProven = (why, best) => best && !best.proven ? `${why} — but '${best.slug}' is unproven (${best.unprovenBecause ?? 'no passing run yet'}), so it may not work; a passing run proves it` : why;
90
- /** The best flow's steps and the login values they need, for an agent driving it itself. */
91
- async function plan(app, slug) {
174
+ /** `3 days ago`, `5 hours ago` — for a person reading `why`. */
175
+ function ago(iso, now = Date.now()) {
176
+ const mins = Math.max(0, Math.round((now - Date.parse(iso)) / 60_000));
177
+ if (mins < 60)
178
+ return `${mins} min ago`;
179
+ const hours = Math.round(mins / 60);
180
+ if (hours < 48)
181
+ return `${hours} hour${hours === 1 ? '' : 's'} ago`;
182
+ return `${Math.round(hours / 24)} days ago`;
183
+ }
184
+ /**
185
+ * The verdict's reason, plus a warning when the flow it picked may not work:
186
+ * unproven, its last run failed, or it last passed on a path nobody accepted.
187
+ * A confident match on a stale flow is the most misleading thing recall can say.
188
+ */
189
+ export function withWarnings(why, best, now = Date.now()) {
190
+ if (!best)
191
+ return why;
192
+ if (!best.proven)
193
+ return `${why} — but '${best.slug}' is unproven (${best.unprovenBecause ?? 'no passing run yet'}), so it may not work; a passing run proves it`;
194
+ const failed = best.lastFailed;
195
+ if (failed && (!best.lastPassed || failed.at > best.lastPassed)) {
196
+ const passed = best.lastPassed ? `; it last passed ${ago(best.lastPassed, now)}` : '';
197
+ return `${why} — but its last run failed ${ago(failed.at, now)}, at its step ${failed.step}${failed.error ? ` (${failed.error})` : ''}${passed}. The app may have changed: check that step before trusting it`;
198
+ }
199
+ if (best.pathNotAccepted)
200
+ return `${why} — but its last pass took a changed path nobody has accepted yet (see understudy_findings, flow_drift)`;
201
+ return why;
202
+ }
203
+ /** How many recent runs to read history from, across the matched flows. */
204
+ const HISTORY_RUNS = 200;
205
+ /**
206
+ * Each flow's last pass and last failure, from recent runs. A run of a plan
207
+ * counts for a flow only if it got to that flow: a failure is the flow's when
208
+ * the first failed step is inside its steps (`starts`), and a pass up to a
209
+ * commit counts, since that is all a commit-shaped flow is ever run to.
210
+ */
211
+ export async function withHistory(app, matches, variant) {
212
+ if (!matches.length)
213
+ return matches;
214
+ const slugs = matches.map((m) => m.slug);
215
+ const { runs } = await collections();
216
+ // A variant's copy has the variant's runs as its history; a main flow, the
217
+ // runs made without a variant.
218
+ const recent = await runs
219
+ .find({ app, plan: { $in: slugs }, mode: { $in: ['replay', 'run'] }, status: { $in: ['passed', 'failed'] }, ...(variant ? { $or: [runsOf(), runsOf(variant)] } : runsOf()) }, { projection: { plan: 1, starts: 1, status: 1, steps: 1, stoppedBefore: 1, accepted: 1, startedAt: 1, variant: 1 } })
220
+ .sort({ startedAt: -1 })
221
+ .limit(HISTORY_RUNS)
222
+ .toArray();
223
+ const seen = new Map();
224
+ for (const run of recent) {
225
+ const at = run.startedAt.toISOString();
226
+ const failedStep = run.status === 'failed' ? run.steps.find((s) => !s.ok) : undefined;
227
+ for (const [i, slug] of run.plan.entries()) {
228
+ if (!slugs.includes(slug))
229
+ continue;
230
+ if (matches.find((m) => m.slug === slug)?.variant !== run.variant)
231
+ continue;
232
+ const start = run.starts?.[i] ?? 0;
233
+ const end = run.starts?.[i + 1] ?? Infinity;
234
+ const h = seen.get(slug) ?? {};
235
+ if (run.stoppedBefore !== undefined && run.stoppedBefore < start)
236
+ continue; // stopped before it began
237
+ if (failedStep && failedStep.seq < start)
238
+ continue; // never got to it
239
+ if (failedStep && failedStep.seq < end) {
240
+ h.lastFailed ??= { at, step: failedStep.seq - start, ...(failedStep.error ? { error: failedStep.error.split('\n')[0].slice(0, 160) } : {}) };
241
+ }
242
+ else if (!h.lastPassed) {
243
+ h.lastPassed = at;
244
+ if (run.accepted === false)
245
+ h.pathNotAccepted = true;
246
+ }
247
+ seen.set(slug, h);
248
+ }
249
+ }
250
+ return matches.map((m) => ({ ...m, ...seen.get(m.slug) }));
251
+ }
252
+ /**
253
+ * Name the branches that have their own copy of each matched flow, so an
254
+ * agent that didn't ask for a variant still learns one exists — and can ask
255
+ * the user whether the run is for that branch.
256
+ */
257
+ async function withVariantNames(app, r, asked) {
258
+ if (!r.flows.length)
259
+ return r;
92
260
  const { flows } = await collections();
93
- const flow = await flows.findOne({ app, slug }, { projection: { steps: 1 } });
261
+ const copies = await flows
262
+ .find({ app, slug: { $in: r.flows.map((f) => f.slug) }, variant: { $exists: true, ...(asked ? { $ne: asked } : {}) } }, { projection: { slug: 1, variant: 1 } })
263
+ .toArray();
264
+ if (!copies.length)
265
+ return r;
266
+ const named = (m) => {
267
+ const v = copies.filter((c) => c.slug === m.slug).map((c) => c.variant).sort();
268
+ return v.length ? { ...m, variants: v } : m;
269
+ };
270
+ return { ...r, flows: r.flows.map(named), ...(r.best ? { best: named(r.best) } : {}) };
271
+ }
272
+ /** The best flow's steps and the login values they need, for an agent driving it itself. */
273
+ async function plan(app, slug, variant) {
274
+ const flow = await resolveFlow(app, slug, variant);
94
275
  if (!flow)
95
276
  return {};
96
- const steps = flow.steps.map((s, n) => {
97
- const nth = typeof s.hints?.nth === 'number' ? s.hints.nth : undefined;
98
- const addressed = Boolean(s.role && s.name);
99
- return {
100
- n, action: s.action,
101
- ...(s.role ? { role: s.role } : {}), ...(s.name ? { name: s.name } : {}),
102
- ...(!addressed && s.testId ? { testId: s.testId } : {}),
103
- ...(!addressed && !s.testId && s.css ? { css: s.css } : {}),
104
- ...(nth !== undefined ? { nth } : {}),
105
- ...(s.valueRef ? { placeholder: s.valueRef } : s.value !== undefined ? { value: s.value } : s.action === 'goto' ? { value: s.url } : {}),
106
- };
107
- });
277
+ const steps = flow.steps.map(briefStep);
108
278
  const refs = valueRefsOf(flow.steps);
109
279
  const found = valuesFromEnv(refs, app);
110
280
  const needs = refs.map((placeholder) => ({ placeholder, readFrom: valueEnvNames(placeholder, app), set: placeholder in found }));
@@ -116,39 +286,66 @@ async function plan(app, slug) {
116
286
  * for the planner, which only needs to know which flow.
117
287
  */
118
288
  export async function recall(app, goal, opts = {}) {
289
+ const found = await recallFlows(app, goal, opts);
290
+ const r = await withVariantNames(app, found, opts.variant);
291
+ if (!r.best)
292
+ return r;
293
+ const flow = await resolveFlow(app, r.best.slug, r.best.variant);
294
+ const changed = flow ? await flowPagesChanged(app, flow, r.best.lastPassed) : [];
295
+ return {
296
+ ...r,
297
+ ...(r.best.variant ? { differsFromMain: await variantDiff(app, r.best.slug, r.best.variant) } : {}),
298
+ ...(changed.length ? {
299
+ pagesChanged: changed,
300
+ why: `${r.why} — and since it last passed, ${changed.map((c) => c.page).join(', ')} ${changed.length === 1 ? 'has' : 'have'} been seen looking different (see pagesChanged)`,
301
+ } : {}),
302
+ };
303
+ }
304
+ async function recallFlows(app, goal, opts) {
119
305
  const limit = opts.limit ?? 5;
306
+ const variant = checkVariant(opts.variant);
120
307
  const c = await collections();
121
308
  const needle = goal.trim().toLowerCase();
309
+ const steps = (slug) => (opts.withSteps ? plan(app, slug, variant) : Promise.resolve({}));
122
310
  // 1. The goal names a flow exactly: no search needed, and no doubt.
123
- const exact = await c.flows.findOne({ app, $or: [{ slug: needle }, { title: { $regex: `^${needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`, $options: 'i' } }] }, { projection: { embedding: 0, steps: 0 } });
311
+ const [exact] = pickVariant(await c.flows.find({ app, $or: [{ slug: needle }, { title: { $regex: `^${needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`, $options: 'i' } }] }, { projection: { embedding: 0, steps: 0 } }).toArray(), variant);
124
312
  if (exact) {
125
- const best = toMatch(exact, 1);
126
- return { goal, method: 'exact', verdict: 'known', best, why: withProven('named exactly', best), flows: [best], notes: [], ...(opts.withSteps ? await plan(app, best.slug) : {}) };
313
+ const [best] = await withHistory(app, [toMatch(exact, 1)], variant);
314
+ return { goal, method: 'exact', verdict: 'known', best, why: withWarnings('named exactly', best), flows: [best], notes: [], ...(await steps(best.slug)) };
127
315
  }
128
316
  // 2. By meaning, if there's a model.
129
- if (embedderConfig()) {
130
- const [vector] = await embed([goal], 'query');
131
- const [flows, notes] = await Promise.all([
132
- vectorSearch(c.flows, app, vector, { limit }),
317
+ const cfg = embedderConfig();
318
+ if (cfg) {
319
+ const [vector] = await embed([goal], 'query', cfg);
320
+ const [flows, notes, rule] = await Promise.all([
321
+ // Extra, since other variants' copies are dropped after.
322
+ vectorSearch(c.flows, app, vector, { limit: limit * 3 }).then((found) => pickVariant(found, variant).slice(0, limit)),
133
323
  vectorSearch(c.notes, app, vector, { limit }),
324
+ cutoffsFor(app, cfg),
134
325
  ]);
135
- const matches = rank(flows.map((f) => toMatch(f, f.score)));
136
- const { verdict, why } = judge(matches.map((m) => m.score), MEANING);
326
+ const matches = await withHistory(app, rank(flows.map((f) => toMatch(f, f.score))), variant);
327
+ const judged = judge(matches.map((m) => m.score), rule);
328
+ const { verdict } = judged;
329
+ let why = verdict === 'known' ? withWarnings(judged.why, matches[0]) : judged.why;
330
+ if (rule.source === 'uncalibrated' && matches.length) {
331
+ why += ` (cutoffs not fitted for ${cfg.model} — run: understudy calibrate ${app})`;
332
+ }
333
+ const { source, ...cutoffs } = rule;
137
334
  return {
138
- goal, method: 'meaning', verdict, why: verdict === 'known' ? withProven(why, matches[0]) : why, flows: matches,
139
- ...(verdict === 'known' ? { best: matches[0], ...(opts.withSteps ? await plan(app, matches[0].slug) : {}) } : {}),
335
+ goal, method: 'meaning', verdict, why, flows: matches, cutoffs: { ...cutoffs, source },
336
+ ...(verdict === 'known' ? { best: matches[0], ...(await steps(matches[0].slug)) } : {}),
140
337
  notes: notes.map((n) => ({ kind: n.kind, text: n.text, score: n.score })),
141
338
  };
142
339
  }
143
340
  // 3. By words, with no model. Corpora are small, so scoring every flow is fine.
144
- const all = await c.flows.find({ app }, { projection: { slug: 1, title: 1, intent: 1, kind: 1, madeBy: 1, proven: 1, unprovenBecause: 1, provenUpTo: 1, requires: 1, establishes: 1, destructive: 1, requiresSession: 1 } }).toArray();
341
+ const all = pickVariant(await c.flows.find({ app }, { projection: { slug: 1, variant: 1, title: 1, intent: 1, kind: 1, madeBy: 1, proven: 1, unprovenBecause: 1, provenUpTo: 1, requires: 1, establishes: 1, destructive: 1, requiresSession: 1 } }).toArray(), variant);
145
342
  const matches = all
146
343
  .map((f) => toMatch(f, wordScore(goal, f)))
147
344
  .filter((m) => m.score > 0);
148
- const ranked = rank(matches).slice(0, limit);
345
+ const ranked = await withHistory(app, rank(matches).slice(0, limit), variant);
149
346
  const { verdict, why } = judge(ranked.map((m) => m.score), WORDS);
150
347
  return {
151
- goal, method: 'words', verdict, why: verdict === 'known' ? withProven(why, ranked[0]) : why, flows: ranked, notes: [],
152
- ...(verdict === 'known' ? { best: ranked[0], ...(opts.withSteps ? await plan(app, ranked[0].slug) : {}) } : {}),
348
+ goal, method: 'words', verdict, why: verdict === 'known' ? withWarnings(why, ranked[0]) : why, flows: ranked, notes: [],
349
+ ...(verdict === 'known' ? { best: ranked[0], ...(await steps(ranked[0].slug)) } : {}),
153
350
  };
154
351
  }
@@ -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))