@jeffawe/understudy 0.5.1 → 0.6.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.
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Keeping segments with the steps they were cut from when their flow's steps
3
+ * change — an edit, or a flow that extends another being rebuilt.
4
+ *
5
+ * A segment holds a copy of steps [start, end) of its flow. After a change it
6
+ * holds the same steps wherever they are now; a step added INSIDE that range
7
+ * joins it, and then the segment must be proven again like its flow.
8
+ * Segments are cut from main flows only, so a variant's change moves none.
9
+ */
10
+ import { collections } from '../store/db.js';
11
+ import { stepKey } from '../core/step-ids.js';
12
+ import { MAIN } from './variants.js';
13
+ /**
14
+ * `steps` is the flow now; `origin[j]` is the index its j-th step had before
15
+ * (undefined: new). Returns the segments that changed.
16
+ */
17
+ export async function moveSegments(flow, steps, origin, why) {
18
+ if (flow.variant)
19
+ return [];
20
+ const { flows } = await collections();
21
+ const segments = await flows.find({ app: flow.app, kind: 'segment', 'from.flow': flow.slug, ...MAIN }).toArray();
22
+ const now = new Date();
23
+ const moved = [];
24
+ for (const seg of segments) {
25
+ const [start, end] = seg.from.steps;
26
+ const inside = origin.flatMap((o, j) => (o !== undefined && o >= start && o < end ? [j] : []));
27
+ const from = inside.length ? inside[0] : origin.filter((o) => o !== undefined && o < start).length;
28
+ const to = inside.length ? inside.at(-1) + 1 : from;
29
+ const segSteps = steps.slice(from, to);
30
+ const changed = segSteps.length !== seg.steps.length || segSteps.some((x, i) => stepKey(x) !== stepKey(seg.steps[i]));
31
+ if (!changed && from === start && to === end)
32
+ continue;
33
+ await flows.updateOne({ _id: seg._id }, {
34
+ $set: {
35
+ 'from.steps': [from, to], steps: segSteps, updatedAt: now,
36
+ ...(changed ? { proven: false, unprovenBecause: why } : {}),
37
+ },
38
+ });
39
+ moved.push(seg.slug);
40
+ }
41
+ return moved;
42
+ }
43
+ /** Pure: where each of `after`'s steps was in `before`, matched by id. */
44
+ export const originById = (before, after) => {
45
+ const at = new Map(before.flatMap((s, i) => (s.id ? [[s.id, i]] : [])));
46
+ return after.map((s) => (s.id ? at.get(s.id) : undefined));
47
+ };
@@ -28,7 +28,9 @@
28
28
  import { randomBytes } from 'node:crypto';
29
29
  import { openLease } from '../core/browser.js';
30
30
  import { Stepper, describeLocator } from '../core/replay.js';
31
- import { buildRecording, rebase, redactValue, valueRefsOf } from '../core/recording.js';
31
+ import { buildRecording, rebase, valueRefsOf } from '../core/recording.js';
32
+ import { passwordField, readStep } from './steps.js';
33
+ import { varsOf } from '../core/vars.js';
32
34
  import { outlineOf, diffOutline, describeControl } from '../core/outline.js';
33
35
  import { changesSince, pageOf, rememberOutline } from '../memory/pages.js';
34
36
  import { ensureSchema } from '../store/db.js';
@@ -44,15 +46,6 @@ import { checkVariant, resolveFlow } from './variants.js';
44
46
  export const IDLE_MS = 15 * 60_000;
45
47
  /** Open at once — each is a browser. */
46
48
  const MAX_SESSIONS = 3;
47
- /** Actions an agent may take in a session. A person's step (`human`) is a flow's, written in a script. */
48
- const SESSION_ACTIONS = new Set([
49
- 'goto', 'click', 'fill', 'press', 'select', 'check', 'uncheck', 'scroll_container',
50
- 'wait_url', 'wait_text', 'wait_response', 'assert',
51
- ]);
52
- /** Step fields an agent may set — the stored step shape, minus what Understudy fills in. */
53
- const STEP_FIELDS = new Set(['action', 'role', 'name', 'exact', 'value', 'valueRef', 'css', 'testId', 'testIdAttr', 'frameHint', 'nth', 'hints']);
54
- /** What recall adds or renames, taken so a recalled step can be sent as it is: `n`, its number, is dropped; `placeholder` is its word for valueRef. */
55
- const FROM_RECALL = new Set(['n', 'placeholder']);
56
49
  const sessions = new Map();
