@jeffawe/understudy 0.2.3 → 0.4.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 +69 -19
- 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 +70 -1
- package/dist/core/replay.js +251 -12
- package/dist/entry/cli.js +187 -11
- package/dist/entry/mcp.d.ts +2 -1
- package/dist/entry/mcp.js +187 -33
- 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 +15 -3
- 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/calibrate.d.ts +114 -0
- package/dist/memory/calibrate.js +258 -0
- package/dist/memory/recall.d.ts +42 -25
- package/dist/memory/recall.js +61 -21
- 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/reembed.js +18 -7
- package/dist/store/types.d.ts +78 -2
- package/package.json +1 -1
package/dist/flows/execute.js
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
* caller decides how to show it.
|
|
11
11
|
*/
|
|
12
12
|
import { loadSession, forgetSession, loadSessionById, forgetSessionById } from '../core/auth-cache.js';
|
|
13
|
+
import { valueRefsOf } from '../core/recording.js';
|
|
13
14
|
import { replay } from '../core/replay.js';
|
|
14
15
|
import { foldLessons, lessonsFor } from '../memory/notes.js';
|
|
15
16
|
import { valuesFromEnv, valueEnvNames, reloadEnvFiles, writableEnvFile } from '../store/settings.js';
|
|
@@ -34,7 +35,7 @@ export class MissingValuesError extends Error {
|
|
|
34
35
|
/** The login values this recording needs that neither `given` nor the environment supply. */
|
|
35
36
|
export function missingValuesFor(recording, given = {}) {
|
|
36
37
|
reloadEnvFiles();
|
|
37
|
-
const refs = new Set(recording.events
|
|
38
|
+
const refs = new Set(valueRefsOf(recording.events));
|
|
38
39
|
const found = { ...valuesFromEnv(refs, recording.appSlug), ...given };
|
|
39
40
|
return [...refs].filter((r) => !(r in found)).map((r) => ({ placeholder: r, setOneOf: valueEnvNames(r, recording.appSlug) }));
|
|
40
41
|
}
|
|
@@ -46,7 +47,7 @@ export async function execute(recording, opts = {}) {
|
|
|
46
47
|
// Login values: given explicitly, else from UNDERSTUDY_<REF> in the environment
|
|
47
48
|
// (env files re-read, so one just added is seen).
|
|
48
49
|
reloadEnvFiles();
|
|
49
|
-
const refs = new Set(recording.events
|
|
50
|
+
const refs = new Set(valueRefsOf(recording.events));
|
|
50
51
|
const values = { ...valuesFromEnv(refs, recording.appSlug), ...(opts.values ?? {}) };
|
|
51
52
|
const missingValues = [...refs].filter((r) => !(r in values));
|
|
52
53
|
// Checked BEFORE a browser opens: a run that reached the password step
|
|
@@ -73,11 +74,26 @@ export async function execute(recording, opts = {}) {
|
|
|
73
74
|
sessionRestoredFrom = cached.savedAt;
|
|
74
75
|
}
|
|
75
76
|
const app = recording.appSlug;
|
|
77
|
+
// A person's step needs a browser they can see — unless told otherwise (CI).
|
|
78
|
+
const forPerson = Boolean(opts.onHuman) && recording.events.some((e) => e.action === 'human') && process.env.UNDERSTUDY_HEADLESS !== '1';
|
|
79
|
+
const headed = Boolean(opts.headed) || forPerson;
|
|
80
|
+
const onStuck = opts.onStuck;
|
|
76
81
|
const result = await replay(recording, {
|
|
77
82
|
values,
|
|
78
83
|
...(storageState ? { storageState } : {}),
|
|
79
|
-
...(
|
|
84
|
+
...(headed ? { headless: false } : {}),
|
|
85
|
+
...(opts.onHuman ? { onHuman: opts.onHuman } : {}),
|
|
86
|
+
...(opts.endChecks ? { endChecks: true } : {}),
|
|
87
|
+
...(onStuck && headed
|
|
88
|
+
? {
|
|
89
|
+
onHandoff: async (r) => {
|
|
90
|
+
const said = await onStuck({ seq: r.seq, action: r.failed?.action ?? 'step', ...(r.failed?.target ? { target: r.failed.target } : {}), error: r.reason, url: r.url });
|
|
91
|
+
return said === 'done' ? { action: 'continue' } : { action: 'abort', reason: 'declined at the handoff' };
|
|
92
|
+
},
|
|
93
|
+
}
|
|
94
|
+
: {}),
|
|
80
95
|
...(opts.useLessons ? { lessonsFor: (ctx) => lessonsFor(app, ctx) } : {}),
|
|
96
|
+
...(opts.stopBefore !== undefined ? { stopBefore: opts.stopBefore } : {}),
|
|
81
97
|
});
|
|
82
98
|
const out = { result, missingValues, ...(sessionRestoredFrom ? { sessionRestoredFrom } : {}) };
|
|
83
99
|
// Step 0 of a late-armed recording carries the fingerprint of where it was
|
package/dist/flows/findings.d.ts
CHANGED
|
@@ -32,11 +32,13 @@ export declare function listFindings(coll: Collection<Finding>, app: string, opt
|
|
|
32
32
|
all?: boolean;
|
|
33
33
|
limit?: number;
|
|
34
34
|
}): Promise<Finding[]>;
|
|
35
|
-
export type Verdict = 'issue' | 'lesson' | 'noise';
|
|
35
|
+
export type Verdict = 'issue' | 'lesson' | 'noise' | 'expected';
|
|
36
36
|
/**
|
|
37
37
|
* Route open findings. issue: the app is wrong and someone should fix it.
|
|
38
38
|
* lesson: accepted — the agent works around it (pass the lesson to store).
|
|
39
39
|
* noise: not a problem (third-party telemetry, framework warnings).
|
|
40
|
+
* expected: a changed path the app made on purpose — flow_drift only. The
|
|
41
|
+
* caller then accepts the runs that took it (runs.ts, acceptPaths).
|
|
40
42
|
* Returns what couldn't be routed instead of throwing, so one bad item
|
|
41
43
|
* doesn't lose the rest.
|
|
42
44
|
*/
|
|
@@ -46,4 +48,5 @@ export declare function triage(coll: Collection<Finding>, app: string, items: {
|
|
|
46
48
|
}[]): Promise<{
|
|
47
49
|
routed: number;
|
|
48
50
|
problems: string[];
|
|
51
|
+
expected: string[];
|
|
49
52
|
}>;
|
package/dist/flows/findings.js
CHANGED
|
@@ -138,22 +138,34 @@ export async function listFindings(coll, app, opts = {}) {
|
|
|
138
138
|
* Route open findings. issue: the app is wrong and someone should fix it.
|
|
139
139
|
* lesson: accepted — the agent works around it (pass the lesson to store).
|
|
140
140
|
* noise: not a problem (third-party telemetry, framework warnings).
|
|
141
|
+
* expected: a changed path the app made on purpose — flow_drift only. The
|
|
142
|
+
* caller then accepts the runs that took it (runs.ts, acceptPaths).
|
|
141
143
|
* Returns what couldn't be routed instead of throwing, so one bad item
|
|
142
144
|
* doesn't lose the rest.
|
|
143
145
|
*/
|
|
144
146
|
export async function triage(coll, app, items) {
|
|
145
147
|
const problems = [];
|
|
148
|
+
const expected = [];
|
|
146
149
|
let routed = 0;
|
|
147
150
|
for (const [i, item] of items.entries()) {
|
|
148
|
-
if (!['issue', 'lesson', 'noise'].includes(item?.verdict)) {
|
|
149
|
-
problems.push(`triage[${i}].verdict must be issue, lesson or
|
|
151
|
+
if (!['issue', 'lesson', 'noise', 'expected'].includes(item?.verdict)) {
|
|
152
|
+
problems.push(`triage[${i}].verdict must be issue, lesson, noise or expected`);
|
|
150
153
|
continue;
|
|
151
154
|
}
|
|
155
|
+
if (item.verdict === 'expected') {
|
|
156
|
+
const f = await coll.findOne({ app, fingerprint: item.fingerprint }, { projection: { kind: 1 } });
|
|
157
|
+
if (f && f.kind !== 'flow_drift') {
|
|
158
|
+
problems.push(`triage[${i}]: expected is for a changed path (flow_drift); this is ${f.kind} — use issue, lesson or noise`);
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
if (f)
|
|
162
|
+
expected.push(item.fingerprint);
|
|
163
|
+
}
|
|
152
164
|
const { matchedCount } = await coll.updateOne({ app, fingerprint: item.fingerprint }, { $set: { status: item.verdict } });
|
|
153
165
|
if (matchedCount)
|
|
154
166
|
routed++;
|
|
155
167
|
else
|
|
156
168
|
problems.push(`triage[${i}]: no finding with fingerprint ${item.fingerprint}`);
|
|
157
169
|
}
|
|
158
|
-
return { routed, problems };
|
|
170
|
+
return { routed, problems, expected };
|
|
159
171
|
}
|
package/dist/flows/runs.d.ts
CHANGED
|
@@ -17,6 +17,8 @@ export interface RecordedRun {
|
|
|
17
17
|
runId: ObjectId;
|
|
18
18
|
drift: Drift;
|
|
19
19
|
findings: FindingDraft[];
|
|
20
|
+
/** It passed on a changed path: kept out of history until that's accepted. */
|
|
21
|
+
pending?: true;
|
|
20
22
|
}
|
|
21
23
|
export declare function recordRun(opts: {
|
|
22
24
|
app: string;
|
|
@@ -39,4 +41,15 @@ export declare function recordRun(opts: {
|
|
|
39
41
|
/** Fill in this existing run (one that was planned first) instead of adding a new one. */
|
|
40
42
|
runId?: ObjectId;
|
|
41
43
|
startedAt?: Date;
|
|
44
|
+
/** Where each flow of the plan starts in the steps. Defaults to [0]. */
|
|
45
|
+
starts?: number[];
|
|
42
46
|
}): Promise<RecordedRun>;
|
|
47
|
+
/**
|
|
48
|
+
* A changed path was triaged `expected`: the runs that took it join the
|
|
49
|
+
* history, and the newest one's pages become what each of its flows expects
|
|
50
|
+
* step by step — so the change is accepted once, not flagged on every run.
|
|
51
|
+
*/
|
|
52
|
+
export declare function acceptPaths(app: string, fingerprints: string[]): Promise<{
|
|
53
|
+
runs: number;
|
|
54
|
+
flows: string[];
|
|
55
|
+
}>;
|
package/dist/flows/runs.js
CHANGED
|
@@ -24,15 +24,18 @@ export async function recordRun(opts) {
|
|
|
24
24
|
// 1. Drift, against the most recent passed runs of this flow — however it
|
|
25
25
|
// was started, it walked the same steps.
|
|
26
26
|
const history = await c.runs
|
|
27
|
-
.find({ app, plan, mode: { $in: ['replay', 'run'] }, status: 'passed', ...(opts.runId ? { _id: { $ne: opts.runId } } : {}) }, { projection: { sigSequence: 1 } })
|
|
27
|
+
.find({ app, plan, mode: { $in: ['replay', 'run'] }, status: 'passed', stoppedBefore: { $exists: false }, accepted: { $ne: false }, ...(opts.runId ? { _id: { $ne: opts.runId } } : {}) }, { projection: { sigSequence: 1 } })
|
|
28
28
|
.sort({ startedAt: -1 })
|
|
29
29
|
.limit(LOOKBACK)
|
|
30
30
|
.toArray();
|
|
31
31
|
// A failed run stops early; comparing its short path would report every
|
|
32
32
|
// page it never reached as "gone", which is noise, not drift.
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
33
|
+
// A run that stopped before its commit step is just as short, on purpose.
|
|
34
|
+
const drift = !result.ok
|
|
35
|
+
? { ...compareToHistory([], []), firstRun: false, notCompared: 'the run failed, so its path is incomplete' }
|
|
36
|
+
: result.stoppedBefore !== undefined
|
|
37
|
+
? { ...compareToHistory([], []), firstRun: false, notCompared: `it stopped before step ${result.stoppedBefore}, its commit, so its path is incomplete` }
|
|
38
|
+
: compareToHistory(result.sigSequence, history.map((h) => h.sigSequence));
|
|
36
39
|
// 2. Findings.
|
|
37
40
|
const name = plan.join(' + ');
|
|
38
41
|
const drafts = extractFindings(result, name);
|
|
@@ -59,7 +62,9 @@ export async function recordRun(opts) {
|
|
|
59
62
|
}
|
|
60
63
|
prev = sig;
|
|
61
64
|
}
|
|
62
|
-
// 4. The run.
|
|
65
|
+
// 4. The run. One whose path changed waits to be accepted before it
|
|
66
|
+
// counts as history — see Run.accepted.
|
|
67
|
+
const changedPath = result.ok && !drift.firstRun && (drift.changed || result.steps.some((s) => s.unexpectedPage));
|
|
63
68
|
const run = {
|
|
64
69
|
app,
|
|
65
70
|
goal: opts.goal ?? flow,
|
|
@@ -77,6 +82,9 @@ export async function recordRun(opts) {
|
|
|
77
82
|
};
|
|
78
83
|
}),
|
|
79
84
|
sigSequence: result.sigSequence,
|
|
85
|
+
...(result.stoppedBefore !== undefined ? { stoppedBefore: result.stoppedBefore } : {}),
|
|
86
|
+
...(changedPath ? { accepted: false } : {}),
|
|
87
|
+
starts: opts.starts ?? [0],
|
|
80
88
|
events: result.signals.slice(0, 200).map((s) => ({ ...s })),
|
|
81
89
|
findings: drafts.map((d) => d.fingerprint),
|
|
82
90
|
durationMs: result.durationMs,
|
|
@@ -86,8 +94,36 @@ export async function recordRun(opts) {
|
|
|
86
94
|
if (opts.runId) {
|
|
87
95
|
// A planned run: keep its question history and planning, add what happened.
|
|
88
96
|
await c.runs.updateOne({ _id: opts.runId }, { $set: run, $unset: { question: '' } });
|
|
89
|
-
return { runId: opts.runId, drift, findings: drafts };
|
|
97
|
+
return { runId: opts.runId, drift, findings: drafts, ...(changedPath ? { pending: true } : {}) };
|
|
90
98
|
}
|
|
91
99
|
const { insertedId } = await c.runs.insertOne(run);
|
|
92
|
-
return { runId: insertedId, drift, findings: drafts };
|
|
100
|
+
return { runId: insertedId, drift, findings: drafts, ...(changedPath ? { pending: true } : {}) };
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* A changed path was triaged `expected`: the runs that took it join the
|
|
104
|
+
* history, and the newest one's pages become what each of its flows expects
|
|
105
|
+
* step by step — so the change is accepted once, not flagged on every run.
|
|
106
|
+
*/
|
|
107
|
+
export async function acceptPaths(app, fingerprints) {
|
|
108
|
+
if (!fingerprints.length)
|
|
109
|
+
return { runs: 0, flows: [] };
|
|
110
|
+
const c = await collections();
|
|
111
|
+
const pending = await c.runs.find({ app, accepted: false, findings: { $in: fingerprints } }).sort({ startedAt: 1 }).toArray();
|
|
112
|
+
if (!pending.length)
|
|
113
|
+
return { runs: 0, flows: [] };
|
|
114
|
+
await c.runs.updateMany({ _id: { $in: pending.map((r) => r._id) } }, { $unset: { accepted: '' } });
|
|
115
|
+
const newest = pending.at(-1);
|
|
116
|
+
const updated = [];
|
|
117
|
+
for (const [i, slug] of newest.plan.entries()) {
|
|
118
|
+
const flow = await c.flows.findOne({ app, slug });
|
|
119
|
+
if (!flow)
|
|
120
|
+
continue;
|
|
121
|
+
const start = newest.starts?.[i] ?? 0;
|
|
122
|
+
const sigAt = new Map(newest.steps.filter((s) => s.sig).map((s) => [s.seq - start, s.sig]));
|
|
123
|
+
const steps = flow.steps.map((s, j) => (sigAt.has(j) ? { ...s, expectedSig: sigAt.get(j) } : s));
|
|
124
|
+
const last = sigAt.get(flow.steps.length - 1);
|
|
125
|
+
await c.flows.updateOne({ _id: flow._id }, { $set: { steps, ...(last ? { endState: last } : {}), updatedAt: new Date() } });
|
|
126
|
+
updated.push(slug);
|
|
127
|
+
}
|
|
128
|
+
return { runs: pending.length, flows: updated };
|
|
93
129
|
}
|
package/dist/flows/save.d.ts
CHANGED
|
@@ -11,7 +11,8 @@
|
|
|
11
11
|
import type { RawRecording } from '../core/recording.js';
|
|
12
12
|
import type { ReplayResult } from '../core/replay.js';
|
|
13
13
|
import type { Flow, Step } from '../store/types.js';
|
|
14
|
-
import { type
|
|
14
|
+
import { type CommitStep } from './destructive.js';
|
|
15
|
+
import { type Executed, type Proven } from './execute.js';
|
|
15
16
|
import { type RecordedRun } from './runs.js';
|
|
16
17
|
import { type Applied } from '../memory/placeholders.js';
|
|
17
18
|
/** "Log in as a member!" → "log-in-as-a-member" */
|
|
@@ -70,5 +71,45 @@ export declare function proveAndSave(recording: RawRecording, opts: ProveAndSave
|
|
|
70
71
|
* An unproven flow that just passed a run is proven now: mark it, and fill in
|
|
71
72
|
* what its missing replay would have recorded — the page each step lands on,
|
|
72
73
|
* and where it starts and ends. `offset` skips steps the run added in front.
|
|
74
|
+
*
|
|
75
|
+
* A run that stopped before the flow's commit step proves it that far
|
|
76
|
+
* (`provenUpTo`); a full run that passes proves the rest, and clears it.
|
|
73
77
|
*/
|
|
74
78
|
export declare function proveByRun(app: string, slug: string, result: ReplayResult, offset?: number): Promise<boolean>;
|
|
79
|
+
export interface ProvedFlow extends Executed {
|
|
80
|
+
flow: Flow;
|
|
81
|
+
/** The commit step it stopped before, when the flow has one. */
|
|
82
|
+
commit?: CommitStep;
|
|
83
|
+
run: RecordedRun;
|
|
84
|
+
/** True when this run changed what the flow is proven to do. */
|
|
85
|
+
newlyProven: boolean;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Prove a saved flow where it stands — the way out for one kept with
|
|
89
|
+
* `verify: false` because it ends in a real purchase. A flow with a commit step
|
|
90
|
+
* is replayed up to it, and the commit's control is checked but never pressed;
|
|
91
|
+
* any other flow is simply run. Either way the run is recorded.
|
|
92
|
+
*/
|
|
93
|
+
export declare function proveFlow(app: string, slug: string, opts?: {
|
|
94
|
+
values?: Record<string, string>;
|
|
95
|
+
headed?: boolean;
|
|
96
|
+
}): Promise<ProvedFlow>;
|
|
97
|
+
export interface StepToAdd {
|
|
98
|
+
/** Goes in front of the step at this index; the flow's length appends. */
|
|
99
|
+
before: number;
|
|
100
|
+
/** As stored: { action, value, hints? }. */
|
|
101
|
+
step: Record<string, unknown>;
|
|
102
|
+
}
|
|
103
|
+
/** Every problem with these additions at once, or the steps to insert. */
|
|
104
|
+
export declare function checkAdditions(flow: Pick<Flow, 'steps' | 'startUrl'>, adds: StepToAdd[]): {
|
|
105
|
+
steps: {
|
|
106
|
+
before: number;
|
|
107
|
+
step: Step;
|
|
108
|
+
}[];
|
|
109
|
+
problems: string[];
|
|
110
|
+
};
|
|
111
|
+
/**
|
|
112
|
+
* Add steps to a saved flow. It is unproven afterwards — a run that passes
|
|
113
|
+
* proves it again — and segments cut from it keep pointing at the same steps.
|
|
114
|
+
*/
|
|
115
|
+
export declare function editFlow(app: string, slug: string, adds: StepToAdd[]): Promise<Flow>;
|
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
|
+
}
|