@jeffawe/understudy 0.5.0 → 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.
- package/CHANGELOG.md +50 -0
- package/README.md +2 -2
- package/REASONER.md +11 -4
- package/dist/adapters/recorder/script.js +50 -6
- package/dist/core/recording.d.ts +8 -0
- package/dist/core/replay.d.ts +3 -2
- package/dist/core/replay.js +10 -1
- package/dist/core/step-ids.d.ts +29 -0
- package/dist/core/step-ids.js +69 -0
- package/dist/core/vars.d.ts +45 -0
- package/dist/core/vars.js +93 -0
- package/dist/entry/cli.js +63 -18
- package/dist/entry/mcp.js +24 -12
- package/dist/flows/emit.js +21 -2
- package/dist/flows/execute.d.ts +6 -0
- package/dist/flows/execute.js +30 -3
- package/dist/flows/extend.d.ts +81 -0
- package/dist/flows/extend.js +269 -0
- package/dist/flows/runs.d.ts +2 -0
- package/dist/flows/runs.js +6 -1
- package/dist/flows/save.d.ts +23 -4
- package/dist/flows/save.js +110 -49
- package/dist/flows/segments.d.ts +17 -0
- package/dist/flows/segments.js +47 -0
- package/dist/flows/session.js +20 -35
- package/dist/flows/steps.d.ts +43 -0
- package/dist/flows/steps.js +179 -0
- package/dist/flows/variants.js +4 -0
- package/dist/memory/recall.d.ts +9 -0
- package/dist/memory/recall.js +12 -6
- package/dist/plan/planner.js +7 -3
- package/dist/store/db.js +6 -0
- package/dist/store/types.d.ts +27 -0
- package/package.json +3 -3
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A flow that extends another: "join-with-bundle, plus the partner's details
|
|
3
|
+
* after it picks the bundle". Its own steps go between that flow's steps,
|
|
4
|
+
* placed after a step's id, so fixing that flow once fixes every flow built
|
|
5
|
+
* on it — rather than one copy to repair per follow-up.
|
|
6
|
+
*
|
|
7
|
+
* The rules that keep it simple:
|
|
8
|
+
*
|
|
9
|
+
* - only ADD. A flow that extends another has all of its steps, in order,
|
|
10
|
+
* unchanged. "Like that one but skip step 5" is a different flow: save it
|
|
11
|
+
* as one. Otherwise reading a flow means working out a diff.
|
|
12
|
+
* - one level. A flow that extends another can't be extended, and can't
|
|
13
|
+
* extend one that does — so one change never ripples through a chain.
|
|
14
|
+
* - the result is stored. `steps` and `vars` are the full flow, rebuilt
|
|
15
|
+
* here whenever the flow it extends changes; everything else reads it like
|
|
16
|
+
* any flow. A rebuilt flow is unproven: nobody has run that version.
|
|
17
|
+
* - an anchor that goes away is never guessed at. The flow keeps its last
|
|
18
|
+
* steps, is marked unproven, and says which steps it lost.
|
|
19
|
+
*/
|
|
20
|
+
import { collections, ensureSchema } from '../store/db.js';
|
|
21
|
+
import { START, stepKey, withIds } from '../core/step-ids.js';
|
|
22
|
+
import { matchTemplate, varsOf, withDefaults } from '../core/vars.js';
|
|
23
|
+
import { flowDestructiveReason } from './destructive.js';
|
|
24
|
+
import { resolveFlow } from './variants.js';
|
|
25
|
+
import { moveSegments, originById } from './segments.js';
|
|
26
|
+
/** A step as a person can find it in an error: `click button "Next"`. */
|
|
27
|
+
const said = (s) => `${s.action}${s.role ? ` ${s.role}` : ''}${s.name ? ` "${s.name}"` : s.testId ? ` [${s.testId}]` : s.css ? ` [${s.css}]` : s.value ? ` ${s.value}` : ''}`;
|
|
28
|
+
/**
|
|
29
|
+
* Pure: is `got` (a recorded step) the base step `base`, whose name or value
|
|
30
|
+
* may hold `{{variables}}`? Returns the values the variables took, or null.
|
|
31
|
+
*/
|
|
32
|
+
export function sameStep(base, got) {
|
|
33
|
+
if (base.action !== got.action)
|
|
34
|
+
return null;
|
|
35
|
+
if (base.role && base.role !== got.role)
|
|
36
|
+
return null;
|
|
37
|
+
if (base.testId && base.testId !== got.testId)
|
|
38
|
+
return null;
|
|
39
|
+
if (!base.role && !base.name && !base.testId && base.css && base.css !== got.css)
|
|
40
|
+
return null;
|
|
41
|
+
const caught = {};
|
|
42
|
+
const fit = (template, text) => {
|
|
43
|
+
if (template === undefined)
|
|
44
|
+
return true;
|
|
45
|
+
const m = matchTemplate(template, text ?? '');
|
|
46
|
+
if (!m)
|
|
47
|
+
return false;
|
|
48
|
+
Object.assign(caught, m);
|
|
49
|
+
return true;
|
|
50
|
+
};
|
|
51
|
+
if (!fit(base.name, got.name))
|
|
52
|
+
return null;
|
|
53
|
+
if (base.valueRef !== undefined) {
|
|
54
|
+
// An email the app keeps as a placeholder was typed as itself in the new recording.
|
|
55
|
+
const same = got.valueRef === base.valueRef || (base.valueRef.startsWith('USER.') && got.value !== undefined);
|
|
56
|
+
if (!same)
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
else if (base.action === 'goto') {
|
|
60
|
+
if (base.value !== undefined && !fit(base.value, got.value ?? got.url))
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
else if (!fit(base.value, got.value))
|
|
64
|
+
return null;
|
|
65
|
+
return caught;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Pure: line a recording up against the flow it extends. Every base step must
|
|
69
|
+
* be in it, in order; whatever else it does is its own. Lined up by longest
|
|
70
|
+
* common run, so a step of its own that looks like a base step can't steal
|
|
71
|
+
* that step's place.
|
|
72
|
+
*/
|
|
73
|
+
export function alignToBase(base, got) {
|
|
74
|
+
const n = base.steps.length;
|
|
75
|
+
const m = got.length;
|
|
76
|
+
const fits = base.steps.map((b) => got.map((g) => sameStep(b, g)));
|
|
77
|
+
const lcs = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
|
|
78
|
+
for (let i = n - 1; i >= 0; i--)
|
|
79
|
+
for (let j = m - 1; j >= 0; j--) {
|
|
80
|
+
lcs[i][j] = fits[i][j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
|
|
81
|
+
}
|
|
82
|
+
const pairs = new Map(); // recording index → base index
|
|
83
|
+
for (let i = 0, j = 0; i < n && j < m;) {
|
|
84
|
+
if (fits[i][j] && lcs[i][j] === lcs[i + 1][j + 1] + 1) {
|
|
85
|
+
pairs.set(j, i);
|
|
86
|
+
i++;
|
|
87
|
+
j++;
|
|
88
|
+
}
|
|
89
|
+
else if (lcs[i + 1][j] >= lcs[i][j + 1])
|
|
90
|
+
i++;
|
|
91
|
+
else
|
|
92
|
+
j++;
|
|
93
|
+
}
|
|
94
|
+
const problems = [];
|
|
95
|
+
const matched = new Set(pairs.values());
|
|
96
|
+
const missing = base.steps.map((s, i) => ({ s, i })).filter(({ i }) => !matched.has(i));
|
|
97
|
+
if (missing.length) {
|
|
98
|
+
problems.push(`it doesn't do ${missing.length === 1 ? 'this step' : 'these steps'} of '${base.slug}': ` +
|
|
99
|
+
`${missing.slice(0, 5).map(({ s, i }) => `${i} ${said(s)}`).join('; ')}${missing.length > 5 ? '; …' : ''}. ` +
|
|
100
|
+
'A flow that extends another has all its steps and only adds its own — or save it without extends');
|
|
101
|
+
}
|
|
102
|
+
const caught = {};
|
|
103
|
+
for (const [j, i] of pairs) {
|
|
104
|
+
for (const [k, v] of Object.entries(fits[i][j])) {
|
|
105
|
+
if (caught[k] !== undefined && caught[k] !== v)
|
|
106
|
+
problems.push(`{{${k}}} is "${caught[k]}" at one step of '${base.slug}' and "${v}" at another`);
|
|
107
|
+
caught[k] = v;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
const steps = got.map((g, j) => {
|
|
111
|
+
const i = pairs.get(j);
|
|
112
|
+
if (i !== undefined)
|
|
113
|
+
return { ...base.steps[i], ...(g.expectedSig ? { expectedSig: g.expectedSig } : {}) };
|
|
114
|
+
const { id: _theirs, ...own } = g;
|
|
115
|
+
return own;
|
|
116
|
+
});
|
|
117
|
+
return { steps, inherited: base.steps.map((s) => s.id), caught, problems };
|
|
118
|
+
}
|
|
119
|
+
/** Steps of this flow that are its own, grouped by the inherited step they come after (START: before all of them). */
|
|
120
|
+
function ownSteps(flow) {
|
|
121
|
+
const inherited = new Set(flow.extends.inherited);
|
|
122
|
+
const groups = new Map();
|
|
123
|
+
let after = START;
|
|
124
|
+
for (const s of flow.steps) {
|
|
125
|
+
if (s.id && inherited.has(s.id)) {
|
|
126
|
+
after = s.id;
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
(groups.get(after) ?? groups.set(after, []).get(after)).push(s);
|
|
130
|
+
}
|
|
131
|
+
return groups;
|
|
132
|
+
}
|
|
133
|
+
/** The variables a list of steps uses, with their defaults: the flow's own first, then the base's. */
|
|
134
|
+
const varsFor = (steps, base, own) => {
|
|
135
|
+
const all = { ...base, ...own };
|
|
136
|
+
const used = varsOf(steps).filter((v) => all[v] !== undefined);
|
|
137
|
+
return used.length ? Object.fromEntries(used.map((v) => [v, all[v]])) : undefined;
|
|
138
|
+
};
|
|
139
|
+
/**
|
|
140
|
+
* Pure: the flow rebuilt on the base as it is now — its own steps after the
|
|
141
|
+
* same base steps as before. `lost`: anchors the base no longer has (then
|
|
142
|
+
* nothing is rebuilt). An inherited step the base didn't change keeps the page
|
|
143
|
+
* this flow saw after it, which may differ from the base's own.
|
|
144
|
+
*/
|
|
145
|
+
export function rebuild(base, flow) {
|
|
146
|
+
const groups = ownSteps(flow);
|
|
147
|
+
const ids = new Set(base.steps.map((s) => s.id));
|
|
148
|
+
const lost = [...groups.keys()].filter((k) => k !== START && !ids.has(k));
|
|
149
|
+
const mine = new Map(flow.steps.filter((s) => s.id).map((s) => [s.id, s]));
|
|
150
|
+
const steps = [...(groups.get(START) ?? [])];
|
|
151
|
+
for (const b of base.steps) {
|
|
152
|
+
const was = b.id ? mine.get(b.id) : undefined;
|
|
153
|
+
steps.push(was && stepKey(was) === stepKey(b) && was.expectedSig ? { ...b, expectedSig: was.expectedSig } : b);
|
|
154
|
+
steps.push(...(groups.get(b.id) ?? []));
|
|
155
|
+
}
|
|
156
|
+
const vars = varsFor(steps, base.vars, flow.extends.vars);
|
|
157
|
+
return { steps, ...(vars ? { vars } : {}), inherited: base.steps.map((s) => s.id), lost };
|
|
158
|
+
}
|
|
159
|
+
/** The flow this one extends, with an id on every step (giving it ids, if it was saved before ids existed). */
|
|
160
|
+
async function baseWithIds(app, slug, variant) {
|
|
161
|
+
const base = await resolveFlow(app, slug, variant);
|
|
162
|
+
if (!base || base.steps.every((s) => s.id))
|
|
163
|
+
return base;
|
|
164
|
+
const steps = withIds(base.steps);
|
|
165
|
+
await (await collections()).flows.updateOne({ _id: base._id }, { $set: { steps } });
|
|
166
|
+
return { ...base, steps };
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Turn a recording of the whole path into one that extends `baseSlug`: the
|
|
170
|
+
* base's steps where it does them, its own elsewhere, and the base's variables
|
|
171
|
+
* set to what the recording did. Throws, with every problem, if it can't.
|
|
172
|
+
*/
|
|
173
|
+
export async function extendRecording(rec, baseSlug, opts) {
|
|
174
|
+
await ensureSchema();
|
|
175
|
+
const app = rec.appSlug;
|
|
176
|
+
if (baseSlug === opts.slug)
|
|
177
|
+
throw new Error(`a flow can't extend itself`);
|
|
178
|
+
const base = await baseWithIds(app, baseSlug, opts.variant);
|
|
179
|
+
if (!base)
|
|
180
|
+
throw new Error(`no flow '${baseSlug}' to extend, for app '${app}'`);
|
|
181
|
+
if (base.extends)
|
|
182
|
+
throw new Error(`'${baseSlug}' extends '${base.extends.flow}' itself — extend '${base.extends.flow}', or a flow that extends nothing (one level only)`);
|
|
183
|
+
if (base.kind !== 'recording')
|
|
184
|
+
throw new Error(`'${baseSlug}' is a segment — extend the flow it was cut from (${base.from?.flow})`);
|
|
185
|
+
const { flows } = await collections();
|
|
186
|
+
const builtOn = await flows.findOne({ app, 'extends.flow': opts.slug }, { projection: { slug: 1 } });
|
|
187
|
+
if (builtOn)
|
|
188
|
+
throw new Error(`'${builtOn.slug}' extends '${opts.slug}', so '${opts.slug}' can't extend another flow (one level only)`);
|
|
189
|
+
const got = rec.events.map(({ seq: _s, ts: _t, ...e }) => e);
|
|
190
|
+
const aligned = alignToBase(base, got);
|
|
191
|
+
if (aligned.problems.length)
|
|
192
|
+
throw new Error(`not saved — it can't extend '${baseSlug}':\n- ${aligned.problems.join('\n- ')}`);
|
|
193
|
+
const own = Object.fromEntries(Object.entries(aligned.caught).filter(([k, v]) => base.vars?.[k] !== v));
|
|
194
|
+
const vars = varsFor(aligned.steps, base.vars, own);
|
|
195
|
+
return {
|
|
196
|
+
recording: { ...rec, ...(vars ? { vars } : {}), events: aligned.steps.map((s, i) => ({ ...s, seq: i, ts: i })) },
|
|
197
|
+
extends: { flow: baseSlug, inherited: aligned.inherited, ...(Object.keys(own).length ? { vars: own } : {}) },
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Pure: after an edit, are this flow's inherited steps all still there, in
|
|
202
|
+
* order, unchanged? An edit may add, change or remove only its own steps.
|
|
203
|
+
*/
|
|
204
|
+
export function inheritedProblems(before, after, ext) {
|
|
205
|
+
const at = new Map(after.map((s, j) => [s.id, j]));
|
|
206
|
+
const problems = [];
|
|
207
|
+
let last = -1;
|
|
208
|
+
for (const id of ext.inherited) {
|
|
209
|
+
const i = before.findIndex((s) => s.id === id);
|
|
210
|
+
const j = at.get(id);
|
|
211
|
+
if (j === undefined || stepKey(after[j]) !== stepKey(before[i]) || j < last) {
|
|
212
|
+
problems.push(`step ${i} comes from '${ext.flow}', which this flow extends — change it there, and this flow follows`);
|
|
213
|
+
}
|
|
214
|
+
if (j !== undefined)
|
|
215
|
+
last = j;
|
|
216
|
+
}
|
|
217
|
+
return problems;
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* The flow `slug` changed: rebuild every flow that extends it (each through
|
|
221
|
+
* its own variant). Returns the ones that changed, and the ones that lost an
|
|
222
|
+
* anchor and need saving again.
|
|
223
|
+
*/
|
|
224
|
+
export async function refreshExtenders(app, slug) {
|
|
225
|
+
const { flows } = await collections();
|
|
226
|
+
const children = await flows.find({ app, 'extends.flow': slug }).toArray();
|
|
227
|
+
const out = { rebuilt: [], lost: [] };
|
|
228
|
+
const now = new Date();
|
|
229
|
+
for (const child of children) {
|
|
230
|
+
const name = child.variant ? `${child.slug} (${child.variant})` : child.slug;
|
|
231
|
+
const base = await baseWithIds(app, slug, child.variant);
|
|
232
|
+
if (!base) {
|
|
233
|
+
await flows.updateOne({ _id: child._id }, { $set: { proven: false, unprovenBecause: `'${slug}', the flow it extends, is gone — save it again without extends`, updatedAt: now } });
|
|
234
|
+
out.lost.push(name);
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
const next = rebuild(base, child);
|
|
238
|
+
if (next.lost.length) {
|
|
239
|
+
await flows.updateOne({ _id: child._id }, {
|
|
240
|
+
$set: {
|
|
241
|
+
'extends.lost': next.lost, proven: false, updatedAt: now,
|
|
242
|
+
unprovenBecause: `'${slug}' no longer has the step(s) its own steps come after (${next.lost.join(', ')}) — record or save it again with extends '${slug}'`,
|
|
243
|
+
},
|
|
244
|
+
});
|
|
245
|
+
out.lost.push(name);
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
const same = next.steps.length === child.steps.length && next.steps.every((s, i) => stepKey(s) === stepKey(child.steps[i]))
|
|
249
|
+
&& JSON.stringify(next.vars ?? {}) === JSON.stringify(child.vars ?? {});
|
|
250
|
+
if (same) {
|
|
251
|
+
if (child.extends?.lost)
|
|
252
|
+
await flows.updateOne({ _id: child._id }, { $unset: { 'extends.lost': '' } });
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
const why = flowDestructiveReason(withDefaults(next.steps, next.vars));
|
|
256
|
+
await flows.updateOne({ _id: child._id }, {
|
|
257
|
+
$set: {
|
|
258
|
+
steps: next.steps, 'extends.inherited': next.inherited, ...(next.vars ? { vars: next.vars } : {}),
|
|
259
|
+
proven: false, unprovenBecause: `'${slug}', the flow it extends, changed — the next passing run proves it`,
|
|
260
|
+
destructive: Boolean(why), ...(why ? { destructiveBecause: why } : {}), updatedAt: now,
|
|
261
|
+
},
|
|
262
|
+
$unset: { provenUpTo: '', 'extends.lost': '', ...(next.vars ? {} : { vars: '' }), ...(why ? {} : { destructiveBecause: '' }) },
|
|
263
|
+
});
|
|
264
|
+
// Segments cut from it keep their steps, wherever the rebuild put them.
|
|
265
|
+
await moveSegments(child, next.steps, originById(child.steps, next.steps), `'${slug}', which the flow it was cut from extends, changed — the next passing run proves it`);
|
|
266
|
+
out.rebuilt.push(name);
|
|
267
|
+
}
|
|
268
|
+
return out;
|
|
269
|
+
}
|
package/dist/flows/runs.d.ts
CHANGED
|
@@ -30,6 +30,8 @@ export declare function recordRun(opts: {
|
|
|
30
30
|
mode?: 'replay' | 'run';
|
|
31
31
|
/** Run with this variant's flows. Its history is compared with its own runs only. */
|
|
32
32
|
variant?: string;
|
|
33
|
+
/** Values it used for `{{variables}}` other than the defaults. Compared only with runs that used the same. */
|
|
34
|
+
vars?: Record<string, string>;
|
|
33
35
|
/** What was asked for. Defaults to the flow's slug. */
|
|
34
36
|
goal?: string;
|
|
35
37
|
/** The flows run, in order, when it was more than one. Defaults to [flow]. */
|
package/dist/flows/runs.js
CHANGED
|
@@ -20,12 +20,13 @@ const LOOKBACK = 5;
|
|
|
20
20
|
export async function recordRun(opts) {
|
|
21
21
|
const { app, flow, result, steps } = opts;
|
|
22
22
|
const plan = opts.plan ?? [flow];
|
|
23
|
+
const vars = opts.vars && Object.keys(opts.vars).length ? opts.vars : undefined;
|
|
23
24
|
const c = await collections();
|
|
24
25
|
const now = new Date();
|
|
25
26
|
// 1. Drift, against the most recent passed runs of this flow — however it
|
|
26
27
|
// was started, it walked the same steps.
|
|
27
28
|
const history = await c.runs
|
|
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 } })
|
|
29
|
+
.find({ app, plan, ...runsOf(opts.variant), vars: vars ?? { $exists: false }, mode: { $in: ['replay', 'run'] }, status: 'passed', stoppedBefore: { $exists: false }, accepted: { $ne: false }, ...(opts.runId ? { _id: { $ne: opts.runId } } : {}) }, { projection: { sigSequence: 1 } })
|
|
29
30
|
.sort({ startedAt: -1 })
|
|
30
31
|
.limit(LOOKBACK)
|
|
31
32
|
.toArray();
|
|
@@ -73,6 +74,7 @@ export async function recordRun(opts) {
|
|
|
73
74
|
goal: opts.goal ?? flow,
|
|
74
75
|
mode: opts.mode ?? 'replay',
|
|
75
76
|
...(opts.variant ? { variant: opts.variant } : {}),
|
|
77
|
+
...(vars ? { vars } : {}),
|
|
76
78
|
status: result.ok ? 'passed' : 'failed',
|
|
77
79
|
plan,
|
|
78
80
|
steps: result.steps.map((s) => {
|
|
@@ -116,8 +118,11 @@ export async function acceptPaths(app, fingerprints) {
|
|
|
116
118
|
if (!pending.length)
|
|
117
119
|
return { runs: 0, flows: [] };
|
|
118
120
|
await c.runs.updateMany({ _id: { $in: pending.map((r) => r._id) } }, { $unset: { accepted: '' } });
|
|
121
|
+
// The pages each flow expects are its defaults' pages: a run with other values doesn't set them.
|
|
119
122
|
const newest = pending.at(-1);
|
|
120
123
|
const updated = [];
|
|
124
|
+
if (newest.vars)
|
|
125
|
+
return { runs: pending.length, flows: updated };
|
|
121
126
|
for (const [i, slug] of newest.plan.entries()) {
|
|
122
127
|
const flow = await resolveFlow(app, slug, newest.variant);
|
|
123
128
|
if (!flow)
|
package/dist/flows/save.d.ts
CHANGED
|
@@ -15,6 +15,8 @@ import { type CommitStep } from './destructive.js';
|
|
|
15
15
|
import { type Executed, type Proven } from './execute.js';
|
|
16
16
|
import { type RecordedRun } from './runs.js';
|
|
17
17
|
import { type Applied } from '../memory/placeholders.js';
|
|
18
|
+
import { type StepEdit } from './steps.js';
|
|
19
|
+
import type { FlowExtends } from '../store/types.js';
|
|
18
20
|
/** "Log in as a member!" → "log-in-as-a-member" */
|
|
19
21
|
export declare function slugify(title: string): string;
|
|
20
22
|
/** A recording's events, as the steps of a flow. Drops recorder bookkeeping and empty fields. */
|
|
@@ -33,6 +35,8 @@ export interface SaveOptions {
|
|
|
33
35
|
madeBy?: 'user' | 'agent';
|
|
34
36
|
/** Set when it's being kept without a passing replay: why. Marks the flow unproven. */
|
|
35
37
|
unproven?: string;
|
|
38
|
+
/** It extends another flow (flows/extend.ts): the recording is already lined up against it. */
|
|
39
|
+
extends?: FlowExtends;
|
|
36
40
|
}
|
|
37
41
|
export declare function saveFlow(recording: RawRecording, result: ReplayResult, opts: SaveOptions): Promise<Flow>;
|
|
38
42
|
export interface ProveAndSave extends SaveOptions {
|
|
@@ -77,7 +81,7 @@ export declare function proveAndSave(recording: RawRecording, opts: ProveAndSave
|
|
|
77
81
|
* A run that stopped before the flow's commit step proves it that far
|
|
78
82
|
* (`provenUpTo`); a full run that passes proves the rest, and clears it.
|
|
79
83
|
*/
|
|
80
|
-
export declare function proveByRun(app: string, slug: string, result: ReplayResult, offset?: number, variant?: string): Promise<boolean>;
|
|
84
|
+
export declare function proveByRun(app: string, slug: string, result: ReplayResult, offset?: number, variant?: string, vars?: Record<string, string>): Promise<boolean>;
|
|
81
85
|
export interface ProvedFlow extends Executed {
|
|
82
86
|
flow: Flow;
|
|
83
87
|
/** The commit step it stopped before, when the flow has one. */
|
|
@@ -111,8 +115,23 @@ export declare function checkAdditions(flow: Pick<Flow, 'steps' | 'startUrl'>, a
|
|
|
111
115
|
}[];
|
|
112
116
|
problems: string[];
|
|
113
117
|
};
|
|
118
|
+
/** What one call may change in a saved flow. Every index means the step where it is now. */
|
|
119
|
+
export interface FlowChange {
|
|
120
|
+
/** Waits, checks and a person's steps, each before step n. */
|
|
121
|
+
add?: StepToAdd[];
|
|
122
|
+
/** Change a step's fields, or remove it. */
|
|
123
|
+
edit?: StepEdit[];
|
|
124
|
+
/** Defaults for `{{variables}}`: the value it is proven with. null drops one no step uses. */
|
|
125
|
+
vars?: Record<string, string | null>;
|
|
126
|
+
}
|
|
114
127
|
/**
|
|
115
|
-
*
|
|
116
|
-
*
|
|
128
|
+
* Change a saved flow: add waits and checks, change or remove steps, set the
|
|
129
|
+
* defaults of its `{{variables}}`. Every problem at once, nothing written
|
|
130
|
+
* unless all is valid. It is unproven afterwards — a run that passes proves it
|
|
131
|
+
* again (`understudy_save { flow, edit }` replays it at once) — and segments
|
|
132
|
+
* cut from it keep pointing at the same steps.
|
|
133
|
+
*
|
|
134
|
+
* A flow that extends another may change only its own steps; one others
|
|
135
|
+
* extend changes them too (flows/extend.ts).
|
|
117
136
|
*/
|
|
118
|
-
export declare function editFlow(app: string, slug: string,
|
|
137
|
+
export declare function editFlow(app: string, slug: string, change: FlowChange | StepToAdd[], variant?: string): Promise<Flow>;
|
package/dist/flows/save.js
CHANGED
|
@@ -8,7 +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,
|
|
11
|
+
import { checkVariant, flowKey, resolveFlow } from './variants.js';
|
|
12
12
|
import { collections, ensureSchema } from '../store/db.js';
|
|
13
13
|
import { embed, embedderConfig } from '../store/embed.js';
|
|
14
14
|
import { commitSteps, flowDestructiveReason } from './destructive.js';
|
|
@@ -17,6 +17,11 @@ import { destructiveControls } from '../memory/notes.js';
|
|
|
17
17
|
import { forgetSessionById } from '../core/auth-cache.js';
|
|
18
18
|
import { recordRun } from './runs.js';
|
|
19
19
|
import { applyPlaceholders } from '../memory/placeholders.js';
|
|
20
|
+
import { stepKey, withIds } from '../core/step-ids.js';
|
|
21
|
+
import { varsOf, VAR_NAME, withDefaults } from '../core/vars.js';
|
|
22
|
+
import { applyEdits } from './steps.js';
|
|
23
|
+
import { inheritedProblems, refreshExtenders } from './extend.js';
|
|
24
|
+
import { moveSegments } from './segments.js';
|
|
20
25
|
/** "Log in as a member!" → "log-in-as-a-member" */
|
|
21
26
|
export function slugify(title) {
|
|
22
27
|
return title.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 80);
|
|
@@ -59,6 +64,7 @@ export function recordingFrom(flow) {
|
|
|
59
64
|
startUrl: flow.startUrl,
|
|
60
65
|
createdAt: flow.updatedAt.toISOString(),
|
|
61
66
|
hash: flow.recording,
|
|
67
|
+
...(flow.vars ? { vars: flow.vars } : {}),
|
|
62
68
|
...(flow.requiresSession
|
|
63
69
|
? { entry: { requiresSession: true, ...(flow.startState ? { startState: flow.startState } : {}), ...(flow.session ? { session: flow.session } : {}) } }
|
|
64
70
|
: {}),
|
|
@@ -74,8 +80,11 @@ export async function saveFlow(recording, result, opts) {
|
|
|
74
80
|
throw new Error(`can't make a flow name from "${opts.title}" — pass --slug`);
|
|
75
81
|
const variant = checkVariant(opts.variant);
|
|
76
82
|
const key = flowKey(app, slug, variant);
|
|
77
|
-
|
|
78
|
-
const
|
|
83
|
+
// Ids carried over from the version this replaces, so whatever points at its steps still does.
|
|
84
|
+
const previous = await flows.findOne(key, { projection: { steps: 1, vars: 1 } });
|
|
85
|
+
const steps = withIds(stepsFrom(recording, result), previous?.steps);
|
|
86
|
+
const vars = defaultsFor(steps, recording.vars);
|
|
87
|
+
const why = flowDestructiveReason(withDefaults(steps, vars));
|
|
79
88
|
const upTo = stoppedAt(recording, result);
|
|
80
89
|
const intent = opts.intent ?? opts.title;
|
|
81
90
|
const searchText = [opts.title, intent !== opts.title ? intent : ''].filter(Boolean).join('. ');
|
|
@@ -103,6 +112,8 @@ export async function saveFlow(recording, result, opts) {
|
|
|
103
112
|
...(result.sigSequence.length && upTo === undefined ? { endState: result.sigSequence.at(-1) } : {}),
|
|
104
113
|
...(upTo !== undefined && !opts.unproven ? { provenUpTo: upTo } : {}),
|
|
105
114
|
steps,
|
|
115
|
+
...(vars ? { vars } : {}),
|
|
116
|
+
...(opts.extends ? { extends: opts.extends } : {}),
|
|
106
117
|
searchText,
|
|
107
118
|
...(embedding ? { embedding } : {}),
|
|
108
119
|
...(opts.unproven ? { proven: false, unprovenBecause: opts.unproven } : {}),
|
|
@@ -125,11 +136,34 @@ export async function saveFlow(recording, result, opts) {
|
|
|
125
136
|
unset.provenUpTo = '';
|
|
126
137
|
if (upTo !== undefined)
|
|
127
138
|
unset.endState = '';
|
|
139
|
+
if (!vars)
|
|
140
|
+
unset.vars = '';
|
|
141
|
+
if (!opts.extends)
|
|
142
|
+
unset.extends = '';
|
|
128
143
|
await flows.updateOne(key, { $set: flow, $setOnInsert: { createdAt: now }, ...(Object.keys(unset).length ? { $unset: unset } : {}) }, { upsert: true });
|
|
129
144
|
// Make sure the app exists, remembering where it lives.
|
|
130
145
|
await apps.updateOne({ slug: app }, { $setOnInsert: { slug: app, name: app, urls: { default: new URL(recording.startUrl).origin }, createdAt: now } }, { upsert: true });
|
|
146
|
+
// Flows that extend this one follow it — when what it does changed.
|
|
147
|
+
const changed = previous && (previous.steps.length !== steps.length || previous.steps.some((p, i) => stepKey(p) !== stepKey(steps[i]))
|
|
148
|
+
|| JSON.stringify(previous.vars ?? {}) !== JSON.stringify(vars ?? {}));
|
|
149
|
+
if (changed)
|
|
150
|
+
await refreshExtenders(app, slug);
|
|
131
151
|
return (await flows.findOne(key));
|
|
132
152
|
}
|
|
153
|
+
/**
|
|
154
|
+
* The defaults for the `{{variables}}` these steps use, from the values it
|
|
155
|
+
* was proven with. Every variable needs one: the default is what a run uses
|
|
156
|
+
* when nobody passes a value, and it must be a value that worked.
|
|
157
|
+
*/
|
|
158
|
+
function defaultsFor(steps, values) {
|
|
159
|
+
const used = varsOf(steps);
|
|
160
|
+
if (!used.length)
|
|
161
|
+
return undefined;
|
|
162
|
+
const missing = used.filter((v) => values?.[v] === undefined);
|
|
163
|
+
if (missing.length)
|
|
164
|
+
throw new Error(`not saved — ${missing.map((v) => `{{${v}}}`).join(', ')} ha${missing.length === 1 ? 's' : 've'} no value: pass ${missing.map((v) => `"${v}": "…"`).join(', ')} in values; it becomes the default`);
|
|
165
|
+
return Object.fromEntries(used.map((v) => [v, values[v]]));
|
|
166
|
+
}
|
|
133
167
|
/**
|
|
134
168
|
* What `save` does, for the CLI and the MCP server alike: prove the recording
|
|
135
169
|
* (replaying it headless, working out whether it needs to start signed in),
|
|
@@ -138,6 +172,10 @@ export async function saveFlow(recording, result, opts) {
|
|
|
138
172
|
* then as unproven. With verify: false there's no replay at all.
|
|
139
173
|
*/
|
|
140
174
|
export async function proveAndSave(recording, opts) {
|
|
175
|
+
// A value passed for a {{variable}} is what it's proven with, so it becomes the default.
|
|
176
|
+
const used = varsOf(recording.events).filter((v) => opts.values?.[v] !== undefined);
|
|
177
|
+
if (used.length)
|
|
178
|
+
recording = { ...recording, vars: { ...recording.vars, ...Object.fromEntries(used.map((v) => [v, opts.values[v]])) } };
|
|
141
179
|
if (opts.verify === false) {
|
|
142
180
|
// No replay, so nothing can say whether a copied sign-in is needed. Unless
|
|
143
181
|
// the user said it is (ticked "I'm signed in here"), don't keep it.
|
|
@@ -158,7 +196,7 @@ export async function proveAndSave(recording, opts) {
|
|
|
158
196
|
// PROVE IT, BUT DON'T BUY ANYTHING. A flow that commits something real is
|
|
159
197
|
// replayed up to its first commit step, whose control is checked and never
|
|
160
198
|
// pressed. Saving used to replay the whole thing, purchase included.
|
|
161
|
-
const commit = await firstStop(recording.appSlug, stepsFrom(recording));
|
|
199
|
+
const commit = await firstStop(recording.appSlug, withDefaults(stepsFrom(recording), recording.vars));
|
|
162
200
|
const proven = await prove(recording, {
|
|
163
201
|
...(opts.values ? { values: opts.values } : {}), ...(opts.headed ? { headed: true } : {}),
|
|
164
202
|
...(commit ? { stopBefore: recording.events[commit.index].seq } : { endChecks: true }),
|
|
@@ -202,14 +240,20 @@ async function firstStop(app, steps) {
|
|
|
202
240
|
* A run that stopped before the flow's commit step proves it that far
|
|
203
241
|
* (`provenUpTo`); a full run that passes proves the rest, and clears it.
|
|
204
242
|
*/
|
|
205
|
-
export async function proveByRun(app, slug, result, offset = 0, variant) {
|
|
243
|
+
export async function proveByRun(app, slug, result, offset = 0, variant, vars) {
|
|
206
244
|
if (!result.ok)
|
|
207
245
|
return false;
|
|
246
|
+
// Run with other values than its defaults: it proves those, not the flow as saved.
|
|
247
|
+
if (vars && Object.keys(vars).length)
|
|
248
|
+
return false;
|
|
208
249
|
const { flows } = await collections();
|
|
209
250
|
// The flow the run used: the variant's copy if it has one, else the main flow.
|
|
210
251
|
const ran = await resolveFlow(app, slug, variant);
|
|
211
252
|
if (!ran || (ran.proven !== false && ran.provenUpTo === undefined))
|
|
212
253
|
return false;
|
|
254
|
+
// Its own steps lost their place in the flow it extends: passing doesn't fix that.
|
|
255
|
+
if (ran.extends?.lost?.length)
|
|
256
|
+
return false;
|
|
213
257
|
const flow = ran;
|
|
214
258
|
const stopped = result.stoppedBefore === undefined ? undefined : result.stoppedBefore - offset;
|
|
215
259
|
// Stopped before this flow began: none of it ran.
|
|
@@ -248,7 +292,7 @@ export async function proveFlow(app, slug, opts = {}) {
|
|
|
248
292
|
const flow = await flows.findOne(flowKey(app, slug, checkVariant(variant)));
|
|
249
293
|
if (!flow)
|
|
250
294
|
throw new Error(`no flow '${slug}'${variant ? ` (variant "${variant}")` : ''} for app '${app}'`);
|
|
251
|
-
const commit = await firstStop(app, flow.steps);
|
|
295
|
+
const commit = await firstStop(app, withDefaults(flow.steps, flow.vars));
|
|
252
296
|
const recording = recordingFrom(flow);
|
|
253
297
|
const executed = await execute(recording, {
|
|
254
298
|
...run, useLessons: true,
|
|
@@ -257,8 +301,9 @@ export async function proveFlow(app, slug, opts = {}) {
|
|
|
257
301
|
const recorded = await recordRun({
|
|
258
302
|
app, flow: slug, result: executed.result, steps: flow.steps, mode: 'replay',
|
|
259
303
|
...(flow.variant ? { variant: flow.variant } : {}), ...(flow.proven === false ? { unproven: true } : {}),
|
|
304
|
+
...(executed.vars ? { vars: executed.vars } : {}),
|
|
260
305
|
});
|
|
261
|
-
const newlyProven = await proveByRun(app, slug, executed.result, 0, flow.variant);
|
|
306
|
+
const newlyProven = await proveByRun(app, slug, executed.result, 0, flow.variant, executed.vars);
|
|
262
307
|
return { ...executed, flow: (await flows.findOne({ _id: flow._id })), ...(commit ? { commit } : {}), run: recorded, newlyProven };
|
|
263
308
|
}
|
|
264
309
|
/**
|
|
@@ -270,7 +315,7 @@ const ADDABLE = {
|
|
|
270
315
|
human: ['untilText', 'untilUrl', 'untilResponse'],
|
|
271
316
|
// A check of what the page shows — how a flow should end. Addressed by
|
|
272
317
|
// role + name, which is a look, not a click.
|
|
273
|
-
assert: ['assert', 'timeoutMs'],
|
|
318
|
+
assert: ['assert', 'timeoutMs', 'nth'],
|
|
274
319
|
wait_response: ['method', 'status', 'field', 'equals', 'above', 'urlRegex', 'urlFlags', 'timeoutMs'],
|
|
275
320
|
wait_url: ['timeoutMs'],
|
|
276
321
|
wait_text: ['timeoutMs'],
|
|
@@ -303,6 +348,9 @@ export function checkAdditions(flow, adds) {
|
|
|
303
348
|
if (ms !== undefined && (!Number.isInteger(ms) || ms < 1000 || ms > 600_000)) {
|
|
304
349
|
problems.push(`${at}.step.hints.timeoutMs must be a whole number of ms from 1000 to 600000`);
|
|
305
350
|
}
|
|
351
|
+
const nth = hints?.nth;
|
|
352
|
+
if (nth !== undefined && !(Number.isInteger(nth) && nth >= -1))
|
|
353
|
+
problems.push(`${at}.step.hints.nth must be a whole number: 0 is the first match, -1 the last`);
|
|
306
354
|
const needsValue = !isAssert || kind === 'text' || kind === 'contains';
|
|
307
355
|
if (needsValue && (typeof value !== 'string' || !value.trim())) {
|
|
308
356
|
problems.push(`${at}.step.value is required: ${action === 'human' ? 'what the person does' : action === 'wait_response' ? 'the address' : isAssert ? 'the text to expect' : 'what to wait for'}`);
|
|
@@ -327,60 +375,73 @@ export function checkAdditions(flow, adds) {
|
|
|
327
375
|
return { steps, problems };
|
|
328
376
|
}
|
|
329
377
|
/**
|
|
330
|
-
*
|
|
331
|
-
*
|
|
378
|
+
* Change a saved flow: add waits and checks, change or remove steps, set the
|
|
379
|
+
* defaults of its `{{variables}}`. Every problem at once, nothing written
|
|
380
|
+
* unless all is valid. It is unproven afterwards — a run that passes proves it
|
|
381
|
+
* again (`understudy_save { flow, edit }` replays it at once) — and segments
|
|
382
|
+
* cut from it keep pointing at the same steps.
|
|
383
|
+
*
|
|
384
|
+
* A flow that extends another may change only its own steps; one others
|
|
385
|
+
* extend changes them too (flows/extend.ts).
|
|
332
386
|
*/
|
|
333
|
-
export async function editFlow(app, slug,
|
|
387
|
+
export async function editFlow(app, slug, change, variant) {
|
|
388
|
+
await ensureSchema();
|
|
334
389
|
const { flows } = await collections();
|
|
390
|
+
const { add = [], edit = [], vars: setVars } = Array.isArray(change) ? { add: change } : change;
|
|
335
391
|
const flow = await flows.findOne(flowKey(app, slug, checkVariant(variant)));
|
|
336
392
|
if (!flow)
|
|
337
393
|
throw new Error(`no flow '${slug}'${variant ? ` (variant "${variant}")` : ''} for app '${app}'`);
|
|
338
394
|
if (flow.kind !== 'recording')
|
|
339
|
-
throw new Error(`'${slug}' is a segment —
|
|
340
|
-
if (!
|
|
341
|
-
throw new Error('nothing to add');
|
|
342
|
-
const { steps: inserts, problems } = checkAdditions(flow,
|
|
395
|
+
throw new Error(`'${slug}' is a segment — change the flow it was cut from (${flow.from?.flow})`);
|
|
396
|
+
if (!add.length && !edit.length && !setVars)
|
|
397
|
+
throw new Error('nothing to change — pass add, edit or vars');
|
|
398
|
+
const { steps: inserts, problems } = checkAdditions(flow, add);
|
|
399
|
+
const current = withIds(flow.steps);
|
|
400
|
+
const applied = applyEdits(current, edit, inserts);
|
|
401
|
+
problems.push(...applied.problems);
|
|
402
|
+
const steps = applied.steps;
|
|
403
|
+
if (flow.extends)
|
|
404
|
+
problems.push(...inheritedProblems(current, steps, flow.extends));
|
|
405
|
+
// Defaults: a flow that extends another keeps its own beside that flow's.
|
|
406
|
+
const base = flow.extends ? await resolveFlow(app, flow.extends.flow, flow.variant) : null;
|
|
407
|
+
const own = { ...(flow.extends ? flow.extends.vars : flow.vars) };
|
|
408
|
+
for (const [k, v] of Object.entries(setVars ?? {})) {
|
|
409
|
+
if (!VAR_NAME.test(k))
|
|
410
|
+
problems.push(`vars.${k}: a name is a letter, then letters, digits or _`);
|
|
411
|
+
else if (v === null)
|
|
412
|
+
delete own[k];
|
|
413
|
+
else if (typeof v !== 'string')
|
|
414
|
+
problems.push(`vars.${k} must be a string (or null to drop it)`);
|
|
415
|
+
else
|
|
416
|
+
own[k] = v;
|
|
417
|
+
}
|
|
418
|
+
const all = { ...base?.vars, ...own };
|
|
419
|
+
const used = varsOf(steps);
|
|
420
|
+
for (const k of Object.keys(setVars ?? {}))
|
|
421
|
+
if (setVars[k] !== null && !used.includes(k))
|
|
422
|
+
problems.push(`vars.${k}: no step uses {{${k}}} — set a step's name or value to include it`);
|
|
423
|
+
for (const k of used)
|
|
424
|
+
if (all[k] === undefined)
|
|
425
|
+
problems.push(`{{${k}}} has no default: pass vars {"${k}": "<the value it was recorded with>"}`);
|
|
343
426
|
if (problems.length)
|
|
344
427
|
throw new Error(`nothing changed — fix these and send it again:\n- ${problems.join('\n- ')}`);
|
|
345
|
-
|
|
346
|
-
const
|
|
347
|
-
const
|
|
348
|
-
|
|
349
|
-
steps.splice(before, 0, step);
|
|
350
|
-
const why = flowDestructiveReason(steps);
|
|
428
|
+
const vars = used.length ? Object.fromEntries(used.map((k) => [k, all[k]])) : undefined;
|
|
429
|
+
const ownVars = Object.fromEntries(Object.entries(own).filter(([k]) => used.includes(k)));
|
|
430
|
+
const what = [add.length && `${add.length} step(s) added`, edit.length && `${edit.length} step(s) changed`, setVars && 'defaults set'].filter(Boolean).join(', ');
|
|
431
|
+
const why = flowDestructiveReason(withDefaults(steps, vars));
|
|
351
432
|
const now = new Date();
|
|
352
433
|
await flows.updateOne({ _id: flow._id }, {
|
|
353
434
|
$set: {
|
|
354
|
-
steps, proven: false, unprovenBecause: `edited: ${
|
|
435
|
+
steps, proven: false, unprovenBecause: `edited: ${what} — the next passing run proves it`,
|
|
436
|
+
...(vars ? { vars } : {}), ...(flow.extends && Object.keys(ownVars).length ? { 'extends.vars': ownVars } : {}),
|
|
355
437
|
destructive: Boolean(why), ...(why ? { destructiveBecause: why } : {}), updatedAt: now,
|
|
356
438
|
},
|
|
357
|
-
$unset: {
|
|
439
|
+
$unset: {
|
|
440
|
+
provenUpTo: '', ...(why ? {} : { destructiveBecause: '' }), ...(vars ? {} : { vars: '' }),
|
|
441
|
+
...(flow.extends && !Object.keys(ownVars).length ? { 'extends.vars': '' } : {}),
|
|
442
|
+
},
|
|
358
443
|
});
|
|
359
|
-
|
|
360
|
-
|
|
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) {
|
|
364
|
-
let [start, end] = seg.from.steps;
|
|
365
|
-
const segSteps = [...seg.steps];
|
|
366
|
-
let changed = false;
|
|
367
|
-
for (const { before, step } of sorted) {
|
|
368
|
-
if (before <= start) {
|
|
369
|
-
start++;
|
|
370
|
-
end++;
|
|
371
|
-
}
|
|
372
|
-
else if (before < end) {
|
|
373
|
-
segSteps.splice(before - start, 0, step);
|
|
374
|
-
end++;
|
|
375
|
-
changed = true;
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
await flows.updateOne({ _id: seg._id }, {
|
|
379
|
-
$set: {
|
|
380
|
-
'from.steps': [start, end], steps: segSteps, updatedAt: now,
|
|
381
|
-
...(changed ? { proven: false, unprovenBecause: `its flow '${slug}' was edited — the next passing run proves it` } : {}),
|
|
382
|
-
},
|
|
383
|
-
});
|
|
384
|
-
}
|
|
444
|
+
await moveSegments(flow, steps, applied.origin, `its flow '${slug}' was edited — the next passing run proves it`);
|
|
445
|
+
await refreshExtenders(app, slug);
|
|
385
446
|
return (await flows.findOne({ _id: flow._id }));
|
|
386
447
|
}
|