57
50
  function touch(s) {
58
51
  if (s.timer)
@@ -112,6 +105,9 @@ export async function startSession(opts) {
112
105
  const flow = await resolveFlow(app, opts.flow, variant);
113
106
  if (!flow)
114
107
  throw new Error(`no flow '${opts.flow}' for app '${app}'`);
108
+ // Its {{variables}}: the values passed, else the flow's defaults.
109
+ for (const [k, v] of Object.entries(flow.vars ?? {}))
110
+ values[k] ??= v;
115
111
  const saved = recordingFrom(flow);
116
112
  const rec = opts.baseUrl ? rebase(saved, opts.baseUrl) : saved;
117
113
  const upTo = opts.upTo ?? rec.events.length;
@@ -175,42 +171,6 @@ export async function startSession(opts) {
175
171
  throw e;
176
172
  }
177
173
  }
178
- /** Check a step the agent sent; return the problems, or the step. */
179
- function readStep(raw) {
180
- const problems = [];
181
- const extra = Object.keys(raw).filter((k) => !STEP_FIELDS.has(k) && !FROM_RECALL.has(k));
182
- if (extra.length)
183
- problems.push(`a step can't have ${extra.join(', ')} (it can have ${[...STEP_FIELDS].join(', ')})`);
184
- const action = raw.action;
185
- if (!SESSION_ACTIONS.has(action))
186
- problems.push(`action must be one of ${[...SESSION_ACTIONS].join(', ')}`);
187
- for (const k of ['role', 'name', 'value', 'valueRef', 'placeholder', 'css', 'testId', 'testIdAttr', 'frameHint']) {
188
- if (raw[k] !== undefined && typeof raw[k] !== 'string')
189
- problems.push(`${k} must be a string`);
190
- }
191
- if (raw.hints !== undefined && (typeof raw.hints !== 'object' || raw.hints === null || Array.isArray(raw.hints)))
192
- problems.push('hints must be an object');
193
- if (action === 'goto' && typeof raw.value !== 'string')
194
- problems.push('a goto needs value: the address');
195
- if (raw.placeholder !== undefined && raw.valueRef !== undefined && raw.placeholder !== raw.valueRef)
196
- problems.push('placeholder and valueRef differ — send one');
197
- // Recall shows `nth` beside the other fields; a stored step keeps it in hints. Either is taken.
198
- const { n: _number, placeholder, nth: beside, ...rest } = raw;
199
- const inHints = raw.hints?.nth;
200
- const nth = beside ?? inHints;
201
- if (nth !== undefined && !(Number.isInteger(nth) && nth >= -1))
202
- problems.push('nth must be a whole number: 0 is the first match, -1 the last');
203
- if (beside !== undefined && inHints !== undefined && beside !== inHints)
204
- problems.push('nth and hints.nth differ — send one');
205
- if (problems.length)
206
- return { problems };
207
- const read = {
208
- ...rest,
209
- ...(placeholder !== undefined ? { valueRef: placeholder } : {}),
210
- ...(nth !== undefined ? { hints: { ...rest.hints, nth } } : {}),
211
- };
212
- return { step: read, problems };
213
- }
214
174
  export async function step(id, raw) {
215
175
  const s = get(id);
216
176
  const { step: given, problems } = readStep(raw);
@@ -218,12 +178,10 @@ export async function step(id, raw) {
218
178
  throw new Error(`step not run — ${problems.join('; ')}`);
219
179
  const page = s.lease.page;
220
180
  // A typed password is never kept: the agent says which login value it is.
221
- if (given.action === 'fill' && given.value !== undefined) {
181
+ const secret = passwordField(given);
182
+ if (secret) {
222
183
  const hint = given.name ?? given.testId ?? given.css ?? 'field';
223
- const redacted = redactValue(hint, given.value, undefined, [given.name, given.css, given.testId].filter(Boolean).join(' '));
224
- if (redacted.valueRef) {
225
- throw new Error(`"${hint}" looks like a password field — pass valueRef "${redacted.valueRef}" instead of the value (set ${valueEnvNames(redacted.valueRef, s.app)[0]}, or pass it in values at start)`);
226
- }
184
+ throw new Error(`"${hint}" looks like a password field — pass valueRef "${secret}" instead of the value (set ${valueEnvNames(secret, s.app)[0]}, or pass it in values at start)`);
227
185
  }
228
186
  // A commit runs only when allowed; saving proves a flow up to it anyway.
229
187
  const fact = given.name ? (await destructiveControls(s.app)).get(given.name.toLowerCase()) : undefined;
@@ -318,7 +276,12 @@ export async function saveSession(id, opts) {
318
276
  events.unshift({ seq: 0, ts: 0, action: 'goto', value: first.url, url: first.url, resolution: 'synthesized' });
319
277
  events.forEach((e, i) => { e.seq = i; e.ts = i; });
320
278
  }
321
- const recording = buildRecording({ source: 'live', origin: `session:${s.id}`, appSlug: s.app, startUrl: s.startUrl || first.url, ...(s.entry ? { entry: s.entry } : {}) }, events);
279
+ // The {{variables}} its steps use keep the values they ran with here as defaults.
280
+ const used = varsOf(events).filter((v) => s.values[v] !== undefined);
281
+ const recording = buildRecording({
282
+ source: 'live', origin: `session:${s.id}`, appSlug: s.app, startUrl: s.startUrl || first.url, ...(s.entry ? { entry: s.entry } : {}),
283
+ ...(used.length ? { vars: Object.fromEntries(used.map((v) => [v, s.values[v]])) } : {}),
284
+ }, events);
322
285
  await saveRecording(recording);
323
286
  const refs = valueRefsOf(events);
324
287
  const variant = checkVariant(opts.variant) ?? s.variant;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Steps an agent writes: checking one it sends (a session's step, a field it
3
+ * sets on a saved step), and applying edits to a saved flow's steps.
4
+ *
5
+ * Edits exist so a repair is one call: change the name a button goes by,
6
+ * remove a step the app no longer has, turn "Family" into `{{bundle}}`.
7
+ * Nothing edited is trusted until it replays — the caller marks the flow
8
+ * unproven, and `understudy_save { flow, edit }` replays it straight away.
9
+ */
10
+ import type { Step } from '../store/types.js';
11
+ import { type RecordedAction } from '../core/recording.js';
12
+ /** Actions an agent may take in a session, or set on a saved step. A person's step (`human`) is a flow's, written in a script. */
13
+ export declare const SESSION_ACTIONS: Set<RecordedAction>;
14
+ /** Check a step the agent sent; return the problems, or the step. */
15
+ export declare function readStep(raw: Record<string, unknown>): {
16
+ step?: Omit<Step, 'url' | 'resolution'>;
17
+ problems: string[];
18
+ };
19
+ /** Would typing this value into this field keep a password in memory? Then it must be a valueRef. */
20
+ export declare function passwordField(s: Pick<Step, 'action' | 'name' | 'testId' | 'css' | 'value' | 'hints'>): string | undefined;
21
+ /** One change to a saved step. */
22
+ export interface StepEdit {
23
+ /** The step: its index in the flow as it is now, or its id. */
24
+ at: number | string;
25
+ /** Fields to change. null removes one; `hints` merge key by key (null removes a key). */
26
+ set?: Record<string, unknown>;
27
+ remove?: boolean;
28
+ }
29
+ /**
30
+ * Pure: a flow's steps after these edits and additions, all addressed by where
31
+ * steps are NOW — so one call can change step 3, remove step 5 and add before
32
+ * step 6 without counting what the others did. `origin[j]` is the index the
33
+ * j-th new step had before (undefined: added). Every problem at once; when
34
+ * there are any, `steps` is the flow unchanged.
35
+ */
36
+ export declare function applyEdits(steps: Step[], edits: StepEdit[], inserts?: {
37
+ before: number;
38
+ step: Step;
39
+ }[]): {
40
+ steps: Step[];
41
+ origin: (number | undefined)[];
42
+ problems: string[];
43
+ };
@@ -0,0 +1,179 @@
1
+ /**
2
+ * Steps an agent writes: checking one it sends (a session's step, a field it
3
+ * sets on a saved step), and applying edits to a saved flow's steps.
4
+ *
5
+ * Edits exist so a repair is one call: change the name a button goes by,
6
+ * remove a step the app no longer has, turn "Family" into `{{bundle}}`.
7
+ * Nothing edited is trusted until it replays — the caller marks the flow
8
+ * unproven, and `understudy_save { flow, edit }` replays it straight away.
9
+ */
10
+ import { redactValue } from '../core/recording.js';
11
+ import { withIds } from '../core/step-ids.js';
12
+ /** Actions an agent may take in a session, or set on a saved step. A person's step (`human`) is a flow's, written in a script. */
13
+ export const SESSION_ACTIONS = new Set([
14
+ 'goto', 'click', 'fill', 'press', 'select', 'check', 'uncheck', 'scroll_container',
15
+ 'wait_url', 'wait_text', 'wait_response', 'assert',
16
+ ]);
17
+ /** Step fields an agent may set — the stored step shape, minus what Understudy fills in. */
18
+ const STEP_FIELDS = new Set(['action', 'role', 'name', 'exact', 'value', 'valueRef', 'css', 'testId', 'testIdAttr', 'frameHint', 'nth', 'hints']);
19
+ /**
20
+ * What recall adds or renames, taken so a recalled step can be sent as it is:
21
+ * `n`, its number, `id`, and `from` (the flow it extends) are dropped;
22
+ * `placeholder` is its word for valueRef.
23
+ */
24
+ const FROM_RECALL = new Set(['n', 'id', 'from', 'placeholder']);
25
+ /** Check a step the agent sent; return the problems, or the step. */
26
+ export function readStep(raw) {
27
+ const problems = [];
28
+ const extra = Object.keys(raw).filter((k) => !STEP_FIELDS.has(k) && !FROM_RECALL.has(k));
29
+ if (extra.length)
30
+ problems.push(`a step can't have ${extra.join(', ')} (it can have ${[...STEP_FIELDS].join(', ')})`);
31
+ const action = raw.action;
32
+ if (!SESSION_ACTIONS.has(action))
33
+ problems.push(`action must be one of ${[...SESSION_ACTIONS].join(', ')}`);
34
+ for (const k of ['role', 'name', 'value', 'valueRef', 'placeholder', 'css', 'testId', 'testIdAttr', 'frameHint']) {
35
+ if (raw[k] !== undefined && typeof raw[k] !== 'string')
36
+ problems.push(`${k} must be a string`);
37
+ }
38
+ if (raw.hints !== undefined && (typeof raw.hints !== 'object' || raw.hints === null || Array.isArray(raw.hints)))
39
+ problems.push('hints must be an object');
40
+ if (action === 'goto' && typeof raw.value !== 'string')
41
+ problems.push('a goto needs value: the address');
42
+ if (raw.placeholder !== undefined && raw.valueRef !== undefined && raw.placeholder !== raw.valueRef)
43
+ problems.push('placeholder and valueRef differ — send one');
44
+ // Recall shows `nth` beside the other fields; a stored step keeps it in hints. Either is taken.
45
+ const { n: _number, id: _id, from: _from, placeholder, nth: beside, ...rest } = raw;
46
+ const inHints = raw.hints?.nth;
47
+ const nth = beside ?? inHints;
48
+ if (nth !== undefined && !(Number.isInteger(nth) && nth >= -1))
49
+ problems.push('nth must be a whole number: 0 is the first match, -1 the last');
50
+ if (beside !== undefined && inHints !== undefined && beside !== inHints)
51
+ problems.push('nth and hints.nth differ — send one');
52
+ if (problems.length)
53
+ return { problems };
54
+ const read = {
55
+ ...rest,
56
+ ...(placeholder !== undefined ? { valueRef: placeholder } : {}),
57
+ ...(nth !== undefined ? { hints: { ...rest.hints, nth } } : {}),
58
+ };
59
+ return { step: read, problems };
60
+ }
61
+ /** Would typing this value into this field keep a password in memory? Then it must be a valueRef. */
62
+ export function passwordField(s) {
63
+ if (s.action !== 'fill' || s.value === undefined)
64
+ return undefined;
65
+ const hint = s.name ?? s.testId ?? s.css ?? 'field';
66
+ const inputType = typeof s.hints?.inputType === 'string' ? s.hints.inputType : undefined;
67
+ return redactValue(hint, s.value, inputType, [s.name, s.css, s.testId].filter(Boolean).join(' ')).valueRef;
68
+ }
69
+ /** Fields `set` may change: what a step does and which element it means. */
70
+ const SETTABLE = new Set(['action', 'role', 'name', 'exact', 'value', 'valueRef', 'css', 'testId', 'testIdAttr', 'frameHint', 'hints']);
71
+ /** Changing any of these makes it a different step to find: what it was last seen doing no longer applies. */
72
+ const LOCATING = new Set(['action', 'role', 'name', 'exact', 'css', 'testId', 'testIdAttr', 'frameHint', 'hints']);
73
+ /**
74
+ * Pure: a flow's steps after these edits and additions, all addressed by where
75
+ * steps are NOW — so one call can change step 3, remove step 5 and add before
76
+ * step 6 without counting what the others did. `origin[j]` is the index the
77
+ * j-th new step had before (undefined: added). Every problem at once; when
78
+ * there are any, `steps` is the flow unchanged.
79
+ */
80
+ export function applyEdits(steps, edits, inserts = []) {
81
+ const problems = [];
82
+ const changed = new Map();
83
+ edits.forEach((e, k) => {
84
+ const at = `edit[${k}]`;
85
+ const i = typeof e.at === 'number' ? e.at : steps.findIndex((s) => s.id === e.at);
86
+ if (typeof e.at === 'number' ? !Number.isInteger(i) || i < 0 || i >= steps.length : i < 0) {
87
+ return problems.push(`${at}.at: no step ${JSON.stringify(e.at)} — an index from 0 to ${steps.length - 1}, or a step's id`);
88
+ }
89
+ if (changed.has(i))
90
+ return problems.push(`${at}: step ${i} is edited twice — one edit per step`);
91
+ if (Boolean(e.remove) === Boolean(e.set))
92
+ return problems.push(`${at}: give set (fields to change) or remove: true — one of them`);
93
+ if (e.remove)
94
+ return changed.set(i, null);
95
+ const set = e.set;
96
+ if (typeof set !== 'object' || Array.isArray(set) || !Object.keys(set).length)
97
+ return problems.push(`${at}.set must be an object of fields to change`);
98
+ const bad = Object.keys(set).filter((f) => !SETTABLE.has(f));
99
+ if (bad.length)
100
+ return problems.push(`${at}.set can't change ${bad.join(', ')} (it can change ${[...SETTABLE].join(', ')})`);
101
+ const step = { ...steps[i] };
102
+ const fields = step;
103
+ for (const [f, v] of Object.entries(set)) {
104
+ if (v === null) {
105
+ delete fields[f];
106
+ continue;
107
+ }
108
+ if (f === 'exact') {
109
+ if (typeof v !== 'boolean')
110
+ problems.push(`${at}.set.exact must be true or false`);
111
+ else
112
+ fields[f] = v;
113
+ }
114
+ else if (f === 'hints') {
115
+ if (typeof v !== 'object' || Array.isArray(v)) {
116
+ problems.push(`${at}.set.hints must be an object`);
117
+ continue;
118
+ }
119
+ const hints = { ...step.hints };
120
+ for (const [h, hv] of Object.entries(v)) {
121
+ if (hv === null)
122
+ delete hints[h];
123
+ else
124
+ hints[h] = hv;
125
+ }
126
+ if (Object.keys(hints).length)
127
+ step.hints = hints;
128
+ else
129
+ delete step.hints;
130
+ }
131
+ else if (typeof v !== 'string' || (f !== 'value' && !v.trim())) {
132
+ problems.push(`${at}.set.${f} must be a string${f === 'value' ? '' : ', not empty'} (or null to remove it)`);
133
+ }
134
+ else
135
+ fields[f] = v;
136
+ }
137
+ if (set.action !== undefined && !SESSION_ACTIONS.has(step.action))
138
+ problems.push(`${at}.set.action must be one of ${[...SESSION_ACTIONS].join(', ')}`);
139
+ if (step.value !== undefined && step.valueRef !== undefined)
140
+ problems.push(`${at}: step ${i} would have both value and valueRef — set the other to null`);
141
+ const nth = step.hints?.nth;
142
+ if (nth !== undefined && !(Number.isInteger(nth) && nth >= -1))
143
+ problems.push(`${at}.set.hints.nth must be a whole number: 0 is the first match, -1 the last`);
144
+ const secret = passwordField(step);
145
+ if (secret)
146
+ problems.push(`${at}: "${step.name ?? step.testId ?? step.css}" looks like a password field — set valueRef "${secret}" (and value null), never the value`);
147
+ if (Object.keys(set).some((f) => LOCATING.has(f))) {
148
+ delete step.expectedSig;
149
+ step.resolution = 'script-literal';
150
+ }
151
+ changed.set(i, step);
152
+ });
153
+ for (const a of inserts) {
154
+ if (!Number.isInteger(a.before) || a.before < 0 || a.before > steps.length)
155
+ problems.push(`add: before must be a step index from 0 to ${steps.length}`);
156
+ }
157
+ if (problems.length)
158
+ return { steps, origin: steps.map((_, i) => i), problems };
159
+ const out = [];
160
+ const origin = [];
161
+ const addAt = (i) => {
162
+ for (const a of inserts.filter((x) => x.before === i)) {
163
+ out.push(a.step);
164
+ origin.push(undefined);
165
+ }
166
+ };
167
+ steps.forEach((s, i) => {
168
+ addAt(i);
169
+ const c = changed.get(i);
170
+ if (c === null)
171
+ return;
172
+ out.push(c ?? s);
173
+ origin.push(i);
174
+ });
175
+ addAt(steps.length);
176
+ if (!out.length)
177
+ return { steps, origin: steps.map((_, i) => i), problems: ['that would remove every step — save a new flow instead'] };
178
+ return { steps: withIds(out), origin, problems };
179
+ }
@@ -69,6 +69,8 @@ export async function promoteVariant(app, slug, variant) {
69
69
  const { _id, variant: _v, ...rest } = v;
70
70
  await flows.replaceOne(flowKey(app, slug), { ...rest, createdAt: main?.createdAt ?? v.createdAt, updatedAt: new Date() }, { upsert: true });
71
71
  await flows.deleteOne({ _id: _id });
72
+ // Imported here: extend.ts resolves flows through this module.
73
+ await (await import('./extend.js')).refreshExtenders(app, slug);
72
74
  const segments = main ? await flows.find({ app, kind: 'segment', 'from.flow': slug, ...MAIN }, { projection: { slug: 1 } }).toArray() : [];
73
75
  return { flow: slug, variant, replaced: Boolean(main), staleSegments: segments.map((s) => s.slug) };
74
76
  }
@@ -135,5 +137,7 @@ export async function dropVariant(app, slug, variant) {
135
137
  const { deletedCount } = await flows.deleteOne({ app, slug, variant });
136
138
  if (!deletedCount)
137
139
  throw new Error(`no variant "${variant}" of '${slug}' for app '${app}'`);
140
+ // That variant's flows that extend this one now extend the main flow.
141
+ await (await import('./extend.js')).refreshExtenders(app, slug);
138
142
  return { flow: slug, variant, dropped: true };
139
143
  }
@@ -43,6 +43,7 @@ export interface FlowMatch {
43
43
  at: string;
44
44
  step: number;
45
45
  error?: string;
46
+ with?: Record<string, string>;
46
47
  };
47
48
  /** Its newest pass took a changed path that nobody has accepted yet. */
48
49
  pathNotAccepted?: true;
@@ -52,6 +53,10 @@ export interface FlowMatch {
52
53
  /** One step of the flow to run, in a form an agent can drive from directly. */
53
54
  export interface BriefStep {
54
55
  n: number;
56
+ /** Its id: stays with it when steps around it change. An edit or an extending flow names it. */
57
+ id?: string;
58
+ /** It is the step of this flow it extends: change it there. */
59
+ from?: string;
55
60
  action: string;
56
61
  role?: string;
57
62
  name?: string;
@@ -109,6 +114,10 @@ export interface Recall {
109
114
  steps?: BriefStep[];
110
115
  /** When known: the login values those steps need. */
111
116
  needs?: Need[];
117
+ /** When known: the `{{variables}}` its steps use, and their defaults. Pass others in a run's values. */
118
+ vars?: Record<string, string>;
119
+ /** When known and it extends another flow: which. Its steps marked `from` are that flow's. */
120
+ extends?: string;
112
121
  /** Why the verdict, in one line a person can read. */
113
122
  why: string;
114
123
  flows: FlowMatch[];
@@ -36,7 +36,7 @@ export function briefStep(s, n) {
36
36
  hints.force = true;
37
37
  const placeholder = valueRefsOf([s])[0];
38
38
  return {
39
- n, action: s.action,
39
+ n, ...(s.id ? { id: s.id } : {}), action: s.action,
40
40
  ...(s.role ? { role: s.role } : {}), ...(s.name ? { name: s.name } : {}),
41
41
  ...(s.exact ? { exact: true } : {}),
42
42
  ...(s.testId ? { testId: s.testId, ...(s.testIdAttr ? { testIdAttr: s.testIdAttr } : {}) } : {}),
@@ -194,7 +194,8 @@ export function withWarnings(why, best, now = Date.now()) {
194
194
  const failed = best.lastFailed;
195
195
  if (failed && (!best.lastPassed || failed.at > best.lastPassed)) {
196
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`;
197
+ const using = failed.with ? ` with ${Object.entries(failed.with).map(([k, v]) => `${k}=${JSON.stringify(v)}`).join(', ')}` : '';
198
+ return `${why} — but its last run${using} 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
  }
199
200
  if (best.pathNotAccepted)
200
201
  return `${why} — but its last pass took a changed path nobody has accepted yet (see understudy_findings, flow_drift)`;
@@ -216,7 +217,7 @@ export async function withHistory(app, matches, variant) {
216
217
  // A variant's copy has the variant's runs as its history; a main flow, the
217
218
  // runs made without a variant.
218
219
  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
+ .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, vars: 1 } })
220
221
  .sort({ startedAt: -1 })
221
222
  .limit(HISTORY_RUNS)
222
223
  .toArray();
@@ -237,7 +238,7 @@ export async function withHistory(app, matches, variant) {
237
238
  if (failedStep && failedStep.seq < start)
238
239
  continue; // never got to it
239
240
  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
+ h.lastFailed ??= { at, step: failedStep.seq - start, ...(failedStep.error ? { error: failedStep.error.split('\n')[0].slice(0, 160) } : {}), ...(run.vars ? { with: run.vars } : {}) };
241
242
  }
242
243
  else if (!h.lastPassed) {
243
244
  h.lastPassed = at;
@@ -274,11 +275,16 @@ async function plan(app, slug, variant) {
274
275
  const flow = await resolveFlow(app, slug, variant);
275
276
  if (!flow)
276
277
  return {};
277
- const steps = flow.steps.map(briefStep);
278
+ const inherited = new Set(flow.extends?.inherited);
279
+ const steps = flow.steps.map((s, n) => ({ ...briefStep(s, n), ...(s.id && inherited.has(s.id) ? { from: flow.extends.flow } : {}) }));
278
280
  const refs = valueRefsOf(flow.steps);
279
281
  const found = valuesFromEnv(refs, app);
280
282
  const needs = refs.map((placeholder) => ({ placeholder, readFrom: valueEnvNames(placeholder, app), set: placeholder in found }));
281
- return { steps, ...(needs.length ? { needs } : {}) };
283
+ return {
284
+ steps, ...(needs.length ? { needs } : {}),
285
+ ...(flow.vars && Object.keys(flow.vars).length ? { vars: flow.vars } : {}),
286
+ ...(flow.extends ? { extends: flow.extends.flow } : {}),
287
+ };
282
288
  }
283
289
  /**
284
290
  * `withSteps`: when the verdict is known, also return the best flow's steps and
@@ -15,6 +15,7 @@
15
15
  * seam { steps: [{ action: "click", role: "link", name: "Cart" }] } — or [] if unknown
16
16
  * state { use: "buy-a-bundle" } — run that flow first — or { holds: true }
17
17
  */
18
+ import { withDefaults } from '../core/vars.js';
18
19
  import { ObjectId } from 'mongodb';
19
20
  import { collections } from '../store/db.js';
20
21
  import { recall } from '../memory/recall.js';
@@ -212,7 +213,7 @@ async function advance(run) {
212
213
  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`);
213
214
  const controls = await destructiveControls(run.app);
214
215
  for (const f of chain) {
215
- const hit = f.steps.find((s) => s.name && ['click', 'press', 'dispatch_click'].includes(s.action) && controls.has(s.name.toLowerCase()));
216
+ const hit = withDefaults(f.steps, f.vars).find((s) => s.name && ['click', 'press', 'dispatch_click'].includes(s.action) && controls.has(s.name.toLowerCase()));
216
217
  if (hit)
217
218
  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`);
218
219
  }
@@ -273,6 +274,8 @@ export async function recordingForPlan(runId) {
273
274
  ...(first.requiresSession
274
275
  ? { entry: { requiresSession: true, ...(first.startState ? { startState: first.startState } : {}), ...(first.session ? { session: first.session } : {}) } }
275
276
  : {}),
277
+ // Each flow's {{variable}} defaults; where two flows share a name, the first one's.
278
+ ...(chain.some((f) => f.vars) ? { vars: Object.assign({}, ...[...chain].reverse().map((f) => f.vars ?? {})) } : {}),
276
279
  events: steps.map((s, seq) => ({ ...s, seq, ts: seq })),
277
280
  };
278
281
  const recording = run.planning?.baseUrl ? rebase(built, run.planning.baseUrl) : built;
@@ -287,7 +290,7 @@ export async function runPlan(runId, opts = {}) {
287
290
  // Up to the commit: the first step that commits something, counting facts.
288
291
  // Not a human step — unlike proving a save, a run has someone to ask.
289
292
  const commit = run.planning?.stopBeforeCommit && !run.planning.allowPurchases
290
- ? commitSteps(steps, await destructiveControls(run.app))[0]
293
+ ? commitSteps(withDefaults(steps, { ...recording.vars, ...opts.values }), await destructiveControls(run.app))[0]
291
294
  : undefined;
292
295
  const executed = await execute(recording, {
293
296
  ...opts, useLessons: true, ...(commit ? { stopBefore: recording.events[commit.index].seq } : {}),
@@ -295,11 +298,12 @@ export async function runPlan(runId, opts = {}) {
295
298
  const recorded = await recordRun({
296
299
  app: run.app, flow: run.plan.join('+'), plan: run.plan, goal: run.goal, mode: 'run', ...(run.variant ? { variant: run.variant } : {}),
297
300
  result: executed.result, steps, runId: run._id, starts, ...(unproven ? { unproven: true } : {}),
301
+ ...(executed.vars ? { vars: executed.vars } : {}),
298
302
  });
299
303
  // Each unproven flow in a plan that passed is proven now.
300
304
  const nowProven = [];
301
305
  for (const [i, slug] of run.plan.entries()) {
302
- if (await proveByRun(run.app, slug, executed.result, starts[i], run.variant))
306
+ if (await proveByRun(run.app, slug, executed.result, starts[i], run.variant, executed.vars))
303
307
  nowProven.push(slug);
304
308
  }
305
309
  return { executed, recorded, plan: run.plan, nowProven, ...(commit ? { commit } : {}) };
package/dist/store/db.js CHANGED
@@ -8,6 +8,7 @@
8
8
  import './settings.js'; // loads settings before anything reads them
9
9
  import { MongoClient } from 'mongodb';
10
10
  import { embedderConfig } from './embed.js';
11
+ import { withIds } from '../core/step-ids.js';
11
12
  /** Vector length when no model has ever been configured. */
12
13
  const DEFAULT_DIMS = 1024;
13
14
  let client;
@@ -127,6 +128,11 @@ export async function ensureSchema() {
127
128
  await d.collection(name).createIndex(ix.key, ix.unique ? { unique: true } : {});
128
129
  }
129
130
  }
131
+ // Flows saved before steps had ids get them, once — an edit or an extending flow names steps by id.
132
+ const flows = d.collection('flows');
133
+ for await (const f of flows.find({ 'steps.0': { $exists: true }, 'steps.id': { $exists: false } }, { projection: { steps: 1 } })) {
134
+ await flows.updateOne({ _id: f._id }, { $set: { steps: withIds(f.steps) } });
135
+ }
130
136
  for (const name of VECTOR_COLLECTIONS) {
131
137
  const coll = d.collection(name);
132
138
  const current = await vectorIndexInfo(coll);
@@ -145,12 +145,33 @@ export interface Flow {
145
145
  endState?: string;
146
146
  /** Each step's `expectedSig` is the page seen after it when the flow was proven. */
147
147
  steps: Step[];
148
+ /**
149
+ * Defaults for the `{{variables}}` its steps use — the values it was proven
150
+ * with. A run passes `values` to use others. See core/vars.ts.
151
+ */
152
+ vars?: Record<string, string>;
153
+ /**
154
+ * This flow is another flow plus steps of its own: a reference, so fixing
155
+ * the other flow fixes this one. `steps` and `vars` are the full result, so
156
+ * everything that reads a flow reads this one the same way. See flows/extend.ts.
157
+ */
158
+ extends?: FlowExtends;
148
159
  /** The text that gets embedded and searched: title + intent + outcome. */
149
160
  searchText: string;
150
161
  embedding?: number[];
151
162
  createdAt: Date;
152
163
  updatedAt: Date;
153
164
  }
165
+ export interface FlowExtends {
166
+ /** The flow it starts as (its variant's copy, for a variant). */
167
+ flow: string;
168
+ /** Ids of the steps that are that flow's, as last copied. The rest of `steps` are this flow's own. */
169
+ inherited: string[];
170
+ /** Its own defaults: for its own steps, and where it picks differently from that flow. */
171
+ vars?: Record<string, string>;
172
+ /** Steps of that flow its own steps come after, which that flow no longer has. Until re-saved, it can't follow that flow's changes. */
173
+ lost?: string[];
174
+ }
154
175
  export interface Page {
155
176
  _id?: ObjectId;
156
177
  app: string;
@@ -244,6 +265,12 @@ export interface Run {
244
265
  mode: 'run' | 'replay' | 'attributed';
245
266
  /** Run with this variant's flows, where it has them. Its history is its own. */
246
267
  variant?: string;
268
+ /**
269
+ * Values it used for the flows' `{{variables}}` that differ from their
270
+ * defaults, keys sorted. A run with other values walks other pages, so it
271
+ * is compared only with runs that used the same ones.
272
+ */
273
+ vars?: Record<string, string>;
247
274
  /**
248
275
  * The run stopped, as asked, before this step — the flow's commit — rather
249
276
  * than doing it. Its path is partial, so it is never drift history.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jeffawe/understudy",
3
- "version": "0.5.1",
3
+ "version": "0.6.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",