@jeffawe/understudy 0.2.2 → 0.3.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/README.md +60 -12
- package/REASONER.md +31 -4
- package/dist/adapters/recorder/script.js +206 -4
- package/dist/core/distill.d.ts +12 -0
- package/dist/core/distill.js +25 -32
- package/dist/core/recording.d.ts +49 -1
- package/dist/core/recording.js +60 -0
- package/dist/core/replay.d.ts +81 -1
- package/dist/core/replay.js +319 -19
- package/dist/entry/cli.js +112 -10
- package/dist/entry/mcp.d.ts +1 -1
- package/dist/entry/mcp.js +175 -35
- package/dist/flows/destructive.d.ts +17 -1
- package/dist/flows/destructive.js +23 -5
- package/dist/flows/distill.js +2 -0
- package/dist/flows/emit.js +88 -5
- package/dist/flows/execute.d.ts +22 -2
- package/dist/flows/execute.js +19 -3
- package/dist/flows/findings.d.ts +4 -1
- package/dist/flows/findings.js +25 -7
- package/dist/flows/runs.d.ts +13 -0
- package/dist/flows/runs.js +43 -7
- package/dist/flows/save.d.ts +42 -1
- package/dist/flows/save.js +214 -14
- package/dist/memory/recall.d.ts +10 -1
- package/dist/memory/recall.js +12 -5
- package/dist/memory/vocabulary.js +9 -3
- package/dist/plan/planner.d.ts +8 -4
- package/dist/plan/planner.js +77 -4
- package/dist/store/types.d.ts +46 -2
- package/package.json +1 -1
package/dist/flows/save.js
CHANGED
|
@@ -10,8 +10,9 @@
|
|
|
10
10
|
*/
|
|
11
11
|
import { collections, ensureSchema } from '../store/db.js';
|
|
12
12
|
import { embed, embedderConfig } from '../store/embed.js';
|
|
13
|
-
import { flowDestructiveReason } from './destructive.js';
|
|
14
|
-
import { prove } from './execute.js';
|
|
13
|
+
import { commitSteps, flowDestructiveReason } from './destructive.js';
|
|
14
|
+
import { execute, prove } from './execute.js';
|
|
15
|
+
import { destructiveControls } from '../memory/notes.js';
|
|
15
16
|
import { forgetSessionById } from '../core/auth-cache.js';
|
|
16
17
|
import { recordRun } from './runs.js';
|
|
17
18
|
import { applyPlaceholders } from '../memory/placeholders.js';
|
|
@@ -19,18 +20,34 @@ import { applyPlaceholders } from '../memory/placeholders.js';
|
|
|
19
20
|
export function slugify(title) {
|
|
20
21
|
return title.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 80);
|
|
21
22
|
}
|
|
23
|
+
/**
|
|
24
|
+
* The page a step really ran on, when the replay saw it and the step's own
|
|
25
|
+
* `url` is only a guess. A script is read without running it, so each of its
|
|
26
|
+
* steps carries the address of the last `goto` before it — "Pay Now" stamped
|
|
27
|
+
* with the page three clicks earlier. That address feeds the step's
|
|
28
|
+
* fingerprint, the payment-site check and seam questions, so the first replay
|
|
29
|
+
* that sees the truth replaces it. Recorded steps already have the truth.
|
|
30
|
+
*/
|
|
31
|
+
function observedUrl(step, at) {
|
|
32
|
+
return at && step.resolution === 'script-literal' && step.action !== 'goto' ? at : undefined;
|
|
33
|
+
}
|
|
22
34
|
/** A recording's events, as the steps of a flow. Drops recorder bookkeeping and empty fields. */
|
|
23
35
|
export function stepsFrom(recording, result) {
|
|
24
|
-
const observed = new Map(result?.steps.map((s) => [s.seq, s
|
|
36
|
+
const observed = new Map(result?.steps.map((s) => [s.seq, s]));
|
|
25
37
|
return recording.events.map((e) => {
|
|
26
38
|
const { seq, ts, ...rest } = e;
|
|
27
39
|
const step = Object.fromEntries(Object.entries(rest).filter(([, v]) => v !== undefined));
|
|
28
|
-
const
|
|
29
|
-
if (sig)
|
|
30
|
-
step.expectedSig = sig;
|
|
40
|
+
const outcome = observed.get(seq);
|
|
41
|
+
if (outcome?.sig)
|
|
42
|
+
step.expectedSig = outcome.sig;
|
|
43
|
+
const url = observedUrl(step, outcome?.at);
|
|
44
|
+
if (url)
|
|
45
|
+
step.url = url;
|
|
31
46
|
return step;
|
|
32
47
|
});
|
|
33
48
|
}
|
|
49
|
+
/** The index of the step a stopped replay stopped before, if it stopped. */
|
|
50
|
+
const stoppedAt = (recording, result) => result.stoppedBefore === undefined ? undefined : recording.events.findIndex((e) => e.seq === result.stoppedBefore);
|
|
34
51
|
/** Turn a flow back into a recording that replay can run. */
|
|
35
52
|
export function recordingFrom(flow) {
|
|
36
53
|
return {
|
|
@@ -56,6 +73,7 @@ export async function saveFlow(recording, result, opts) {
|
|
|
56
73
|
throw new Error(`can't make a flow name from "${opts.title}" — pass --slug`);
|
|
57
74
|
const steps = stepsFrom(recording, result);
|
|
58
75
|
const why = flowDestructiveReason(steps);
|
|
76
|
+
const upTo = stoppedAt(recording, result);
|
|
59
77
|
const intent = opts.intent ?? opts.title;
|
|
60
78
|
const searchText = [opts.title, intent !== opts.title ? intent : ''].filter(Boolean).join('. ');
|
|
61
79
|
const [embedding] = embedderConfig() ? await embed([searchText], 'document') : [];
|
|
@@ -77,7 +95,9 @@ export async function saveFlow(recording, result, opts) {
|
|
|
77
95
|
requiresSession: Boolean(recording.entry?.requiresSession),
|
|
78
96
|
...(recording.entry?.session ? { session: recording.entry.session } : {}),
|
|
79
97
|
...(result.sigSequence[0] ? { startState: recording.entry?.startState ?? result.sigSequence[0] } : {}),
|
|
80
|
-
|
|
98
|
+
// A replay that stopped before the commit never saw where the flow ends.
|
|
99
|
+
...(result.sigSequence.length && upTo === undefined ? { endState: result.sigSequence.at(-1) } : {}),
|
|
100
|
+
...(upTo !== undefined && !opts.unproven ? { provenUpTo: upTo } : {}),
|
|
81
101
|
steps,
|
|
82
102
|
searchText,
|
|
83
103
|
...(embedding ? { embedding } : {}),
|
|
@@ -97,6 +117,10 @@ export async function saveFlow(recording, result, opts) {
|
|
|
97
117
|
unset.proven = '';
|
|
98
118
|
unset.unprovenBecause = '';
|
|
99
119
|
}
|
|
120
|
+
if (upTo === undefined || opts.unproven)
|
|
121
|
+
unset.provenUpTo = '';
|
|
122
|
+
if (upTo !== undefined)
|
|
123
|
+
unset.endState = '';
|
|
100
124
|
await flows.updateOne({ app, slug }, { $set: flow, $setOnInsert: { createdAt: now }, ...(Object.keys(unset).length ? { $unset: unset } : {}) }, { upsert: true });
|
|
101
125
|
// Make sure the app exists, remembering where it lives.
|
|
102
126
|
await apps.updateOne({ slug: app }, { $setOnInsert: { slug: app, name: app, urls: { default: new URL(recording.startUrl).origin }, createdAt: now } }, { upsert: true });
|
|
@@ -127,7 +151,14 @@ export async function proveAndSave(recording, opts) {
|
|
|
127
151
|
const flow = await saveFlow(rec, none, { ...opts, unproven: opts.unproven ?? 'saved without a replay' });
|
|
128
152
|
return { saved: true, verified: false, ...(await withPlaceholders(flow)) };
|
|
129
153
|
}
|
|
130
|
-
|
|
154
|
+
// PROVE IT, BUT DON'T BUY ANYTHING. A flow that commits something real is
|
|
155
|
+
// replayed up to its first commit step, whose control is checked and never
|
|
156
|
+
// pressed. Saving used to replay the whole thing, purchase included.
|
|
157
|
+
const commit = await firstStop(recording.appSlug, stepsFrom(recording));
|
|
158
|
+
const proven = await prove(recording, {
|
|
159
|
+
...(opts.values ? { values: opts.values } : {}), ...(opts.headed ? { headed: true } : {}),
|
|
160
|
+
...(commit ? { stopBefore: recording.events[commit.index].seq } : { endChecks: true }),
|
|
161
|
+
});
|
|
131
162
|
let unproven = opts.unproven;
|
|
132
163
|
if (!proven.result.ok) {
|
|
133
164
|
const keep = opts.force || (opts.keepIfFailed ? await opts.keepIfFailed(proven) : false);
|
|
@@ -147,25 +178,194 @@ async function withPlaceholders(flow) {
|
|
|
147
178
|
return { flow, placeholders };
|
|
148
179
|
return { flow: (await (await collections()).flows.findOne({ _id: flow._id })), placeholders };
|
|
149
180
|
}
|
|
181
|
+
/**
|
|
182
|
+
* The first step a proof must not do: one that commits something real
|
|
183
|
+
* (counting what facts say), or one only a person can do.
|
|
184
|
+
*/
|
|
185
|
+
async function firstStop(app, steps) {
|
|
186
|
+
const commit = commitSteps(steps, await destructiveControls(app))[0];
|
|
187
|
+
const human = steps.findIndex((s) => s.action === 'human');
|
|
188
|
+
if (human >= 0 && (!commit || human < commit.index)) {
|
|
189
|
+
return { index: human, reason: `a step only a person can do: ${steps[human].value ?? 'unnamed'}` };
|
|
190
|
+
}
|
|
191
|
+
return commit;
|
|
192
|
+
}
|
|
150
193
|
/**
|
|
151
194
|
* An unproven flow that just passed a run is proven now: mark it, and fill in
|
|
152
195
|
* what its missing replay would have recorded — the page each step lands on,
|
|
153
196
|
* and where it starts and ends. `offset` skips steps the run added in front.
|
|
197
|
+
*
|
|
198
|
+
* A run that stopped before the flow's commit step proves it that far
|
|
199
|
+
* (`provenUpTo`); a full run that passes proves the rest, and clears it.
|
|
154
200
|
*/
|
|
155
201
|
export async function proveByRun(app, slug, result, offset = 0) {
|
|
156
202
|
if (!result.ok)
|
|
157
203
|
return false;
|
|
158
204
|
const { flows } = await collections();
|
|
159
|
-
const flow = await flows.findOne({ app, slug, proven: false });
|
|
205
|
+
const flow = await flows.findOne({ app, slug, $or: [{ proven: false }, { provenUpTo: { $exists: true } }] });
|
|
160
206
|
if (!flow)
|
|
161
207
|
return false;
|
|
162
|
-
const
|
|
163
|
-
|
|
208
|
+
const stopped = result.stoppedBefore === undefined ? undefined : result.stoppedBefore - offset;
|
|
209
|
+
// Stopped before this flow began: none of it ran.
|
|
210
|
+
if (stopped !== undefined && stopped < 0)
|
|
211
|
+
return false;
|
|
212
|
+
const partial = stopped !== undefined && stopped < flow.steps.length;
|
|
213
|
+
// Proven this far already — a partial run can't add anything.
|
|
214
|
+
if (partial && flow.proven !== false)
|
|
215
|
+
return false;
|
|
216
|
+
const outcomes = new Map(result.steps.map((s) => [s.seq - offset, s]));
|
|
217
|
+
const steps = flow.steps.map((s, i) => {
|
|
218
|
+
const o = outcomes.get(i);
|
|
219
|
+
const url = observedUrl(s, o?.at);
|
|
220
|
+
return { ...s, ...(o?.sig ? { expectedSig: o.sig } : {}), ...(url ? { url } : {}) };
|
|
221
|
+
});
|
|
164
222
|
const first = offset > 0 ? result.steps.find((s) => s.seq === offset - 1)?.sig : result.sigSequence[0];
|
|
165
|
-
const last =
|
|
223
|
+
const last = partial ? undefined : outcomes.get(flow.steps.length - 1)?.sig;
|
|
166
224
|
await flows.updateOne({ _id: flow._id }, {
|
|
167
|
-
$set: {
|
|
168
|
-
|
|
225
|
+
$set: {
|
|
226
|
+
steps, ...(first && !flow.startState ? { startState: first } : {}), ...(last ? { endState: last } : {}),
|
|
227
|
+
...(partial ? { provenUpTo: stopped } : {}), updatedAt: new Date(),
|
|
228
|
+
},
|
|
229
|
+
$unset: { proven: '', unprovenBecause: '', ...(partial ? {} : { provenUpTo: '' }) },
|
|
169
230
|
});
|
|
170
231
|
return true;
|
|
171
232
|
}
|
|
233
|
+
/**
|
|
234
|
+
* Prove a saved flow where it stands — the way out for one kept with
|
|
235
|
+
* `verify: false` because it ends in a real purchase. A flow with a commit step
|
|
236
|
+
* is replayed up to it, and the commit's control is checked but never pressed;
|
|
237
|
+
* any other flow is simply run. Either way the run is recorded.
|
|
238
|
+
*/
|
|
239
|
+
export async function proveFlow(app, slug, opts = {}) {
|
|
240
|
+
const { flows } = await collections();
|
|
241
|
+
const flow = await flows.findOne({ app, slug });
|
|
242
|
+
if (!flow)
|
|
243
|
+
throw new Error(`no flow '${slug}' for app '${app}'`);
|
|
244
|
+
const commit = await firstStop(app, flow.steps);
|
|
245
|
+
const recording = recordingFrom(flow);
|
|
246
|
+
const executed = await execute(recording, {
|
|
247
|
+
...opts, useLessons: true,
|
|
248
|
+
...(commit ? { stopBefore: recording.events[commit.index].seq } : {}),
|
|
249
|
+
});
|
|
250
|
+
const run = await recordRun({
|
|
251
|
+
app, flow: slug, result: executed.result, steps: flow.steps, mode: 'replay',
|
|
252
|
+
...(flow.proven === false ? { unproven: true } : {}),
|
|
253
|
+
});
|
|
254
|
+
const newlyProven = await proveByRun(app, slug, executed.result);
|
|
255
|
+
return { ...executed, flow: (await flows.findOne({ _id: flow._id })), ...(commit ? { commit } : {}), run, newlyProven };
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Steps that can be added to a saved flow by hand — mostly to fix up flows
|
|
259
|
+
* saved before these existed. Only ones that need no locator: a wait, or a
|
|
260
|
+
* person's step. Anything that clicks is recorded, never typed in.
|
|
261
|
+
*/
|
|
262
|
+
const ADDABLE = {
|
|
263
|
+
human: ['untilText', 'untilUrl', 'untilResponse'],
|
|
264
|
+
// A check of what the page shows — how a flow should end. Addressed by
|
|
265
|
+
// role + name, which is a look, not a click.
|
|
266
|
+
assert: ['assert'],
|
|
267
|
+
wait_response: ['method', 'status', 'field', 'equals', 'above'],
|
|
268
|
+
wait_url: [],
|
|
269
|
+
wait_text: [],
|
|
270
|
+
};
|
|
271
|
+
/** Every problem with these additions at once, or the steps to insert. */
|
|
272
|
+
export function checkAdditions(flow, adds) {
|
|
273
|
+
const problems = [];
|
|
274
|
+
const steps = [];
|
|
275
|
+
adds.forEach((a, i) => {
|
|
276
|
+
const at = `add[${i}]`;
|
|
277
|
+
const { action, value, hints } = (a.step ?? {});
|
|
278
|
+
if (!Number.isInteger(a.before) || a.before < 0 || a.before > flow.steps.length) {
|
|
279
|
+
problems.push(`${at}.before must be a step index from 0 to ${flow.steps.length}`);
|
|
280
|
+
}
|
|
281
|
+
const allowed = typeof action === 'string' ? ADDABLE[action] : undefined;
|
|
282
|
+
if (!allowed)
|
|
283
|
+
return problems.push(`${at}.step.action must be one of ${Object.keys(ADDABLE).join(', ')}`);
|
|
284
|
+
const { role, name } = (a.step ?? {});
|
|
285
|
+
const kind = hints?.assert;
|
|
286
|
+
const isAssert = action === 'assert';
|
|
287
|
+
if (isAssert) {
|
|
288
|
+
if (typeof role !== 'string' || typeof name !== 'string' || !name.trim())
|
|
289
|
+
problems.push(`${at}.step: an assert needs role and name, e.g. {"role":"heading","name":"Visit booked"}`);
|
|
290
|
+
if (!['visible', 'hidden', 'checked', 'unchecked', 'text', 'contains'].includes(String(kind)))
|
|
291
|
+
problems.push(`${at}.step.hints.assert must be visible, hidden, checked, unchecked, text or contains`);
|
|
292
|
+
}
|
|
293
|
+
const needsValue = !isAssert || kind === 'text' || kind === 'contains';
|
|
294
|
+
if (needsValue && (typeof value !== 'string' || !value.trim())) {
|
|
295
|
+
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'}`);
|
|
296
|
+
}
|
|
297
|
+
if (hints !== undefined && (typeof hints !== 'object' || hints === null || Array.isArray(hints)))
|
|
298
|
+
problems.push(`${at}.step.hints must be an object`);
|
|
299
|
+
const extra = Object.keys(hints ?? {}).filter((k) => !allowed.includes(k));
|
|
300
|
+
if (extra.length)
|
|
301
|
+
problems.push(`${at}.step.hints can't have ${extra.join(', ')}${allowed.length ? ` (it can have ${allowed.join(', ')})` : ''}`);
|
|
302
|
+
const prev = flow.steps[Math.min(a.before, flow.steps.length) - 1];
|
|
303
|
+
steps.push({
|
|
304
|
+
before: a.before,
|
|
305
|
+
step: {
|
|
306
|
+
action: action,
|
|
307
|
+
...(typeof value === 'string' && value.trim() ? { value: value.trim() } : {}),
|
|
308
|
+
...(isAssert && typeof role === 'string' ? { role } : {}), ...(isAssert && typeof name === 'string' ? { name } : {}),
|
|
309
|
+
url: prev?.url ?? flow.startUrl, resolution: 'synthesized',
|
|
310
|
+
...(hints && Object.keys(hints).length ? { hints: hints } : {}),
|
|
311
|
+
},
|
|
312
|
+
});
|
|
313
|
+
});
|
|
314
|
+
return { steps, problems };
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* Add steps to a saved flow. It is unproven afterwards — a run that passes
|
|
318
|
+
* proves it again — and segments cut from it keep pointing at the same steps.
|
|
319
|
+
*/
|
|
320
|
+
export async function editFlow(app, slug, adds) {
|
|
321
|
+
const { flows } = await collections();
|
|
322
|
+
const flow = await flows.findOne({ app, slug });
|
|
323
|
+
if (!flow)
|
|
324
|
+
throw new Error(`no flow '${slug}' for app '${app}'`);
|
|
325
|
+
if (flow.kind !== 'recording')
|
|
326
|
+
throw new Error(`'${slug}' is a segment — add the steps to the flow it was cut from (${flow.from?.flow})`);
|
|
327
|
+
if (!adds.length)
|
|
328
|
+
throw new Error('nothing to add');
|
|
329
|
+
const { steps: inserts, problems } = checkAdditions(flow, adds);
|
|
330
|
+
if (problems.length)
|
|
331
|
+
throw new Error(`nothing changed — fix these and send it again:\n- ${problems.join('\n- ')}`);
|
|
332
|
+
// Last first, so each index still means the step it meant.
|
|
333
|
+
const sorted = [...inserts].sort((a, b) => b.before - a.before);
|
|
334
|
+
const steps = [...flow.steps];
|
|
335
|
+
for (const { before, step } of sorted)
|
|
336
|
+
steps.splice(before, 0, step);
|
|
337
|
+
const why = flowDestructiveReason(steps);
|
|
338
|
+
const now = new Date();
|
|
339
|
+
await flows.updateOne({ _id: flow._id }, {
|
|
340
|
+
$set: {
|
|
341
|
+
steps, proven: false, unprovenBecause: `edited: ${inserts.length} step(s) added — the next passing run proves it`,
|
|
342
|
+
destructive: Boolean(why), ...(why ? { destructiveBecause: why } : {}), updatedAt: now,
|
|
343
|
+
},
|
|
344
|
+
$unset: { provenUpTo: '', ...(why ? {} : { destructiveBecause: '' }) },
|
|
345
|
+
});
|
|
346
|
+
// A segment AFTER an insertion moves along; one an insertion lands INSIDE
|
|
347
|
+
// gets the step too, and must be proven again like its parent.
|
|
348
|
+
for (const seg of await flows.find({ app, kind: 'segment', 'from.flow': slug }).toArray()) {
|
|
349
|
+
let [start, end] = seg.from.steps;
|
|
350
|
+
const segSteps = [...seg.steps];
|
|
351
|
+
let changed = false;
|
|
352
|
+
for (const { before, step } of sorted) {
|
|
353
|
+
if (before <= start) {
|
|
354
|
+
start++;
|
|
355
|
+
end++;
|
|
356
|
+
}
|
|
357
|
+
else if (before < end) {
|
|
358
|
+
segSteps.splice(before - start, 0, step);
|
|
359
|
+
end++;
|
|
360
|
+
changed = true;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
await flows.updateOne({ _id: seg._id }, {
|
|
364
|
+
$set: {
|
|
365
|
+
'from.steps': [start, end], steps: segSteps, updatedAt: now,
|
|
366
|
+
...(changed ? { proven: false, unprovenBecause: `its flow '${slug}' was edited — the next passing run proves it` } : {}),
|
|
367
|
+
},
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
return (await flows.findOne({ _id: flow._id }));
|
|
371
|
+
}
|
package/dist/memory/recall.d.ts
CHANGED
|
@@ -24,6 +24,11 @@ export interface FlowMatch {
|
|
|
24
24
|
proven: boolean;
|
|
25
25
|
/** Why it's unproven, when it is. */
|
|
26
26
|
unprovenBecause?: string;
|
|
27
|
+
/** Proven only up to this step, its commit: found ready, never pressed. */
|
|
28
|
+
provenUpTo?: number;
|
|
29
|
+
/** App states it needs first, and ones it makes true. */
|
|
30
|
+
requires?: string[];
|
|
31
|
+
establishes?: string[];
|
|
27
32
|
score: number;
|
|
28
33
|
destructive: boolean;
|
|
29
34
|
requiresSession: boolean;
|
|
@@ -105,7 +110,11 @@ export declare function judge(scores: number[], rule: {
|
|
|
105
110
|
};
|
|
106
111
|
/** Share of the goal's words that appear in the flow's name, slug or intent. */
|
|
107
112
|
export declare function wordScore(goal: string, flow: Pick<Flow, 'slug' | 'title' | 'intent'>): number;
|
|
108
|
-
/**
|
|
113
|
+
/**
|
|
114
|
+
* Highest score first; on a tie, a proven flow ahead of an unproven one, then
|
|
115
|
+
* one a person recorded ahead of one an agent made — a person's recording is
|
|
116
|
+
* the better word on how the app is meant to be used.
|
|
117
|
+
*/
|
|
109
118
|
export declare function rank(matches: FlowMatch[]): FlowMatch[];
|
|
110
119
|
/**
|
|
111
120
|
* `withSteps`: when the verdict is known, also return the best flow's steps and
|
package/dist/memory/recall.js
CHANGED
|
@@ -17,6 +17,7 @@
|
|
|
17
17
|
import { collections, vectorSearch } from '../store/db.js';
|
|
18
18
|
import { embed, embedderConfig } from '../store/embed.js';
|
|
19
19
|
import { valuesFromEnv, valueEnvNames } from '../store/settings.js';
|
|
20
|
+
import { valueRefsOf } from '../core/recording.js';
|
|
20
21
|
/**
|
|
21
22
|
* When a match by MEANING is good enough to act on. Calibrated 2026-11-18 on
|
|
22
23
|
* a real 28-flow corpus with voyage-4-lite (15 known goals, 14 plausible
|
|
@@ -69,14 +70,20 @@ export function wordScore(goal, flow) {
|
|
|
69
70
|
}
|
|
70
71
|
const toMatch = (f, score) => ({
|
|
71
72
|
slug: f.slug, title: f.title, kind: f.kind, madeBy: f.madeBy ?? 'user', proven: f.proven !== false,
|
|
72
|
-
...(f.proven === false && f.unprovenBecause ? { unprovenBecause: f.unprovenBecause } : {}),
|
|
73
|
+
...(f.proven === false && f.unprovenBecause ? { unprovenBecause: f.unprovenBecause } : {}),
|
|
74
|
+
...(f.provenUpTo !== undefined ? { provenUpTo: f.provenUpTo } : {}),
|
|
75
|
+
...(f.requires?.length ? { requires: f.requires } : {}), ...(f.establishes?.length ? { establishes: f.establishes } : {}), score,
|
|
73
76
|
destructive: f.destructive, requiresSession: f.requiresSession,
|
|
74
77
|
});
|
|
75
78
|
/** Scores this close are a tie. */
|
|
76
79
|
const TIE = 0.005;
|
|
77
|
-
/**
|
|
80
|
+
/**
|
|
81
|
+
* Highest score first; on a tie, a proven flow ahead of an unproven one, then
|
|
82
|
+
* one a person recorded ahead of one an agent made — a person's recording is
|
|
83
|
+
* the better word on how the app is meant to be used.
|
|
84
|
+
*/
|
|
78
85
|
export function rank(matches) {
|
|
79
|
-
return [...matches].sort((a, b) => (Math.abs(a.score - b.score) <= TIE ? Number(b.proven) - Number(a.proven) || b.score - a.score : b.score - a.score));
|
|
86
|
+
return [...matches].sort((a, b) => (Math.abs(a.score - b.score) <= TIE ? Number(b.proven) - Number(a.proven) || Number(b.madeBy === 'user') - Number(a.madeBy === 'user') || b.score - a.score : b.score - a.score));
|
|
80
87
|
}
|
|
81
88
|
/** The verdict's reason, plus a warning when the flow it picked may not work. */
|
|
82
89
|
const withProven = (why, best) => best && !best.proven ? `${why} — but '${best.slug}' is unproven (${best.unprovenBecause ?? 'no passing run yet'}), so it may not work; a passing run proves it` : why;
|
|
@@ -98,7 +105,7 @@ async function plan(app, slug) {
|
|
|
98
105
|
...(s.valueRef ? { placeholder: s.valueRef } : s.value !== undefined ? { value: s.value } : s.action === 'goto' ? { value: s.url } : {}),
|
|
99
106
|
};
|
|
100
107
|
});
|
|
101
|
-
const refs =
|
|
108
|
+
const refs = valueRefsOf(flow.steps);
|
|
102
109
|
const found = valuesFromEnv(refs, app);
|
|
103
110
|
const needs = refs.map((placeholder) => ({ placeholder, readFrom: valueEnvNames(placeholder, app), set: placeholder in found }));
|
|
104
111
|
return { steps, ...(needs.length ? { needs } : {}) };
|
|
@@ -134,7 +141,7 @@ export async function recall(app, goal, opts = {}) {
|
|
|
134
141
|
};
|
|
135
142
|
}
|
|
136
143
|
// 3. By words, with no model. Corpora are small, so scoring every flow is fine.
|
|
137
|
-
const all = await c.flows.find({ app }, { projection: { slug: 1, title: 1, intent: 1, kind: 1, madeBy: 1, proven: 1, unprovenBecause: 1, destructive: 1, requiresSession: 1 } }).toArray();
|
|
144
|
+
const all = await c.flows.find({ app }, { projection: { slug: 1, title: 1, intent: 1, kind: 1, madeBy: 1, proven: 1, unprovenBecause: 1, provenUpTo: 1, requires: 1, establishes: 1, destructive: 1, requiresSession: 1 } }).toArray();
|
|
138
145
|
const matches = all
|
|
139
146
|
.map((f) => toMatch(f, wordScore(goal, f)))
|
|
140
147
|
.filter((m) => m.score > 0);
|
|
@@ -9,16 +9,22 @@ import { collections } from '../store/db.js';
|
|
|
9
9
|
export async function vocabulary(app) {
|
|
10
10
|
const { flows, notes } = await collections();
|
|
11
11
|
const rows = await flows
|
|
12
|
-
.find({ app }, { projection: { slug: 1, title: 1, intent: 1, kind: 1, preconditions: 1, outcome: 1, steps: 1 } })
|
|
12
|
+
.find({ app }, { projection: { slug: 1, title: 1, intent: 1, kind: 1, preconditions: 1, outcome: 1, steps: 1, requires: 1, establishes: 1 } })
|
|
13
13
|
.sort({ kind: -1, slug: 1 })
|
|
14
14
|
.toArray();
|
|
15
15
|
const facts = await notes.find({ app, kind: 'fact' }, { projection: { text: 1 } }).toArray();
|
|
16
|
+
const stateOf = (f) => ({
|
|
17
|
+
...(f.requires?.length ? { requires: f.requires } : {}),
|
|
18
|
+
...(f.establishes?.length ? { establishes: f.establishes } : {}),
|
|
19
|
+
});
|
|
20
|
+
const states = [...new Set(rows.flatMap((f) => [...(f.requires ?? []), ...(f.establishes ?? [])]))].sort();
|
|
16
21
|
return {
|
|
17
22
|
segments: rows.filter((f) => f.kind === 'segment').map((f) => ({
|
|
18
23
|
slug: f.slug, title: f.title, intent: f.intent, steps: f.steps.length,
|
|
19
|
-
preconditions: f.preconditions, outcome: f.outcome || null,
|
|
24
|
+
preconditions: f.preconditions, outcome: f.outcome || null, ...stateOf(f),
|
|
20
25
|
})),
|
|
21
|
-
flows: rows.filter((f) => f.kind === 'recording').map((f) => ({ slug: f.slug, title: f.title, intent: f.intent })),
|
|
26
|
+
flows: rows.filter((f) => f.kind === 'recording').map((f) => ({ slug: f.slug, title: f.title, intent: f.intent, ...stateOf(f) })),
|
|
27
|
+
...(states.length ? { states } : {}),
|
|
22
28
|
facts: facts.map((n) => n.text),
|
|
23
29
|
};
|
|
24
30
|
}
|
package/dist/plan/planner.d.ts
CHANGED
|
@@ -13,9 +13,11 @@
|
|
|
13
13
|
* Questions:
|
|
14
14
|
* decompose { subGoals: ["log in as a member", "open the cart"] }
|
|
15
15
|
* seam { steps: [{ action: "click", role: "link", name: "Cart" }] } — or [] if unknown
|
|
16
|
+
* state { use: "buy-a-bundle" } — run that flow first — or { holds: true }
|
|
16
17
|
*/
|
|
17
18
|
import type { Run, Step } from '../store/types.js';
|
|
18
19
|
import type { RawRecording } from '../core/recording.js';
|
|
20
|
+
import { type ExecuteOptions } from '../flows/execute.js';
|
|
19
21
|
export interface PlanRequest {
|
|
20
22
|
app: string;
|
|
21
23
|
goal: string;
|
|
@@ -41,6 +43,11 @@ export type PlanState = {
|
|
|
41
43
|
before: string;
|
|
42
44
|
how: string;
|
|
43
45
|
}[];
|
|
46
|
+
/** App states the plan needed, and how each was made true. */
|
|
47
|
+
states?: {
|
|
48
|
+
state: string;
|
|
49
|
+
how: string;
|
|
50
|
+
}[];
|
|
44
51
|
dryRun: boolean;
|
|
45
52
|
};
|
|
46
53
|
export declare function start(req: PlanRequest): Promise<PlanState>;
|
|
@@ -58,10 +65,7 @@ export declare function recordingForPlan(runId: string): Promise<{
|
|
|
58
65
|
* Run a planned run: one recording for the whole plan, with lessons, and the
|
|
59
66
|
* outcome written onto the same run document.
|
|
60
67
|
*/
|
|
61
|
-
export declare function runPlan(runId: string, opts?: {
|
|
62
|
-
values?: Record<string, string>;
|
|
63
|
-
headed?: boolean;
|
|
64
|
-
}): Promise<{
|
|
68
|
+
export declare function runPlan(runId: string, opts?: Pick<ExecuteOptions, 'values' | 'headed' | 'onHuman' | 'onStuck'>): Promise<{
|
|
65
69
|
executed: import("../flows/execute.js").Executed;
|
|
66
70
|
recorded: import("../flows/runs.js").RecordedRun;
|
|
67
71
|
plan: string[];
|
package/dist/plan/planner.js
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
* Questions:
|
|
14
14
|
* decompose { subGoals: ["log in as a member", "open the cart"] }
|
|
15
15
|
* seam { steps: [{ action: "click", role: "link", name: "Cart" }] } — or [] if unknown
|
|
16
|
+
* state { use: "buy-a-bundle" } — run that flow first — or { holds: true }
|
|
16
17
|
*/
|
|
17
18
|
import { ObjectId } from 'mongodb';
|
|
18
19
|
import { collections } from '../store/db.js';
|
|
@@ -28,7 +29,30 @@ const DECOMPOSE_HOW = [
|
|
|
28
29
|
'Phrase each sub-goal in the words of a flow listed below — near-verbatim where one does the thing. Each sub-goal is a search.',
|
|
29
30
|
'Include prerequisites the goal leaves implicit (e.g. log in first, if the next flow needs it).',
|
|
30
31
|
'If one recorded flow already covers the whole goal, one sub-goal naming it beats several naming its parts.',
|
|
32
|
+
'Answer { "subGoals": ["…", "…"] }, and tell the user what they are.',
|
|
31
33
|
].join(' ');
|
|
34
|
+
const STATE_HOW = [
|
|
35
|
+
'The flow in neededBy only works when this app state is already true.',
|
|
36
|
+
'Answer { "use": "<slug>" } to run a flow from establishedBy first, or { "holds": true } if it is already true for the account this run uses.',
|
|
37
|
+
'Ask the user if you don\'t know: "holds" on a guess sends the run to a page it doesn\'t expect. Answers last for this run only — the account can change.',
|
|
38
|
+
].join(' ');
|
|
39
|
+
/**
|
|
40
|
+
* The first state a flow in the chain needs that nothing before it makes
|
|
41
|
+
* true, and that hasn't been declared already true.
|
|
42
|
+
*/
|
|
43
|
+
function unmet(chain, states = {}) {
|
|
44
|
+
const made = new Set();
|
|
45
|
+
for (const [at, flow] of chain.entries()) {
|
|
46
|
+
for (const state of flow.requires ?? []) {
|
|
47
|
+
const said = states[state];
|
|
48
|
+
if (!made.has(state) && !(said && 'holds' in said))
|
|
49
|
+
return { state, at, neededBy: flow.slug };
|
|
50
|
+
}
|
|
51
|
+
for (const state of flow.establishes ?? [])
|
|
52
|
+
made.add(state);
|
|
53
|
+
}
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
32
56
|
const SEAM_HOW = [
|
|
33
57
|
'How do you get from where the first flow ends to where the next begins?',
|
|
34
58
|
'Answer { "steps": [...] } with one click ({action:"click",role,name}) or a goto ({action:"goto",url}).',
|
|
@@ -67,6 +91,22 @@ export async function answer(runId, reply) {
|
|
|
67
91
|
}
|
|
68
92
|
planning.subGoals = subGoals.map((g) => g.trim());
|
|
69
93
|
}
|
|
94
|
+
else if (q.kind === 'state') {
|
|
95
|
+
const state = q.state;
|
|
96
|
+
const r = reply;
|
|
97
|
+
if (r?.holds === true) {
|
|
98
|
+
planning.states = { ...planning.states, [state]: { holds: true } };
|
|
99
|
+
}
|
|
100
|
+
else if (typeof r?.use === 'string') {
|
|
101
|
+
if (!(await flows.findOne({ app: run.app, slug: r.use, establishes: state }))) {
|
|
102
|
+
throw new Error(`"${r.use}" isn't a flow that establishes "${state}" — pick one from establishedBy, or answer { "holds": true }`);
|
|
103
|
+
}
|
|
104
|
+
planning.states = { ...planning.states, [state]: { use: r.use } };
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
throw new Error('answer { "use": "<slug>" } (a flow from establishedBy, run first) or { "holds": true } (already true for this account)');
|
|
108
|
+
}
|
|
109
|
+
}
|
|
70
110
|
else if (q.kind === 'seam') {
|
|
71
111
|
const i = q.before;
|
|
72
112
|
const [from, to] = await Promise.all([
|
|
@@ -122,10 +162,40 @@ async function advance(run) {
|
|
|
122
162
|
}
|
|
123
163
|
planning.bound = bound;
|
|
124
164
|
}
|
|
125
|
-
const
|
|
126
|
-
|
|
165
|
+
const load = async () => {
|
|
166
|
+
const found = await Promise.all(planning.bound.map((slug) => flows.findOne({ app: run.app, slug })));
|
|
167
|
+
return found.some((f) => !f) ? undefined : found;
|
|
168
|
+
};
|
|
169
|
+
let chain = await load();
|
|
170
|
+
if (!chain)
|
|
127
171
|
return block(run, 'a bound flow no longer exists — plan again');
|
|
128
|
-
|
|
172
|
+
// 2b. App state. A flow that needs "member-has-active-bundle" gets a flow
|
|
173
|
+
// that makes it true run before it — the one the agent chose — or the
|
|
174
|
+
// agent's word that it already holds. Never guessed: the wrong choice either
|
|
175
|
+
// buys something nobody asked for, or lands on a page the flow doesn't expect.
|
|
176
|
+
for (let added = 0;; added++) {
|
|
177
|
+
const need = unmet(chain, planning.states);
|
|
178
|
+
if (!need)
|
|
179
|
+
break;
|
|
180
|
+
if (added >= 8)
|
|
181
|
+
return block(run, `satisfying app states keeps adding flows — check the requires/establishes names around "${need.state}" for a loop`);
|
|
182
|
+
const chosen = planning.states?.[need.state];
|
|
183
|
+
if (chosen && 'use' in chosen) {
|
|
184
|
+
planning.bound.splice(need.at, 0, chosen.use);
|
|
185
|
+
chain = await load();
|
|
186
|
+
if (!chain)
|
|
187
|
+
return block(run, `"${chosen.use}" no longer exists — plan again`);
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
const makers = await flows
|
|
191
|
+
.find({ app: run.app, establishes: need.state }, { projection: { slug: 1, title: 1, destructive: 1, proven: 1 } })
|
|
192
|
+
.toArray();
|
|
193
|
+
return ask(run, {
|
|
194
|
+
kind: 'state', state: need.state, neededBy: need.neededBy,
|
|
195
|
+
establishedBy: makers.map((f) => ({ slug: f.slug, title: f.title, ...(f.destructive ? { destructive: true } : {}), ...(f.proven === false ? { unproven: true } : {}) })),
|
|
196
|
+
how: STATE_HOW,
|
|
197
|
+
});
|
|
198
|
+
}
|
|
129
199
|
// 3. Safety: refuse anything that commits something real, unless allowed.
|
|
130
200
|
if (!planning.allowPurchases) {
|
|
131
201
|
const risky = chain.find((f) => f.destructive);
|
|
@@ -162,6 +232,9 @@ async function advance(run) {
|
|
|
162
232
|
runId: run._id.toHexString(),
|
|
163
233
|
plan: planning.bound,
|
|
164
234
|
seams: Object.entries(planning.seams).map(([i, s]) => ({ before: planning.bound[Number(i)], how: s.how })),
|
|
235
|
+
...(planning.states && Object.keys(planning.states).length
|
|
236
|
+
? { states: Object.entries(planning.states).map(([state, h]) => ({ state, how: 'holds' in h ? 'already true, the agent said' : `made true by running ${h.use} first` })) }
|
|
237
|
+
: {}),
|
|
165
238
|
dryRun: Boolean(planning.dryRun),
|
|
166
239
|
};
|
|
167
240
|
}
|
|
@@ -204,7 +277,7 @@ export async function runPlan(runId, opts = {}) {
|
|
|
204
277
|
const executed = await execute(recording, { ...opts, useLessons: true });
|
|
205
278
|
const recorded = await recordRun({
|
|
206
279
|
app: run.app, flow: run.plan.join('+'), plan: run.plan, goal: run.goal, mode: 'run',
|
|
207
|
-
result: executed.result, steps, runId: run._id, ...(unproven ? { unproven: true } : {}),
|
|
280
|
+
result: executed.result, steps, runId: run._id, starts, ...(unproven ? { unproven: true } : {}),
|
|
208
281
|
});
|
|
209
282
|
// Each unproven flow in a plan that passed is proven now.
|
|
210
283
|
const nowProven = [];
|
package/dist/store/types.d.ts
CHANGED
|
@@ -58,12 +58,32 @@ export interface Flow {
|
|
|
58
58
|
proven?: boolean;
|
|
59
59
|
/** Why it's unproven, e.g. "saved without a replay". */
|
|
60
60
|
unprovenBecause?: string;
|
|
61
|
+
/**
|
|
62
|
+
* Proven only UP TO this step: the first that commits something real (a
|
|
63
|
+
* purchase, a submission) or that only a person can do. Every step before it replayed and passed, and its
|
|
64
|
+
* control was found ready — but it was never pressed, so nothing after it has
|
|
65
|
+
* run. Missing = proven all the way (or not at all: see `proven`). A full run
|
|
66
|
+
* that passes (with purchases allowed) clears it.
|
|
67
|
+
*/
|
|
68
|
+
provenUpTo?: number;
|
|
61
69
|
/** Segments only: the flow it was cut from, and which of its steps ([start, end)). */
|
|
62
70
|
from?: {
|
|
63
71
|
flow: string;
|
|
64
72
|
steps: [number, number];
|
|
65
73
|
};
|
|
66
74
|
preconditions: Precondition[];
|
|
75
|
+
/**
|
|
76
|
+
* App states this flow needs before it can run, e.g. "member-has-active-bundle".
|
|
77
|
+
* The page it expects depends on them — the same button leads somewhere else
|
|
78
|
+
* without. A plan satisfies each with an earlier flow that `establishes` it,
|
|
79
|
+
* or with the agent's word that it already holds.
|
|
80
|
+
*
|
|
81
|
+
* Names are kebab-case and belong to the app: reuse an existing one rather
|
|
82
|
+
* than coin a synonym, or the planner never connects the two.
|
|
83
|
+
*/
|
|
84
|
+
requires?: string[];
|
|
85
|
+
/** App states this flow makes true, e.g. buying a bundle establishes "member-has-active-bundle". */
|
|
86
|
+
establishes?: string[];
|
|
67
87
|
outcome: string;
|
|
68
88
|
/** True if running it commits something real (a purchase, a submission). */
|
|
69
89
|
destructive: boolean;
|
|
@@ -151,8 +171,12 @@ export interface Finding {
|
|
|
151
171
|
occurrences: number;
|
|
152
172
|
firstSeen: Date;
|
|
153
173
|
lastSeen: Date;
|
|
154
|
-
/**
|
|
155
|
-
|
|
174
|
+
/**
|
|
175
|
+
* open until someone triages it: a real bug (issue), a workaround (lesson),
|
|
176
|
+
* noise, or — for a changed path — expected: the app changed on purpose, and
|
|
177
|
+
* the new path is the normal one from now on.
|
|
178
|
+
*/
|
|
179
|
+
status: 'open' | 'issue' | 'lesson' | 'noise' | 'expected';
|
|
156
180
|
}
|
|
157
181
|
/**
|
|
158
182
|
* Which embedding model filled this database. Vectors from two models can't be
|
|
@@ -174,6 +198,20 @@ export interface Run {
|
|
|
174
198
|
* attributed: an agent reached the goal by other means and reported it.
|
|
175
199
|
*/
|
|
176
200
|
mode: 'run' | 'replay' | 'attributed';
|
|
201
|
+
/**
|
|
202
|
+
* The run stopped, as asked, before this step — the flow's commit — rather
|
|
203
|
+
* than doing it. Its path is partial, so it is never drift history.
|
|
204
|
+
*/
|
|
205
|
+
stoppedBefore?: number;
|
|
206
|
+
/**
|
|
207
|
+
* false: it passed, but its path changed (new pages, or a step landing
|
|
208
|
+
* somewhere unexpected), and nobody has said that's right yet. Kept out of
|
|
209
|
+
* drift history until its finding is triaged `expected` — otherwise a wrong
|
|
210
|
+
* ending that passes becomes "normal" after a few runs. Missing = accepted.
|
|
211
|
+
*/
|
|
212
|
+
accepted?: false;
|
|
213
|
+
/** Where each flow of `plan` starts in `steps`, so an accepted path can update each flow. */
|
|
214
|
+
starts?: number[];
|
|
177
215
|
/**
|
|
178
216
|
* waiting: planning paused on a question for the agent (`question` says what).
|
|
179
217
|
* planned: a dry run — the plan is complete, nothing ran.
|
|
@@ -212,6 +250,12 @@ export interface Run {
|
|
|
212
250
|
steps: Step[];
|
|
213
251
|
how: string;
|
|
214
252
|
}>;
|
|
253
|
+
/** How each required state was satisfied: by running a flow first, or because it already holds. */
|
|
254
|
+
states?: Record<string, {
|
|
255
|
+
use: string;
|
|
256
|
+
} | {
|
|
257
|
+
holds: true;
|
|
258
|
+
}>;
|
|
215
259
|
dryRun?: boolean;
|
|
216
260
|
allowPurchases?: boolean;
|
|
217
261
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jeffawe/understudy",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.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",
|