@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.
@@ -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[];
@@ -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 plan = await Promise.all(planning.bound.map((slug) => flows.findOne({ app: run.app, slug })));
126
- if (plan.some((f) => !f))
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
- const chain = plan;
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 = [];
@@ -13,20 +13,31 @@ export async function reembed() {
13
13
  if (!cfg)
14
14
  throw new Error('no embedding model configured — set EMBED_KEY (Voyage), or EMBED_URL and EMBED_MODEL for another model');
15
15
  const c = await collections();
16
- // Record the new model first, so ensureSchema accepts it and resizes the indexes.
16
+ const flows = c.flows;
17
+ const notes = c.notes;
18
+ // Embed everything BEFORE changing anything: if the model fails (wrong
19
+ // name, not pulled, out of quota), the database is left as it was — still
20
+ // recorded as the old model, with the old model's vectors.
21
+ const [flowVectors, noteVectors] = [await vectorsFor(flows), await vectorsFor(notes)];
22
+ // Record the new model, so ensureSchema accepts it and resizes the indexes.
17
23
  await c.meta.replaceOne({ _id: 'embedder' }, { model: cfg.model, dims: cfg.dims, setAt: new Date() }, { upsert: true });
18
24
  await ensureSchema();
19
25
  return {
20
- flows: await reembedCollection(c.flows),
21
- notes: await reembedCollection(c.notes),
26
+ flows: await write(flows, flowVectors),
27
+ notes: await write(notes, noteVectors),
22
28
  model: cfg.model,
23
29
  };
24
30
  }
