@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
@@ -9,6 +9,7 @@
9
9
  * No replay here: a saved flow was proven when it was saved (or by a run since —
10
10
  * unproven ones are refused), so its steps and the page each one reached are on record.
11
11
  */
12
+ import { MAIN } from './variants.js';
12
13
  import { buildDistillRequest, validateDistilled } from '../core/distill.js';
13
14
  import { collections, ensureSchema } from '../store/db.js';
14
15
  import { embed, embedderConfig } from '../store/embed.js';
@@ -18,9 +19,13 @@ import { flowDestructiveReason } from './destructive.js';
18
19
  import { recordingFrom } from './save.js';
19
20
  async function loadFlow(app, slug) {
20
21
  const { flows } = await collections();
21
- const flow = await flows.findOne({ app, slug });
22
- if (!flow)
23
- throw new Error(`no flow '${slug}' for app '${app}'`);
22
+ const flow = await flows.findOne({ app, slug, ...MAIN });
23
+ if (!flow) {
24
+ const copy = await flows.findOne({ app, slug }, { projection: { variant: 1 } });
25
+ throw new Error(copy?.variant
26
+ ? `'${slug}' exists only as variant "${copy.variant}" — segments are cut from main flows; promote it first (understudy_save { flow, variant, promote: true })`
27
+ : `no flow '${slug}' for app '${app}'`);
28
+ }
24
29
  if (flow.kind !== 'recording')
25
30
  throw new Error(`'${slug}' is a segment — distill the recording it came from (${flow.from?.flow})`);
26
31
  // Distilling trusts every step to have passed; an unproven one may not have,
@@ -52,7 +57,7 @@ export async function saveDistilled(app, slug, answer) {
52
57
  const parentText = searchTextOf(flow.title, d.intent, d.outcome);
53
58
  // One request embeds the parent and every segment.
54
59
  const vectors = embedderConfig() ? await embed([parentText, ...segmentDocs.map((s) => s.searchText)], 'document') : [];
55
- await c.flows.updateOne({ app, slug }, {
60
+ await c.flows.updateOne({ app, slug, ...MAIN }, {
56
61
  $set: {
57
62
  intent: d.intent, outcome: d.outcome, preconditions: d.preconditions,
58
63
  requires: d.requires ?? [], establishes: d.establishes ?? [],
@@ -64,7 +69,7 @@ export async function saveDistilled(app, slug, answer) {
64
69
  for (const [i, seg] of segmentDocs.entries()) {
65
70
  // Reusing an existing slug REPLACES that segment: segments belong to the
66
71
  // app, so the same block from a new recording merges instead of competing.
67
- const existed = await c.flows.findOne({ app, slug: seg.slug }, { projection: { kind: 1 } });
72
+ const existed = await c.flows.findOne({ app, slug: seg.slug, ...MAIN }, { projection: { kind: 1 } });
68
73
  if (existed && existed.kind !== 'segment')
69
74
  throw new Error(`"${seg.slug}" is already a recorded flow's slug — pick another for the segment`);
70
75
  const unset = {};
@@ -72,7 +77,7 @@ export async function saveDistilled(app, slug, answer) {
72
77
  unset.embedding = '';
73
78
  if (!seg.destructiveBecause)
74
79
  unset.destructiveBecause = '';
75
- await c.flows.updateOne({ app, slug: seg.slug }, { $set: { ...seg, ...(vectors[i + 1] ? { embedding: vectors[i + 1] } : {}), updatedAt: now }, $setOnInsert: { createdAt: now }, ...(Object.keys(unset).length ? { $unset: unset } : {}) }, { upsert: true });
80
+ await c.flows.updateOne({ app, slug: seg.slug, ...MAIN }, { $set: { ...seg, ...(vectors[i + 1] ? { embedding: vectors[i + 1] } : {}), updatedAt: now }, $setOnInsert: { createdAt: now }, ...(Object.keys(unset).length ? { $unset: unset } : {}) }, { upsert: true });
76
81
  saved.push({ slug: seg.slug, steps: seg.steps.length, replaced: Boolean(existed) });
77
82
  }
78
83
  const lessons = d.candidateLessons?.length
@@ -20,4 +20,11 @@ export interface Emitted {
20
20
  /** Value references the test reads from the environment. */
21
21
  requiredValues: string[];
22
22
  }
23
+ /**
24
+ * The variable a test reads a login value from: SECRET.password →
25
+ * UNDERSTUDY_SECRET_PASSWORD, the same one replay reads, so one setting serves
26
+ * both. `ENV.X` came from a script that read `process.env.X`, so the test reads
27
+ * X — the variable that script's author actually set.
28
+ */
29
+ export declare const envName: (ref: string) => string;
23
30
  export declare function emitFlow(flow: Flow, framework?: Framework): Emitted;
@@ -11,12 +11,17 @@
11
11
  *
12
12
  * Ported from the old emit.ts; it now reads the flow document directly.
13
13
  */
14
- import { forced, humanUntil, responseCheckOf, valueRefsOf } from '../core/recording.js';
14
+ import { forced, humanUntil, literalValue, responseCheckOf, valueRefsOf } from '../core/recording.js';
15
15
  import { urlGlob } from '../core/replay.js';
16
16
  import { valueEnvName } from '../store/settings.js';
17
17
  const quote = (s) => `'${s.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
18
- /** SECRET.password → UNDERSTUDY_SECRET_PASSWORD: the same variable replay reads, so one setting serves both. */
19
- const envName = valueEnvName;
18
+ /**
19
+ * The variable a test reads a login value from: SECRET.password →
20
+ * UNDERSTUDY_SECRET_PASSWORD, the same one replay reads, so one setting serves
21
+ * both. `ENV.X` came from a script that read `process.env.X`, so the test reads
22
+ * X — the variable that script's author actually set.
23
+ */
24
+ export const envName = (ref) => (ref.startsWith('ENV.') ? ref.slice(4) : valueEnvName(ref));
20
25
  const describe = (s) => `${s.action} ${s.role ?? ''} ${s.name ?? s.testId ?? s.css ?? ''}`.replace(/\s+/g, ' ').trim();
21
26
  /**
22
27
  * Narrowing replay applies after finding the element, in the same order:
@@ -49,16 +54,22 @@ const matcher = (s, flag, flags) => s.hints?.[flag] ? `/${s.value ?? ''}/${Strin
49
54
  function assertion(s, loc, value, pw, warn) {
50
55
  const kind = String(s.hints?.assert ?? 'visible');
51
56
  const expected = s.valueRef ? value : matcher(s, 'valueRegex', 'valueFlags');
57
+ // A step that may wait longer than the default says so in the test too.
58
+ const opt = typeof s.hints?.timeoutMs === 'number' ? `{ timeout: ${s.hints.timeoutMs} }` : '';
52
59
  if (pw) {
53
60
  switch (kind) {
54
61
  case 'title': return `await expect(page).toHaveTitle(${expected});`;
55
- case 'visible': return `await expect(${loc}).toBeVisible();`;
56
- case 'hidden': return `await expect(${loc}).toBeHidden();`;
62
+ case 'visible': return `await expect(${loc}).toBeVisible(${opt});`;
63
+ case 'hidden': return `await expect(${loc}).toBeHidden(${opt});`;
57
64
  case 'text': return `await expect(${loc}).toHaveText(${expected});`;
58
65
  case 'contains': return `await expect(${loc}).toContainText(${expected});`;
59
66
  case 'value': return `await expect(${loc}).toHaveValue(${expected});`;
60
- case 'checked': return `await expect(${loc}).toBeChecked();`;
61
- case 'unchecked': return `await expect(${loc}).not.toBeChecked();`;
67
+ case 'checked': return `await expect(${loc}).toBeChecked(${opt});`;
68
+ case 'unchecked': return `await expect(${loc}).not.toBeChecked(${opt});`;
69
+ case 'enabled': return `await expect(${loc}).toBeEnabled(${opt});`;
70
+ case 'disabled': return `await expect(${loc}).toBeDisabled(${opt});`;
71
+ case 'editable': return `await expect(${loc}).toBeEditable(${opt});`;
72
+ case 'focused': return `await expect(${loc}).toBeFocused(${opt});`;
62
73
  }
63
74
  }
64
75
  else {
@@ -74,6 +85,10 @@ function assertion(s, loc, value, pw, warn) {
74
85
  case 'value': return `${loc}.should('have.value', ${v});`;
75
86
  case 'checked': return `${loc}.should('be.checked');`;
76
87
  case 'unchecked': return `${loc}.should('not.be.checked');`;
88
+ case 'enabled': return `${loc}.should('be.enabled');`;
89
+ case 'disabled': return `${loc}.should('be.disabled');`;
90
+ case 'editable': return `${loc}.should('not.be.disabled').and('not.have.attr', 'readonly');`;
91
+ case 'focused': return `${loc}.should('have.focus');`;
77
92
  }
78
93
  }
79
94
  warn(`"${describe(s)}" is an assertion of a kind this output doesn't know (${kind}); skipped`);
@@ -81,7 +96,8 @@ function assertion(s, loc, value, pw, warn) {
81
96
  }
82
97
  /** `r => r.url().includes('/api/visits') && r.request().method() === 'POST' && r.status() === 201` */
83
98
  function responsePredicate(c) {
84
- const url = c.url.includes('*') ? `/${urlGlob(c.url).source}/.test(r.url())` : `r.url().includes(${quote(c.url)})`;
99
+ const url = c.regexFlags !== undefined ? `/${c.url}/${c.regexFlags}.test(r.url())`
100
+ : c.url.includes('*') ? `/${urlGlob(c.url).source}/.test(r.url())` : `r.url().includes(${quote(c.url)})`;
85
101
  return `(r) => ${[url, c.method && `r.request().method() === ${quote(c.method)}`, c.status !== undefined && `r.status() === ${c.status}`].filter(Boolean).join(' && ')}`;
86
102
  }
87
103
  /** `body.items[0].id` as optional chaining, so a missing field fails the expect, not the line. */
@@ -93,7 +109,7 @@ function playwrightResponseCheck(c, name) {
93
109
  return [`expect(${v})${c.equals !== undefined ? `.toBe(${JSON.stringify(c.equals)})` : c.above !== undefined ? `.toBeGreaterThan(${c.above})` : '.toBeDefined()'};`];
94
110
  }
95
111
  function cypressIntercept(c, name) {
96
- const url = c.url.includes('*') ? quote(c.url) : `new RegExp(${quote(c.url.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))})`;
112
+ const url = c.regexFlags !== undefined ? `/${c.url}/${c.regexFlags}` : c.url.includes('*') ? quote(c.url) : `new RegExp(${quote(c.url.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))})`;
97
113
  return `cy.intercept({ ${c.method ? `method: ${quote(c.method)}, ` : ''}url: ${url} }).as(${quote(name)});`;
98
114
  }
99
115
  function cypressResponseCheck(c, name) {
@@ -154,7 +170,7 @@ export function emitFlow(flow, framework = 'playwright-ts') {
154
170
  const pageLevel = ['goto', 'wait_url', 'wait_text', 'wait_response', 'human'].includes(s.action) || (s.action === 'assert' && s.hints?.assert === 'title');
155
171
  const loc = pageLevel ? '' : narrow(s, pw ? playwrightLocator(s, warn) : cypressLocator(s, warn), pw, warn);
156
172
  const ref = valueRefsOf([s])[0];
157
- const value = ref ? (required.add(ref), envName(ref).replace(/^UNDERSTUDY_/, '')) : quote(s.value ?? (s.action === 'goto' ? s.url : ''));
173
+ const value = ref ? (required.add(ref), envName(ref).replace(/^UNDERSTUDY_/, '')) : quote(literalValue(s) ?? (s.action === 'goto' ? s.url : ''));
158
174
  // Both frameworks spell it the same way.
159
175
  const force = forced(s) ? '{ force: true }' : '';
160
176
  switch (s.action) {
@@ -9,6 +9,7 @@
9
9
  * the MCP server. Throws with a readable message instead of printing, so each
10
10
  * caller decides how to show it.
11
11
  */
12
+ import { type StorageState } from '../core/auth-cache.js';
12
13
  import { type RawRecording } from '../core/recording.js';
13
14
  import { type ReplayOptions, type ReplayResult } from '../core/replay.js';
14
15
  /** A login value a recording needs, and where it may be set. */
@@ -50,6 +51,8 @@ export interface ExecuteOptions {
50
51
  onStuck?: (stuck: StuckStep) => Promise<'done' | 'abort'>;
51
52
  /** Read the last page into `result.endChecks`, after a full pass. */
52
53
  endChecks?: boolean;
54
+ /** How long a step may wait. Default: the app's setting, else UNDERSTUDY_TIMEOUT_MS, else replay's 10 s. */
55
+ timeoutMs?: number;
53
56
  }
54
57
  /** A step that failed, put to a person who can see the browser. */
55
58
  export interface StuckStep {
@@ -74,6 +77,15 @@ export interface Executed {
74
77
  };
75
78
  sessionRestoredFrom?: string;
76
79
  }
80
+ /**
81
+ * The saved session a recording that starts signed in needs. A late-armed
82
+ * recording starts signed in; a cold browser would land on a login page and
83
+ * fail somewhere confusing, so a missing one is an error, said plainly.
84
+ */
85
+ export declare function restoreSession(recording: RawRecording, values: Record<string, string>): Promise<{
86
+ storageState?: StorageState;
87
+ savedAt?: string;
88
+ }>;
77
89
  export declare function execute(recording: RawRecording, opts?: ExecuteOptions): Promise<Executed>;
78
90
  export interface Proven extends Executed {
79
91
  /** The recording as it should be saved: with `requiresSession` set, or its unneeded session dropped. */
@@ -14,6 +14,7 @@ import { valueRefsOf } from '../core/recording.js';
14
14
  import { replay } from '../core/replay.js';
15
15
  import { foldLessons, lessonsFor } from '../memory/notes.js';
16
16
  import { valuesFromEnv, valueEnvNames, reloadEnvFiles, writableEnvFile } from '../store/settings.js';
17
+ import { timeoutFor } from '../store/app-settings.js';
17
18
  /**
18
19
  * Thrown before any browser opens when login values are missing, so a caller
19
20
  * can ask for them (the terminal) or say where to put them (MCP), then retry.
@@ -39,6 +40,25 @@ export function missingValuesFor(recording, given = {}) {
39
40
  const found = { ...valuesFromEnv(refs, recording.appSlug), ...given };
40
41
  return [...refs].filter((r) => !(r in found)).map((r) => ({ placeholder: r, setOneOf: valueEnvNames(r, recording.appSlug) }));
41
42
  }
43
+ /**
44
+ * The saved session a recording that starts signed in needs. A late-armed
45
+ * recording starts signed in; a cold browser would land on a login page and
46
+ * fail somewhere confusing, so a missing one is an error, said plainly.
47
+ */
48
+ export async function restoreSession(recording, values) {
49
+ if (!recording.entry?.requiresSession)
50
+ return {};
51
+ const sessionId = recording.entry.session;
52
+ const cached = sessionId ? await loadSessionById(recording.appSlug, sessionId) : await loadSession(recording.appSlug, values);
53
+ if (!cached) {
54
+ throw new Error(sessionId
55
+ ? `this starts from the signed-in tab it was recorded in, and that saved session (${sessionId}) is gone or older ` +
56
+ 'than 12 hours — record it again from the extension, or start the plan with a flow that logs in'
57
+ : 'this starts from a signed-in browser, and no saved session matches these credentials — pass the same ' +
58
+ '--value credentials it was recorded with, re-record with --arm-manually, or start the plan with a flow that logs in');
59
+ }
60
+ return { storageState: cached.storageState, savedAt: cached.savedAt };
61
+ }
42
62
  export async function execute(recording, opts = {}) {
43
63
  if (recording.entry?.prelude?.length) {
44
64
  throw new Error(`this starts after other flows (${recording.entry.prelude.join(' -> ')}), and preludes are parked in the rewrite — ` +
@@ -56,30 +76,17 @@ export async function execute(recording, opts = {}) {
56
76
  if (missingValues.length) {
57
77
  throw new MissingValuesError(missingValues.map((r) => ({ placeholder: r, setOneOf: valueEnvNames(r, recording.appSlug) })));
58
78
  }
59
- // A late-armed recording starts signed in; a cold browser would land on a
60
- // login page and fail somewhere confusing.
61
- let storageState;
62
- let sessionRestoredFrom;
79
+ const { storageState, savedAt: sessionRestoredFrom } = await restoreSession(recording, values);
63
80
  const sessionId = recording.entry?.session;
64
- if (recording.entry?.requiresSession) {
65
- const cached = sessionId ? await loadSessionById(recording.appSlug, sessionId) : await loadSession(recording.appSlug, values);
66
- if (!cached) {
67
- throw new Error(sessionId
68
- ? `this starts from the signed-in tab it was recorded in, and that saved session (${sessionId}) is gone or older ` +
69
- 'than 12 hours — record it again from the extension, or start the plan with a flow that logs in'
70
- : 'this starts from a signed-in browser, and no saved session matches these credentials — pass the same ' +
71
- '--value credentials it was recorded with, re-record with --arm-manually, or start the plan with a flow that logs in');
72
- }
73
- storageState = cached.storageState;
74
- sessionRestoredFrom = cached.savedAt;
75
- }
76
81
  const app = recording.appSlug;
77
82
  // A person's step needs a browser they can see — unless told otherwise (CI).
78
83
  const forPerson = Boolean(opts.onHuman) && recording.events.some((e) => e.action === 'human') && process.env.UNDERSTUDY_HEADLESS !== '1';
79
84
  const headed = Boolean(opts.headed) || forPerson;
80
85
  const onStuck = opts.onStuck;
86
+ const timeoutMs = opts.timeoutMs ?? (await timeoutFor(app));
81
87
  const result = await replay(recording, {
82
88
  values,
89
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
83
90
  ...(storageState ? { storageState } : {}),
84
91
  ...(headed ? { headless: false } : {}),
85
92
  ...(opts.onHuman ? { onHuman: opts.onHuman } : {}),
@@ -28,6 +28,8 @@ export declare function recordRun(opts: {
28
28
  steps: Step[];
29
29
  /** 'replay' when a flow was named; 'run' when it was found from a goal. */
30
30
  mode?: 'replay' | 'run';
31
+ /** Run with this variant's flows. Its history is compared with its own runs only. */
32
+ variant?: string;
31
33
  /** What was asked for. Defaults to the flow's slug. */
32
34
  goal?: string;
33
35
  /** The flows run, in order, when it was more than one. Defaults to [flow]. */
@@ -12,6 +12,7 @@ import { collections } from '../store/db.js';
12
12
  import { compareToHistory, driftFinding } from './drift.js';
13
13
  import { extractFindings, saveFindings } from './findings.js';
14
14
  import { stepFingerprint } from '../core/fingerprint.js';
15
+ import { resolveFlow, runsOf } from './variants.js';
15
16
  /** `/inventory.html#bf3dd322` → `/inventory.html` */
16
17
  const pageOf = (sig) => sig.slice(0, sig.lastIndexOf('#')) || sig;
17
18
  /** How many recent passed runs drift compares with. */
@@ -24,7 +25,7 @@ export async function recordRun(opts) {
24
25
  // 1. Drift, against the most recent passed runs of this flow — however it
25
26
  // was started, it walked the same steps.
26
27
  const history = await c.runs
27
- .find({ app, plan, mode: { $in: ['replay', 'run'] }, status: 'passed', stoppedBefore: { $exists: false }, accepted: { $ne: false }, ...(opts.runId ? { _id: { $ne: opts.runId } } : {}) }, { projection: { sigSequence: 1 } })
28
+ .find({ app, plan, ...runsOf(opts.variant), mode: { $in: ['replay', 'run'] }, status: 'passed', stoppedBefore: { $exists: false }, accepted: { $ne: false }, ...(opts.runId ? { _id: { $ne: opts.runId } } : {}) }, { projection: { sigSequence: 1 } })
28
29
  .sort({ startedAt: -1 })
29
30
  .limit(LOOKBACK)
30
31
  .toArray();
@@ -55,7 +56,9 @@ export async function recordRun(opts) {
55
56
  continue;
56
57
  const step = steps[outcome.seq];
57
58
  const via = step?.role && step.name ? { role: step.role, name: step.name } : undefined;
58
- await c.pages.updateOne({ app, sig }, { $set: { lastSeen: now }, $setOnInsert: { app, sig, urlPattern: pageOf(sig), links: [], firstSeen: now } }, { upsert: true });
59
+ await c.pages.updateOne({ app, sig },
60
+ // What it looked like, kept so the next visit can say what changed.
61
+ { $set: { lastSeen: now, ...(outcome.outline ? { outline: outcome.outline, outlineAt: now } : {}) }, $setOnInsert: { app, sig, urlPattern: pageOf(sig), links: [], firstSeen: now } }, { upsert: true });
59
62
  // A link belongs to the page it leaves FROM: "on prev, clicking `via` leads to sig".
60
63
  if (prev && prev !== sig && via) {
61
64
  await c.pages.updateOne({ app, sig: prev }, { $addToSet: { links: { to: sig, via } } });
@@ -69,6 +72,7 @@ export async function recordRun(opts) {
69
72
  app,
70
73
  goal: opts.goal ?? flow,
71
74
  mode: opts.mode ?? 'replay',
75
+ ...(opts.variant ? { variant: opts.variant } : {}),
72
76
  status: result.ok ? 'passed' : 'failed',
73
77
  plan,
74
78
  steps: result.steps.map((s) => {
@@ -115,7 +119,7 @@ export async function acceptPaths(app, fingerprints) {
115
119
  const newest = pending.at(-1);
116
120
  const updated = [];
117
121
  for (const [i, slug] of newest.plan.entries()) {
118
- const flow = await c.flows.findOne({ app, slug });
122
+ const flow = await resolveFlow(app, slug, newest.variant);
119
123
  if (!flow)
120
124
  continue;
121
125
  const start = newest.starts?.[i] ?? 0;
@@ -23,6 +23,8 @@ export declare function stepsFrom(recording: RawRecording, result?: ReplayResult
23
23
  export declare function recordingFrom(flow: Flow): RawRecording;
24
24
  export interface SaveOptions {
25
25
  title: string;
26
+ /** Save it as this variant's copy, beside the main flow (flows/variants.ts). */
27
+ variant?: string;
26
28
  /** Defaults to slugify(title). */
27
29
  slug?: string;
28
30
  /** What the flow is for, if different from the title. */
@@ -75,7 +77,7 @@ export declare function proveAndSave(recording: RawRecording, opts: ProveAndSave
75
77
  * A run that stopped before the flow's commit step proves it that far
76
78
  * (`provenUpTo`); a full run that passes proves the rest, and clears it.
77
79
  */
78
- export declare function proveByRun(app: string, slug: string, result: ReplayResult, offset?: number): Promise<boolean>;
80
+ export declare function proveByRun(app: string, slug: string, result: ReplayResult, offset?: number, variant?: string): Promise<boolean>;
79
81
  export interface ProvedFlow extends Executed {
80
82
  flow: Flow;
81
83
  /** The commit step it stopped before, when the flow has one. */
@@ -93,6 +95,7 @@ export interface ProvedFlow extends Executed {
93
95
  export declare function proveFlow(app: string, slug: string, opts?: {
94
96
  values?: Record<string, string>;
95
97
  headed?: boolean;
98
+ variant?: string;
96
99
  }): Promise<ProvedFlow>;
97
100
  export interface StepToAdd {
98
101
  /** Goes in front of the step at this index; the flow's length appends. */
@@ -112,4 +115,4 @@ export declare function checkAdditions(flow: Pick<Flow, 'steps' | 'startUrl'>, a
112
115
  * Add steps to a saved flow. It is unproven afterwards — a run that passes
113
116
  * proves it again — and segments cut from it keep pointing at the same steps.
114
117
  */
115
- export declare function editFlow(app: string, slug: string, adds: StepToAdd[]): Promise<Flow>;
118
+ export declare function editFlow(app: string, slug: string, adds: StepToAdd[], variant?: string): Promise<Flow>;
@@ -8,6 +8,7 @@
8
8
  *
9
9
  * Saving the same name again replaces the flow — re-record, re-save, done.
10
10
  */
11
+ import { checkVariant, flowKey, MAIN, resolveFlow } from './variants.js';
11
12
  import { collections, ensureSchema } from '../store/db.js';
12
13
  import { embed, embedderConfig } from '../store/embed.js';
13
14
  import { commitSteps, flowDestructiveReason } from './destructive.js';
@@ -71,6 +72,8 @@ export async function saveFlow(recording, result, opts) {
71
72
  const slug = opts.slug ?? slugify(opts.title);
72
73
  if (!slug)
73
74
  throw new Error(`can't make a flow name from "${opts.title}" — pass --slug`);
75
+ const variant = checkVariant(opts.variant);
76
+ const key = flowKey(app, slug, variant);
74
77
  const steps = stepsFrom(recording, result);
75
78
  const why = flowDestructiveReason(steps);
76
79
  const upTo = stoppedAt(recording, result);
@@ -81,6 +84,7 @@ export async function saveFlow(recording, result, opts) {
81
84
  const flow = {
82
85
  app,
83
86
  slug,
87
+ ...(variant ? { variant } : {}),
84
88
  title: opts.title,
85
89
  intent,
86
90
  kind: 'recording',
@@ -121,10 +125,10 @@ export async function saveFlow(recording, result, opts) {
121
125
  unset.provenUpTo = '';
122
126
  if (upTo !== undefined)
123
127
  unset.endState = '';
124
- await flows.updateOne({ app, slug }, { $set: flow, $setOnInsert: { createdAt: now }, ...(Object.keys(unset).length ? { $unset: unset } : {}) }, { upsert: true });
128
+ await flows.updateOne(key, { $set: flow, $setOnInsert: { createdAt: now }, ...(Object.keys(unset).length ? { $unset: unset } : {}) }, { upsert: true });
125
129
  // Make sure the app exists, remembering where it lives.
126
130
  await apps.updateOne({ slug: app }, { $setOnInsert: { slug: app, name: app, urls: { default: new URL(recording.startUrl).origin }, createdAt: now } }, { upsert: true });
127
- return (await flows.findOne({ app, slug }));
131
+ return (await flows.findOne(key));
128
132
  }
129
133
  /**
130
134
  * What `save` does, for the CLI and the MCP server alike: prove the recording
@@ -168,7 +172,7 @@ export async function proveAndSave(recording, opts) {
168
172
  }
169
173
  const saved = await saveFlow(proven.recording, proven.result, { ...opts, ...(unproven ? { unproven } : {}) });
170
174
  const { flow, placeholders } = await withPlaceholders(saved);
171
- const run = await recordRun({ app: flow.app, flow: flow.slug, result: proven.result, steps: flow.steps, ...(flow.proven === false ? { unproven: true } : {}) });
175
+ const run = await recordRun({ app: flow.app, flow: flow.slug, result: proven.result, steps: flow.steps, ...(flow.variant ? { variant: flow.variant } : {}), ...(flow.proven === false ? { unproven: true } : {}) });
172
176
  return { saved: true, verified: proven.result.ok, proven, flow, run, placeholders };
173
177
  }
174
178
  /** The app keeps email fields as placeholders? Convert now — after proving, which used the real address. */
@@ -198,13 +202,15 @@ async function firstStop(app, steps) {
198
202
  * A run that stopped before the flow's commit step proves it that far
199
203
  * (`provenUpTo`); a full run that passes proves the rest, and clears it.
200
204
  */
201
- export async function proveByRun(app, slug, result, offset = 0) {
205
+ export async function proveByRun(app, slug, result, offset = 0, variant) {
202
206
  if (!result.ok)
203
207
  return false;
204
208
  const { flows } = await collections();
205
- const flow = await flows.findOne({ app, slug, $or: [{ proven: false }, { provenUpTo: { $exists: true } }] });
206
- if (!flow)
209
+ // The flow the run used: the variant's copy if it has one, else the main flow.
210
+ const ran = await resolveFlow(app, slug, variant);
211
+ if (!ran || (ran.proven !== false && ran.provenUpTo === undefined))
207
212
  return false;
213
+ const flow = ran;
208
214
  const stopped = result.stoppedBefore === undefined ? undefined : result.stoppedBefore - offset;
209
215
  // Stopped before this flow began: none of it ran.
210
216
  if (stopped !== undefined && stopped < 0)
@@ -238,21 +244,22 @@ export async function proveByRun(app, slug, result, offset = 0) {
238
244
  */
239
245
  export async function proveFlow(app, slug, opts = {}) {
240
246
  const { flows } = await collections();
241
- const flow = await flows.findOne({ app, slug });
247
+ const { variant, ...run } = opts;
248
+ const flow = await flows.findOne(flowKey(app, slug, checkVariant(variant)));
242
249
  if (!flow)
243
- throw new Error(`no flow '${slug}' for app '${app}'`);
250
+ throw new Error(`no flow '${slug}'${variant ? ` (variant "${variant}")` : ''} for app '${app}'`);
244
251
  const commit = await firstStop(app, flow.steps);
245
252
  const recording = recordingFrom(flow);
246
253
  const executed = await execute(recording, {
247
- ...opts, useLessons: true,
254
+ ...run, useLessons: true,
248
255
  ...(commit ? { stopBefore: recording.events[commit.index].seq } : {}),
249
256
  });
250
- const run = await recordRun({
257
+ const recorded = await recordRun({
251
258
  app, flow: slug, result: executed.result, steps: flow.steps, mode: 'replay',
252
- ...(flow.proven === false ? { unproven: true } : {}),
259
+ ...(flow.variant ? { variant: flow.variant } : {}), ...(flow.proven === false ? { unproven: true } : {}),
253
260
  });
254
- const newlyProven = await proveByRun(app, slug, executed.result);
255
- return { ...executed, flow: (await flows.findOne({ _id: flow._id })), ...(commit ? { commit } : {}), run, newlyProven };
261
+ const newlyProven = await proveByRun(app, slug, executed.result, 0, flow.variant);
262
+ return { ...executed, flow: (await flows.findOne({ _id: flow._id })), ...(commit ? { commit } : {}), run: recorded, newlyProven };
256
263
  }
257
264
  /**
258
265
  * Steps that can be added to a saved flow by hand — mostly to fix up flows
@@ -263,11 +270,13 @@ const ADDABLE = {
263
270
  human: ['untilText', 'untilUrl', 'untilResponse'],
264
271
  // A check of what the page shows — how a flow should end. Addressed by
265
272
  // role + name, which is a look, not a click.
266
- assert: ['assert'],
267
- wait_response: ['method', 'status', 'field', 'equals', 'above'],
268
- wait_url: [],
269
- wait_text: [],
273
+ assert: ['assert', 'timeoutMs'],
274
+ wait_response: ['method', 'status', 'field', 'equals', 'above', 'urlRegex', 'urlFlags', 'timeoutMs'],
275
+ wait_url: ['timeoutMs'],
276
+ wait_text: ['timeoutMs'],
270
277
  };
278
+ /** What an added assert may check: no expected value, or text to expect. */
279
+ const ADDABLE_CHECKS = ['visible', 'hidden', 'checked', 'unchecked', 'enabled', 'disabled', 'editable', 'focused', 'text', 'contains'];
271
280
  /** Every problem with these additions at once, or the steps to insert. */
272
281
  export function checkAdditions(flow, adds) {
273
282
  const problems = [];
@@ -287,8 +296,12 @@ export function checkAdditions(flow, adds) {
287
296
  if (isAssert) {
288
297
  if (typeof role !== 'string' || typeof name !== 'string' || !name.trim())
289
298
  problems.push(`${at}.step: an assert needs role and name, e.g. {"role":"heading","name":"Visit booked"}`);
290
- if (!['visible', 'hidden', 'checked', 'unchecked', 'text', 'contains'].includes(String(kind)))
291
- problems.push(`${at}.step.hints.assert must be visible, hidden, checked, unchecked, text or contains`);
299
+ if (!ADDABLE_CHECKS.includes(String(kind)))
300
+ problems.push(`${at}.step.hints.assert must be one of ${ADDABLE_CHECKS.join(', ')}`);
301
+ }
302
+ const ms = hints?.timeoutMs;
303
+ if (ms !== undefined && (!Number.isInteger(ms) || ms < 1000 || ms > 600_000)) {
304
+ problems.push(`${at}.step.hints.timeoutMs must be a whole number of ms from 1000 to 600000`);
292
305
  }
293
306
  const needsValue = !isAssert || kind === 'text' || kind === 'contains';
294
307
  if (needsValue && (typeof value !== 'string' || !value.trim())) {
@@ -317,11 +330,11 @@ export function checkAdditions(flow, adds) {
317
330
  * Add steps to a saved flow. It is unproven afterwards — a run that passes
318
331
  * proves it again — and segments cut from it keep pointing at the same steps.
319
332
  */
320
- export async function editFlow(app, slug, adds) {
333
+ export async function editFlow(app, slug, adds, variant) {
321
334
  const { flows } = await collections();
322
- const flow = await flows.findOne({ app, slug });
335
+ const flow = await flows.findOne(flowKey(app, slug, checkVariant(variant)));
323
336
  if (!flow)
324
- throw new Error(`no flow '${slug}' for app '${app}'`);
337
+ throw new Error(`no flow '${slug}'${variant ? ` (variant "${variant}")` : ''} for app '${app}'`);
325
338
  if (flow.kind !== 'recording')
326
339
  throw new Error(`'${slug}' is a segment — add the steps to the flow it was cut from (${flow.from?.flow})`);
327
340
  if (!adds.length)
@@ -345,7 +358,9 @@ export async function editFlow(app, slug, adds) {
345
358
  });
346
359
  // A segment AFTER an insertion moves along; one an insertion lands INSIDE
347
360
  // gets the step too, and must be proven again like its parent.
348
- for (const seg of await flows.find({ app, kind: 'segment', 'from.flow': slug }).toArray()) {
361
+ // Segments are cut from main flows only, so a variant's edit moves none.
362
+ const segments = flow.variant ? [] : await flows.find({ app, kind: 'segment', 'from.flow': slug, ...MAIN }).toArray();
363
+ for (const seg of segments) {
349
364
  let [start, end] = seg.from.steps;
350
365
  const segSteps = [...seg.steps];
351
366
  let changed = false;