@jeffawe/understudy 0.0.0-stage → 0.2.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 (99) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +171 -2
  3. package/REASONER.md +67 -0
  4. package/build/extension/firefox/background.js +186 -0
  5. package/build/extension/firefox/icons/icon-128.png +0 -0
  6. package/build/extension/firefox/icons/icon-16.png +0 -0
  7. package/build/extension/firefox/icons/icon-32.png +0 -0
  8. package/build/extension/firefox/icons/icon-48.png +0 -0
  9. package/build/extension/firefox/manifest.json +54 -0
  10. package/build/extension/firefox/popup.html +52 -0
  11. package/build/extension/firefox/popup.js +106 -0
  12. package/build/extension/firefox/recorder.js +362 -0
  13. package/dist/adapters/recorder/accname-bundle.d.ts +12 -0
  14. package/dist/adapters/recorder/accname-bundle.js +12 -0
  15. package/dist/adapters/recorder/extension.d.ts +57 -0
  16. package/dist/adapters/recorder/extension.js +146 -0
  17. package/dist/adapters/recorder/injected.d.ts +21 -0
  18. package/dist/adapters/recorder/injected.js +352 -0
  19. package/dist/adapters/recorder/live.d.ts +105 -0
  20. package/dist/adapters/recorder/live.js +317 -0
  21. package/dist/adapters/recorder/script.d.ts +43 -0
  22. package/dist/adapters/recorder/script.js +530 -0
  23. package/dist/adapters/recorder/wire.d.ts +42 -0
  24. package/dist/adapters/recorder/wire.js +51 -0
  25. package/dist/core/auth-cache.d.ts +119 -0
  26. package/dist/core/auth-cache.js +216 -0
  27. package/dist/core/browser.d.ts +47 -0
  28. package/dist/core/browser.js +82 -0
  29. package/dist/core/distill.d.ts +118 -0
  30. package/dist/core/distill.js +197 -0
  31. package/dist/core/fingerprint.d.ts +15 -0
  32. package/dist/core/fingerprint.js +21 -0
  33. package/dist/core/recording-store.d.ts +34 -0
  34. package/dist/core/recording-store.js +64 -0
  35. package/dist/core/recording.d.ts +185 -0
  36. package/dist/core/recording.js +100 -0
  37. package/dist/core/replay.d.ts +307 -0
  38. package/dist/core/replay.js +804 -0
  39. package/dist/core/sig.d.ts +70 -0
  40. package/dist/core/sig.js +0 -0
  41. package/dist/core/trigger.d.ts +18 -0
  42. package/dist/core/trigger.js +35 -0
  43. package/dist/core/types.d.ts +28 -0
  44. package/dist/core/types.js +8 -0
  45. package/dist/core/visual.d.ts +80 -0
  46. package/dist/core/visual.js +111 -0
  47. package/dist/entry/cli.d.ts +9 -0
  48. package/dist/entry/cli.js +1008 -0
  49. package/dist/entry/mcp.d.ts +20 -0
  50. package/dist/entry/mcp.js +288 -0
  51. package/dist/flows/destructive.d.ts +19 -0
  52. package/dist/flows/destructive.js +48 -0
  53. package/dist/flows/distill.d.ts +28 -0
  54. package/dist/flows/distill.js +109 -0
  55. package/dist/flows/drift.d.ts +43 -0
  56. package/dist/flows/drift.js +116 -0
  57. package/dist/flows/emit.d.ts +23 -0
  58. package/dist/flows/emit.js +133 -0
  59. package/dist/flows/execute.d.ts +75 -0
  60. package/dist/flows/execute.js +133 -0
  61. package/dist/flows/findings.d.ts +38 -0
  62. package/dist/flows/findings.js +136 -0
  63. package/dist/flows/runs.d.ts +42 -0
  64. package/dist/flows/runs.js +93 -0
  65. package/dist/flows/save.d.ts +74 -0
  66. package/dist/flows/save.js +171 -0
  67. package/dist/memory/notes.d.ts +89 -0
  68. package/dist/memory/notes.js +163 -0
  69. package/dist/memory/placeholders.d.ts +41 -0
  70. package/dist/memory/placeholders.js +139 -0
  71. package/dist/memory/recall.d.ts +118 -0
  72. package/dist/memory/recall.js +147 -0
  73. package/dist/memory/vocabulary.d.ts +9 -0
  74. package/dist/memory/vocabulary.js +24 -0
  75. package/dist/plan/planner.d.ts +69 -0
  76. package/dist/plan/planner.js +211 -0
  77. package/dist/plan/seams.d.ts +58 -0
  78. package/dist/plan/seams.js +99 -0
  79. package/dist/store/db.d.ts +62 -0
  80. package/dist/store/db.js +183 -0
  81. package/dist/store/embed.d.ts +46 -0
  82. package/dist/store/embed.js +100 -0
  83. package/dist/store/reembed.d.ts +13 -0
  84. package/dist/store/reembed.js +32 -0
  85. package/dist/store/settings.d.ts +67 -0
  86. package/dist/store/settings.js +151 -0
  87. package/dist/store/types.d.ts +220 -0
  88. package/dist/store/types.js +14 -0
  89. package/extension/README.md +79 -0
  90. package/extension/background.js +186 -0
  91. package/extension/icons/icon-128.png +0 -0
  92. package/extension/icons/icon-16.png +0 -0
  93. package/extension/icons/icon-32.png +0 -0
  94. package/extension/icons/icon-48.png +0 -0
  95. package/extension/manifest.json +38 -0
  96. package/extension/popup.html +52 -0
  97. package/extension/popup.js +106 -0
  98. package/extension/recorder.js +362 -0
  99. package/package.json +68 -4
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Recording what happened when a flow ran.
3
+ *
4
+ * Every replay of a saved flow — including the one that proves it on save —
5
+ * goes through recordRun, which:
6
+ * 1. compares the path taken with recent passed runs (drift)
7
+ * 2. turns captured errors into findings, deduped (findings)
8
+ * 3. adds the pages it passed through to the page map (pages)
9
+ * 4. stores the run itself (runs)
10
+ */
11
+ import type { ObjectId } from 'mongodb';
12
+ import type { ReplayResult } from '../core/replay.js';
13
+ import type { Step } from '../store/types.js';
14
+ import { type Drift } from './drift.js';
15
+ import { type FindingDraft } from './findings.js';
16
+ export interface RecordedRun {
17
+ runId: ObjectId;
18
+ drift: Drift;
19
+ findings: FindingDraft[];
20
+ }
21
+ export declare function recordRun(opts: {
22
+ app: string;
23
+ flow: string;
24
+ result: ReplayResult;
25
+ /** The flow's steps, for naming the links between pages. */
26
+ steps: Step[];
27
+ /** 'replay' when a flow was named; 'run' when it was found from a goal. */
28
+ mode?: 'replay' | 'run';
29
+ /** What was asked for. Defaults to the flow's slug. */
30
+ goal?: string;
31
+ /** The flows run, in order, when it was more than one. Defaults to [flow]. */
32
+ plan?: string[];
33
+ /**
34
+ * A flow in this run is unproven. If the run fails, what it saw may come from
35
+ * the recording being wrong (landing on a page the flow never meant to), not
36
+ * the app — its findings say so.
37
+ */
38
+ unproven?: boolean;
39
+ /** Fill in this existing run (one that was planned first) instead of adding a new one. */
40
+ runId?: ObjectId;
41
+ startedAt?: Date;
42
+ }): Promise<RecordedRun>;
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Recording what happened when a flow ran.
3
+ *
4
+ * Every replay of a saved flow — including the one that proves it on save —
5
+ * goes through recordRun, which:
6
+ * 1. compares the path taken with recent passed runs (drift)
7
+ * 2. turns captured errors into findings, deduped (findings)
8
+ * 3. adds the pages it passed through to the page map (pages)
9
+ * 4. stores the run itself (runs)
10
+ */
11
+ import { collections } from '../store/db.js';
12
+ import { compareToHistory, driftFinding } from './drift.js';
13
+ import { extractFindings, saveFindings } from './findings.js';
14
+ import { stepFingerprint } from '../core/fingerprint.js';
15
+ /** `/inventory.html#bf3dd322` → `/inventory.html` */
16
+ const pageOf = (sig) => sig.slice(0, sig.lastIndexOf('#')) || sig;
17
+ /** How many recent passed runs drift compares with. */
18
+ const LOOKBACK = 5;
19
+ export async function recordRun(opts) {
20
+ const { app, flow, result, steps } = opts;
21
+ const plan = opts.plan ?? [flow];
22
+ const c = await collections();
23
+ const now = new Date();
24
+ // 1. Drift, against the most recent passed runs of this flow — however it
25
+ // was started, it walked the same steps.
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 } })
28
+ .sort({ startedAt: -1 })
29
+ .limit(LOOKBACK)
30
+ .toArray();
31
+ // A failed run stops early; comparing its short path would report every
32
+ // page it never reached as "gone", which is noise, not drift.
33
+ const drift = result.ok
34
+ ? compareToHistory(result.sigSequence, history.map((h) => h.sigSequence))
35
+ : compareToHistory([], []);
36
+ // 2. Findings.
37
+ const name = plan.join(' + ');
38
+ const drafts = extractFindings(result, name);
39
+ if (opts.unproven && !result.ok) {
40
+ for (const d of drafts)
41
+ d.evidence = { ...d.evidence, fromUnprovenFlow: 'a failed run of an unproven flow — may be the recording, not the app' };
42
+ }
43
+ const fromDrift = driftFinding(name, drift);
44
+ if (fromDrift)
45
+ drafts.push(fromDrift);
46
+ await saveFindings(c.findings, app, drafts, now);
47
+ // 3. Pages, and the control that led from one to the next.
48
+ let prev;
49
+ for (const outcome of result.steps) {
50
+ const sig = outcome.sig;
51
+ if (!sig)
52
+ continue;
53
+ const step = steps[outcome.seq];
54
+ const via = step?.role && step.name ? { role: step.role, name: step.name } : undefined;
55
+ await c.pages.updateOne({ app, sig }, { $set: { lastSeen: now }, $setOnInsert: { app, sig, urlPattern: pageOf(sig), links: [], firstSeen: now } }, { upsert: true });
56
+ // A link belongs to the page it leaves FROM: "on prev, clicking `via` leads to sig".
57
+ if (prev && prev !== sig && via) {
58
+ await c.pages.updateOne({ app, sig: prev }, { $addToSet: { links: { to: sig, via } } });
59
+ }
60
+ prev = sig;
61
+ }
62
+ // 4. The run.
63
+ const run = {
64
+ app,
65
+ goal: opts.goal ?? flow,
66
+ mode: opts.mode ?? 'replay',
67
+ status: result.ok ? 'passed' : 'failed',
68
+ plan,
69
+ steps: result.steps.map((s) => {
70
+ const step = steps[s.seq];
71
+ return {
72
+ seq: s.seq, action: s.action, ok: s.ok,
73
+ ...(s.sig ? { sig: s.sig } : {}),
74
+ ...(s.error ? { error: s.error } : {}),
75
+ // Identifies "this kind of step" across runs — how a lesson knows a step like it has failed before.
76
+ ...(step ? { fingerprint: stepFingerprint({ ...step, seq: s.seq, ts: 0 }) } : {}),
77
+ };
78
+ }),
79
+ sigSequence: result.sigSequence,
80
+ events: result.signals.slice(0, 200).map((s) => ({ ...s })),
81
+ findings: drafts.map((d) => d.fingerprint),
82
+ durationMs: result.durationMs,
83
+ startedAt: opts.startedAt ?? new Date(now.getTime() - result.durationMs),
84
+ endedAt: now,
85
+ };
86
+ if (opts.runId) {
87
+ // A planned run: keep its question history and planning, add what happened.
88
+ await c.runs.updateOne({ _id: opts.runId }, { $set: run, $unset: { question: '' } });
89
+ return { runId: opts.runId, drift, findings: drafts };
90
+ }
91
+ const { insertedId } = await c.runs.insertOne(run);
92
+ return { runId: insertedId, drift, findings: drafts };
93
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Saving a recording as a flow — turning a capture into memory.
3
+ *
4
+ * The recording must have replayed cleanly first (the caller proves it), so
5
+ * what's stored is a flow that is known to work, not a story about one. Each
6
+ * step keeps the page it landed on during that proof as its `expectedSig`,
7
+ * which is how a later replay notices it ended up somewhere unexpected.
8
+ *
9
+ * Saving the same name again replaces the flow — re-record, re-save, done.
10
+ */
11
+ import type { RawRecording } from '../core/recording.js';
12
+ import type { ReplayResult } from '../core/replay.js';
13
+ import type { Flow, Step } from '../store/types.js';
14
+ import { type Proven } from './execute.js';
15
+ import { type RecordedRun } from './runs.js';
16
+ import { type Applied } from '../memory/placeholders.js';
17
+ /** "Log in as a member!" → "log-in-as-a-member" */
18
+ export declare function slugify(title: string): string;
19
+ /** A recording's events, as the steps of a flow. Drops recorder bookkeeping and empty fields. */
20
+ export declare function stepsFrom(recording: RawRecording, result?: ReplayResult): Step[];
21
+ /** Turn a flow back into a recording that replay can run. */
22
+ export declare function recordingFrom(flow: Flow): RawRecording;
23
+ export interface SaveOptions {
24
+ title: string;
25
+ /** Defaults to slugify(title). */
26
+ slug?: string;
27
+ /** What the flow is for, if different from the title. */
28
+ intent?: string;
29
+ /** 'agent' when an agent drove it and handed over the script. Default 'user'. */
30
+ madeBy?: 'user' | 'agent';
31
+ /** Set when it's being kept without a passing replay: why. Marks the flow unproven. */
32
+ unproven?: string;
33
+ }
34
+ export declare function saveFlow(recording: RawRecording, result: ReplayResult, opts: SaveOptions): Promise<Flow>;
35
+ export interface ProveAndSave extends SaveOptions {
36
+ /** Login values, if not in the environment as UNDERSTUDY_<REF>. */
37
+ values?: Record<string, string>;
38
+ headed?: boolean;
39
+ /**
40
+ * false: keep it without replaying it — e.g. it ends in a real purchase, or
41
+ * the caller already knows it works. It's saved as unproven; the first run
42
+ * that passes proves it.
43
+ */
44
+ verify?: boolean;
45
+ /** Keep it even though the replay failed (saved as unproven). */
46
+ force?: boolean;
47
+ /** Asked when the replay fails: keep it anyway, as unproven? (The terminal asks the user.) */
48
+ keepIfFailed?: (proven: Proven) => Promise<boolean>;
49
+ }
50
+ export type SaveOutcome = {
51
+ saved: false;
52
+ proven: Proven;
53
+ } | {
54
+ saved: true;
55
+ verified: boolean;
56
+ proven?: Proven;
57
+ flow: Flow;
58
+ run?: RecordedRun;
59
+ placeholders: Applied;
60
+ };
61
+ /**
62
+ * What `save` does, for the CLI and the MCP server alike: prove the recording
63
+ * (replaying it headless, working out whether it needs to start signed in),
64
+ * then store it as a flow and record that first run. A recording that fails
65
+ * its replay is only kept if the caller says so (force / keepIfFailed), and
66
+ * then as unproven. With verify: false there's no replay at all.
67
+ */
68
+ export declare function proveAndSave(recording: RawRecording, opts: ProveAndSave): Promise<SaveOutcome>;
69
+ /**
70
+ * An unproven flow that just passed a run is proven now: mark it, and fill in
71
+ * what its missing replay would have recorded — the page each step lands on,
72
+ * and where it starts and ends. `offset` skips steps the run added in front.
73
+ */
74
+ export declare function proveByRun(app: string, slug: string, result: ReplayResult, offset?: number): Promise<boolean>;
@@ -0,0 +1,171 @@
1
+ /**
2
+ * Saving a recording as a flow — turning a capture into memory.
3
+ *
4
+ * The recording must have replayed cleanly first (the caller proves it), so
5
+ * what's stored is a flow that is known to work, not a story about one. Each
6
+ * step keeps the page it landed on during that proof as its `expectedSig`,
7
+ * which is how a later replay notices it ended up somewhere unexpected.
8
+ *
9
+ * Saving the same name again replaces the flow — re-record, re-save, done.
10
+ */
11
+ import { collections, ensureSchema } from '../store/db.js';
12
+ import { embed, embedderConfig } from '../store/embed.js';
13
+ import { flowDestructiveReason } from './destructive.js';
14
+ import { prove } from './execute.js';
15
+ import { forgetSessionById } from '../core/auth-cache.js';
16
+ import { recordRun } from './runs.js';
17
+ import { applyPlaceholders } from '../memory/placeholders.js';
18
+ /** "Log in as a member!" → "log-in-as-a-member" */
19
+ export function slugify(title) {
20
+ return title.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 80);
21
+ }
22
+ /** A recording's events, as the steps of a flow. Drops recorder bookkeeping and empty fields. */
23
+ export function stepsFrom(recording, result) {
24
+ const observed = new Map(result?.steps.map((s) => [s.seq, s.sig]));
25
+ return recording.events.map((e) => {
26
+ const { seq, ts, ...rest } = e;
27
+ const step = Object.fromEntries(Object.entries(rest).filter(([, v]) => v !== undefined));
28
+ const sig = observed.get(seq);
29
+ if (sig)
30
+ step.expectedSig = sig;
31
+ return step;
32
+ });
33
+ }
34
+ /** Turn a flow back into a recording that replay can run. */
35
+ export function recordingFrom(flow) {
36
+ return {
37
+ version: 1,
38
+ source: 'import',
39
+ origin: `flow:${flow.slug}`,
40
+ appSlug: flow.app,
41
+ startUrl: flow.startUrl,
42
+ createdAt: flow.updatedAt.toISOString(),
43
+ hash: flow.recording,
44
+ ...(flow.requiresSession
45
+ ? { entry: { requiresSession: true, ...(flow.startState ? { startState: flow.startState } : {}), ...(flow.session ? { session: flow.session } : {}) } }
46
+ : {}),
47
+ events: flow.steps.map((s, i) => ({ ...s, seq: i, ts: i })),
48
+ };
49
+ }
50
+ export async function saveFlow(recording, result, opts) {
51
+ await ensureSchema(); // also refuses to mix embedding models
52
+ const { apps, flows } = await collections();
53
+ const app = recording.appSlug;
54
+ const slug = opts.slug ?? slugify(opts.title);
55
+ if (!slug)
56
+ throw new Error(`can't make a flow name from "${opts.title}" — pass --slug`);
57
+ const steps = stepsFrom(recording, result);
58
+ const why = flowDestructiveReason(steps);
59
+ const intent = opts.intent ?? opts.title;
60
+ const searchText = [opts.title, intent !== opts.title ? intent : ''].filter(Boolean).join('. ');
61
+ const [embedding] = embedderConfig() ? await embed([searchText], 'document') : [];
62
+ const now = new Date();
63
+ const flow = {
64
+ app,
65
+ slug,
66
+ title: opts.title,
67
+ intent,
68
+ kind: 'recording',
69
+ madeBy: opts.madeBy ?? 'user',
70
+ preconditions: recording.entry?.requiresSession ? ['authenticated'] : [],
71
+ outcome: '',
72
+ destructive: Boolean(why),
73
+ ...(why ? { destructiveBecause: why } : {}),
74
+ corrections: [],
75
+ recording: recording.hash,
76
+ startUrl: recording.startUrl,
77
+ requiresSession: Boolean(recording.entry?.requiresSession),
78
+ ...(recording.entry?.session ? { session: recording.entry.session } : {}),
79
+ ...(result.sigSequence[0] ? { startState: recording.entry?.startState ?? result.sigSequence[0] } : {}),
80
+ ...(result.sigSequence.length ? { endState: result.sigSequence.at(-1) } : {}),
81
+ steps,
82
+ searchText,
83
+ ...(embedding ? { embedding } : {}),
84
+ ...(opts.unproven ? { proven: false, unprovenBecause: opts.unproven } : {}),
85
+ updatedAt: now,
86
+ };
87
+ // Replace, not merge: a re-saved flow must not keep a stale embedding or
88
+ // destructive mark from the previous version.
89
+ const unset = {};
90
+ if (!embedding)
91
+ unset.embedding = '';
92
+ if (!why)
93
+ unset.destructiveBecause = '';
94
+ if (!recording.entry?.session)
95
+ unset.session = '';
96
+ if (!opts.unproven) {
97
+ unset.proven = '';
98
+ unset.unprovenBecause = '';
99
+ }
100
+ await flows.updateOne({ app, slug }, { $set: flow, $setOnInsert: { createdAt: now }, ...(Object.keys(unset).length ? { $unset: unset } : {}) }, { upsert: true });
101
+ // Make sure the app exists, remembering where it lives.
102
+ await apps.updateOne({ slug: app }, { $setOnInsert: { slug: app, name: app, urls: { default: new URL(recording.startUrl).origin }, createdAt: now } }, { upsert: true });
103
+ return (await flows.findOne({ app, slug }));
104
+ }
105
+ /**
106
+ * What `save` does, for the CLI and the MCP server alike: prove the recording
107
+ * (replaying it headless, working out whether it needs to start signed in),
108
+ * then store it as a flow and record that first run. A recording that fails
109
+ * its replay is only kept if the caller says so (force / keepIfFailed), and
110
+ * then as unproven. With verify: false there's no replay at all.
111
+ */
112
+ export async function proveAndSave(recording, opts) {
113
+ if (opts.verify === false) {
114
+ // No replay, so nothing can say whether a copied sign-in is needed. Unless
115
+ // the user said it is (ticked "I'm signed in here"), don't keep it.
116
+ let rec = recording;
117
+ if (rec.entry?.session && !rec.entry.requiresSession) {
118
+ await forgetSessionById(rec.appSlug, rec.entry.session);
119
+ const { session: _gone, ...rest } = rec.entry;
120
+ rec = { ...rec };
121
+ if (Object.keys(rest).length)
122
+ rec.entry = rest;
123
+ else
124
+ delete rec.entry;
125
+ }
126
+ const none = { ok: true, steps: [], sigSequence: [], signals: [], durationMs: 0 };
127
+ const flow = await saveFlow(rec, none, { ...opts, unproven: opts.unproven ?? 'saved without a replay' });
128
+ return { saved: true, verified: false, ...(await withPlaceholders(flow)) };
129
+ }
130
+ const proven = await prove(recording, { ...(opts.values ? { values: opts.values } : {}), ...(opts.headed ? { headed: true } : {}) });
131
+ let unproven = opts.unproven;
132
+ if (!proven.result.ok) {
133
+ const keep = opts.force || (opts.keepIfFailed ? await opts.keepIfFailed(proven) : false);
134
+ if (!keep)
135
+ return { saved: false, proven };
136
+ unproven ??= 'its replay failed, and it was kept anyway';
137
+ }
138
+ const saved = await saveFlow(proven.recording, proven.result, { ...opts, ...(unproven ? { unproven } : {}) });
139
+ const { flow, placeholders } = await withPlaceholders(saved);
140
+ const run = await recordRun({ app: flow.app, flow: flow.slug, result: proven.result, steps: flow.steps, ...(flow.proven === false ? { unproven: true } : {}) });
141
+ return { saved: true, verified: proven.result.ok, proven, flow, run, placeholders };
142
+ }
143
+ /** The app keeps email fields as placeholders? Convert now — after proving, which used the real address. */
144
+ async function withPlaceholders(flow) {
145
+ const placeholders = await applyPlaceholders(flow.app, undefined, flow.slug);
146
+ if (!placeholders.converted.length)
147
+ return { flow, placeholders };
148
+ return { flow: (await (await collections()).flows.findOne({ _id: flow._id })), placeholders };
149
+ }
150
+ /**
151
+ * An unproven flow that just passed a run is proven now: mark it, and fill in
152
+ * what its missing replay would have recorded — the page each step lands on,
153
+ * and where it starts and ends. `offset` skips steps the run added in front.
154
+ */
155
+ export async function proveByRun(app, slug, result, offset = 0) {
156
+ if (!result.ok)
157
+ return false;
158
+ const { flows } = await collections();
159
+ const flow = await flows.findOne({ app, slug, proven: false });
160
+ if (!flow)
161
+ return false;
162
+ const sigAt = new Map(result.steps.map((s) => [s.seq - offset, s.sig]));
163
+ const steps = flow.steps.map((s, i) => (sigAt.get(i) ? { ...s, expectedSig: sigAt.get(i) } : s));
164
+ const first = offset > 0 ? result.steps.find((s) => s.seq === offset - 1)?.sig : result.sigSequence[0];
165
+ const last = sigAt.get(flow.steps.length - 1);
166
+ await flows.updateOne({ _id: flow._id }, {
167
+ $set: { steps, ...(first && !flow.startState ? { startState: first } : {}), ...(last ? { endState: last } : {}), updatedAt: new Date() },
168
+ $unset: { proven: '', unprovenBecause: '' },
169
+ });
170
+ return true;
171
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Writing down what was learned, and using it.
3
+ *
4
+ * remember() one validated batch of facts, lessons, findings, and goals
5
+ * reached by other means. Every problem is reported at once,
6
+ * and nothing is written unless the whole batch is clean.
7
+ * lessonsFor() the lessons whose trigger matches a step — replay asks
8
+ * before every step.
9
+ * foldLessons() after a run, count which lessons fired and whether they
10
+ * helped.
11
+ *
12
+ * A FACT changes what you plan ("order history is at /past-invoices").
13
+ * A LESSON changes one step ("when filling Card number, dismiss Stripe Link first").
14
+ * A FINDING says the app is broken and someone should fix it.
15
+ * Ported from the old remember.ts and lessons.ts.
16
+ */
17
+ import type { RawEvent } from '../core/recording.js';
18
+ import type { Trigger } from '../store/types.js';
19
+ export interface RememberInput {
20
+ facts?: {
21
+ text: string;
22
+ marksDestructive?: string;
23
+ }[];
24
+ lessons?: {
25
+ title: string;
26
+ text: string;
27
+ kind: string;
28
+ trigger: Trigger;
29
+ }[];
30
+ findings?: {
31
+ kind: string;
32
+ severity: 'low' | 'medium' | 'high';
33
+ statement: string;
34
+ fingerprint: string;
35
+ evidence?: Record<string, unknown>;
36
+ }[];
37
+ /** A goal an agent reached WITHOUT Understudy driving (its own Playwright, by hand…). */
38
+ reached?: {
39
+ goal: string;
40
+ passed: boolean;
41
+ drivenBy?: string;
42
+ note?: string;
43
+ sigSequence?: string[];
44
+ }[];
45
+ }
46
+ /** Every problem in the batch, so one round trip is enough to fix them all. */
47
+ export declare function validateRemember(input: RememberInput): string[];
48
+ export interface RememberResult {
49
+ facts: {
50
+ written: number;
51
+ alreadyKnown: number;
52
+ };
53
+ lessons: {
54
+ written: number;
55
+ alreadyKnown: number;
56
+ };
57
+ findings: number;
58
+ reached: number;
59
+ }
60
+ export declare function remember(app: string, input: RememberInput): Promise<RememberResult>;
61
+ /** What replay hands over before each step. */
62
+ export type StepContext = Trigger;
63
+ /**
64
+ * Lessons whose trigger matches this step: every field the trigger names must
65
+ * equal the step's; fields it leaves out match anything.
66
+ */
67
+ export declare function lessonsFor(app: string, ctx: StepContext): Promise<{
68
+ lessonId: string;
69
+ kind: string;
70
+ title: string;
71
+ body: string;
72
+ }[]>;
73
+ /**
74
+ * Count lesson firings after a run. `timesHelped` only counts when the step
75
+ * passed AND a step like it has failed before — otherwise there was nothing
76
+ * for the lesson to fix, and "it fired, the step passed" proves nothing.
77
+ */
78
+ export declare function foldLessons(app: string, steps: {
79
+ seq: number;
80
+ ok: boolean;
81
+ lessonsApplied?: {
82
+ lessonId: string;
83
+ }[];
84
+ }[], events: RawEvent[]): Promise<{
85
+ fired: number;
86
+ helped: number;
87
+ }>;
88
+ /** Controls that facts say commit something real: clicking one makes a flow destructive. */
89
+ export declare function destructiveControls(app: string): Promise<Map<string, string>>;
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Writing down what was learned, and using it.
3
+ *
4
+ * remember() one validated batch of facts, lessons, findings, and goals
5
+ * reached by other means. Every problem is reported at once,
6
+ * and nothing is written unless the whole batch is clean.
7
+ * lessonsFor() the lessons whose trigger matches a step — replay asks
8
+ * before every step.
9
+ * foldLessons() after a run, count which lessons fired and whether they
10
+ * helped.
11
+ *
12
+ * A FACT changes what you plan ("order history is at /past-invoices").
13
+ * A LESSON changes one step ("when filling Card number, dismiss Stripe Link first").
14
+ * A FINDING says the app is broken and someone should fix it.
15
+ * Ported from the old remember.ts and lessons.ts.
16
+ */
17
+ import { ObjectId } from 'mongodb';
18
+ import { collections, ensureSchema } from '../store/db.js';
19
+ import { embed, embedderConfig } from '../store/embed.js';
20
+ import { triggerProblems } from '../core/trigger.js';
21
+ import { stepFingerprint } from '../core/fingerprint.js';
22
+ import { saveFindings } from '../flows/findings.js';
23
+ const SEVERITIES = ['low', 'medium', 'high'];
24
+ const filled = (v) => typeof v === 'string' && v.trim().length > 0;
25
+ /** Every problem in the batch, so one round trip is enough to fix them all. */
26
+ export function validateRemember(input) {
27
+ const p = [];
28
+ const { facts = [], lessons = [], findings = [], reached = [] } = input ?? {};
29
+ if (!facts.length && !lessons.length && !findings.length && !reached.length) {
30
+ p.push('nothing to write: facts, lessons, findings and reached are all empty');
31
+ }
32
+ facts.forEach((f, i) => {
33
+ if (!filled(f?.text))
34
+ p.push(`facts[${i}].text is required`);
35
+ if (f?.marksDestructive !== undefined && !filled(f.marksDestructive))
36
+ p.push(`facts[${i}].marksDestructive must be a control's name`);
37
+ });
38
+ lessons.forEach((l, i) => {
39
+ for (const k of ['title', 'text', 'kind'])
40
+ if (!filled(l?.[k]))
41
+ p.push(`lessons[${i}].${k} is required`);
42
+ for (const e of triggerProblems(l?.trigger))
43
+ p.push(`lessons[${i}].${e}`);
44
+ });
45
+ findings.forEach((f, i) => {
46
+ for (const k of ['kind', 'statement', 'fingerprint'])
47
+ if (!filled(f?.[k]))
48
+ p.push(`findings[${i}].${k} is required`);
49
+ if (!SEVERITIES.includes(f?.severity))
50
+ p.push(`findings[${i}].severity must be one of ${SEVERITIES.join(', ')}`);
51
+ });
52
+ reached.forEach((r, i) => {
53
+ if (!filled(r?.goal))
54
+ p.push(`reached[${i}].goal is required`);
55
+ if (typeof r?.passed !== 'boolean')
56
+ p.push(`reached[${i}].passed must be true or false`);
57
+ });
58
+ return p;
59
+ }
60
+ export async function remember(app, input) {
61
+ const problems = validateRemember(input);
62
+ if (problems.length)
63
+ throw new Error(`nothing written — fix these and send the batch again:\n- ${problems.join('\n- ')}`);
64
+ await ensureSchema();
65
+ const c = await collections();
66
+ const { facts = [], lessons = [], findings = [], reached = [] } = input;
67
+ const out = { facts: { written: 0, alreadyKnown: 0 }, lessons: { written: 0, alreadyKnown: 0 }, findings: 0, reached: 0 };
68
+ const now = new Date();
69
+ // Only new notes are embedded, all in one request.
70
+ const newFacts = [];
71
+ for (const f of facts) {
72
+ if (await c.notes.findOne({ app, kind: 'fact', text: f.text }))
73
+ out.facts.alreadyKnown++;
74
+ else
75
+ newFacts.push(f);
76
+ }
77
+ const newLessons = [];
78
+ for (const l of lessons) {
79
+ // Deduped by title: a lesson stored twice fires twice and splits its counts.
80
+ if (await c.notes.findOne({ app, kind: 'lesson', title: l.title }))
81
+ out.lessons.alreadyKnown++;
82
+ else
83
+ newLessons.push(l);
84
+ }
85
+ const texts = [...newFacts.map((f) => f.text), ...newLessons.map((l) => `${l.title}. ${l.text}`)];
86
+ const vectors = embedderConfig() && texts.length ? await embed(texts, 'document') : [];
87
+ const docs = [
88
+ ...newFacts.map((f, i) => ({
89
+ app, kind: 'fact', text: f.text, searchText: f.text,
90
+ ...(f.marksDestructive ? { marksDestructive: f.marksDestructive } : {}),
91
+ ...(vectors[i] ? { embedding: vectors[i] } : {}),
92
+ timesApplied: 0, timesHelped: 0, createdAt: now,
93
+ })),
94
+ ...newLessons.map((l, i) => ({
95
+ app, kind: 'lesson', title: l.title, text: l.text, lessonKind: l.kind, trigger: l.trigger,
96
+ searchText: `${l.title}. ${l.text}`,
97
+ ...(vectors[newFacts.length + i] ? { embedding: vectors[newFacts.length + i] } : {}),
98
+ timesApplied: 0, timesHelped: 0, createdAt: now,
99
+ })),
100
+ ];
101
+ if (docs.length)
102
+ await c.notes.insertMany(docs);
103
+ out.facts.written = newFacts.length;
104
+ out.lessons.written = newLessons.length;
105
+ await saveFindings(c.findings, app, findings.map((f) => ({ ...f, evidence: f.evidence ?? {} })), now);
106
+ out.findings = findings.length;
107
+ // "This goal works" from something other than Understudy's executor. Stored
108
+ // as 'attributed', never as a replay: only a replay proves the executor can do it.
109
+ for (const r of reached) {
110
+ await c.runs.insertOne({
111
+ app, goal: r.goal, mode: 'attributed', status: r.passed ? 'passed' : 'failed',
112
+ plan: [], steps: [], sigSequence: r.sigSequence ?? [],
113
+ events: [{ drivenBy: r.drivenBy ?? 'unspecified', ...(r.note ? { note: r.note } : {}) }],
114
+ findings: [], durationMs: 0, startedAt: now, endedAt: now,
115
+ });
116
+ out.reached++;
117
+ }
118
+ return out;
119
+ }
120
+ /**
121
+ * Lessons whose trigger matches this step: every field the trigger names must
122
+ * equal the step's; fields it leaves out match anything.
123
+ */
124
+ export async function lessonsFor(app, ctx) {
125
+ const { notes } = await collections();
126
+ // Each trigger field must either be absent or equal the step's value.
127
+ const match = (k) => ({ $or: [{ [`trigger.${k}`]: { $exists: false } }, { [`trigger.${k}`]: ctx[k] ?? null }] });
128
+ const rows = await notes
129
+ .find({ app, kind: 'lesson', $and: [match('url_pattern'), match('action'), match('role'), match('name')] })
130
+ .toArray();
131
+ return rows.map((n) => ({ lessonId: String(n._id), kind: n.lessonKind ?? 'other', title: n.title ?? '', body: n.text }));
132
+ }
133
+ /**
134
+ * Count lesson firings after a run. `timesHelped` only counts when the step
135
+ * passed AND a step like it has failed before — otherwise there was nothing
136
+ * for the lesson to fix, and "it fired, the step passed" proves nothing.
137
+ */
138
+ export async function foldLessons(app, steps, events) {
139
+ const c = await collections();
140
+ const bySeq = new Map(events.map((e) => [e.seq, e]));
141
+ let fired = 0;
142
+ let helped = 0;
143
+ for (const s of steps) {
144
+ if (!s.lessonsApplied?.length)
145
+ continue;
146
+ fired += s.lessonsApplied.length;
147
+ const event = bySeq.get(s.seq);
148
+ const failedBefore = s.ok && event
149
+ ? Boolean(await c.runs.findOne({ app, steps: { $elemMatch: { fingerprint: stepFingerprint(event), ok: false } } }))
150
+ : false;
151
+ if (failedBefore)
152
+ helped += s.lessonsApplied.length;
153
+ const ids = s.lessonsApplied.map((l) => l.lessonId);
154
+ await c.notes.updateMany({ _id: { $in: ids.map((id) => new ObjectId(id)) } }, { $inc: { timesApplied: 1, ...(failedBefore ? { timesHelped: 1 } : {}) } });
155
+ }
156
+ return { fired, helped };
157
+ }
158
+ /** Controls that facts say commit something real: clicking one makes a flow destructive. */
159
+ export async function destructiveControls(app) {
160
+ const { notes } = await collections();
161
+ const rows = await notes.find({ app, kind: 'fact', marksDestructive: { $exists: true } }).toArray();
162
+ return new Map(rows.map((n) => [n.marksDestructive.toLowerCase(), n.text]));
163
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Keeping more typed values out of memory, per app.
3
+ *
4
+ * Passwords are always placeholders. An app can also choose `email`: every
5
+ * email field in its flows stops storing the address it was recorded with and
6
+ * uses a placeholder instead — `USER.email`, read from the user's env file —
7
+ * so a test account can be swapped per run and personal data doesn't sit in a
8
+ * (possibly shared) database.
9
+ *
10
+ * Turning it on converts the app's existing flows and MOVES each address into
11
+ * the env file, so nothing breaks and nothing needs setting up. New flows are
12
+ * converted when they're saved, after they've been proven with the real value.
13
+ *
14
+ * Several different addresses in one app (several test accounts) each get
15
+ * their own placeholder — the most used is USER.email, then USER.email_2 … —
16
+ * because merging them would quietly log some flows in as the wrong account.
17
+ */
18
+ import { type PlaceholderKind, type Step } from '../store/types.js';
19
+ /** Is this a step that types an email address the recording stored as-is? */
20
+ export declare function isEmailStep(s: Step): boolean;
21
+ export interface Applied {
22
+ app: string;
23
+ placeholders: PlaceholderKind[];
24
+ /** Each placeholder, the flows now using it, and where its value lives. */
25
+ converted: {
26
+ placeholder: string;
27
+ flows: string[];
28
+ valueIn: string;
29
+ }[];
30
+ /** The env file values were written to, if any were. */
31
+ envFile?: string;
32
+ }
33
+ /** The app's chosen kinds (validated). */
34
+ export declare function appPlaceholders(app: string): Promise<PlaceholderKind[]>;
35
+ /** Choose which kinds of value an app keeps as placeholders, and apply it to its flows now. */
36
+ export declare function setPlaceholders(app: string, kinds: string[]): Promise<Applied>;
37
+ /**
38
+ * Convert the app's flows (or just `onlyFlow`) to placeholders for the chosen
39
+ * kinds, moving each value into the env file unless the environment already has it.
40
+ */
41
+ export declare function applyPlaceholders(app: string, kinds?: PlaceholderKind[], onlyFlow?: string): Promise<Applied>;