25
- async function reembedCollection(coll) {
31
+ async function vectorsFor(coll) {
26
32
  const docs = await coll.find({}, { projection: { searchText: 1 } }).toArray();
27
33
  if (!docs.length)
28
- return 0;
34
+ return [];
29
35
  const vectors = await embed(docs.map((d) => d.searchText), 'document');
30
- await coll.bulkWrite(docs.map((d, i) => ({ updateOne: { filter: { _id: d._id }, update: { $set: { embedding: vectors[i] } } } })));
31
- return docs.length;
36
+ return docs.map((d, i) => ({ _id: d._id, embedding: vectors[i] }));
37
+ }
38
+ async function write(coll, vectors) {
39
+ if (!vectors.length)
40
+ return 0;
41
+ await coll.bulkWrite(vectors.map((v) => ({ updateOne: { filter: { _id: v._id }, update: { $set: { embedding: v.embedding } } } })));
42
+ return vectors.length;
32
43
  }
@@ -33,8 +33,40 @@ export interface App {
33
33
  * value moves to the user's env file. See memory/placeholders.ts.
34
34
  */
35
35
  placeholders?: PlaceholderKind[];
36
+ /**
37
+ * Goals to fit recall's known/unknown cutoffs from (`understudy calibrate`).
38
+ * Kept so `reembed` can re-fit them for a new model without asking again.
39
+ */
40
+ calibrationGoals?: CalibrationGoals;
41
+ /** The cutoffs fitted from them, for one embedding model. Ignored when the model changes. */
42
+ cutoffs?: FittedCutoffs;
36
43
  createdAt: Date;
37
44
  }
45
+ /** Goals labelled with the flow that does them; `unknown` ones the app doesn't have. */
46
+ export interface CalibrationGoals {
47
+ known: {
48
+ flow: string;
49
+ goal: string;
50
+ }[];
51
+ unknown: string[];
52
+ }
53
+ /** recall's rule for "known": top ≥ strong, or top ≥ good and ≥ margin ahead of the next flow. */
54
+ export interface Cutoffs {
55
+ strong: number;
56
+ good: number;
57
+ margin: number;
58
+ }
59
+ export interface FittedCutoffs extends Cutoffs {
60
+ model: string;
61
+ dims: number;
62
+ fittedAt: Date;
63
+ /** How many goals it was fitted on, and how many the cutoffs put on the right side. */
64
+ goals: {
65
+ known: number;
66
+ unknown: number;
67
+ };
68
+ correct: number;
69
+ }
38
70
  export interface Flow {
39
71
  _id?: ObjectId;
40
72
  app: string;
@@ -58,12 +90,32 @@ export interface Flow {
58
90
  proven?: boolean;
59
91
  /** Why it's unproven, e.g. "saved without a replay". */
60
92
  unprovenBecause?: string;
93
+ /**
94
+ * Proven only UP TO this step: the first that commits something real (a
95
+ * purchase, a submission) or that only a person can do. Every step before it replayed and passed, and its
96
+ * control was found ready — but it was never pressed, so nothing after it has
97
+ * run. Missing = proven all the way (or not at all: see `proven`). A full run
98
+ * that passes (with purchases allowed) clears it.
99
+ */
100
+ provenUpTo?: number;
61
101
  /** Segments only: the flow it was cut from, and which of its steps ([start, end)). */
62
102
  from?: {
63
103
  flow: string;
64
104
  steps: [number, number];
65
105
  };
66
106
  preconditions: Precondition[];
107
+ /**
108
+ * App states this flow needs before it can run, e.g. "member-has-active-bundle".
109
+ * The page it expects depends on them — the same button leads somewhere else
110
+ * without. A plan satisfies each with an earlier flow that `establishes` it,
111
+ * or with the agent's word that it already holds.
112
+ *
113
+ * Names are kebab-case and belong to the app: reuse an existing one rather
114
+ * than coin a synonym, or the planner never connects the two.
115
+ */
116
+ requires?: string[];
117
+ /** App states this flow makes true, e.g. buying a bundle establishes "member-has-active-bundle". */
118
+ establishes?: string[];
67
119
  outcome: string;
68
120
  /** True if running it commits something real (a purchase, a submission). */
69
121
  destructive: boolean;
@@ -151,8 +203,12 @@ export interface Finding {
151
203
  occurrences: number;
152
204
  firstSeen: Date;
153
205
  lastSeen: Date;
154
- /** open until someone triages it: a real bug (issue), a workaround (lesson), or noise. */
155
- status: 'open' | 'issue' | 'lesson' | 'noise';
206
+ /**
207
+ * open until someone triages it: a real bug (issue), a workaround (lesson),
208
+ * noise, or — for a changed path — expected: the app changed on purpose, and
209
+ * the new path is the normal one from now on.
210
+ */
211
+ status: 'open' | 'issue' | 'lesson' | 'noise' | 'expected';
156
212
  }
157
213
  /**
158
214
  * Which embedding model filled this database. Vectors from two models can't be
@@ -174,6 +230,20 @@ export interface Run {
174
230
  * attributed: an agent reached the goal by other means and reported it.
175
231
  */
176
232
  mode: 'run' | 'replay' | 'attributed';
233
+ /**
234
+ * The run stopped, as asked, before this step — the flow's commit — rather
235
+ * than doing it. Its path is partial, so it is never drift history.
236
+ */
237
+ stoppedBefore?: number;
238
+ /**
239
+ * false: it passed, but its path changed (new pages, or a step landing
240
+ * somewhere unexpected), and nobody has said that's right yet. Kept out of
241
+ * drift history until its finding is triaged `expected` — otherwise a wrong
242
+ * ending that passes becomes "normal" after a few runs. Missing = accepted.
243
+ */
244
+ accepted?: false;
245
+ /** Where each flow of `plan` starts in `steps`, so an accepted path can update each flow. */
246
+ starts?: number[];
177
247
  /**
178
248
  * waiting: planning paused on a question for the agent (`question` says what).
179
249
  * planned: a dry run — the plan is complete, nothing ran.
@@ -212,6 +282,12 @@ export interface Run {
212
282
  steps: Step[];
213
283
  how: string;
214
284
  }>;
285
+ /** How each required state was satisfied: by running a flow first, or because it already holds. */
286
+ states?: Record<string, {
287
+ use: string;
288
+ } | {
289
+ holds: true;
290
+ }>;
215
291
  dryRun?: boolean;
216
292
  allowPurchases?: boolean;
217
293
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jeffawe/understudy",
3
- "version": "0.2.3",
3
+ "version": "0.4.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",