@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,20 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * understudy MCP server — memory and execution for any agent that speaks MCP
4
+ * (Claude Code, Codex, Cursor…). The agent is the model: Understudy never
5
+ * calls one. REASONER.md is the contract for using these tools.
6
+ *
7
+ * understudy_recall what memory knows about a goal (free, nothing runs)
8
+ * understudy_run plan a goal; returns a question, or runs it
9
+ * understudy_answer answer a run's question; returns the next one, or runs it
10
+ * understudy_distill a saved flow's numbered steps, to name and split
11
+ * understudy_save_distilled store that answer (validated; every problem at once)
12
+ * understudy_remember store facts, lessons, findings, goals reached by other means
13
+ * understudy_findings list open findings; triage them
14
+ * understudy_record wait for the user to record a flow in their Chrome
15
+ * understudy_save prove a recording by replaying it, then keep it as a flow
16
+ * understudy_app an app's settings — e.g. keep email fields as placeholders
17
+ *
18
+ * Long-lived: reconnect (/mcp) after changing the source.
19
+ */
20
+ export {};
@@ -0,0 +1,288 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * understudy MCP server — memory and execution for any agent that speaks MCP
4
+ * (Claude Code, Codex, Cursor…). The agent is the model: Understudy never
5
+ * calls one. REASONER.md is the contract for using these tools.
6
+ *
7
+ * understudy_recall what memory knows about a goal (free, nothing runs)
8
+ * understudy_run plan a goal; returns a question, or runs it
9
+ * understudy_answer answer a run's question; returns the next one, or runs it
10
+ * understudy_distill a saved flow's numbered steps, to name and split
11
+ * understudy_save_distilled store that answer (validated; every problem at once)
12
+ * understudy_remember store facts, lessons, findings, goals reached by other means
13
+ * understudy_findings list open findings; triage them
14
+ * understudy_record wait for the user to record a flow in their Chrome
15
+ * understudy_save prove a recording by replaying it, then keep it as a flow
16
+ * understudy_app an app's settings — e.g. keep email fields as placeholders
17
+ *
18
+ * Long-lived: reconnect (/mcp) after changing the source.
19
+ */
20
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
21
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
22
+ import { z } from 'zod';
23
+ import { recall } from '../memory/recall.js';
24
+ import { remember } from '../memory/notes.js';
25
+ import { start, answer, runPlan } from '../plan/planner.js';
26
+ import { distillRequest, saveDistilled } from '../flows/distill.js';
27
+ import { triage } from '../flows/findings.js';
28
+ import { collections } from '../store/db.js';
29
+ import { startExtensionRecorder, extensionDir } from '../adapters/recorder/extension.js';
30
+ import { saveRecording, loadRecording } from '../core/recording-store.js';
31
+ import { proveAndSave } from '../flows/save.js';
32
+ import { MissingValuesError } from '../flows/execute.js';
33
+ import { parseScript } from '../adapters/recorder/script.js';
34
+ import { setPlaceholders, appPlaceholders } from '../memory/placeholders.js';
35
+ /**
36
+ * Sent to the agent when it connects — its copy of the contract, since an
37
+ * agent that installed Understudy from npm never sees REASONER.md. Kept short:
38
+ * every session pays for it.
39
+ */
40
+ const INSTRUCTIONS = `Understudy remembers the user's web-app flows and runs them as end-to-end tests. You supply judgement; it calls no model.
41
+ - Recall first: free, runs nothing. A known flow comes with its steps and the login values it needs. Run it with understudy_run, or drive it yourself — say which.
42
+ - Runs ask before a browser opens. decompose: subGoals in the order the app does them, in the words of its flows. seam: one click or goto, or [] unless you know — answers are reused forever. Start with dryRun.
43
+ - Never ask for a password in chat. Values come from the user's settings (UNDERSTUDY_<NAME>), or pass ones you fetched yourself.
44
+ - No flow for it? understudy_record (the user records) then understudy_save — or save a Playwright script of what you drove (understudy_save with script). Save what's worth testing again.
45
+ - Ask the user before each distill. Gather facts, lessons and findings, get approval, then one understudy_remember.
46
+ Full guide: REASONER.md in the package.`;
47
+ const server = new McpServer({ name: 'understudy', version: '0.2.0' }, { instructions: INSTRUCTIONS });
48
+ /** Credentials passed to `run`, kept in memory (never stored) until the run executes. */
49
+ const valuesByRun = new Map();
50
+ const ok = (data) => ({ content: [{ type: 'text', text: JSON.stringify(data, null, 1) }] });
51
+ const err = (e) => ({ isError: true, content: [{ type: 'text', text: e instanceof Error ? e.message : String(e) }] });
52
+ /** Run a handler, returning its result as JSON or its error as a readable message. */
53
+ const wrap = async (fn) => {
54
+ try {
55
+ return ok(await fn());
56
+ }
57
+ catch (e) {
58
+ return e instanceof MissingValuesError ? ok(missingValues(e)) : err(e);
59
+ }
60
+ };
61
+ /**
62
+ * Login values are missing, and nothing ran. Never ask for the value in chat:
63
+ * say which line goes in which file, and that a retry re-reads the file.
64
+ */
65
+ const missingValues = (e, retry) => ({
66
+ ran: false,
67
+ missingLoginValues: e.missing,
68
+ envFile: e.envFile,
69
+ next: `Ask the user to add ${e.missing.map((m) => `${m.setOneOf[0]}=<value>`).join(', ')} to ${e.envFile} ` +
70
+ '(or run `understudy config set …`) — never to paste it into chat — then call this again; the file is re-read. ' +
71
+ 'Or pass a value you fetched yourself in values.',
72
+ ...(retry ? { retry } : {}),
73
+ });
74
+ /** Drop undefined fields: the zod types allow them, the functions here don't. */
75
+ const defined = (o) => Object.fromEntries(Object.entries(o).filter(([, v]) => v !== undefined));
76
+ /** After planning: run it now, unless it was a dry run or is waiting/blocked. */
77
+ async function continueRun(state, opts) {
78
+ if (state.status !== 'planned' || state.dryRun)
79
+ return state;
80
+ const values = valuesByRun.get(state.runId) ?? {};
81
+ const { executed, recorded, plan, nowProven } = await runPlan(state.runId, { values, ...opts });
82
+ valuesByRun.delete(state.runId);
83
+ const r = executed.result;
84
+ return {
85
+ status: r.ok ? 'passed' : 'failed',
86
+ runId: state.runId,
87
+ plan,
88
+ seams: state.seams,
89
+ failedSteps: r.steps.filter((s) => !s.ok).map((s) => ({ seq: s.seq, action: s.action, error: s.error })),
90
+ unexpectedPages: r.steps.filter((s) => s.unexpectedPage).map((s) => ({ seq: s.seq, ...s.unexpectedPage })),
91
+ path: r.sigSequence,
92
+ drift: recorded.drift.firstRun ? 'first run' : recorded.drift.changed
93
+ ? { added: recorded.drift.added, removed: recorded.drift.removed, stateChanged: recorded.drift.stateChanged }
94
+ : 'same path',
95
+ findings: recorded.findings.map((f) => ({ kind: f.kind, severity: f.severity, statement: f.statement })),
96
+ ...(executed.lessons?.fired ? { lessons: executed.lessons } : {}),
97
+ ...(nowProven.length ? { nowProven } : {}),
98
+ ...(executed.missingValues.length ? { missingValues: executed.missingValues } : {}),
99
+ ...(executed.staleSession ? { staleSession: executed.staleSession } : {}),
100
+ };
101
+ }
102
+ const values = z.record(z.string(), z.string()).optional()
103
+ .describe('Login values you fetched yourself, e.g. {"SECRET.password":"…"}; otherwise read from settings. Never stored.');
104
+ server.registerTool('understudy_recall', {
105
+ description: 'What memory knows about a goal: closest flows and notes, and a verdict. A known flow comes with its steps and needed login values. Free; nothing runs.',
106
+ inputSchema: { app: z.string(), goal: z.string(), limit: z.number().int().positive().optional() },
107
+ }, ({ app, goal, limit }) => wrap(() => recall(app, goal, { withSteps: true, ...(limit ? { limit } : {}) })));
108
+ server.registerTool('understudy_run', {
109
+ description: 'Plan a goal and run it headless. Returns a question to answer with understudy_answer, "blocked" with why, or the result.',
110
+ inputSchema: {
111
+ app: z.string(), goal: z.string(),
112
+ subGoals: z.array(z.string()).optional().describe('Skip the decompose question.'),
113
+ dryRun: z.boolean().optional().describe('Plan only; open no browser.'),
114
+ allowPurchases: z.boolean().optional(),
115
+ values, headed: z.boolean().optional(),
116
+ },
117
+ }, (a) => wrap(async () => {
118
+ const state = await start({
119
+ app: a.app, goal: a.goal,
120
+ ...(a.subGoals ? { subGoals: a.subGoals } : {}),
121
+ ...(a.dryRun ? { dryRun: true } : {}),
122
+ ...(a.allowPurchases ? { allowPurchases: true } : {}),
123
+ });
124
+ if (a.values)
125
+ valuesByRun.set(state.runId, a.values);
126
+ return continueRun(state, a.headed ? { headed: true } : {});
127
+ }));
128
+ server.registerTool('understudy_answer', {
129
+ description: 'Answer a waiting run\'s question; returns the next one, or the result. decompose: {"subGoals":[…]}. seam: {"steps":[…]}, or {"steps":[]} unless you know.',
130
+ inputSchema: { runId: z.string(), answer: z.record(z.string(), z.unknown()), values, headed: z.boolean().optional() },
131
+ }, (a) => wrap(async () => {
132
+ if (a.values)
133
+ valuesByRun.set(a.runId, a.values);
134
+ return continueRun(await answer(a.runId, a.answer), a.headed ? { headed: true } : {});
135
+ }));
136
+ server.registerTool('understudy_distill', {
137
+ description: 'A saved flow\'s numbered steps and the app\'s vocabulary, to name it and split it into segments. Ask the user first.',
138
+ inputSchema: { app: z.string(), flow: z.string() },
139
+ }, ({ app, flow }) => wrap(() => distillRequest(app, flow)));
140
+ server.registerTool('understudy_save_distilled', {
141
+ description: 'Store a distillation. Validated; every problem returned at once; nothing written unless all is valid.',
142
+ inputSchema: { app: z.string(), flow: z.string(), distilled: z.record(z.string(), z.unknown()) },
143
+ }, ({ app, flow, distilled }) => wrap(() => saveDistilled(app, flow, distilled)));
144
+ server.registerTool('understudy_remember', {
145
+ description: 'Store what you learned, as one approved batch: facts, lessons (trigger never empty), findings, and goals you reached without understudy_run.',
146
+ inputSchema: {
147
+ app: z.string(),
148
+ facts: z.array(z.object({ text: z.string(), marksDestructive: z.string().optional() })).optional(),
149
+ lessons: z.array(z.object({ title: z.string(), text: z.string(), kind: z.string(), trigger: z.record(z.string(), z.string()) })).optional(),
150
+ findings: z.array(z.object({ kind: z.string(), severity: z.enum(['low', 'medium', 'high']), statement: z.string(), fingerprint: z.string(), evidence: z.record(z.string(), z.unknown()).optional() })).optional(),
151
+ reached: z.array(z.object({ goal: z.string(), passed: z.boolean(), drivenBy: z.string().optional(), note: z.string().optional(), sigSequence: z.array(z.string()).optional() })).optional(),
152
+ },
153
+ }, ({ app, facts, lessons, findings, reached }) => wrap(() => remember(app, defined({
154
+ facts: facts?.map((f) => defined(f)),
155
+ lessons,
156
+ findings: findings?.map((f) => defined(f)),
157
+ reached: reached?.map((r) => defined(r)),
158
+ }))));
159
+ server.registerTool('understudy_findings', {
160
+ description: 'Open findings for an app, most frequent first. Pass triage to route them: issue, lesson or noise.',
161
+ inputSchema: {
162
+ app: z.string(),
163
+ triage: z.array(z.object({ fingerprint: z.string(), verdict: z.enum(['issue', 'lesson', 'noise']) })).optional(),
164
+ all: z.boolean().optional().describe('Include already-triaged findings.'),
165
+ },
166
+ }, ({ app, triage: items, all }) => wrap(async () => {
167
+ const { findings } = await collections();
168
+ const routed = items?.length ? await triage(findings, app, items) : undefined;
169
+ const rows = await findings.find(all ? { app } : { app, status: 'open' }).sort({ occurrences: -1, lastSeen: -1 }).limit(40).toArray();
170
+ return {
171
+ ...(routed ? { triaged: routed } : {}),
172
+ findings: rows.map((f) => ({ fingerprint: f.fingerprint, kind: f.kind, severity: f.severity, occurrences: f.occurrences, status: f.status, statement: f.statement })),
173
+ };
174
+ }));
175
+ /** The recording in progress (one at a time), and the last finished one per app. */
176
+ let recording = null;
177
+ const finished = new Map();
178
+ server.registerTool('understudy_record', {
179
+ description: 'Wait for the user to record a flow in their Chrome. Returns at once with what to tell them; then call understudy_save.',
180
+ inputSchema: { app: z.string(), port: z.number().int().min(0).max(65535).optional().describe('Default 7397.') },
181
+ }, ({ app, port }) => wrap(async () => {
182
+ if (recording)
183
+ throw new Error(`already waiting for a recording of "${recording.app}" — the user needs to stop it first`);
184
+ const rec = await startExtensionRecorder({ appSlug: app, savedBy: 'agent', ...(port ? { port } : {}) });
185
+ recording = { app, rec };
186
+ rec.done.then(async (out) => {
187
+ recording = null;
188
+ if (!out.started || !out.recording.events.some((e) => e.action !== 'goto'))
189
+ return;
190
+ await saveRecording(out.recording);
191
+ finished.set(app, { hash: out.recording.hash, steps: out.recording.events.length, droppedUploads: out.droppedUploads, at: new Date() });
192
+ }).catch(() => { recording = null; });
193
+ return {
194
+ status: 'waiting for the user',
195
+ listening: rec.url,
196
+ tellTheUser: [
197
+ 'In Chrome, go to the page where the flow starts.',
198
+ 'Click the Understudy icon → "Record from this page" (tick "I\'m signed in here" if the flow starts signed in).',
199
+ 'Do the flow as normal, then click the icon → "Stop".',
200
+ `Extension not loaded yet? chrome://extensions → Developer mode → Load unpacked → ${extensionDir()}`,
201
+ ],
202
+ then: 'When they say they\'ve stopped, call understudy_save with a name for the flow.',
203
+ };
204
+ }));
205
+ server.registerTool('understudy_save', {
206
+ description: 'Prove a flow by replaying it, and keep it only if every step passes: the user\'s latest recording, a recording hash, or a script of a flow you drove.',
207
+ inputSchema: {
208
+ app: z.string(), name: z.string().describe('What the flow does, as someone would ask for it.'),
209
+ hash: z.string().optional(),
210
+ script: z.string().optional().describe('Path to a Playwright script of a flow you drove; read passwords from process.env.'),
211
+ intent: z.string().optional(), slug: z.string().optional(), values,
212
+ verify: z.boolean().optional().describe('false: keep it without replaying (e.g. it ends in a real purchase). Saved as unproven until a run passes.'),
213
+ note: z.string().optional().describe('With verify false: why, e.g. what you checked yourself.'),
214
+ },
215
+ }, (a) => wrap(async () => {
216
+ let rec;
217
+ let madeBy = 'user';
218
+ if (a.script) {
219
+ // A flow the agent drove: read its script into steps, exactly like `understudy import`.
220
+ const { apps } = await collections();
221
+ const base = (await apps.findOne({ slug: a.app }))?.urls.default;
222
+ const parsed = await parseScript(a.script, a.app, base);
223
+ if (!parsed.recording.events.length)
224
+ throw new Error(`no Playwright actions found in ${a.script} — expected calls like page.getByRole(...).click()`);
225
+ if (parsed.warnings.length)
226
+ throw new Error(`these calls in the script can't be replayed, so it wasn't kept — rewrite them as plain Playwright actions:\n- ${parsed.warnings.slice(0, 10).join('\n- ')}`);
227
+ rec = parsed.recording;
228
+ await saveRecording(rec);
229
+ madeBy = 'agent';
230
+ }
231
+ else {
232
+ if (!a.hash && recording?.app === a.app)
233
+ throw new Error('the user is still recording — ask them to click "Stop" in the extension first');
234
+ const hash = a.hash ?? finished.get(a.app)?.hash;
235
+ if (!hash)
236
+ throw new Error(`no finished recording for "${a.app}" — start one with understudy_record, pass a hash, or pass a script`);
237
+ rec = await loadRecording(hash);
238
+ }
239
+ const hash = rec.hash;
240
+ let out;
241
+ try {
242
+ out = await proveAndSave(rec, {
243
+ title: a.name, madeBy,
244
+ ...(a.verify === false ? { verify: false, unproven: a.note ? `saved by an agent without a replay: ${a.note}` : 'saved by an agent without a replay' } : {}),
245
+ ...(a.values ? { values: a.values } : {}), ...(a.intent ? { intent: a.intent } : {}), ...(a.slug ? { slug: a.slug } : {}),
246
+ });
247
+ }
248
+ catch (e) {
249
+ // The recording is kept; saving it again by hash needs nothing re-recorded.
250
+ if (e instanceof MissingValuesError)
251
+ return { saved: false, ...missingValues(e, { tool: 'understudy_save', hash, name: a.name }) };
252
+ throw e;
253
+ }
254
+ const r = out.proven?.result;
255
+ const base = {
256
+ recording: hash,
257
+ ...(r ? {
258
+ passed: r.ok,
259
+ failedSteps: r.steps.filter((s) => !s.ok).map((s) => ({ seq: s.seq, action: s.action, error: s.error })),
260
+ signIn: out.proven.signIn,
261
+ } : { replayed: false }),
262
+ ...(finished.get(a.app)?.droppedUploads ? { droppedUploads: finished.get(a.app).droppedUploads } : {}),
263
+ };
264
+ if (!out.saved)
265
+ return { saved: false, ...base, why: 'it did not replay cleanly, so it was not kept. Fix the step, or pass verify: false to keep it unproven.' };
266
+ return {
267
+ saved: true, flow: out.flow.slug, steps: out.flow.steps.length, madeBy, ...base,
268
+ ...(out.flow.proven === false ? {
269
+ unproven: out.flow.unprovenBecause,
270
+ proveIt: `when it should pass: understudy_run with subGoals ["${out.flow.slug}"] — a passing run proves it`,
271
+ } : {}),
272
+ ...(out.flow.destructive ? { destructive: out.flow.destructiveBecause } : {}),
273
+ ...(out.run ? { findings: out.run.findings.map((f) => f.statement) } : {}),
274
+ ...(out.placeholders.converted.length ? { placeholders: out.placeholders.converted } : {}),
275
+ };
276
+ }));
277
+ server.registerTool('understudy_app', {
278
+ description: 'An app\'s settings. placeholders ["email"] keeps email addresses out of memory: they become placeholders, and the values move to the user\'s env file.',
279
+ inputSchema: {
280
+ app: z.string(),
281
+ placeholders: z.array(z.enum(['email'])).optional().describe('[] turns it off for new flows.'),
282
+ },
283
+ }, ({ app, placeholders }) => wrap(async () => {
284
+ if (placeholders)
285
+ return setPlaceholders(app, placeholders);
286
+ return { app, placeholders: await appPlaceholders(app) };
287
+ }));
288
+ await server.connect(new StdioServerTransport());
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Does running this flow commit something real — a purchase, a deletion?
3
+ *
4
+ * Inferred from evidence, never asked. It FAILS OPEN: no signal means not
5
+ * destructive. A false positive only blocks a harmless test until someone says
6
+ * it's fine; asking about every flow is how a tool gets switched off.
7
+ *
8
+ * Two signals today, both readable from the steps alone:
9
+ * 1. a control whose name commits something ("Place order", "Delete")
10
+ * 2. the flow reaches a payment provider's site
11
+ * The old version had three more that need stored knowledge (exploration
12
+ * boundaries, facts, other destructive flows). They return with the safety
13
+ * gate in phase 3 — see `git show legacy-cockroach:src/core/destructive.ts`.
14
+ */
15
+ import type { Step } from '../store/types.js';
16
+ /** Why this step is destructive, or null if nothing says it is. */
17
+ export declare function destructiveReason(step: Pick<Step, 'action' | 'name' | 'url'>): string | null;
18
+ /** The first reason any step in the flow is destructive, or null. */
19
+ export declare function flowDestructiveReason(steps: Pick<Step, 'action' | 'name' | 'url'>[]): string | null;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Does running this flow commit something real — a purchase, a deletion?
3
+ *
4
+ * Inferred from evidence, never asked. It FAILS OPEN: no signal means not
5
+ * destructive. A false positive only blocks a harmless test until someone says
6
+ * it's fine; asking about every flow is how a tool gets switched off.
7
+ *
8
+ * Two signals today, both readable from the steps alone:
9
+ * 1. a control whose name commits something ("Place order", "Delete")
10
+ * 2. the flow reaches a payment provider's site
11
+ * The old version had three more that need stored knowledge (exploration
12
+ * boundaries, facts, other destructive flows). They return with the safety
13
+ * gate in phase 3 — see `git show legacy-cockroach:src/core/destructive.ts`.
14
+ */
15
+ const COMMIT_WORDS = /\b(pay|purchase|buy|place order|order now|checkout|check out|confirm|delete|remove account|reset|deactivate|destroy|publish|subscribe|charge|submit order)\b/i;
16
+ const PAYMENT_HOSTS = /(^|\.)(stripe|paypal|braintree|adyen|checkout|squareup|klarna|worldpay|authorize)\.(com|net|io)$/i;
17
+ /**
18
+ * Only these actions can commit anything. Typing into "Confirm password" or
19
+ * ticking "Delete my data after 30 days" doesn't; clicking "Confirm" does.
20
+ * (The old version judged every step, so a "Confirm password" field marked a
21
+ * whole signup flow destructive.)
22
+ */
23
+ const COMMITTING_ACTIONS = new Set(['click', 'press', 'dispatch_click']);
24
+ /** Why this step is destructive, or null if nothing says it is. */
25
+ export function destructiveReason(step) {
26
+ const name = (step.name ?? '').trim();
27
+ if (name && COMMITTING_ACTIONS.has(step.action) && COMMIT_WORDS.test(name)) {
28
+ return `commit-shaped control "${name}"`;
29
+ }
30
+ try {
31
+ const host = new URL(step.url).hostname;
32
+ if (PAYMENT_HOSTS.test(host))
33
+ return `reaches payment site ${host}`;
34
+ }
35
+ catch {
36
+ // not a URL we can judge
37
+ }
38
+ return null;
39
+ }
40
+ /** The first reason any step in the flow is destructive, or null. */
41
+ export function flowDestructiveReason(steps) {
42
+ for (const [i, s] of steps.entries()) {
43
+ const why = destructiveReason(s);
44
+ if (why)
45
+ return `step ${i}: ${why}`;
46
+ }
47
+ return null;
48
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Distilling a saved flow: hand an agent its numbered steps, take back names
3
+ * and segments, validate, store.
4
+ *
5
+ * distillRequest(app, flow) → steps + the app's vocabulary + instructions
6
+ * saveDistilled(app, flow, answer) → validated; every problem at once; nothing
7
+ * written unless the whole answer is clean
8
+ *
9
+ * No replay here: a saved flow was proven when it was saved (or by a run since —
10
+ * unproven ones are refused), so its steps and the page each one reached are on record.
11
+ */
12
+ import { type DistillRequest } from '../core/distill.js';
13
+ export declare function distillRequest(app: string, slug: string): Promise<DistillRequest & {
14
+ flow: string;
15
+ }>;
16
+ export interface DistillSaved {
17
+ flow: string;
18
+ segments: {
19
+ slug: string;
20
+ steps: number;
21
+ replaced: boolean;
22
+ }[];
23
+ lessons: {
24
+ written: number;
25
+ alreadyKnown: number;
26
+ };
27
+ }
28
+ export declare function saveDistilled(app: string, slug: string, answer: unknown): Promise<DistillSaved>;
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Distilling a saved flow: hand an agent its numbered steps, take back names
3
+ * and segments, validate, store.
4
+ *
5
+ * distillRequest(app, flow) → steps + the app's vocabulary + instructions
6
+ * saveDistilled(app, flow, answer) → validated; every problem at once; nothing
7
+ * written unless the whole answer is clean
8
+ *
9
+ * No replay here: a saved flow was proven when it was saved (or by a run since —
10
+ * unproven ones are refused), so its steps and the page each one reached are on record.
11
+ */
12
+ import { buildDistillRequest, validateDistilled } from '../core/distill.js';
13
+ import { collections, ensureSchema } from '../store/db.js';
14
+ import { embed, embedderConfig } from '../store/embed.js';
15
+ import { vocabulary } from '../memory/vocabulary.js';
16
+ import { remember } from '../memory/notes.js';
17
+ import { flowDestructiveReason } from './destructive.js';
18
+ import { recordingFrom } from './save.js';
19
+ async function loadFlow(app, slug) {
20
+ const { flows } = await collections();
21
+ const flow = await flows.findOne({ app, slug });
22
+ if (!flow)
23
+ throw new Error(`no flow '${slug}' for app '${app}'`);
24
+ if (flow.kind !== 'recording')
25
+ throw new Error(`'${slug}' is a segment — distill the recording it came from (${flow.from?.flow})`);
26
+ // Distilling trusts every step to have passed; an unproven one may not have,
27
+ // and its segments would carry the bad step into other plans.
28
+ if (flow.proven === false) {
29
+ throw new Error(`'${slug}' is unproven (${flow.unprovenBecause ?? 'never replayed cleanly'}) — run it once; when a run passes it's proven, and can be distilled`);
30
+ }
31
+ return flow;
32
+ }
33
+ export async function distillRequest(app, slug) {
34
+ const flow = await loadFlow(app, slug);
35
+ // Every saved step passed when it was proven; its expectedSig is the page it reached.
36
+ const proven = { steps: flow.steps.map((s, seq) => ({ seq, ok: true, ...(s.expectedSig ? { sig: s.expectedSig } : {}) })) };
37
+ return { flow: slug, ...buildDistillRequest(recordingFrom(flow), proven, await vocabulary(app)) };
38
+ }
39
+ export async function saveDistilled(app, slug, answer) {
40
+ const flow = await loadFlow(app, slug);
41
+ const check = validateDistilled(answer, flow.steps.length);
42
+ const errors = [...check.errors];
43
+ const d = check.value;
44
+ if (d?.segments.some((s) => s.slug === slug))
45
+ errors.push(`a segment can't have the same slug as the flow it is cut from ("${slug}")`);
46
+ if (errors.length || !d)
47
+ throw new Error(`nothing written — fix these and send it again:\n- ${errors.join('\n- ')}`);
48
+ await ensureSchema();
49
+ const c = await collections();
50
+ const now = new Date();
51
+ const segmentDocs = d.segments.map((s) => segmentFrom(flow, s));
52
+ const parentText = searchTextOf(flow.title, d.intent, d.outcome);
53
+ // One request embeds the parent and every segment.
54
+ const vectors = embedderConfig() ? await embed([parentText, ...segmentDocs.map((s) => s.searchText)], 'document') : [];
55
+ await c.flows.updateOne({ app, slug }, {
56
+ $set: {
57
+ intent: d.intent, outcome: d.outcome, preconditions: d.preconditions,
58
+ corrections: (d.corrections ?? []).map((x) => `${x.rule}: ${x.detail}${x.stepIndex !== undefined ? ` (step ${x.stepIndex})` : ''}`),
59
+ searchText: parentText, ...(vectors[0] ? { embedding: vectors[0] } : {}), updatedAt: now,
60
+ },
61
+ });
62
+ const saved = [];
63
+ for (const [i, seg] of segmentDocs.entries()) {
64
+ // Reusing an existing slug REPLACES that segment: segments belong to the
65
+ // app, so the same block from a new recording merges instead of competing.
66
+ const existed = await c.flows.findOne({ app, slug: seg.slug }, { projection: { kind: 1 } });
67
+ if (existed && existed.kind !== 'segment')
68
+ throw new Error(`"${seg.slug}" is already a recorded flow's slug — pick another for the segment`);
69
+ const unset = {};
70
+ if (!vectors[i + 1])
71
+ unset.embedding = '';
72
+ if (!seg.destructiveBecause)
73
+ unset.destructiveBecause = '';
74
+ await c.flows.updateOne({ app, slug: seg.slug }, { $set: { ...seg, ...(vectors[i + 1] ? { embedding: vectors[i + 1] } : {}), updatedAt: now }, $setOnInsert: { createdAt: now }, ...(Object.keys(unset).length ? { $unset: unset } : {}) }, { upsert: true });
75
+ saved.push({ slug: seg.slug, steps: seg.steps.length, replaced: Boolean(existed) });
76
+ }
77
+ const lessons = d.candidateLessons?.length
78
+ ? (await remember(app, {
79
+ lessons: d.candidateLessons.map((l) => ({ title: l.title, text: l.body, kind: l.kind, trigger: l.trigger })),
80
+ })).lessons
81
+ : { written: 0, alreadyKnown: 0 };
82
+ return { flow: slug, segments: saved, lessons };
83
+ }
84
+ const searchTextOf = (title, intent, outcome) => [title, intent !== title ? intent : '', outcome ?? ''].filter(Boolean).join('. ');
85
+ /** A segment is a copy of a range of its parent's steps, with its own name. */
86
+ function segmentFrom(parent, s) {
87
+ const [start, end] = s.stepRange;
88
+ const steps = parent.steps.slice(start, end);
89
+ const why = flowDestructiveReason(steps);
90
+ // Where it begins: the page the step BEFORE it reached (or the parent's start).
91
+ const startState = start === 0 ? parent.startState : parent.steps[start - 1]?.expectedSig;
92
+ const endState = steps.at(-1)?.expectedSig;
93
+ return {
94
+ app: parent.app, slug: s.slug, title: s.title, intent: s.intent, kind: 'segment',
95
+ madeBy: parent.madeBy ?? 'user',
96
+ from: { flow: parent.slug, steps: [start, end] },
97
+ preconditions: (s.preconditions ?? []),
98
+ outcome: s.outcome ?? '',
99
+ destructive: Boolean(why), ...(why ? { destructiveBecause: why } : {}),
100
+ corrections: [], recording: parent.recording,
101
+ startUrl: steps[0]?.url ?? parent.startUrl,
102
+ // Only the very first segment can use the parent's saved session; a later
103
+ // one starts mid-flow and needs the flows before it in the same plan.
104
+ requiresSession: start === 0 && parent.requiresSession,
105
+ ...(start === 0 && parent.session ? { session: parent.session } : {}),
106
+ ...(startState ? { startState } : {}), ...(endState ? { endState } : {}),
107
+ steps, searchText: searchTextOf(s.title, s.intent, s.outcome),
108
+ };
109
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Flow drift: did this run take a different path through the app than before?
3
+ *
4
+ * last week: /login → /inventory → /cart → /checkout → /complete
5
+ * today: /login → /inventory → /cart → /promo-upsell → /checkout → /complete
6
+ * ^^^^^^^^^^^^^ never seen before
7
+ *
8
+ * A text diff over page fingerprints — no model, no screenshots. A normal test
9
+ * suite can't do this: it has no memory of what the flow looked like before.
10
+ *
11
+ * Reported as a finding, not a failure: a new page in checkout might be a bug
12
+ * or a feature someone shipped on purpose, and deciding which is a judgement.
13
+ * Ported from the old drift.ts; this file is pure, runs.ts fetches history.
14
+ */
15
+ import type { FindingDraft } from './findings.js';
16
+ export interface DriftStep {
17
+ change: 'same' | 'added' | 'removed' | 'changed';
18
+ sig: string;
19
+ /** For 'changed': the sig it replaced. */
20
+ was?: string;
21
+ }
22
+ export interface Drift {
23
+ /** No earlier passed run to compare with — not drift, just the first time. */
24
+ firstRun: boolean;
25
+ changed: boolean;
26
+ /** Pages no recent run has ever visited. The interesting case. */
27
+ added: string[];
28
+ /** Pages every recent run visited and this one didn't. */
29
+ removed: string[];
30
+ /** Same page, new state (e.g. cart with 2 items instead of 1). Lower signal. */
31
+ stateChanged: string[];
32
+ baseline: string[];
33
+ current: string[];
34
+ diff: DriftStep[];
35
+ }
36
+ /**
37
+ * Compare a path with recent passed runs of the same flow, newest first.
38
+ * Something only counts as new if NO recent run has seen it, so a flow that
39
+ * legitimately alternates between two paths doesn't drift every time.
40
+ */
41
+ export declare function compareToHistory(current: string[], histories: string[][]): Drift;
42
+ /** Drift as a finding, fingerprinted on WHAT changed so a recurring drift accumulates. */
43
+ export declare function driftFinding(flow: string, drift: Drift): FindingDraft | null;