@jeffawe/understudy 0.4.0 → 0.5.1

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 +140 -0
  2. package/README.md +71 -174
  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 +41 -23
  25. package/dist/flows/session.d.ts +176 -0
  26. package/dist/flows/session.js +405 -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 +5 -4
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Agent sessions: an agent explores an app THROUGH Understudy, one step at a
3
+ * time, and keeps the steps that worked as a flow.
4
+ *
5
+ * Before this, an agent explored with throwaway Playwright scripts (page
6
+ * dumps, "which question appears after this answer?"), then rewrote the path
7
+ * that worked in the format `understudy_save` reads, then had it replayed.
8
+ * Most of its tokens went on the first part, and everything it learned there
9
+ * was lost. Here exploring IS recording:
10
+ *
11
+ * start open a browser — at an address, or partway along a saved flow
12
+ * (`upTo`), which is also how a stale flow is repaired: replay it to
13
+ * the step that fails and explore from there
14
+ * step one click, fill, pick… run by the same Stepper replay uses, so a
15
+ * step that works here works when the flow replays. Returns only
16
+ * what changed: controls that appeared or went, the address, errors,
17
+ * API calls
18
+ * look the page's controls — role, name, state, options; no field values
19
+ * save the steps the agent keeps, PROVEN BY A REPLAY IN A FRESH BROWSER
20
+ * (up to a commit, as any save). One pass in a warm, slow session
21
+ * proves little: the agent paused to think between steps, which
22
+ * hides every wait the flow really needs.
23
+ *
24
+ * No model here either: the agent decides what to do; this does it and keeps
25
+ * the record. Sessions live in this process (the MCP server); a restart loses
26
+ * them, and one left alone closes after IDLE_MS.
27
+ */
28
+ import { type StepOutcome } from '../core/replay.js';
29
+ import { type RawRecording } from '../core/recording.js';
30
+ import { type SaveOutcome } from './save.js';
31
+ import type { Step } from '../store/types.js';
32
+ /** A session nobody has used for this long is closed. */
33
+ export declare const IDLE_MS: number;
34
+ interface Tried {
35
+ n: number;
36
+ step: Step;
37
+ ok: boolean;
38
+ error?: string;
39
+ /** From the flow it started along, rather than tried by the agent. */
40
+ fromFlow?: true;
41
+ /** Controls it revealed on the same page — a follow-up question, a hidden field. */
42
+ revealed?: string[];
43
+ }
44
+ export interface PageNow {
45
+ url: string;
46
+ title: string;
47
+ /** The page's controls, one line each. */
48
+ controls: string[];
49
+ /** Set when the outline was cut at OUTLINE_MAX. */
50
+ more?: true;
51
+ }
52
+ export interface StartOptions {
53
+ app: string;
54
+ /** Open this address. */
55
+ url?: string;
56
+ /** Or start along this saved flow… */
57
+ flow?: string;
58
+ /** …running its steps before this one (default: all of them). */
59
+ upTo?: number;
60
+ headed?: boolean;
61
+ values?: Record<string, string>;
62
+ /** Let a step that commits something real (pay, book, delete) run. */
63
+ allowPurchases?: boolean;
64
+ /** Use this variant's copy of the flow, if it has one — and save to it. */
65
+ variant?: string;
66
+ /** With flow: run it against the app at this address (a branch's preview deploy). */
67
+ baseUrl?: string;
68
+ }
69
+ export declare function startSession(opts: StartOptions): Promise<{
70
+ sinceLastSeen?: import("../memory/pages.js").PageChange;
71
+ page: PageNow;
72
+ how?: string;
73
+ session: string;
74
+ ran: number;
75
+ stoppedAt: {
76
+ step: string;
77
+ foundBy?: string;
78
+ matched?: number;
79
+ saw?: string;
80
+ error?: string;
81
+ ok: boolean;
82
+ n: number;
83
+ };
84
+ } | {
85
+ sinceLastSeen?: import("../memory/pages.js").PageChange;
86
+ session: string;
87
+ ran: number;
88
+ page: PageNow;
89
+ }>;
90
+ export declare function step(id: string, raw: Record<string, unknown>): Promise<{
91
+ ok: boolean;
92
+ refused: string;
93
+ how: string;
94
+ } | {
95
+ errors?: string[];
96
+ responses?: string[];
97
+ sinceLastSeen?: import("../memory/pages.js").PageChange;
98
+ changed?: string[];
99
+ gone?: string[];
100
+ appeared?: string[];
101
+ newPage?: boolean;
102
+ ms: number;
103
+ url: string;
104
+ foundBy?: string;
105
+ matched?: number;
106
+ saw?: string;
107
+ error?: string;
108
+ ok: boolean;
109
+ n: number;
110
+ refused?: never;
111
+ how?: never;
112
+ }>;
113
+ export declare function look(id: string, within?: string): Promise<{
114
+ steps: string[];
115
+ url: string;
116
+ title: string;
117
+ /** The page's controls, one line each. */
118
+ controls: string[];
119
+ /** Set when the outline was cut at OUTLINE_MAX. */
120
+ more?: true;
121
+ }>;
122
+ export interface SaveFromSession {
123
+ name: string;
124
+ /** Session step numbers to keep, in order. Default: every step that worked. */
125
+ keep?: number[];
126
+ intent?: string;
127
+ slug?: string;
128
+ /** Save as this variant's copy. Default: the variant the session started with, if any. */
129
+ variant?: string;
130
+ }
131
+ /**
132
+ * Keep the session's steps as a flow — proven by replaying them in a fresh
133
+ * browser first, exactly as `understudy_save` proves a recording.
134
+ */
135
+ export declare function saveSession(id: string, opts: SaveFromSession): Promise<{
136
+ recording: RawRecording;
137
+ out: SaveOutcome;
138
+ suggestions?: Suggestions;
139
+ }>;
140
+ /** What a session noticed, for the agent to put to the user. Nothing here is written by itself. */
141
+ export interface Suggestions {
142
+ /** Checks to add before a step that needed the page to be ready: `understudy_save { flow, add }`. */
143
+ waits?: {
144
+ before: number;
145
+ step: Record<string, unknown>;
146
+ why: string;
147
+ }[];
148
+ /** Facts worth remembering: `understudy_remember`. */
149
+ facts?: {
150
+ text: string;
151
+ why: string;
152
+ }[];
153
+ /** Controls that stayed disabled: maybe an app state the flow needs (`requires`, when distilling). */
154
+ states?: {
155
+ control: string;
156
+ why: string;
157
+ }[];
158
+ how: string;
159
+ }
160
+ /**
161
+ * Pure: what the session's own record says the saved flow may need. Exported
162
+ * for tests.
163
+ *
164
+ * a step that failed at first and worked when tried again → the page wasn't ready: a wait before it
165
+ * a step that took over half the time a step may wait, in
166
+ * the fresh-browser replay → a wait before it, with room to spare
167
+ * a kept step that revealed controls on the same page → a fact: "picking Yes shows Which bundle?"
168
+ * a step that failed "not enabled", never done after → a control that stayed disabled: an app state?
169
+ */
170
+ export declare function suggest(tried: Tried[], kept: Tried[], offset: number, proof: Pick<StepOutcome, 'seq' | 'durationMs'>[], timeoutMs: number): Suggestions | undefined;
171
+ export declare function closeSession(id: string): Promise<{
172
+ closed: boolean;
173
+ }>;
174
+ /** Close every session — on shutdown, and in tests. */
175
+ export declare function closeAllSessions(): Promise<void>;
176
+ export {};
@@ -0,0 +1,405 @@
1
+ /**
2
+ * Agent sessions: an agent explores an app THROUGH Understudy, one step at a
3
+ * time, and keeps the steps that worked as a flow.
4
+ *
5
+ * Before this, an agent explored with throwaway Playwright scripts (page
6
+ * dumps, "which question appears after this answer?"), then rewrote the path
7
+ * that worked in the format `understudy_save` reads, then had it replayed.
8
+ * Most of its tokens went on the first part, and everything it learned there
9
+ * was lost. Here exploring IS recording:
10
+ *
11
+ * start open a browser — at an address, or partway along a saved flow
12
+ * (`upTo`), which is also how a stale flow is repaired: replay it to
13
+ * the step that fails and explore from there
14
+ * step one click, fill, pick… run by the same Stepper replay uses, so a
15
+ * step that works here works when the flow replays. Returns only
16
+ * what changed: controls that appeared or went, the address, errors,
17
+ * API calls
18
+ * look the page's controls — role, name, state, options; no field values
19
+ * save the steps the agent keeps, PROVEN BY A REPLAY IN A FRESH BROWSER
20
+ * (up to a commit, as any save). One pass in a warm, slow session
21
+ * proves little: the agent paused to think between steps, which
22
+ * hides every wait the flow really needs.
23
+ *
24
+ * No model here either: the agent decides what to do; this does it and keeps
25
+ * the record. Sessions live in this process (the MCP server); a restart loses
26
+ * them, and one left alone closes after IDLE_MS.
27
+ */
28
+ import { randomBytes } from 'node:crypto';
29
+ import { openLease } from '../core/browser.js';
30
+ import { Stepper, describeLocator } from '../core/replay.js';
31
+ import { buildRecording, rebase, redactValue, valueRefsOf } from '../core/recording.js';
32
+ import { outlineOf, diffOutline, describeControl } from '../core/outline.js';
33
+ import { changesSince, pageOf, rememberOutline } from '../memory/pages.js';
34
+ import { ensureSchema } from '../store/db.js';
35
+ import { valuesFromEnv, valueEnvNames, reloadEnvFiles } from '../store/settings.js';
36
+ import { timeoutFor } from '../store/app-settings.js';
37
+ import { lessonsFor, destructiveControls } from '../memory/notes.js';
38
+ import { destructiveReason } from './destructive.js';
39
+ import { recordingFrom, proveAndSave } from './save.js';
40
+ import { restoreSession } from './execute.js';
41
+ import { saveRecording } from '../core/recording-store.js';
42
+ import { checkVariant, resolveFlow } from './variants.js';
43
+ /** A session nobody has used for this long is closed. */
44
+ export const IDLE_MS = 15 * 60_000;
45
+ /** Open at once — each is a browser. */
46
+ 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
+ const sessions = new Map();
57
+ function touch(s) {
58
+ if (s.timer)
59
+ clearTimeout(s.timer);
60
+ s.timer = setTimeout(() => { void closeSession(s.id); }, IDLE_MS);
61
+ s.timer.unref?.();
62
+ }
63
+ function get(id) {
64
+ const s = sessions.get(id);
65
+ if (!s)
66
+ throw new Error(`no session ${id} — it was closed, left idle for ${IDLE_MS / 60_000} min, or the server restarted; start another`);
67
+ touch(s);
68
+ return s;
69
+ }
70
+ /** Login values for these refs: the agent's, then the environment's (re-read, so a line just added counts). */
71
+ function valuesFor(s, refs) {
72
+ reloadEnvFiles();
73
+ return { ...valuesFromEnv(refs, s.app), ...s.values };
74
+ }
75
+ async function pageNow(s, within) {
76
+ const page = s.lease.page;
77
+ const all = await outlineOf(page);
78
+ s.outline = all;
79
+ const needle = within?.toLowerCase();
80
+ const shown = needle
81
+ ? all.filter((c) => [c.name, c.group, c.text, ...(c.options ?? [])].some((t) => t?.toLowerCase().includes(needle)))
82
+ : all;
83
+ return {
84
+ url: page.url(), title: await page.title().catch(() => ''),
85
+ controls: shown.map(describeControl), ...(all.length >= 150 ? { more: true } : {}),
86
+ };
87
+ }
88
+ /** What a step outcome tells an agent: did it work, and if not, why. */
89
+ const result = (o) => ({
90
+ ok: o.ok, ...(o.error ? { error: o.error } : {}), ...(o.saw ? { saw: o.saw } : {}),
91
+ ...(o.matched !== undefined && o.matched > 1 ? { matched: o.matched } : {}),
92
+ ...(o.roleHadNoMatch ? { foundBy: o.roleHadNoMatch.fellBackTo } : {}),
93
+ });
94
+ export async function startSession(opts) {
95
+ if (!opts.url === !opts.flow)
96
+ throw new Error('start needs a url, or a flow to start along — one of them');
97
+ if (sessions.size >= MAX_SESSIONS)
98
+ throw new Error(`${MAX_SESSIONS} sessions are open already — close one first`);
99
+ // A session writes to the page map from its first step: make sure the
100
+ // collections and their indexes exist first, rather than created on write.
101
+ await ensureSchema();
102
+ const app = opts.app;
103
+ const variant = checkVariant(opts.variant);
104
+ if (opts.baseUrl !== undefined && !/^https?:\/\/[^/]/.test(opts.baseUrl))
105
+ throw new Error(`baseUrl must be an http(s) address, not "${opts.baseUrl}"`);
106
+ let fromFlow = [];
107
+ let entry;
108
+ let startUrl = opts.url ?? '';
109
+ const values = { ...(opts.values ?? {}) };
110
+ let storageState;
111
+ if (opts.flow) {
112
+ const flow = await resolveFlow(app, opts.flow, variant);
113
+ if (!flow)
114
+ throw new Error(`no flow '${opts.flow}' for app '${app}'`);
115
+ const saved = recordingFrom(flow);
116
+ const rec = opts.baseUrl ? rebase(saved, opts.baseUrl) : saved;
117
+ const upTo = opts.upTo ?? rec.events.length;
118
+ if (!Number.isInteger(upTo) || upTo < 0 || upTo > rec.events.length)
119
+ throw new Error(`upTo must be 0 to ${rec.events.length}, the flow's step count`);
120
+ fromFlow = rec.events.slice(0, upTo);
121
+ startUrl = rec.startUrl;
122
+ if (flow.requiresSession)
123
+ entry = { requiresSession: true, ...(flow.session ? { session: flow.session } : {}) };
124
+ const refs = valueRefsOf(fromFlow);
125
+ const found = valuesFor({ app, values }, refs);
126
+ const missing = refs.filter((r) => !(r in found));
127
+ if (missing.length) {
128
+ throw new Error(`missing login value(s) for the flow's steps — nothing was opened: ${missing.map((r) => `${r} (set ${valueEnvNames(r, app)[0]})`).join(', ')}`);
129
+ }
130
+ ({ storageState } = await restoreSession({ ...rec, ...(entry ? { entry } : {}) }, found));
131
+ }
132
+ const lease = await openLease({ headless: !opts.headed, ...(storageState ? { storageState } : {}) });
133
+ const timeoutMs = await timeoutFor(app);
134
+ // The same object the session adds login values to, so each step sees them.
135
+ const stepper = new Stepper(lease, {
136
+ values,
137
+ ...(timeoutMs !== undefined ? { timeoutMs } : {}),
138
+ lessonsFor: (ctx) => lessonsFor(app, ctx),
139
+ }, [], () => false);
140
+ const s = {
141
+ id: randomBytes(4).toString('hex'), app, lease, stepper, tried: [], startUrl, values,
142
+ allowPurchases: Boolean(opts.allowPurchases), outline: [], ...(entry ? { entry } : {}), ...(variant ? { variant } : {}),
143
+ };
144
+ sessions.set(s.id, s);
145
+ touch(s);
146
+ try {
147
+ // Along the flow: its steps run first, and are kept like any other.
148
+ if (opts.url)
149
+ fromFlow = [{ seq: 0, ts: 0, action: 'goto', value: opts.url, url: opts.url, resolution: 'synthesized' }];
150
+ let sinceLastSeen;
151
+ for (const e of fromFlow) {
152
+ const n = s.tried.length;
153
+ const event = { ...e, seq: n, ts: n };
154
+ // Its own login values, read the same way replay reads them.
155
+ Object.assign(s.values, valuesFor(s, valueRefsOf([event])));
156
+ const o = await stepper.run(event);
157
+ if (o.sig && o.outline) {
158
+ sinceLastSeen = await changesSince(app, o.sig, o.outline);
159
+ await rememberOutline(app, o.sig, o.outline);
160
+ }
161
+ const { seq: _s, ts: _t, ...step } = event;
162
+ s.tried.push({ n, step: { ...step, url: o.at ?? step.url, ...(o.sig ? { expectedSig: o.sig } : {}) }, ok: o.ok, ...(o.error ? { error: o.error } : {}), ...(opts.flow ? { fromFlow: true } : {}) });
163
+ if (!o.ok) {
164
+ return {
165
+ session: s.id, ran: n, stoppedAt: { n, ...result(o), step: describeLocator(event) },
166
+ ...(opts.flow ? { how: 'The flow fails here: this is the step to repair. Look, try other steps, then save.' } : {}),
167
+ page: await pageNow(s), ...(sinceLastSeen ? { sinceLastSeen } : {}),
168
+ };
169
+ }
170
+ }
171
+ return { session: s.id, ran: s.tried.length, page: await pageNow(s), ...(sinceLastSeen ? { sinceLastSeen } : {}) };
172
+ }
173
+ catch (e) {
174
+ await closeSession(s.id);
175
+ throw e;
176
+ }
177
+ }
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
+ export async function step(id, raw) {
215
+ const s = get(id);
216
+ const { step: given, problems } = readStep(raw);
217
+ if (!given)
218
+ throw new Error(`step not run — ${problems.join('; ')}`);
219
+ const page = s.lease.page;
220
+ // A typed password is never kept: the agent says which login value it is.
221
+ if (given.action === 'fill' && given.value !== undefined) {
222
+ 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
+ }
227
+ }
228
+ // A commit runs only when allowed; saving proves a flow up to it anyway.
229
+ const fact = given.name ? (await destructiveControls(s.app)).get(given.name.toLowerCase()) : undefined;
230
+ const commits = destructiveReason({ action: given.action, ...(given.name ? { name: given.name } : {}), url: page.url() })
231
+ ?? (fact && ['click', 'press'].includes(given.action) ? `a fact says it commits something real: ${fact}` : null);
232
+ if (commits && !s.allowPurchases) {
233
+ return {
234
+ ok: false, refused: commits,
235
+ how: 'Not run. Save now (a save checks this control and never presses it), or start a session with allowPurchases if running it is fine.',
236
+ };
237
+ }
238
+ const n = s.tried.length;
239
+ const event = { ...given, seq: n, ts: n, url: page.url(), resolution: 'script-literal' };
240
+ if (event.valueRef) {
241
+ const found = valuesFor(s, [event.valueRef]);
242
+ if (!(event.valueRef in found)) {
243
+ throw new Error(`no value for ${event.valueRef} — nothing was typed. Ask the user to add ${valueEnvNames(event.valueRef, s.app)[0]}=… to their env file (never to paste it in chat), or pass it in values at start`);
244
+ }
245
+ Object.assign(s.values, found);
246
+ }
247
+ const before = s.outline.length ? s.outline : await outlineOf(page);
248
+ const signalsBefore = s.stepper.signals.length;
249
+ const sigBefore = s.stepper.sigSequence.at(-1);
250
+ const startedAt = Date.now();
251
+ const o = await s.stepper.run(event);
252
+ const ms = Date.now() - startedAt;
253
+ const after = o.outline ?? await outlineOf(page);
254
+ s.outline = after;
255
+ // A new page: say how it differs from the last time it looked otherwise, then keep it.
256
+ const sinceLastSeen = o.sig && o.sig !== sigBefore ? await changesSince(s.app, o.sig, after) : undefined;
257
+ if (o.sig)
258
+ await rememberOutline(s.app, o.sig, after);
259
+ const diff = diffOutline(before, after);
260
+ const samePage = !(o.sig && o.sig !== sigBefore) || pageOf(o.sig) === pageOf(sigBefore ?? '');
261
+ s.tried.push({
262
+ n, step: { ...given, url: o.at ?? event.url, resolution: 'script-literal', ...(o.sig ? { expectedSig: o.sig } : {}) }, ok: o.ok,
263
+ ...(o.error ? { error: o.error } : {}), ...(o.ok && samePage && diff.appeared.length ? { revealed: diff.appeared } : {}),
264
+ });
265
+ const during = s.stepper.signals.slice(signalsBefore);
266
+ return {
267
+ n, ...result(o), ms,
268
+ url: page.url(),
269
+ ...(o.sig && o.sig !== sigBefore ? { newPage: true } : {}),
270
+ ...(diff.appeared.length ? { appeared: diff.appeared } : {}),
271
+ ...(diff.gone.length ? { gone: diff.gone } : {}),
272
+ ...(diff.changed.length ? { changed: diff.changed } : {}),
273
+ ...(sinceLastSeen ? { sinceLastSeen } : {}),
274
+ ...(during.some((x) => x.kind === 'http')
275
+ ? { responses: during.filter((x) => x.kind === 'http').slice(0, 15).map((x) => `${x.text} ${shortUrl(x.url)}`) }
276
+ : {}),
277
+ ...(during.some((x) => x.kind !== 'http')
278
+ ? { errors: during.filter((x) => x.kind !== 'http' && !(x.kind === 'console' && x.level === 'warning')).slice(0, 8).map((x) => `${x.kind}: ${x.text.slice(0, 200)}`) }
279
+ : {}),
280
+ };
281
+ }
282
+ /** `https://app.test/api/visits?x=1` → `/api/visits` — enough to know which call. */
283
+ function shortUrl(url) {
284
+ if (!url)
285
+ return '';
286
+ try {
287
+ return new URL(url).pathname;
288
+ }
289
+ catch {
290
+ return url;
291
+ }
292
+ }
293
+ export async function look(id, within) {
294
+ const s = get(id);
295
+ return { ...(await pageNow(s, within)), steps: s.tried.map((t) => `${t.n} ${t.ok ? 'ok ' : 'FAILED'} ${t.step.action} ${describeLocator({ ...t.step, seq: t.n, ts: 0 })}${t.fromFlow ? ' (from the flow)' : ''}`) };
296
+ }
297
+ /**
298
+ * Keep the session's steps as a flow — proven by replaying them in a fresh
299
+ * browser first, exactly as `understudy_save` proves a recording.
300
+ */
301
+ export async function saveSession(id, opts) {
302
+ const s = get(id);
303
+ const picked = opts.keep
304
+ ? opts.keep.map((n) => {
305
+ const t = s.tried[n];
306
+ if (!t)
307
+ throw new Error(`no step ${n} in this session (it has 0–${s.tried.length - 1})`);
308
+ if (!t.ok)
309
+ throw new Error(`step ${n} failed in the session (${t.error}) — keep only steps that worked`);
310
+ return t;
311
+ })
312
+ : s.tried.filter((t) => t.ok);
313
+ if (!picked.some((t) => t.step.action !== 'goto'))
314
+ throw new Error('nothing to save — no step that worked besides opening the page');
315
+ const first = picked[0].step;
316
+ const events = picked.map((t, i) => ({ ...t.step, seq: i, ts: i }));
317
+ if (first.action !== 'goto') {
318
+ events.unshift({ seq: 0, ts: 0, action: 'goto', value: first.url, url: first.url, resolution: 'synthesized' });
319
+ events.forEach((e, i) => { e.seq = i; e.ts = i; });
320
+ }
321
+ const recording = buildRecording({ source: 'live', origin: `session:${s.id}`, appSlug: s.app, startUrl: s.startUrl || first.url, ...(s.entry ? { entry: s.entry } : {}) }, events);
322
+ await saveRecording(recording);
323
+ const refs = valueRefsOf(events);
324
+ const variant = checkVariant(opts.variant) ?? s.variant;
325
+ const out = await proveAndSave(recording, {
326
+ title: opts.name, madeBy: 'agent', values: valuesFor(s, refs), ...(variant ? { variant } : {}),
327
+ ...(opts.intent ? { intent: opts.intent } : {}), ...(opts.slug ? { slug: opts.slug } : {}),
328
+ });
329
+ if (!out.saved)
330
+ return { recording, out };
331
+ const suggestions = suggest(s.tried, picked, first.action !== 'goto' ? 1 : 0, out.proven?.result.steps ?? [], (await timeoutFor(s.app)) ?? 10_000);
332
+ return { recording, out, ...(suggestions ? { suggestions } : {}) };
333
+ }
334
+ const keyOf = (s) => [s.action, s.role ?? '', s.name ?? '', s.testId ?? '', s.css ?? '', s.hints?.nth ?? ''].join('\u0000');
335
+ const NOT_READY = /not enabled|not visible|not stable|timeout|matched no elements/i;
336
+ /**
337
+ * Pure: what the session's own record says the saved flow may need. Exported
338
+ * for tests.
339
+ *
340
+ * a step that failed at first and worked when tried again → the page wasn't ready: a wait before it
341
+ * a step that took over half the time a step may wait, in
342
+ * the fresh-browser replay → a wait before it, with room to spare
343
+ * a kept step that revealed controls on the same page → a fact: "picking Yes shows Which bundle?"
344
+ * a step that failed "not enabled", never done after → a control that stayed disabled: an app state?
345
+ */
346
+ export function suggest(tried, kept, offset, proof, timeoutMs) {
347
+ const waits = [];
348
+ const at = (t) => kept.indexOf(t) + offset;
349
+ const check = (t, assert, ms, why) => {
350
+ if (!t.step.role || !t.step.name || waits.some((w) => w.before === at(t)))
351
+ return;
352
+ // The check must look at the same element the step uses, not another with its name.
353
+ const nth = t.step.hints?.nth;
354
+ const hints = { assert, timeoutMs: Math.min(600_000, ms), ...(nth !== undefined ? { nth } : {}) };
355
+ waits.push({ before: at(t), step: { action: 'assert', role: t.step.role, name: t.step.name, hints }, why });
356
+ };
357
+ for (const t of kept) {
358
+ if (t.fromFlow || !['click', 'fill', 'select', 'check', 'uncheck', 'press'].includes(t.step.action))
359
+ continue;
360
+ const earlier = tried.find((f) => f.n < t.n && !f.ok && keyOf(f.step) === keyOf(t.step) && NOT_READY.test(f.error ?? ''));
361
+ if (earlier) {
362
+ check(t, /not enabled/i.test(earlier.error) ? 'enabled' : 'visible', Math.max(timeoutMs * 2, 15_000), `step ${at(t)} failed at first in the session (${earlier.error.slice(0, 120)}) and worked when tried again — the page wasn't ready yet`);
363
+ continue;
364
+ }
365
+ const took = proof.find((p) => p.seq === at(t))?.durationMs ?? 0;
366
+ if (took > timeoutMs / 2) {
367
+ check(t, 'enabled', Math.ceil((took * 2) / 1000) * 1000, `step ${at(t)} took ${(took / 1000).toFixed(1)} s of the ${timeoutMs / 1000} s a step may wait, replayed in a fresh browser`);
368
+ }
369
+ }
370
+ const facts = kept
371
+ .filter((t) => t.revealed?.length)
372
+ .slice(0, 5)
373
+ .map((t) => ({
374
+ text: `On ${pageOf(t.step.expectedSig ?? '') || t.step.url}, ${t.step.action} ${t.step.role ?? ''} "${t.step.name ?? t.step.value ?? ''}" shows: ${t.revealed.slice(0, 3).join('; ')}`.replace(/\s+/g, ' '),
375
+ why: `seen in the session at step ${t.n}`,
376
+ }));
377
+ const done = new Set(kept.map((t) => keyOf(t.step)));
378
+ const states = tried
379
+ .filter((t) => !t.ok && /not enabled/i.test(t.error ?? '') && !done.has(keyOf(t.step)) && t.step.name)
380
+ .filter((t, i, all) => all.findIndex((x) => keyOf(x.step) === keyOf(t.step)) === i)
381
+ .map((t) => ({
382
+ control: `${t.step.role ?? ''} "${t.step.name}"`.trim(),
383
+ why: `it stayed disabled when tried at step ${t.n} — if the account has to be in some state first (e.g. "has-no-active-bundle"), that's a requires state for this flow`,
384
+ }));
385
+ if (!waits.length && !facts.length && !states.length)
386
+ return undefined;
387
+ return {
388
+ ...(waits.length ? { waits } : {}), ...(facts.length ? { facts } : {}), ...(states.length ? { states } : {}),
389
+ how: 'Put these to the user. Add approved waits with understudy_save { flow, add }, facts with understudy_remember; a state goes in requires when the flow is distilled. Nothing here was written.',
390
+ };
391
+ }
392
+ export async function closeSession(id) {
393
+ const s = sessions.get(id);
394
+ if (!s)
395
+ return { closed: false };
396
+ sessions.delete(id);
397
+ if (s.timer)
398
+ clearTimeout(s.timer);
399
+ await s.lease.close().catch(() => { });
400
+ return { closed: true };
401
+ }
402
+ /** Close every session — on shutdown, and in tests. */
403
+ export async function closeAllSessions() {
404
+ await Promise.all([...sessions.keys()].map(closeSession));
405
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Variants: a flow's copy for one version of the app — a branch under test, a
3
+ * preview deploy — kept beside the main flow under the same name.
4
+ *
5
+ * Testing a branch used to mean saving its version of a flow over the main
6
+ * one, so the branch's change became everyone's baseline before it merged.
7
+ * Now:
8
+ *
9
+ * - a variant is its own flow document, `variant: "<name>"`; the main flow
10
+ * has no `variant` at all
11
+ * - anything run with a variant uses that variant's copy of a flow where it
12
+ * has one, and the main flow where it doesn't — a branch that changed the
13
+ * intake form needs a copy of the intake flow only
14
+ * - saving with a variant never touches the main flow
15
+ * - `promote` makes a variant the main flow, once the branch has merged
16
+ *
17
+ * Segments stay main-only: they are shared building blocks, and a branch's
18
+ * copy of one would compete with the real one in every plan.
19
+ */
20
+ import type { Filter } from 'mongodb';
21
+ import type { Flow, Run } from '../store/types.js';
22
+ /** Throws on a name that can't be a variant; returns it trimmed, or undefined for none. */
23
+ export declare function checkVariant(v: string | undefined): string | undefined;
24
+ /** The filter for one flow: the variant's copy, or (no variant) the main one. */
25
+ export declare const flowKey: (app: string, slug: string, variant?: string) => {
26
+ app: string;
27
+ slug: string;
28
+ variant: string;
29
+ } | {
30
+ app: string;
31
+ slug: string;
32
+ variant: {
33
+ $exists: false;
34
+ };
35
+ };
36
+ /** Main flows only — for anything shared across versions (segments, calibration). */
37
+ export declare const MAIN: {
38
+ variant: {
39
+ $exists: false;
40
+ };
41
+ };
42
+ /**
43
+ * The flow a name means when running with this variant: its copy if it has
44
+ * one, else the main flow.
45
+ */
46
+ export declare function resolveFlow(app: string, slug: string, variant?: string): Promise<Flow | null>;
47
+ /**
48
+ * Pure: of flows found by a search, the ones this variant sees — its own
49
+ * copies in place of the main flows they copy, and no other variant's.
50
+ */
51
+ export declare function pickVariant<T extends Pick<Flow, 'slug' | 'variant'>>(found: T[], variant?: string): T[];
52
+ /** The filter for runs made with this variant — or with none. */
53
+ export declare const runsOf: (variant?: string) => Filter<Run>;
54
+ export interface Promoted {
55
+ flow: string;
56
+ variant: string;
57
+ /** There was a main flow, and the variant replaced it. */
58
+ replaced: boolean;
59
+ /** Segments cut from the old main flow, which still hold its old steps. */
60
+ staleSegments: string[];
61
+ }
62
+ /**
63
+ * Make a variant the main flow: its steps, proof and search entry replace the
64
+ * main flow's (or become it, if there was none), and the variant is gone.
65
+ */
66
+ export declare function promoteVariant(app: string, slug: string, variant: string): Promise<Promoted>;
67
+ /**
68
+ * Pure: how a variant's steps differ from the main flow's, one line per
69
+ * change, numbered as in the variant (removed steps as in main). Lined up by
70
+ * longest common run of steps, so an inserted step shows as one insertion,
71
+ * not as every step after it changing.
72
+ */
73
+ export declare function diffFromMain(main: Pick<Flow, 'steps'>, copy: Pick<Flow, 'steps'>, max?: number): string[];
74
+ /** How a variant differs from its main flow, or why there's nothing to compare. */
75
+ export declare function variantDiff(app: string, slug: string, variant: string): Promise<string[]>;
76
+ /** Delete a variant's copy, so runs with that variant use the main flow again. */
77
+ export declare function dropVariant(app: string, slug: string, variant: string): Promise<{
78
+ flow: string;
79
+ variant: string;
80
+ dropped: boolean;
81
+ }>;