@jeffawe/understudy 0.4.0 → 0.5.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +127 -0
  2. package/README.md +69 -172
  3. package/REASONER.md +76 -86
  4. package/dist/adapters/recorder/script.d.ts +25 -2
  5. package/dist/adapters/recorder/script.js +126 -31
  6. package/dist/core/outline.d.ts +43 -0
  7. package/dist/core/outline.js +121 -0
  8. package/dist/core/recording.d.ts +19 -1
  9. package/dist/core/recording.js +38 -2
  10. package/dist/core/replay.d.ts +62 -1
  11. package/dist/core/replay.js +162 -106
  12. package/dist/entry/cli.js +110 -29
  13. package/dist/entry/mcp.d.ts +1 -0
  14. package/dist/entry/mcp.js +114 -23
  15. package/dist/flows/destructive.js +1 -1
  16. package/dist/flows/distill.js +11 -6
  17. package/dist/flows/emit.d.ts +7 -0
  18. package/dist/flows/emit.js +26 -10
  19. package/dist/flows/execute.d.ts +12 -0
  20. package/dist/flows/execute.js +23 -16
  21. package/dist/flows/runs.d.ts +2 -0
  22. package/dist/flows/runs.js +7 -3
  23. package/dist/flows/save.d.ts +5 -2
  24. package/dist/flows/save.js +38 -23
  25. package/dist/flows/session.d.ts +176 -0
  26. package/dist/flows/session.js +383 -0
  27. package/dist/flows/variants.d.ts +81 -0
  28. package/dist/flows/variants.js +139 -0
  29. package/dist/memory/calibrate.js +3 -1
  30. package/dist/memory/pages.d.ts +34 -0
  31. package/dist/memory/pages.js +60 -0
  32. package/dist/memory/recall.d.ts +56 -2
  33. package/dist/memory/recall.js +194 -30
  34. package/dist/plan/planner.d.ts +11 -1
  35. package/dist/plan/planner.js +36 -19
  36. package/dist/store/app-settings.d.ts +26 -0
  37. package/dist/store/app-settings.js +49 -0
  38. package/dist/store/db.js +8 -1
  39. package/dist/store/types.d.ts +18 -0
  40. package/package.json +3 -2
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Variants: a flow's copy for one version of the app — a branch under test, a
3
+ * preview deploy — kept beside the main flow under the same name.
4
+ *
5
+ * Testing a branch used to mean saving its version of a flow over the main
6
+ * one, so the branch's change became everyone's baseline before it merged.
7
+ * Now:
8
+ *
9
+ * - a variant is its own flow document, `variant: "<name>"`; the main flow
10
+ * has no `variant` at all
11
+ * - anything run with a variant uses that variant's copy of a flow where it
12
+ * has one, and the main flow where it doesn't — a branch that changed the
13
+ * intake form needs a copy of the intake flow only
14
+ * - saving with a variant never touches the main flow
15
+ * - `promote` makes a variant the main flow, once the branch has merged
16
+ *
17
+ * Segments stay main-only: they are shared building blocks, and a branch's
18
+ * copy of one would compete with the real one in every plan.
19
+ */
20
+ import { collections } from '../store/db.js';
21
+ /** `feature/new-intake`, `pr-412`, `staging`. */
22
+ const VARIANT = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,79}$/;
23
+ /** Throws on a name that can't be a variant; returns it trimmed, or undefined for none. */
24
+ export function checkVariant(v) {
25
+ if (v === undefined || v.trim() === '')
26
+ return undefined;
27
+ const t = v.trim();
28
+ if (!VARIANT.test(t))
29
+ throw new Error(`variant "${v}" — use letters, digits, . _ / - (a branch name works), up to 80`);
30
+ return t;
31
+ }
32
+ /** The filter for one flow: the variant's copy, or (no variant) the main one. */
33
+ export const flowKey = (app, slug, variant) => variant ? { app, slug, variant } : { app, slug, variant: { $exists: false } };
34
+ /** Main flows only — for anything shared across versions (segments, calibration). */
35
+ export const MAIN = { variant: { $exists: false } };
36
+ /**
37
+ * The flow a name means when running with this variant: its copy if it has
38
+ * one, else the main flow.
39
+ */
40
+ export async function resolveFlow(app, slug, variant) {
41
+ const { flows } = await collections();
42
+ if (variant) {
43
+ const own = await flows.findOne({ app, slug, variant });
44
+ if (own)
45
+ return own;
46
+ }
47
+ return flows.findOne(flowKey(app, slug));
48
+ }
49
+ /**
50
+ * Pure: of flows found by a search, the ones this variant sees — its own
51
+ * copies in place of the main flows they copy, and no other variant's.
52
+ */
53
+ export function pickVariant(found, variant) {
54
+ const own = new Set(found.filter((f) => variant && f.variant === variant).map((f) => f.slug));
55
+ return found.filter((f) => (f.variant === undefined ? !own.has(f.slug) : f.variant === variant));
56
+ }
57
+ /** The filter for runs made with this variant — or with none. */
58
+ export const runsOf = (variant) => variant ? { variant } : { variant: { $exists: false } };
59
+ /**
60
+ * Make a variant the main flow: its steps, proof and search entry replace the
61
+ * main flow's (or become it, if there was none), and the variant is gone.
62
+ */
63
+ export async function promoteVariant(app, slug, variant) {
64
+ const { flows } = await collections();
65
+ const v = await flows.findOne({ app, slug, variant });
66
+ if (!v)
67
+ throw new Error(`no variant "${variant}" of '${slug}' for app '${app}'`);
68
+ const main = await flows.findOne(flowKey(app, slug));
69
+ const { _id, variant: _v, ...rest } = v;
70
+ await flows.replaceOne(flowKey(app, slug), { ...rest, createdAt: main?.createdAt ?? v.createdAt, updatedAt: new Date() }, { upsert: true });
71
+ await flows.deleteOne({ _id: _id });
72
+ const segments = main ? await flows.find({ app, kind: 'segment', 'from.flow': slug, ...MAIN }, { projection: { slug: 1 } }).toArray() : [];
73
+ return { flow: slug, variant, replaced: Boolean(main), staleSegments: segments.map((s) => s.slug) };
74
+ }
75
+ /** One step, as a line a person can compare: `check radio "Yes"`, `fill textbox "Email" = "a@b.c"`. */
76
+ function stepText(s) {
77
+ const target = s.role && s.name ? `${s.role} ${JSON.stringify(s.name)}` : s.name ? JSON.stringify(s.name) : s.testId ? `[${s.testId}]` : s.css ? `[${s.css}]` : '';
78
+ const what = s.valueRef ? ` = <${s.valueRef}>` : s.value !== undefined ? ` = ${JSON.stringify(s.value)}` : '';
79
+ return `${s.action}${target ? ` ${target}` : ''}${what}`;
80
+ }
81
+ /**
82
+ * Pure: how a variant's steps differ from the main flow's, one line per
83
+ * change, numbered as in the variant (removed steps as in main). Lined up by
84
+ * longest common run of steps, so an inserted step shows as one insertion,
85
+ * not as every step after it changing.
86
+ */
87
+ export function diffFromMain(main, copy, max = 12) {
88
+ const a = main.steps.map(stepText);
89
+ const b = copy.steps.map(stepText);
90
+ const lcs = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
91
+ for (let i = a.length - 1; i >= 0; i--)
92
+ for (let j = b.length - 1; j >= 0; j--) {
93
+ lcs[i][j] = a[i] === b[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
94
+ }
95
+ const out = [];
96
+ let i = 0;
97
+ let j = 0;
98
+ while (i < a.length || j < b.length) {
99
+ if (i < a.length && j < b.length && a[i] === b[j]) {
100
+ i++;
101
+ j++;
102
+ continue;
103
+ }
104
+ // A step removed and one added in the same place is one step changed.
105
+ if (i < a.length && j < b.length && lcs[i + 1][j + 1] === lcs[i][j]) {
106
+ out.push(`step ${j}: ${a[i]} → ${b[j]}`);
107
+ i++;
108
+ j++;
109
+ }
110
+ else if (j < b.length && (i >= a.length || lcs[i][j + 1] > lcs[i + 1][j])) {
111
+ out.push(`step ${j} added: ${b[j]}`);
112
+ j++;
113
+ }
114
+ else {
115
+ out.push(`main's step ${i} removed: ${a[i]}`);
116
+ i++;
117
+ }
118
+ }
119
+ return out.length > max ? [...out.slice(0, max), `…and ${out.length - max} more`] : out;
120
+ }
121
+ /** How a variant differs from its main flow, or why there's nothing to compare. */
122
+ export async function variantDiff(app, slug, variant) {
123
+ const { flows } = await collections();
124
+ const [main, copy] = await Promise.all([flows.findOne(flowKey(app, slug)), flows.findOne({ app, slug, variant })]);
125
+ if (!copy)
126
+ return [];
127
+ if (!main)
128
+ return ['no main flow: this exists only on the variant'];
129
+ const diff = diffFromMain(main, copy);
130
+ return diff.length ? diff : ['same steps as the main flow'];
131
+ }
132
+ /** Delete a variant's copy, so runs with that variant use the main flow again. */
133
+ export async function dropVariant(app, slug, variant) {
134
+ const { flows } = await collections();
135
+ const { deletedCount } = await flows.deleteOne({ app, slug, variant });
136
+ if (!deletedCount)
137
+ throw new Error(`no variant "${variant}" of '${slug}' for app '${app}'`);
138
+ return { flow: slug, variant, dropped: true };
139
+ }
@@ -28,6 +28,7 @@
28
28
  * The goals are kept on the app, so `reembed` re-fits every app for a new
29
29
  * model without asking for them again.
30
30
  */
31
+ import { MAIN } from '../flows/variants.js';
31
32
  import { collections } from '../store/db.js';
32
33
  import { embed, embedderConfig } from '../store/embed.js';
33
34
  import { cutoffsFor, isKnown } from './recall.js';
@@ -128,7 +129,8 @@ export async function calibrate(app, input = {}) {
128
129
  if (!cfg)
129
130
  throw new Error('calibrate fits the cutoffs for matching by meaning, and no embedding model is configured — set EMBED_KEY, or EMBED_URL and EMBED_MODEL');
130
131
  const c = await collections();
131
- const flows = await c.flows.find({ app }, { projection: { slug: 1, title: 1, from: 1, embedding: 1 } }).toArray();
132
+ // Main flows only: a variant shares its flow's name, and would be scored as a second, competing answer.
133
+ const flows = await c.flows.find({ app, ...MAIN }, { projection: { slug: 1, title: 1, from: 1, embedding: 1 } }).toArray();
132
134
  if (!flows.length)
133
135
  throw new Error(`no flows for '${app}' — save some first`);
134
136
  const unembedded = flows.filter((f) => f.embedding?.length !== cfg.dims);
@@ -0,0 +1,34 @@
1
+ /**
2
+ * What pages looked like: each page's controls (core/outline.ts) kept on the
3
+ * page map whenever a run or a session sees it, so the next visit can say what
4
+ * is different — "a follow-up question appeared on /intake" — instead of an
5
+ * agent re-reading the whole page, or trusting a flow recorded against a page
6
+ * that has since changed.
7
+ *
8
+ * Kept per page fingerprint (`sig`); compared across fingerprints of the same
9
+ * address, because a page that changed usually changed its fingerprint too.
10
+ */
11
+ import { type Control, type OutlineDiff } from '../core/outline.js';
12
+ import type { Flow } from '../store/types.js';
13
+ /** `/inventory.html#bf3dd322` → `/inventory.html` */
14
+ export declare const pageOf: (sig: string) => string;
15
+ /** Keep what a page looks like now. */
16
+ export declare function rememberOutline(app: string, sig: string, outline: Control[], at?: Date): Promise<void>;
17
+ export interface PageChange extends OutlineDiff {
18
+ /** The page's address pattern. */
19
+ page: string;
20
+ /** When it was last seen looking different from now. */
21
+ since: string;
22
+ }
23
+ /**
24
+ * What differs on this page from the last time it was seen looking otherwise:
25
+ * the newest kept outline of the same address under another fingerprint.
26
+ * Nothing when it has never been seen, or never seen any other way.
27
+ */
28
+ export declare function changesSince(app: string, sig: string, outline: Control[]): Promise<PageChange | undefined>;
29
+ /**
30
+ * The flow's pages that have been seen looking different from what the flow
31
+ * expects, AFTER it last passed — a run of another flow, or a session, got
32
+ * there first. The flow may still work; it is worth checking before trusting.
33
+ */
34
+ export declare function flowPagesChanged(app: string, flow: Pick<Flow, 'steps'>, lastPassed?: string): Promise<PageChange[]>;
@@ -0,0 +1,60 @@
1
+ /**
2
+ * What pages looked like: each page's controls (core/outline.ts) kept on the
3
+ * page map whenever a run or a session sees it, so the next visit can say what
4
+ * is different — "a follow-up question appeared on /intake" — instead of an
5
+ * agent re-reading the whole page, or trusting a flow recorded against a page
6
+ * that has since changed.
7
+ *
8
+ * Kept per page fingerprint (`sig`); compared across fingerprints of the same
9
+ * address, because a page that changed usually changed its fingerprint too.
10
+ */
11
+ import { collections } from '../store/db.js';
12
+ import { diffOutline } from '../core/outline.js';
13
+ /** `/inventory.html#bf3dd322` → `/inventory.html` */
14
+ export const pageOf = (sig) => sig.slice(0, sig.lastIndexOf('#')) || sig;
15
+ /** Keep what a page looks like now. */
16
+ export async function rememberOutline(app, sig, outline, at = new Date()) {
17
+ const { pages } = await collections();
18
+ await pages.updateOne({ app, sig }, { $set: { outline, outlineAt: at, lastSeen: at }, $setOnInsert: { app, sig, urlPattern: pageOf(sig), links: [], firstSeen: at } }, { upsert: true });
19
+ }
20
+ /**
21
+ * What differs on this page from the last time it was seen looking otherwise:
22
+ * the newest kept outline of the same address under another fingerprint.
23
+ * Nothing when it has never been seen, or never seen any other way.
24
+ */
25
+ export async function changesSince(app, sig, outline) {
26
+ const { pages } = await collections();
27
+ const before = await pages.findOne({ app, urlPattern: pageOf(sig), sig: { $ne: sig }, outline: { $exists: true } }, { sort: { outlineAt: -1 }, projection: { outline: 1, outlineAt: 1 } });
28
+ if (!before?.outline)
29
+ return undefined;
30
+ const d = diffOutline(before.outline, outline, 12);
31
+ if (!d.appeared.length && !d.gone.length && !d.changed.length)
32
+ return undefined;
33
+ return { page: pageOf(sig), since: (before.outlineAt ?? new Date(0)).toISOString(), ...d };
34
+ }
35
+ /**
36
+ * The flow's pages that have been seen looking different from what the flow
37
+ * expects, AFTER it last passed — a run of another flow, or a session, got
38
+ * there first. The flow may still work; it is worth checking before trusting.
39
+ */
40
+ export async function flowPagesChanged(app, flow, lastPassed) {
41
+ const expected = [...new Set(flow.steps.map((s) => s.expectedSig).filter((s) => Boolean(s)))];
42
+ if (!expected.length)
43
+ return [];
44
+ const { pages } = await collections();
45
+ const after = lastPassed ? new Date(lastPassed) : new Date(0);
46
+ const out = [];
47
+ for (const page of [...new Set(expected.map(pageOf))]) {
48
+ const ours = expected.filter((s) => pageOf(s) === page);
49
+ const newer = await pages.findOne({ app, urlPattern: page, sig: { $nin: ours }, outline: { $exists: true }, outlineAt: { $gt: after } }, { sort: { outlineAt: -1 }, projection: { outline: 1, outlineAt: 1 } });
50
+ if (!newer?.outline)
51
+ continue;
52
+ const known = await pages.findOne({ app, sig: { $in: ours }, outline: { $exists: true } }, { sort: { outlineAt: -1 }, projection: { outline: 1 } });
53
+ const d = known?.outline
54
+ ? diffOutline(known.outline, newer.outline, 8)
55
+ : { appeared: [], gone: [], changed: ['it looks different, and how it looked before was never kept'] };
56
+ if (d.appeared.length || d.gone.length || d.changed.length)
57
+ out.push({ page, since: newer.outlineAt.toISOString(), ...d });
58
+ }
59
+ return out;
60
+ }
@@ -14,10 +14,13 @@
14
14
  * words no model: match the goal's words against flow names
15
15
  * Either way, a goal that IS a flow's name or slug matches exactly.
16
16
  */
17
- import type { Cutoffs, Flow, Note } from '../store/types.js';
17
+ import type { Cutoffs, Flow, Note, Step } from '../store/types.js';
18
+ import { type PageChange } from './pages.js';
18
19
  import { type EmbedderConfig } from '../store/embed.js';
19
20
  export interface FlowMatch {
20
21
  slug: string;
22
+ /** This is the variant's copy of the flow, not the main one. */
23
+ variant?: string;
21
24
  title: string;
22
25
  kind: Flow['kind'];
23
26
  madeBy: 'user' | 'agent';
@@ -33,6 +36,18 @@ export interface FlowMatch {
33
36
  score: number;
34
37
  destructive: boolean;
35
38
  requiresSession: boolean;
39
+ /** When a run last got through this flow (up to its commit counts). */
40
+ lastPassed?: string;
41
+ /** When a run last failed inside this flow, and at which of its steps. */
42
+ lastFailed?: {
43
+ at: string;
44
+ step: number;
45
+ error?: string;
46
+ };
47
+ /** Its newest pass took a changed path that nobody has accepted yet. */
48
+ pathNotAccepted?: true;
49
+ /** Branches with their own copy of this flow — other than the one asked for. Pass one as `variant` to use it. */
50
+ variants?: string[];
36
51
  }
37
52
  /** One step of the flow to run, in a form an agent can drive from directly. */
38
53
  export interface BriefStep {
@@ -40,16 +55,37 @@ export interface BriefStep {
40
55
  action: string;
41
56
  role?: string;
42
57
  name?: string;
43
- /** How to find it when there's no role + name. */
58
+ /** The name must match exactly. */
59
+ exact?: boolean;
60
+ /** Also tells apart elements that share a role and name. */
44
61
  testId?: string;
62
+ /** The attribute holding the test id, when it was recorded (`data-test`, …). */
63
+ testIdAttr?: string;
64
+ /** How to find it when there's no role + name, or test id. */
45
65
  css?: string;
66
+ /** The iframe it's in: matches the end of the frame's name, or part of its address. */
67
+ frameHint?: string;
46
68
  /** Which of several matching elements (0-based). */
47
69
  nth?: number;
48
70
  /** A literal value to type or select, or the address for a goto. */
49
71
  value?: string;
50
72
  /** A login value that was never stored — see `needs` for where it is. */
51
73
  placeholder?: string;
74
+ /**
75
+ * The rest of what replay reads, under the stored names: how to match (`by`,
76
+ * `scope`, `hasText`, `nameRegex`, `force`), what an `assert` checks, when a
77
+ * `human` step is done (`untilText`, …), what a `wait_response` expects.
78
+ */
79
+ hints?: Record<string, unknown>;
52
80
  }
81
+ /**
82
+ * Pure: a stored step as an agent gets it. Short — css is left out when there's
83
+ * a better way to find the element — but nothing that changes which element is
84
+ * meant, or what counts as passing, may be dropped.
85
+ */
86
+ export declare function briefStep(s: Step, n: number): BriefStep;
87
+ /** Pure: a brief step as one line for a person (`recall --steps`), leaving nothing in it out. */
88
+ export declare function stepLine(s: BriefStep): string;
53
89
  /** A login value the flow needs: where it's set, and whether it is — never the value. */
54
90
  export interface Need {
55
91
  placeholder: string;
@@ -81,6 +117,10 @@ export interface Recall {
81
117
  cutoffs?: Cutoffs & {
82
118
  source: CutoffSource;
83
119
  };
120
+ /** When the best flow is a variant's copy: how its steps differ from the main flow's. */
121
+ differsFromMain?: string[];
122
+ /** The best flow's pages, seen looking different since it last passed. */
123
+ pagesChanged?: PageChange[];
84
124
  }
85
125
  /**
86
126
  * When a match by MEANING is good enough to act on — the built-in cutoffs, for
@@ -124,6 +164,19 @@ export declare function wordScore(goal: string, flow: Pick<Flow, 'slug' | 'title
124
164
  * the better word on how the app is meant to be used.
125
165
  */
126
166
  export declare function rank(matches: FlowMatch[]): FlowMatch[];
167
+ /**
168
+ * The verdict's reason, plus a warning when the flow it picked may not work:
169
+ * unproven, its last run failed, or it last passed on a path nobody accepted.
170
+ * A confident match on a stale flow is the most misleading thing recall can say.
171
+ */
172
+ export declare function withWarnings(why: string, best: FlowMatch | undefined, now?: number): string;
173
+ /**
174
+ * Each flow's last pass and last failure, from recent runs. A run of a plan
175
+ * counts for a flow only if it got to that flow: a failure is the flow's when
176
+ * the first failed step is inside its steps (`starts`), and a pass up to a
177
+ * commit counts, since that is all a commit-shaped flow is ever run to.
178
+ */
179
+ export declare function withHistory(app: string, matches: FlowMatch[], variant?: string): Promise<FlowMatch[]>;
127
180
  /**
128
181
  * `withSteps`: when the verdict is known, also return the best flow's steps and
129
182
  * the login values it needs — what an agent driving the flow itself wants. Off
@@ -132,4 +185,5 @@ export declare function rank(matches: FlowMatch[]): FlowMatch[];
132
185
  export declare function recall(app: string, goal: string, opts?: {
133
186
  limit?: number;
134
187
  withSteps?: boolean;
188
+ variant?: string;
135
189
  }): Promise<Recall>;
@@ -15,9 +15,70 @@
15
15
  * Either way, a goal that IS a flow's name or slug matches exactly.
16
16
  */
17
17
  import { collections, vectorSearch } from '../store/db.js';
18
+ import { checkVariant, pickVariant, resolveFlow, runsOf, variantDiff } from '../flows/variants.js';
19
+ import { flowPagesChanged } from './pages.js';
18
20
  import { embed, embedderConfig, VOYAGE_DEFAULT } from '../store/embed.js';
19
21
  import { valuesFromEnv, valueEnvNames } from '../store/settings.js';
20
- import { valueRefsOf } from '../core/recording.js';
22
+ import { describeResponse, forced, humanUntil, literalValue, responseCheckOf, valueRefsOf } from '../core/recording.js';
23
+ /** Hints that aren't for whoever drives the step: `nth` has its own field, the others are bookkeeping. */
24
+ const NOT_BRIEF = new Set(['nth', 'inputType', 'seamGapBefore', 'unparsedChainStep']);
25
+ /**
26
+ * Pure: a stored step as an agent gets it. Short — css is left out when there's
27
+ * a better way to find the element — but nothing that changes which element is
28
+ * meant, or what counts as passing, may be dropped.
29
+ */
30
+ export function briefStep(s, n) {
31
+ const nth = typeof s.hints?.nth === 'number' ? s.hints.nth : undefined;
32
+ const addressed = Boolean(s.role && s.name);
33
+ const hints = Object.fromEntries(Object.entries(s.hints ?? {}).filter(([k]) => !NOT_BRIEF.has(k)));
34
+ // Older flows carry `{ force: true }` as a click's valueRef; it is not a login value.
35
+ if (forced(s))
36
+ hints.force = true;
37
+ const placeholder = valueRefsOf([s])[0];
38
+ return {
39
+ n, action: s.action,
40
+ ...(s.role ? { role: s.role } : {}), ...(s.name ? { name: s.name } : {}),
41
+ ...(s.exact ? { exact: true } : {}),
42
+ ...(s.testId ? { testId: s.testId, ...(s.testIdAttr ? { testIdAttr: s.testIdAttr } : {}) } : {}),
43
+ ...(!addressed && !s.testId && s.css ? { css: s.css } : {}),
44
+ ...(s.frameHint ? { frameHint: s.frameHint } : {}),
45
+ ...(nth !== undefined ? { nth } : {}),
46
+ ...(placeholder ? { placeholder } : literalValue(s) !== undefined ? { value: literalValue(s) } : s.action === 'goto' ? { value: s.url } : {}),
47
+ ...(Object.keys(hints).length ? { hints } : {}),
48
+ };
49
+ }
50
+ /** Pure: a brief step as one line for a person (`recall --steps`), leaving nothing in it out. */
51
+ export function stepLine(s) {
52
+ const h = s.hints ?? {};
53
+ const text = (v, regex, flags) => (regex ? `/${String(v)}/${String(flags ?? '')}` : `"${String(v)}"`);
54
+ const name = s.name === undefined ? undefined : text(s.name, h.nameRegex, h.nameFlags);
55
+ const target = [
56
+ s.role,
57
+ // With no role, say what the name is looked up as: a placeholder, a label, plain text…
58
+ name !== undefined && (s.role ? name : `${String(h.by ?? 'text')} ${name}`),
59
+ s.testId && `[${s.testIdAttr ?? 'test id'} ${s.testId}]`,
60
+ s.css && `[${s.css}]`,
61
+ h.hasText !== undefined && `with text ${text(h.hasText, h.hasTextRegex, h.hasTextFlags)}`,
62
+ Array.isArray(h.scope) && `inside ${h.scope.join(' >> ')}`,
63
+ s.frameHint && `in frame ${s.frameHint}`,
64
+ s.nth !== undefined && `(#${s.nth})`,
65
+ s.exact && '(exact)',
66
+ h.force === true && '(forced)',
67
+ typeof h.timeoutMs === 'number' && `(waits up to ${h.timeoutMs / 1000}s)`,
68
+ ];
69
+ const response = s.action === 'wait_response' ? responseCheckOf(s.value, h) : undefined;
70
+ const until = s.action === 'human' ? humanUntil(s) : undefined;
71
+ const expects = [
72
+ s.action === 'assert' && String(h.assert ?? 'visible'),
73
+ s.placeholder ? `= <${s.placeholder}>`
74
+ : response ? describeResponse(response)
75
+ : s.value !== undefined && `= ${text(s.value, h.valueRegex ?? h.urlRegex, h.valueFlags ?? h.urlFlags)}`,
76
+ until?.url && `until the address matches "${until.url}"`,
77
+ until?.text && `until the page shows "${until.text}"`,
78
+ until?.response && `until ${describeResponse(until.response)}`,
79
+ ];
80
+ return [`${String(s.n).padStart(3)} ${s.action.padEnd(7)}`, ...target, ...expects].filter(Boolean).join(' ').trimEnd();
81
+ }
21
82
  /**
22
83
  * When a match by MEANING is good enough to act on — the built-in cutoffs, for
23
84
  * voyage-4-lite. Set by hand 2026-11-18 on a real 28-flow corpus (15 known
@@ -94,7 +155,7 @@ export function wordScore(goal, flow) {
94
155
  return hit / g.size;
95
156
  }
96
157
  const toMatch = (f, score) => ({
97
- slug: f.slug, title: f.title, kind: f.kind, madeBy: f.madeBy ?? 'user', proven: f.proven !== false,
158
+ slug: f.slug, ...(f.variant ? { variant: f.variant } : {}), title: f.title, kind: f.kind, madeBy: f.madeBy ?? 'user', proven: f.proven !== false,
98
159
  ...(f.proven === false && f.unprovenBecause ? { unprovenBecause: f.unprovenBecause } : {}),
99
160
  ...(f.provenUpTo !== undefined ? { provenUpTo: f.provenUpTo } : {}),
100
161
  ...(f.requires?.length ? { requires: f.requires } : {}), ...(f.establishes?.length ? { establishes: f.establishes } : {}), score,
@@ -110,26 +171,110 @@ const TIE = 0.005;
110
171
  export function rank(matches) {
111
172
  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));
112
173
  }
113
- /** The verdict's reason, plus a warning when the flow it picked may not work. */
114
- 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;
115
- /** The best flow's steps and the login values they need, for an agent driving it itself. */
116
- async function plan(app, slug) {
174
+ /** `3 days ago`, `5 hours ago` — for a person reading `why`. */
175
+ function ago(iso, now = Date.now()) {
176
+ const mins = Math.max(0, Math.round((now - Date.parse(iso)) / 60_000));
177
+ if (mins < 60)
178
+ return `${mins} min ago`;
179
+ const hours = Math.round(mins / 60);
180
+ if (hours < 48)
181
+ return `${hours} hour${hours === 1 ? '' : 's'} ago`;
182
+ return `${Math.round(hours / 24)} days ago`;
183
+ }
184
+ /**
185
+ * The verdict's reason, plus a warning when the flow it picked may not work:
186
+ * unproven, its last run failed, or it last passed on a path nobody accepted.
187
+ * A confident match on a stale flow is the most misleading thing recall can say.
188
+ */
189
+ export function withWarnings(why, best, now = Date.now()) {
190
+ if (!best)
191
+ return why;
192
+ if (!best.proven)
193
+ return `${why} — but '${best.slug}' is unproven (${best.unprovenBecause ?? 'no passing run yet'}), so it may not work; a passing run proves it`;
194
+ const failed = best.lastFailed;
195
+ if (failed && (!best.lastPassed || failed.at > best.lastPassed)) {
196
+ const passed = best.lastPassed ? `; it last passed ${ago(best.lastPassed, now)}` : '';
197
+ return `${why} — but its last run failed ${ago(failed.at, now)}, at its step ${failed.step}${failed.error ? ` (${failed.error})` : ''}${passed}. The app may have changed: check that step before trusting it`;
198
+ }
199
+ if (best.pathNotAccepted)
200
+ return `${why} — but its last pass took a changed path nobody has accepted yet (see understudy_findings, flow_drift)`;
201
+ return why;
202
+ }
203
+ /** How many recent runs to read history from, across the matched flows. */
204
+ const HISTORY_RUNS = 200;
205
+ /**
206
+ * Each flow's last pass and last failure, from recent runs. A run of a plan
207
+ * counts for a flow only if it got to that flow: a failure is the flow's when
208
+ * the first failed step is inside its steps (`starts`), and a pass up to a
209
+ * commit counts, since that is all a commit-shaped flow is ever run to.
210
+ */
211
+ export async function withHistory(app, matches, variant) {
212
+ if (!matches.length)
213
+ return matches;
214
+ const slugs = matches.map((m) => m.slug);
215
+ const { runs } = await collections();
216
+ // A variant's copy has the variant's runs as its history; a main flow, the
217
+ // runs made without a variant.
218
+ const recent = await runs
219
+ .find({ app, plan: { $in: slugs }, mode: { $in: ['replay', 'run'] }, status: { $in: ['passed', 'failed'] }, ...(variant ? { $or: [runsOf(), runsOf(variant)] } : runsOf()) }, { projection: { plan: 1, starts: 1, status: 1, steps: 1, stoppedBefore: 1, accepted: 1, startedAt: 1, variant: 1 } })
220
+ .sort({ startedAt: -1 })
221
+ .limit(HISTORY_RUNS)
222
+ .toArray();
223
+ const seen = new Map();
224
+ for (const run of recent) {
225
+ const at = run.startedAt.toISOString();
226
+ const failedStep = run.status === 'failed' ? run.steps.find((s) => !s.ok) : undefined;
227
+ for (const [i, slug] of run.plan.entries()) {
228
+ if (!slugs.includes(slug))
229
+ continue;
230
+ if (matches.find((m) => m.slug === slug)?.variant !== run.variant)
231
+ continue;
232
+ const start = run.starts?.[i] ?? 0;
233
+ const end = run.starts?.[i + 1] ?? Infinity;
234
+ const h = seen.get(slug) ?? {};
235
+ if (run.stoppedBefore !== undefined && run.stoppedBefore < start)
236
+ continue; // stopped before it began
237
+ if (failedStep && failedStep.seq < start)
238
+ continue; // never got to it
239
+ if (failedStep && failedStep.seq < end) {
240
+ h.lastFailed ??= { at, step: failedStep.seq - start, ...(failedStep.error ? { error: failedStep.error.split('\n')[0].slice(0, 160) } : {}) };
241
+ }
242
+ else if (!h.lastPassed) {
243
+ h.lastPassed = at;
244
+ if (run.accepted === false)
245
+ h.pathNotAccepted = true;
246
+ }
247
+ seen.set(slug, h);
248
+ }
249
+ }
250
+ return matches.map((m) => ({ ...m, ...seen.get(m.slug) }));
251
+ }
252
+ /**
253
+ * Name the branches that have their own copy of each matched flow, so an
254
+ * agent that didn't ask for a variant still learns one exists — and can ask
255
+ * the user whether the run is for that branch.
256
+ */
257
+ async function withVariantNames(app, r, asked) {
258
+ if (!r.flows.length)
259
+ return r;
117
260
  const { flows } = await collections();
118
- const flow = await flows.findOne({ app, slug }, { projection: { steps: 1 } });
261
+ const copies = await flows
262
+ .find({ app, slug: { $in: r.flows.map((f) => f.slug) }, variant: { $exists: true, ...(asked ? { $ne: asked } : {}) } }, { projection: { slug: 1, variant: 1 } })
263
+ .toArray();
264
+ if (!copies.length)
265
+ return r;
266
+ const named = (m) => {
267
+ const v = copies.filter((c) => c.slug === m.slug).map((c) => c.variant).sort();
268
+ return v.length ? { ...m, variants: v } : m;
269
+ };
270
+ return { ...r, flows: r.flows.map(named), ...(r.best ? { best: named(r.best) } : {}) };
271
+ }
272
+ /** The best flow's steps and the login values they need, for an agent driving it itself. */
273
+ async function plan(app, slug, variant) {
274
+ const flow = await resolveFlow(app, slug, variant);
119
275
  if (!flow)
120
276
  return {};
121
- const steps = flow.steps.map((s, n) => {
122
- const nth = typeof s.hints?.nth === 'number' ? s.hints.nth : undefined;
123
- const addressed = Boolean(s.role && s.name);
124
- return {
125
- n, action: s.action,
126
- ...(s.role ? { role: s.role } : {}), ...(s.name ? { name: s.name } : {}),
127
- ...(!addressed && s.testId ? { testId: s.testId } : {}),
128
- ...(!addressed && !s.testId && s.css ? { css: s.css } : {}),
129
- ...(nth !== undefined ? { nth } : {}),
130
- ...(s.valueRef ? { placeholder: s.valueRef } : s.value !== undefined ? { value: s.value } : s.action === 'goto' ? { value: s.url } : {}),
131
- };
132
- });
277
+ const steps = flow.steps.map(briefStep);
133
278
  const refs = valueRefsOf(flow.steps);
134
279
  const found = valuesFromEnv(refs, app);
135
280
  const needs = refs.map((placeholder) => ({ placeholder, readFrom: valueEnvNames(placeholder, app), set: placeholder in found }));
@@ -141,47 +286,66 @@ async function plan(app, slug) {
141
286
  * for the planner, which only needs to know which flow.
142
287
  */
143
288
  export async function recall(app, goal, opts = {}) {
289
+ const found = await recallFlows(app, goal, opts);
290
+ const r = await withVariantNames(app, found, opts.variant);
291
+ if (!r.best)
292
+ return r;
293
+ const flow = await resolveFlow(app, r.best.slug, r.best.variant);
294
+ const changed = flow ? await flowPagesChanged(app, flow, r.best.lastPassed) : [];
295
+ return {
296
+ ...r,
297
+ ...(r.best.variant ? { differsFromMain: await variantDiff(app, r.best.slug, r.best.variant) } : {}),
298
+ ...(changed.length ? {
299
+ pagesChanged: changed,
300
+ why: `${r.why} — and since it last passed, ${changed.map((c) => c.page).join(', ')} ${changed.length === 1 ? 'has' : 'have'} been seen looking different (see pagesChanged)`,
301
+ } : {}),
302
+ };
303
+ }
304
+ async function recallFlows(app, goal, opts) {
144
305
  const limit = opts.limit ?? 5;
306
+ const variant = checkVariant(opts.variant);
145
307
  const c = await collections();
146
308
  const needle = goal.trim().toLowerCase();
309
+ const steps = (slug) => (opts.withSteps ? plan(app, slug, variant) : Promise.resolve({}));
147
310
  // 1. The goal names a flow exactly: no search needed, and no doubt.
148
- const exact = await c.flows.findOne({ app, $or: [{ slug: needle }, { title: { $regex: `^${needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`, $options: 'i' } }] }, { projection: { embedding: 0, steps: 0 } });
311
+ const [exact] = pickVariant(await c.flows.find({ app, $or: [{ slug: needle }, { title: { $regex: `^${needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`, $options: 'i' } }] }, { projection: { embedding: 0, steps: 0 } }).toArray(), variant);
149
312
  if (exact) {
150
- const best = toMatch(exact, 1);
151
- return { goal, method: 'exact', verdict: 'known', best, why: withProven('named exactly', best), flows: [best], notes: [], ...(opts.withSteps ? await plan(app, best.slug) : {}) };
313
+ const [best] = await withHistory(app, [toMatch(exact, 1)], variant);
314
+ return { goal, method: 'exact', verdict: 'known', best, why: withWarnings('named exactly', best), flows: [best], notes: [], ...(await steps(best.slug)) };
152
315
  }
153
316
  // 2. By meaning, if there's a model.
154
317
  const cfg = embedderConfig();
155
318
  if (cfg) {
156
319
  const [vector] = await embed([goal], 'query', cfg);
157
320
  const [flows, notes, rule] = await Promise.all([
158
- vectorSearch(c.flows, app, vector, { limit }),
321
+ // Extra, since other variants' copies are dropped after.
322
+ vectorSearch(c.flows, app, vector, { limit: limit * 3 }).then((found) => pickVariant(found, variant).slice(0, limit)),
159
323
  vectorSearch(c.notes, app, vector, { limit }),
160
324
  cutoffsFor(app, cfg),
161
325
  ]);
162
- const matches = rank(flows.map((f) => toMatch(f, f.score)));
326
+ const matches = await withHistory(app, rank(flows.map((f) => toMatch(f, f.score))), variant);
163
327
  const judged = judge(matches.map((m) => m.score), rule);
164
328
  const { verdict } = judged;
165
- let why = verdict === 'known' ? withProven(judged.why, matches[0]) : judged.why;
329
+ let why = verdict === 'known' ? withWarnings(judged.why, matches[0]) : judged.why;
166
330
  if (rule.source === 'uncalibrated' && matches.length) {
167
331
  why += ` (cutoffs not fitted for ${cfg.model} — run: understudy calibrate ${app})`;
168
332
  }
169
333
  const { source, ...cutoffs } = rule;
170
334
  return {
171
335
  goal, method: 'meaning', verdict, why, flows: matches, cutoffs: { ...cutoffs, source },
172
- ...(verdict === 'known' ? { best: matches[0], ...(opts.withSteps ? await plan(app, matches[0].slug) : {}) } : {}),
336
+ ...(verdict === 'known' ? { best: matches[0], ...(await steps(matches[0].slug)) } : {}),
173
337
  notes: notes.map((n) => ({ kind: n.kind, text: n.text, score: n.score })),
174
338
  };
175
339
  }
176
340
  // 3. By words, with no model. Corpora are small, so scoring every flow is fine.
177
- 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();
341
+ const all = pickVariant(await c.flows.find({ app }, { projection: { slug: 1, variant: 1, title: 1, intent: 1, kind: 1, madeBy: 1, proven: 1, unprovenBecause: 1, provenUpTo: 1, requires: 1, establishes: 1, destructive: 1, requiresSession: 1 } }).toArray(), variant);
178
342
  const matches = all
179
343
  .map((f) => toMatch(f, wordScore(goal, f)))
180
344
  .filter((m) => m.score > 0);
181
- const ranked = rank(matches).slice(0, limit);
345
+ const ranked = await withHistory(app, rank(matches).slice(0, limit), variant);
182
346
  const { verdict, why } = judge(ranked.map((m) => m.score), WORDS);
183
347
  return {
184
- goal, method: 'words', verdict, why: verdict === 'known' ? withProven(why, ranked[0]) : why, flows: ranked, notes: [],
185
- ...(verdict === 'known' ? { best: ranked[0], ...(opts.withSteps ? await plan(app, ranked[0].slug) : {}) } : {}),
348
+ goal, method: 'words', verdict, why: verdict === 'known' ? withWarnings(why, ranked[0]) : why, flows: ranked, notes: [],
349
+ ...(verdict === 'known' ? { best: ranked[0], ...(await steps(ranked[0].slug)) } : {}),
186
350
  };
187
351
  }