@jeffawe/understudy 0.0.0-stage → 0.2.1

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 +166 -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 +1016 -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 +76 -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,116 @@
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 { createHash } from 'node:crypto';
16
+ /** `/inventory.html#bf3dd322` → `/inventory.html` */
17
+ const pageOf = (sig) => sig.slice(0, sig.lastIndexOf('#')) || sig;
18
+ /** Longest-common-subsequence diff, so an inserted page lines up legibly. */
19
+ function diffSequences(baseline, current) {
20
+ const n = baseline.length;
21
+ const m = current.length;
22
+ const lcs = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
23
+ for (let i = n - 1; i >= 0; i--) {
24
+ for (let j = m - 1; j >= 0; j--) {
25
+ lcs[i][j] = baseline[i] === current[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]);
26
+ }
27
+ }
28
+ const out = [];
29
+ let i = 0;
30
+ let j = 0;
31
+ while (i < n && j < m) {
32
+ if (baseline[i] === current[j]) {
33
+ out.push({ change: 'same', sig: current[j] });
34
+ i++;
35
+ j++;
36
+ }
37
+ else if (lcs[i + 1][j] >= lcs[i][j + 1]) {
38
+ out.push({ change: 'removed', sig: baseline[i++] });
39
+ }
40
+ else {
41
+ out.push({ change: 'added', sig: current[j++] });
42
+ }
43
+ }
44
+ while (i < n)
45
+ out.push({ change: 'removed', sig: baseline[i++] });
46
+ while (j < m)
47
+ out.push({ change: 'added', sig: current[j++] });
48
+ return out;
49
+ }
50
+ /**
51
+ * A page that was removed and another state of the SAME page added is one
52
+ * change of state, not "a page vanished and a new one appeared".
53
+ */
54
+ function collapseSamePage(diff) {
55
+ const out = [];
56
+ for (let i = 0; i < diff.length; i++) {
57
+ const a = diff[i];
58
+ const b = diff[i + 1];
59
+ const isPair = b &&
60
+ ((a.change === 'removed' && b.change === 'added') || (a.change === 'added' && b.change === 'removed')) &&
61
+ pageOf(a.sig) === pageOf(b.sig);
62
+ if (isPair) {
63
+ const [removed, added] = a.change === 'removed' ? [a, b] : [b, a];
64
+ out.push({ change: 'changed', sig: added.sig, was: removed.sig });
65
+ i++;
66
+ }
67
+ else {
68
+ out.push(a);
69
+ }
70
+ }
71
+ return out;
72
+ }
73
+ /**
74
+ * Compare a path with recent passed runs of the same flow, newest first.
75
+ * Something only counts as new if NO recent run has seen it, so a flow that
76
+ * legitimately alternates between two paths doesn't drift every time.
77
+ */
78
+ export function compareToHistory(current, histories) {
79
+ const past = histories.filter((h) => h.length > 0);
80
+ if (!past.length) {
81
+ return {
82
+ firstRun: true, changed: false, added: [], removed: [], stateChanged: [],
83
+ baseline: [], current, diff: current.map((sig) => ({ change: 'same', sig })),
84
+ };
85
+ }
86
+ const baseline = past[0];
87
+ const diff = collapseSamePage(diffSequences(baseline, current));
88
+ const everSeen = new Set(past.flat());
89
+ const seenInAll = (sig) => past.every((h) => h.includes(sig));
90
+ const added = diff.filter((d) => d.change === 'added' && !everSeen.has(d.sig)).map((d) => d.sig);
91
+ const removed = diff.filter((d) => d.change === 'removed' && seenInAll(d.sig)).map((d) => d.sig);
92
+ const stateChanged = diff.filter((d) => d.change === 'changed' && !everSeen.has(d.sig)).map((d) => d.sig);
93
+ return {
94
+ firstRun: false,
95
+ changed: added.length + removed.length + stateChanged.length > 0,
96
+ added, removed, stateChanged, baseline, current, diff,
97
+ };
98
+ }
99
+ /** Drift as a finding, fingerprinted on WHAT changed so a recurring drift accumulates. */
100
+ export function driftFinding(flow, drift) {
101
+ if (!drift.changed)
102
+ return null;
103
+ const statement = `flow "${flow}" took a different path` +
104
+ (drift.added.length ? `; new: ${drift.added.join(', ')}` : '') +
105
+ (drift.removed.length ? `; gone: ${drift.removed.join(', ')}` : '') +
106
+ (drift.stateChanged.length ? `; different state: ${drift.stateChanged.join(', ')}` : '');
107
+ const what = [...drift.added, ...drift.removed, ...drift.stateChanged].sort();
108
+ return {
109
+ kind: 'flow_drift',
110
+ // A page nobody has seen before matters more than a page in another state.
111
+ severity: drift.added.length || drift.removed.length ? 'medium' : 'low',
112
+ statement,
113
+ evidence: { baseline: drift.baseline, current: drift.current, added: drift.added, removed: drift.removed, stateChanged: drift.stateChanged },
114
+ fingerprint: createHash('sha1').update(['drift', flow, ...what].join('|')).digest('hex').slice(0, 20),
115
+ };
116
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Print a saved flow as test code: Playwright (TypeScript) or Cypress.
3
+ *
4
+ * Flows are stored as data, so code is just an output format — the same flow
5
+ * prints either way without re-recording. Two things it won't do quietly:
6
+ *
7
+ * - inline a credential: a `valueRef` becomes an environment variable, never
8
+ * the value (the recording never stored it, and generated files get committed)
9
+ * - pretend: a step it can't address cleanly comes with a warning, not a
10
+ * plausible-looking locator
11
+ *
12
+ * Ported from the old emit.ts; it now reads the flow document directly.
13
+ */
14
+ import type { Flow } from '../store/types.js';
15
+ export type Framework = 'playwright-ts' | 'cypress-js';
16
+ export interface Emitted {
17
+ framework: Framework;
18
+ code: string;
19
+ warnings: string[];
20
+ /** Value references the test reads from the environment. */
21
+ requiredValues: string[];
22
+ }
23
+ export declare function emitFlow(flow: Flow, framework?: Framework): Emitted;
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Print a saved flow as test code: Playwright (TypeScript) or Cypress.
3
+ *
4
+ * Flows are stored as data, so code is just an output format — the same flow
5
+ * prints either way without re-recording. Two things it won't do quietly:
6
+ *
7
+ * - inline a credential: a `valueRef` becomes an environment variable, never
8
+ * the value (the recording never stored it, and generated files get committed)
9
+ * - pretend: a step it can't address cleanly comes with a warning, not a
10
+ * plausible-looking locator
11
+ *
12
+ * Ported from the old emit.ts; it now reads the flow document directly.
13
+ */
14
+ import { valueEnvName } from '../store/settings.js';
15
+ const quote = (s) => `'${s.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
16
+ /** SECRET.password → UNDERSTUDY_SECRET_PASSWORD: the same variable replay reads, so one setting serves both. */
17
+ const envName = valueEnvName;
18
+ const describe = (s) => `${s.action} ${s.role ?? ''} ${s.name ?? s.testId ?? s.css ?? ''}`.replace(/\s+/g, ' ').trim();
19
+ /**
20
+ * Narrowing replay applies after finding the element, in the same order:
21
+ * a text filter first, then position ("the 3rd of these"). The six boxes of a
22
+ * one-time code share one selector and differ only by position, so dropping
23
+ * this would type every digit into the first box.
24
+ */
25
+ function narrow(s, loc, pw, warn) {
26
+ const h = (s.hints ?? {});
27
+ if (h.scope)
28
+ warn(`"${describe(s)}" was scoped inside another element in the source; emitted unscoped`);
29
+ if (typeof h.hasText === 'string') {
30
+ const text = h.hasTextRegex ? `/${h.hasText}/${String(h.hasTextFlags ?? '')}` : quote(h.hasText);
31
+ if (pw)
32
+ loc += `.filter({ hasText: ${text} })`;
33
+ else
34
+ warn(`"${describe(s)}" filters by text, which this Cypress output doesn't express`);
35
+ }
36
+ if (typeof h.nth === 'number')
37
+ loc += h.nth < 0 ? '.last()' : pw ? `.nth(${h.nth})` : `.eq(${h.nth})`;
38
+ return loc;
39
+ }
40
+ /** Best locator first — the same order replay tries, so the code fails where replay would. */
41
+ function playwrightLocator(s, warn) {
42
+ const scope = s.frameHint ? `page.frameLocator(${quote(`[id$="${s.frameHint}"]`)})` : 'page';
43
+ if (s.role && s.name)
44
+ return `${scope}.getByRole(${quote(s.role)}, { name: ${quote(s.name)}${s.exact ? ', exact: true' : ''} })`;
45
+ // Not getByTestId: it only looks at data-testid unless the project reconfigures it.
46
+ if (s.testId)
47
+ return `${scope}.locator(${quote(`[${s.testIdAttr ?? 'data-testid'}="${s.testId}"]`)})`;
48
+ if (s.name)
49
+ return `${scope}.getByText(${quote(s.name)})`;
50
+ if (s.css) {
51
+ warn(`"${describe(s)}" is addressed only by CSS — it breaks on any markup change`);
52
+ return `${scope}.locator(${quote(s.css)})`;
53
+ }
54
+ warn(`"${describe(s)}" has no usable locator; emitted as a TODO`);
55
+ return `${scope}.locator('TODO')`;
56
+ }
57
+ function cypressLocator(s, warn) {
58
+ if (s.testId)
59
+ return `cy.get(${quote(`[${s.testIdAttr ?? 'data-testid'}="${s.testId}"]`)})`;
60
+ if (s.role && s.name) {
61
+ // Cypress has no role engine: a real loss of precision, so say so.
62
+ warn(`"${describe(s)}" used role + name, which Cypress can't express; emitted as a text match`);
63
+ return `cy.contains(${quote(s.name)})`;
64
+ }
65
+ if (s.name)
66
+ return `cy.contains(${quote(s.name)})`;
67
+ if (s.css)
68
+ return `cy.get(${quote(s.css)})`;
69
+ warn(`"${describe(s)}" has no usable locator; emitted as a TODO`);
70
+ return `cy.get('TODO')`;
71
+ }
72
+ export function emitFlow(flow, framework = 'playwright-ts') {
73
+ const warnings = [];
74
+ const warn = (w) => warnings.push(w);
75
+ const required = new Set();
76
+ const pw = framework === 'playwright-ts';
77
+ if (flow.destructive)
78
+ warnings.push(`this flow is DESTRUCTIVE (${flow.destructiveBecause}) — running it commits a real action`);
79
+ if (flow.requiresSession)
80
+ warnings.push('this flow starts signed in; the generated test starts signed out — add a login first');
81
+ const lines = [];
82
+ for (const s of flow.steps) {
83
+ if (s.action === 'snapshot' || s.action === 'assert')
84
+ continue;
85
+ const loc = s.action === 'goto' ? '' : narrow(s, pw ? playwrightLocator(s, warn) : cypressLocator(s, warn), pw, warn);
86
+ const value = s.valueRef ? (required.add(s.valueRef), envName(s.valueRef).replace(/^UNDERSTUDY_/, '')) : quote(s.value ?? (s.action === 'goto' ? s.url : ''));
87
+ switch (s.action) {
88
+ case 'goto':
89
+ lines.push(pw ? `await page.goto(${value});` : `cy.visit(${value});`);
90
+ break;
91
+ case 'fill':
92
+ lines.push(pw ? `await ${loc}.fill(${value});` : `${loc}.type(${value});`);
93
+ break;
94
+ case 'select':
95
+ lines.push(pw ? `await ${loc}.selectOption(${value});` : `${loc}.select(${value});`);
96
+ break;
97
+ case 'check':
98
+ lines.push(pw ? `await ${loc}.check();` : `${loc}.check();`);
99
+ break;
100
+ case 'press':
101
+ lines.push(pw ? `await ${loc}.press(${value});` : `${loc}.type(${value});`);
102
+ break;
103
+ case 'upload':
104
+ lines.push(pw ? `await ${loc}.setInputFiles(${value});` : `${loc}.selectFile(${value});`);
105
+ break;
106
+ case 'scroll_container':
107
+ if (s.value === 'bottom' || s.value === 'top') {
108
+ lines.push(pw
109
+ ? `await ${loc}.evaluate((el) => { el.scrollTop = ${s.value === 'bottom' ? 'el.scrollHeight' : '0'}; });`
110
+ : `${loc}.scrollTo('${s.value}');`);
111
+ }
112
+ else
113
+ lines.push(pw ? `await ${loc}.scrollIntoViewIfNeeded();` : `${loc}.scrollIntoView();`);
114
+ break;
115
+ case 'wait_url':
116
+ lines.push(pw ? `await page.waitForURL(new RegExp(${quote(s.value ?? '')}));` : `cy.url().should('include', ${value});`);
117
+ break;
118
+ case 'wait_text':
119
+ lines.push(pw ? `await page.getByText(${value}).waitFor();` : `cy.contains(${value});`);
120
+ break;
121
+ default: lines.push(pw ? `await ${loc}.click();` : `${loc}.click();`);
122
+ }
123
+ }
124
+ const refs = [...required];
125
+ // Values come from the environment, never the file.
126
+ const preamble = refs.length ? refs.map((r) => `const ${envName(r).replace(/^UNDERSTUDY_/, '')} = process.env.${envName(r)} ?? '';`).join('\n') + '\n\n' : '';
127
+ const header = `// ${flow.intent}\n// Generated by understudy from flow "${flow.app}/${flow.slug}". Regenerate rather than edit.\n\n`;
128
+ const body = (indent) => lines.map((l) => indent + l).join('\n');
129
+ const code = pw
130
+ ? `import { test } from '@playwright/test';\n\n${header}${preamble}test(${quote(flow.title)}, async ({ page }) => {\n${body(' ')}\n});\n`
131
+ : `${header}${preamble}describe(${quote(flow.title)}, () => {\n it(${quote(flow.title)}, () => {\n${body(' ')}\n });\n});\n`;
132
+ return { framework, code, warnings, requiredValues: refs };
133
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Running a recording for real: replay, plus everything around it.
3
+ *
4
+ * - restore the saved session a late-armed recording needs
5
+ * - consult lessons before every step, and count them afterwards
6
+ * - throw away a saved session that turned out to be stale
7
+ *
8
+ * Used by every command that runs something (`replay`, `save`, `run`) and by
9
+ * the MCP server. Throws with a readable message instead of printing, so each
10
+ * caller decides how to show it.
11
+ */
12
+ import type { RawRecording } from '../core/recording.js';
13
+ import { type ReplayResult } from '../core/replay.js';
14
+ /** A login value a recording needs, and where it may be set. */
15
+ export interface MissingValue {
16
+ placeholder: string;
17
+ /** Environment variables (or env file lines) that would supply it, most specific first. */
18
+ setOneOf: string[];
19
+ }
20
+ /**
21
+ * Thrown before any browser opens when login values are missing, so a caller
22
+ * can ask for them (the terminal) or say where to put them (MCP), then retry.
23
+ */
24
+ export declare class MissingValuesError extends Error {
25
+ readonly missing: MissingValue[];
26
+ /** The env file Understudy reads, and writes to. */
27
+ readonly envFile: string;
28
+ constructor(missing: MissingValue[]);
29
+ }
30
+ /** The login values this recording needs that neither `given` nor the environment supply. */
31
+ export declare function missingValuesFor(recording: RawRecording, given?: Record<string, string>): MissingValue[];
32
+ export interface ExecuteOptions {
33
+ /** Values for steps that deliberately don't store theirs, e.g. { 'SECRET.password': '…' }. */
34
+ values?: Record<string, string>;
35
+ headed?: boolean;
36
+ /**
37
+ * Consult this app's lessons. Off when proving a brand-new recording, so
38
+ * what gets saved is what the recording does on its own.
39
+ */
40
+ useLessons?: boolean;
41
+ }
42
+ export interface Executed {
43
+ result: ReplayResult;
44
+ /** Value references the recording needs that weren't supplied. */
45
+ missingValues: string[];
46
+ lessons?: {
47
+ fired: number;
48
+ helped: number;
49
+ };
50
+ /** Set when a restored session didn't land where it was saved, and was discarded. */
51
+ staleSession?: {
52
+ expected: string;
53
+ observed: string;
54
+ };
55
+ sessionRestoredFrom?: string;
56
+ }
57
+ export declare function execute(recording: RawRecording, opts?: ExecuteOptions): Promise<Executed>;
58
+ export interface Proven extends Executed {
59
+ /** The recording as it should be saved: with `requiresSession` set, or its unneeded session dropped. */
60
+ recording: RawRecording;
61
+ /** What proving found out about signing in. */
62
+ signIn: 'not needed' | 'needed' | 'no session to try';
63
+ }
64
+ /**
65
+ * Prove a recording before saving it, and work out whether it needs to start
66
+ * signed in — so nobody has to be asked.
67
+ *
68
+ * A recording from the Chrome extension carries the tab's session as
69
+ * AVAILABLE (`entry.session`) but not required. Replay it in an empty browser
70
+ * first: if that passes, the flow doesn't need anyone signed in, and the
71
+ * session file is deleted. If it fails, try again with the session; if that
72
+ * passes, the flow starts signed in and keeps it. A session is kept on disk
73
+ * only when a flow actually needs one.
74
+ */
75
+ export declare function prove(recording: RawRecording, opts?: ExecuteOptions): Promise<Proven>;
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Running a recording for real: replay, plus everything around it.
3
+ *
4
+ * - restore the saved session a late-armed recording needs
5
+ * - consult lessons before every step, and count them afterwards
6
+ * - throw away a saved session that turned out to be stale
7
+ *
8
+ * Used by every command that runs something (`replay`, `save`, `run`) and by
9
+ * the MCP server. Throws with a readable message instead of printing, so each
10
+ * caller decides how to show it.
11
+ */
12
+ import { loadSession, forgetSession, loadSessionById, forgetSessionById } from '../core/auth-cache.js';
13
+ import { replay } from '../core/replay.js';
14
+ import { foldLessons, lessonsFor } from '../memory/notes.js';
15
+ import { valuesFromEnv, valueEnvNames, reloadEnvFiles, writableEnvFile } from '../store/settings.js';
16
+ /**
17
+ * Thrown before any browser opens when login values are missing, so a caller
18
+ * can ask for them (the terminal) or say where to put them (MCP), then retry.
19
+ */
20
+ export class MissingValuesError extends Error {
21
+ missing;
22
+ /** The env file Understudy reads, and writes to. */
23
+ envFile;
24
+ constructor(missing) {
25
+ const envFile = writableEnvFile();
26
+ super(`missing login value(s) — nothing was run:\n` +
27
+ missing.map((m) => `- ${m.placeholder}: set ${m.setOneOf.join(' or ')}, or pass it for this run`).join('\n') +
28
+ `\n (e.g. add ${missing[0].setOneOf[0]}=… to ${envFile})`);
29
+ this.name = 'MissingValuesError';
30
+ this.missing = missing;
31
+ this.envFile = envFile;
32
+ }
33
+ }
34
+ /** The login values this recording needs that neither `given` nor the environment supply. */
35
+ export function missingValuesFor(recording, given = {}) {
36
+ reloadEnvFiles();
37
+ const refs = new Set(recording.events.map((e) => e.valueRef).filter((r) => Boolean(r)));
38
+ const found = { ...valuesFromEnv(refs, recording.appSlug), ...given };
39
+ return [...refs].filter((r) => !(r in found)).map((r) => ({ placeholder: r, setOneOf: valueEnvNames(r, recording.appSlug) }));
40
+ }
41
+ export async function execute(recording, opts = {}) {
42
+ if (recording.entry?.prelude?.length) {
43
+ throw new Error(`this starts after other flows (${recording.entry.prelude.join(' -> ')}), and preludes are parked in the rewrite — ` +
44
+ 're-record it with --arm-manually');
45
+ }
46
+ // Login values: given explicitly, else from UNDERSTUDY_<REF> in the environment
47
+ // (env files re-read, so one just added is seen).
48
+ reloadEnvFiles();
49
+ const refs = new Set(recording.events.map((e) => e.valueRef).filter((r) => Boolean(r)));
50
+ const values = { ...valuesFromEnv(refs, recording.appSlug), ...(opts.values ?? {}) };
51
+ const missingValues = [...refs].filter((r) => !(r in values));
52
+ // Checked BEFORE a browser opens: a run that reached the password step
53
+ // without a password would spend a real login attempt — and some apps lock
54
+ // the account after a few.
55
+ if (missingValues.length) {
56
+ throw new MissingValuesError(missingValues.map((r) => ({ placeholder: r, setOneOf: valueEnvNames(r, recording.appSlug) })));
57
+ }
58
+ // A late-armed recording starts signed in; a cold browser would land on a
59
+ // login page and fail somewhere confusing.
60
+ let storageState;
61
+ let sessionRestoredFrom;
62
+ const sessionId = recording.entry?.session;
63
+ if (recording.entry?.requiresSession) {
64
+ const cached = sessionId ? await loadSessionById(recording.appSlug, sessionId) : await loadSession(recording.appSlug, values);
65
+ if (!cached) {
66
+ throw new Error(sessionId
67
+ ? `this starts from the signed-in tab it was recorded in, and that saved session (${sessionId}) is gone or older ` +
68
+ 'than 12 hours — record it again from the extension, or start the plan with a flow that logs in'
69
+ : 'this starts from a signed-in browser, and no saved session matches these credentials — pass the same ' +
70
+ '--value credentials it was recorded with, re-record with --arm-manually, or start the plan with a flow that logs in');
71
+ }
72
+ storageState = cached.storageState;
73
+ sessionRestoredFrom = cached.savedAt;
74
+ }
75
+ const app = recording.appSlug;
76
+ const result = await replay(recording, {
77
+ values,
78
+ ...(storageState ? { storageState } : {}),
79
+ ...(opts.headed ? { headless: false } : {}),
80
+ ...(opts.useLessons ? { lessonsFor: (ctx) => lessonsFor(app, ctx) } : {}),
81
+ });
82
+ const out = { result, missingValues, ...(sessionRestoredFrom ? { sessionRestoredFrom } : {}) };
83
+ // Step 0 of a late-armed recording carries the fingerprint of where it was
84
+ // armed; landing elsewhere means the session expired.
85
+ const entry = result.steps.find((s) => s.seq === 0);
86
+ if (recording.entry?.requiresSession && entry?.unexpectedPage) {
87
+ if (sessionId)
88
+ await forgetSessionById(app, sessionId);
89
+ else
90
+ await forgetSession(app, values);
91
+ out.staleSession = entry.unexpectedPage;
92
+ }
93
+ if (opts.useLessons)
94
+ out.lessons = await foldLessons(app, result.steps, recording.events);
95
+ return out;
96
+ }
97
+ /**
98
+ * Prove a recording before saving it, and work out whether it needs to start
99
+ * signed in — so nobody has to be asked.
100
+ *
101
+ * A recording from the Chrome extension carries the tab's session as
102
+ * AVAILABLE (`entry.session`) but not required. Replay it in an empty browser
103
+ * first: if that passes, the flow doesn't need anyone signed in, and the
104
+ * session file is deleted. If it fails, try again with the session; if that
105
+ * passes, the flow starts signed in and keeps it. A session is kept on disk
106
+ * only when a flow actually needs one.
107
+ */
108
+ export async function prove(recording, opts = {}) {
109
+ const id = recording.entry?.session;
110
+ // Already known to need it (--arm-manually), or nothing to try: one replay.
111
+ if (!id || recording.entry?.requiresSession) {
112
+ return { ...(await execute(recording, opts)), recording, signIn: id || recording.entry?.requiresSession ? 'needed' : 'no session to try' };
113
+ }
114
+ // The same recording without the session: what an empty browser would do.
115
+ const { session: _dropped, ...rest } = recording.entry;
116
+ const cold = { ...recording };
117
+ if (Object.keys(rest).length)
118
+ cold.entry = rest;
119
+ else
120
+ delete cold.entry;
121
+ const first = await execute(cold, opts);
122
+ if (first.result.ok) {
123
+ await forgetSessionById(recording.appSlug, id);
124
+ return { ...first, recording: cold, signIn: 'not needed' };
125
+ }
126
+ const warm = { ...recording, entry: { ...recording.entry, requiresSession: true } };
127
+ const second = await execute(warm, opts);
128
+ if (second.result.ok)
129
+ return { ...second, recording: warm, signIn: 'needed' };
130
+ // Broken either way: report the cold attempt, and don't keep a session for a broken flow.
131
+ await forgetSessionById(recording.appSlug, id);
132
+ return { ...first, recording: cold, signIn: 'not needed' };
133
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Findings: "the app looks broken here". Detection is free — it reads what
3
+ * replay already captured — and runs on every replay, no model involved.
4
+ *
5
+ * Each finding has a fingerprint built from what is wrong, not from when it
6
+ * happened, so the same 500 on the same route across ten runs is ONE finding
7
+ * with ten occurrences, not ten findings. Ported from the old run.ts.
8
+ */
9
+ import type { Collection } from 'mongodb';
10
+ import type { ReplayResult } from '../core/replay.js';
11
+ import type { Finding } from '../store/types.js';
12
+ export type FindingDraft = Pick<Finding, 'kind' | 'severity' | 'statement' | 'evidence' | 'fingerprint'>;
13
+ /** Strip what differs run to run (ids, numbers, signed query strings), so one defect fingerprints the same every time. */
14
+ export declare function stable(text: string): string;
15
+ /** Route shape only: `https://x.com/orders/123?a=b` → `https://x.com/orders/:id`. */
16
+ export declare function routeOf(url: string | undefined): string;
17
+ /** Turn one replay's captured signals into findings. Pure: no browser, no database. */
18
+ export declare function extractFindings(result: Pick<ReplayResult, 'signals' | 'steps'>, goal: string): FindingDraft[];
19
+ /**
20
+ * Store findings: new ones are inserted as open, known ones get another
21
+ * occurrence. A finding someone already triaged keeps its status.
22
+ */
23
+ export declare function saveFindings(coll: Collection<Finding>, app: string, drafts: FindingDraft[], at?: Date): Promise<void>;
24
+ export type Verdict = 'issue' | 'lesson' | 'noise';
25
+ /**
26
+ * Route open findings. issue: the app is wrong and someone should fix it.
27
+ * lesson: accepted — the agent works around it (pass the lesson to store).
28
+ * noise: not a problem (third-party telemetry, framework warnings).
29
+ * Returns what couldn't be routed instead of throwing, so one bad item
30
+ * doesn't lose the rest.
31
+ */
32
+ export declare function triage(coll: Collection<Finding>, app: string, items: {
33
+ fingerprint: string;
34
+ verdict: Verdict;
35
+ }[]): Promise<{
36
+ routed: number;
37
+ problems: string[];
38
+ }>;
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Findings: "the app looks broken here". Detection is free — it reads what
3
+ * replay already captured — and runs on every replay, no model involved.
4
+ *
5
+ * Each finding has a fingerprint built from what is wrong, not from when it
6
+ * happened, so the same 500 on the same route across ten runs is ONE finding
7
+ * with ten occurrences, not ten findings. Ported from the old run.ts.
8
+ */
9
+ import { createHash } from 'node:crypto';
10
+ /** Strip what differs run to run (ids, numbers, signed query strings), so one defect fingerprints the same every time. */
11
+ export function stable(text) {
12
+ return text
13
+ .replace(/(https?:\/\/[^\s'"?#]+)\?[^\s'"]*/g, '$1')
14
+ .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, ':uuid')
15
+ .replace(/\b\d{3,}\b/g, ':n')
16
+ .replace(/\s+/g, ' ')
17
+ .trim()
18
+ .slice(0, 300);
19
+ }
20
+ /** Route shape only: `https://x.com/orders/123?a=b` → `https://x.com/orders/:id`. */
21
+ export function routeOf(url) {
22
+ if (!url)
23
+ return '';
24
+ try {
25
+ const u = new URL(url);
26
+ return u.origin + u.pathname.replace(/\/\d+(?=\/|$)/g, '/:id');
27
+ }
28
+ catch {
29
+ return stable(url);
30
+ }
31
+ }
32
+ const fingerprint = (parts) => createHash('sha1').update(parts.map(String).join('|')).digest('hex').slice(0, 20);
33
+ /** Turn one replay's captured signals into findings. Pure: no browser, no database. */
34
+ export function extractFindings(result, goal) {
35
+ const drafts = new Map();
36
+ const add = (d) => {
37
+ if (!drafts.has(d.fingerprint))
38
+ drafts.set(d.fingerprint, d);
39
+ };
40
+ for (const s of result.signals) {
41
+ if (s.kind === 'http' && (s.status ?? 0) >= 400) {
42
+ const route = routeOf(s.url);
43
+ add({
44
+ kind: 'network_error',
45
+ // 5xx is the app breaking; 4xx may be the app correctly refusing.
46
+ severity: (s.status ?? 0) >= 500 ? 'high' : 'medium',
47
+ statement: `${s.text} on ${route}`,
48
+ evidence: { url: s.url, status: s.status, body: s.body, duringStep: s.duringStep, goal },
49
+ fingerprint: fingerprint(['network_error', s.status, route]),
50
+ });
51
+ }
52
+ else if (s.kind === 'console' || s.kind === 'pageerror') {
53
+ add({
54
+ kind: 'console_error',
55
+ severity: s.kind === 'pageerror' ? 'high' : 'low',
56
+ statement: stable(s.text),
57
+ evidence: { text: s.text, duringStep: s.duringStep, goal },
58
+ fingerprint: fingerprint(['console_error', stable(s.text)]),
59
+ });
60
+ }
61
+ else if (s.kind === 'requestfailed') {
62
+ add({
63
+ kind: 'network_error',
64
+ severity: 'medium',
65
+ statement: `request failed: ${s.text} on ${routeOf(s.url)}`,
66
+ evidence: { url: s.url, text: s.text, duringStep: s.duringStep, goal },
67
+ fingerprint: fingerprint(['requestfailed', routeOf(s.url), stable(s.text)]),
68
+ });
69
+ }
70
+ }
71
+ for (const step of result.steps) {
72
+ // Landed on a different page than when the flow was proven.
73
+ if (step.unexpectedPage) {
74
+ add({
75
+ kind: 'flow_drift',
76
+ severity: 'medium',
77
+ statement: `step ${step.seq} (${step.action}) landed on ${step.unexpectedPage.observed}, expected ${step.unexpectedPage.expected}`,
78
+ evidence: { step: step.seq, ...step.unexpectedPage, goal },
79
+ fingerprint: fingerprint(['unexpected_page', step.unexpectedPage.expected, step.unexpectedPage.observed]),
80
+ });
81
+ }
82
+ // A value typed into a field that didn't stay there.
83
+ if (step.roundTripMismatch) {
84
+ add({
85
+ kind: 'persistence',
86
+ severity: 'medium',
87
+ statement: `a value written at step ${step.seq} did not survive: wrote "${step.roundTripMismatch.expected}", read back "${step.roundTripMismatch.actual}"`,
88
+ evidence: { step: step.seq, ...step.roundTripMismatch, goal },
89
+ fingerprint: fingerprint(['persistence', step.action, step.roundTripMismatch.expected.length]),
90
+ });
91
+ }
92
+ }
93
+ return [...drafts.values()];
94
+ }
95
+ /**
96
+ * Store findings: new ones are inserted as open, known ones get another
97
+ * occurrence. A finding someone already triaged keeps its status.
98
+ */
99
+ export async function saveFindings(coll, app, drafts, at = new Date()) {
100
+ if (!drafts.length)
101
+ return;
102
+ await coll.bulkWrite(drafts.map((d) => ({
103
+ updateOne: {
104
+ filter: { app, fingerprint: d.fingerprint },
105
+ update: {
106
+ $set: { kind: d.kind, severity: d.severity, statement: d.statement, evidence: d.evidence, lastSeen: at },
107
+ $inc: { occurrences: 1 },
108
+ $setOnInsert: { app, fingerprint: d.fingerprint, firstSeen: at, status: 'open' },
109
+ },
110
+ upsert: true,
111
+ },
112
+ })));
113
+ }
114
+ /**
115
+ * Route open findings. issue: the app is wrong and someone should fix it.
116
+ * lesson: accepted — the agent works around it (pass the lesson to store).
117
+ * noise: not a problem (third-party telemetry, framework warnings).
118
+ * Returns what couldn't be routed instead of throwing, so one bad item
119
+ * doesn't lose the rest.
120
+ */
121
+ export async function triage(coll, app, items) {
122
+ const problems = [];
123
+ let routed = 0;
124
+ for (const [i, item] of items.entries()) {
125
+ if (!['issue', 'lesson', 'noise'].includes(item?.verdict)) {
126
+ problems.push(`triage[${i}].verdict must be issue, lesson or noise`);
127
+ continue;
128
+ }
129
+ const { matchedCount } = await coll.updateOne({ app, fingerprint: item.fingerprint }, { $set: { status: item.verdict } });
130
+ if (matchedCount)
131
+ routed++;
132
+ else
133
+ problems.push(`triage[${i}]: no finding with fingerprint ${item.fingerprint}`);
134
+ }
135
+ return { routed, problems };
136
+ }