@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,197 @@
1
+ /**
2
+ * Distillation — an agent annotates a saved flow and splits it into segments.
3
+ *
4
+ * Optional. A flow is stored and runnable without it; distilling adds what a
5
+ * person would say the flow is FOR (intent, preconditions, outcome), cuts it
6
+ * into reusable segments (e.g. "log in as a member" out of a checkout
7
+ * recording, so other goals can reuse it), and may suggest lessons.
8
+ *
9
+ * THE AGENT ANNOTATES; IT DOES NOT AUTHOR STEPS. The steps were captured by
10
+ * the recorder and proven by replay; the request numbers them and the answer
11
+ * may only refer to them BY INDEX. It can partition and name, never fabricate.
12
+ * That constraint is what makes it safe to let an agent do this at all.
13
+ *
14
+ * This file is the contract: the request, the answer's schema, and the
15
+ * validator. src/flows/distill.ts builds requests from MongoDB and saves answers.
16
+ */
17
+ import { triggerProblems } from './trigger.js';
18
+ const SCHEMA = {
19
+ type: 'object',
20
+ required: ['intent', 'preconditions', 'outcome', 'segments'],
21
+ properties: {
22
+ intent: { type: 'string', description: 'What this whole flow is FOR, in the user\'s language. Not a list of steps.' },
23
+ preconditions: { type: 'array', items: { type: 'string', enum: ['authenticated', 'not authenticated'] }, description: 'Exactly "authenticated" or "not authenticated" — nothing else. Empty if neither matters.' },
24
+ outcome: { type: 'string', description: 'The state the app is in afterwards.' },
25
+ segments: {
26
+ type: 'array',
27
+ description: 'Reusable chunks. A segment belongs to the APP, not to this recording — a login block cut from a checkout recording must be reusable by every future flow.',
28
+ items: {
29
+ type: 'object',
30
+ required: ['slug', 'title', 'intent', 'stepRange'],
31
+ properties: {
32
+ slug: { type: 'string', description: 'kebab-case, stable, e.g. "log-in-standard-user"' },
33
+ title: { type: 'string' },
34
+ intent: { type: 'string', description: 'What this segment achieves, phrased as a goal someone would ask for.' },
35
+ stepRange: { type: 'array', items: { type: 'integer' }, minItems: 2, maxItems: 2, description: '[start, end) indices into the steps given. Never invent steps.' },
36
+ preconditions: { type: 'array', items: { type: 'string', enum: ['authenticated', 'not authenticated'] } },
37
+ outcome: { type: 'string' },
38
+ },
39
+ },
40
+ },
41
+ candidateLessons: {
42
+ type: 'array',
43
+ description: 'Conditional fixes: "when X, do Y first". Only if the recording actually shows one.',
44
+ items: { type: 'object', required: ['kind', 'title', 'body', 'trigger'] },
45
+ },
46
+ corrections: {
47
+ type: 'array',
48
+ description: 'What you judged wrong or redundant in the raw recording, and why.',
49
+ items: { type: 'object', required: ['rule', 'detail'] },
50
+ },
51
+ },
52
+ };
53
+ const INSTRUCTIONS = `You are distilling a VERIFIED browser recording into reusable memory.
54
+
55
+ The steps below were captured from a real session and every one of them was
56
+ replayed successfully. They are ground truth.
57
+
58
+ YOUR JOB IS TO ANNOTATE AND PARTITION, NOT TO AUTHOR.
59
+ · Do NOT restate, reorder, or invent steps. Reference them by index only.
60
+ · Segments are [start, end) ranges over the step list given.
61
+ · Segments should cut on MEANINGFUL boundaries — a change of page state
62
+ (see sigAfter) is usually one.
63
+
64
+ What matters most:
65
+ · intent — what this flow is FOR, phrased the way someone would ASK for it
66
+ ("log in as a standard user"), never a description of the mechanics
67
+ ("fill two textboxes and click a button").
68
+ · segments — a segment belongs to the APP, not to this recording. A login
69
+ block cut out of a checkout recording must be reusable by every future
70
+ flow, so name and scope it accordingly.
71
+ · preconditions — EXACTLY "authenticated" or "not authenticated", or empty.
72
+ Not "authenticated as a member": the planner checks whole strings, so any
73
+ other wording silently never matches.
74
+
75
+ USE THE APP'S EXISTING VOCABULARY.
76
+ The request includes every segment this app already has. If a block of steps
77
+ here does the same thing as one of those, REUSE its exact slug and phrasing
78
+ rather than inventing a synonym. "Sign in to the app" and "Authenticate as a
79
+ member" as two separate segments is a corpus defect: they compete for the same
80
+ bind slot, and a planner searching for one will not find the other.
81
+ Only invent new wording when the thing genuinely is new.
82
+
83
+ Only report a lesson or a correction if the recording actually shows one.
84
+ Inventing them is worse than leaving the arrays empty.`;
85
+ /**
86
+ * Build the payload handed to whoever is distilling.
87
+ *
88
+ * Only steps that REPLAYED are included — an unverified step must never reach
89
+ * the model, or it can end up named, segmented, and bound like a real one.
90
+ */
91
+ export function buildDistillRequest(recording, replayResult, vocabulary = { segments: [], flows: [], facts: [] }) {
92
+ const okSeqs = new Set(replayResult.steps.filter((s) => s.ok).map((s) => s.seq));
93
+ const sigBySeq = new Map(replayResult.steps.map((s) => [s.seq, s.sig]));
94
+ const steps = recording.events
95
+ .filter((e) => okSeqs.has(e.seq))
96
+ .map((e, index) => ({
97
+ index,
98
+ action: e.action,
99
+ ...(e.role ? { role: e.role } : {}),
100
+ ...(e.name ? { name: e.name } : {}),
101
+ ...(e.value !== undefined ? { value: e.value } : {}),
102
+ ...(e.valueRef ? { valueRef: e.valueRef } : {}),
103
+ ...(sigBySeq.get(e.seq) ? { sigAfter: sigBySeq.get(e.seq) } : {}),
104
+ url: e.url,
105
+ }));
106
+ return {
107
+ recordingHash: recording.hash,
108
+ appSlug: recording.appSlug,
109
+ startUrl: recording.startUrl,
110
+ steps,
111
+ vocabulary,
112
+ instructions: INSTRUCTIONS,
113
+ schema: SCHEMA,
114
+ };
115
+ }
116
+ /**
117
+ * Validate a distillation before ANY of it is written.
118
+ *
119
+ * The server validates, not the agent — PLAN.md is explicit that a mismatch
120
+ * returns errors and the agent retries. This is the only thing standing between
121
+ * a malformed or hallucinated distillation and the corpus, so it checks
122
+ * structure AND the index arithmetic that keeps segments honest.
123
+ */
124
+ export function validateDistilled(input, stepCount) {
125
+ const errors = [];
126
+ const push = (m) => errors.push(m);
127
+ if (typeof input !== 'object' || input === null) {
128
+ return { ok: false, errors: ['distillation must be a JSON object'] };
129
+ }
130
+ const d = input;
131
+ if (typeof d.intent !== 'string' || !d.intent.trim())
132
+ push('intent is required and must be a non-empty string');
133
+ if (typeof d.outcome !== 'string' || !d.outcome.trim())
134
+ push('outcome is required and must be a non-empty string');
135
+ const preconditionProblem = (at, v) => {
136
+ if (v === undefined)
137
+ return;
138
+ if (!Array.isArray(v) || v.some((p) => p !== 'authenticated' && p !== 'not authenticated')) {
139
+ push(`${at} must be an array of exactly "authenticated" or "not authenticated" (got ${JSON.stringify(v)})`);
140
+ }
141
+ };
142
+ if (!Array.isArray(d.preconditions))
143
+ push('preconditions must be an array');
144
+ else
145
+ preconditionProblem('preconditions', d.preconditions);
146
+ if (!Array.isArray(d.segments)) {
147
+ push('segments must be an array');
148
+ return { ok: false, errors };
149
+ }
150
+ const slugs = new Set();
151
+ d.segments.forEach((raw, i) => {
152
+ const s = raw;
153
+ const at = `segments[${i}]`;
154
+ for (const field of ['slug', 'title', 'intent']) {
155
+ if (typeof s[field] !== 'string' || !s[field].trim())
156
+ push(`${at}.${field} is required`);
157
+ }
158
+ if (typeof s.slug === 'string') {
159
+ if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(s.slug))
160
+ push(`${at}.slug must be kebab-case, got "${s.slug}"`);
161
+ if (slugs.has(s.slug))
162
+ push(`${at}.slug "${s.slug}" is duplicated`);
163
+ slugs.add(s.slug);
164
+ }
165
+ // The index arithmetic is the part that actually keeps a distillation
166
+ // honest: a range outside the verified steps would let the model reference
167
+ // something that was never recorded or never replayed.
168
+ preconditionProblem(`${at}.preconditions`, s.preconditions);
169
+ const range = s.stepRange;
170
+ if (!Array.isArray(range) || range.length !== 2 || !range.every((n) => Number.isInteger(n))) {
171
+ push(`${at}.stepRange must be [start, end) integers`);
172
+ return;
173
+ }
174
+ const [start, end] = range;
175
+ if (start < 0 || end > stepCount)
176
+ push(`${at}.stepRange [${start},${end}) is outside 0..${stepCount}`);
177
+ if (start >= end)
178
+ push(`${at}.stepRange [${start},${end}) is empty or inverted`);
179
+ });
180
+ // Ingest writes these straight into `lessons`, so a bad trigger here is a
181
+ // lesson that fires everywhere or nowhere. Validated like every other writer.
182
+ if (d.candidateLessons !== undefined && !Array.isArray(d.candidateLessons)) {
183
+ push('candidateLessons must be an array');
184
+ }
185
+ else {
186
+ d.candidateLessons?.forEach((raw, i) => {
187
+ const l = (raw ?? {});
188
+ for (const field of ['kind', 'title', 'body']) {
189
+ if (typeof l[field] !== 'string' || !l[field].trim())
190
+ push(`candidateLessons[${i}].${field} is required`);
191
+ }
192
+ for (const p of triggerProblems(l.trigger))
193
+ push(`candidateLessons[${i}].${p}`);
194
+ });
195
+ }
196
+ return errors.length ? { ok: false, errors } : { ok: true, errors: [], value: d };
197
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * A step's fingerprint: `sha1(action|role|name|url_pattern)`.
3
+ *
4
+ * Two recordings doing the same thing produce byte-identical fingerprints,
5
+ * which is what lets macro mining spot a recurring block, destructive
6
+ * inference match a step against an already-destructive one, and — see
7
+ * `markApplied` — a lesson ask whether the KIND of step it guards has ever
8
+ * actually failed.
9
+ *
10
+ * Lives in its own module because those three callers have nothing else in
11
+ * common, and importing all of `ingest.ts` to get one hash function drags a
12
+ * replay/embedding dependency into places that need neither.
13
+ */
14
+ import type { RawEvent } from './recording.js';
15
+ export declare function stepFingerprint(event: RawEvent): string;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * A step's fingerprint: `sha1(action|role|name|url_pattern)`.
3
+ *
4
+ * Two recordings doing the same thing produce byte-identical fingerprints,
5
+ * which is what lets macro mining spot a recurring block, destructive
6
+ * inference match a step against an already-destructive one, and — see
7
+ * `markApplied` — a lesson ask whether the KIND of step it guards has ever
8
+ * actually failed.
9
+ *
10
+ * Lives in its own module because those three callers have nothing else in
11
+ * common, and importing all of `ingest.ts` to get one hash function drags a
12
+ * replay/embedding dependency into places that need neither.
13
+ */
14
+ import { createHash } from 'node:crypto';
15
+ import { urlPattern } from './sig.js';
16
+ export function stepFingerprint(event) {
17
+ return createHash('sha1')
18
+ .update([event.action, event.role ?? '', event.name ?? '', urlPattern(event.url)].join('|'))
19
+ .digest('hex')
20
+ .slice(0, 16);
21
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Where raw recordings live on disk.
3
+ *
4
+ * Recordings are keyed by their content hash, which makes this the
5
+ * distillation cache BUILDING.md asks for on day one: distilling is the expensive
6
+ * step, and re-recording the same flow produces the same hash, so the model is
7
+ * paid for once. Two captures of genuinely different flows differ in hash and
8
+ * are stored side by side.
9
+ *
10
+ * Mode A eventually mirrors these to S3; Mode B keeps them local. Nothing here
11
+ * knows which — it is just a directory.
12
+ */
13
+ import type { RawRecording } from './recording.js';
14
+ export declare const RECORDINGS_DIR: string;
15
+ export declare function recordingPath(hash: string): string;
16
+ /**
17
+ * Write a recording, keyed by hash.
18
+ *
19
+ * Returns `existed: true` when this exact recording is already on disk — the
20
+ * caller can then skip distillation entirely rather than paying for it again.
21
+ */
22
+ export declare function saveRecording(rec: RawRecording): Promise<{
23
+ path: string;
24
+ existed: boolean;
25
+ }>;
26
+ export declare function loadRecording(hashOrPath: string): Promise<RawRecording>;
27
+ export interface RecordingSummary {
28
+ hash: string;
29
+ appSlug: string;
30
+ source: RawRecording['source'];
31
+ events: number;
32
+ createdAt: string;
33
+ }
34
+ export declare function listRecordings(appSlug?: string): Promise<RecordingSummary[]>;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Where raw recordings live on disk.
3
+ *
4
+ * Recordings are keyed by their content hash, which makes this the
5
+ * distillation cache BUILDING.md asks for on day one: distilling is the expensive
6
+ * step, and re-recording the same flow produces the same hash, so the model is
7
+ * paid for once. Two captures of genuinely different flows differ in hash and
8
+ * are stored side by side.
9
+ *
10
+ * Mode A eventually mirrors these to S3; Mode B keeps them local. Nothing here
11
+ * knows which — it is just a directory.
12
+ */
13
+ import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
14
+ import { existsSync } from 'node:fs';
15
+ import { join, resolve } from 'node:path';
16
+ export const RECORDINGS_DIR = process.env.UNDERSTUDY_RECORDINGS_DIR ?? resolve('.understudy/recordings');
17
+ export function recordingPath(hash) {
18
+ return join(RECORDINGS_DIR, `${hash}.json`);
19
+ }
20
+ /**
21
+ * Write a recording, keyed by hash.
22
+ *
23
+ * Returns `existed: true` when this exact recording is already on disk — the
24
+ * caller can then skip distillation entirely rather than paying for it again.
25
+ */
26
+ export async function saveRecording(rec) {
27
+ await mkdir(RECORDINGS_DIR, { recursive: true });
28
+ const path = recordingPath(rec.hash);
29
+ const existed = existsSync(path);
30
+ await writeFile(path, JSON.stringify(rec, null, 2), 'utf8');
31
+ return { path, existed };
32
+ }
33
+ export async function loadRecording(hashOrPath) {
34
+ const path = hashOrPath.endsWith('.json') ? hashOrPath : recordingPath(hashOrPath);
35
+ const parsed = JSON.parse(await readFile(path, 'utf8'));
36
+ if (parsed.version !== 1) {
37
+ throw new Error(`recording ${path} is version ${parsed.version}, this build reads version 1`);
38
+ }
39
+ return parsed;
40
+ }
41
+ export async function listRecordings(appSlug) {
42
+ if (!existsSync(RECORDINGS_DIR))
43
+ return [];
44
+ const files = (await readdir(RECORDINGS_DIR)).filter((f) => f.endsWith('.json'));
45
+ const out = [];
46
+ for (const file of files) {
47
+ try {
48
+ const rec = await loadRecording(join(RECORDINGS_DIR, file));
49
+ if (appSlug && rec.appSlug !== appSlug)
50
+ continue;
51
+ out.push({
52
+ hash: rec.hash,
53
+ appSlug: rec.appSlug,
54
+ source: rec.source,
55
+ events: rec.events.length,
56
+ createdAt: rec.createdAt,
57
+ });
58
+ }
59
+ catch {
60
+ // A corrupt or half-written file shouldn't hide every other recording.
61
+ }
62
+ }
63
+ return out.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
64
+ }
@@ -0,0 +1,185 @@
1
+ /**
2
+ * RawRecording — the contract every recording source produces.
3
+ *
4
+ * This is the seam that makes the input side open. A human clicking in a headed
5
+ * browser, a codegen script, a hand-written Playwright suite, or a JSON file
6
+ * handed to us by something else entirely all reduce to this shape, and
7
+ * everything downstream — replay, tracing, distillation, IR, memory — consumes
8
+ * only this. A new source is a new adapter, never a new pipeline.
9
+ *
10
+ * IT IS DATA, NOT CODE. Playwright and Cypress source are things we PRINT at
11
+ * emit time; they are never an input format. Code is lossy in the direction we
12
+ * care about: you cannot swap a value, diff two steps, or re-target a selector
13
+ * in a string of JavaScript.
14
+ */
15
+ /** Actions the IR can express. Mirrors the `steps.action` CHECK constraint. */
16
+ export type RecordedAction = 'goto' | 'click' | 'fill' | 'press' | 'select' | 'check' | 'uncheck' | 'upload' | 'wait_url' | 'wait_text' | 'dispatch_click' | 'scroll_container' | 'snapshot' | 'assert';
17
+ /**
18
+ * How we came to believe an event's role and name — the honesty field.
19
+ *
20
+ * Role and name are the system's addressing scheme: selectors dedupe on
21
+ * `(role, name, frame_hint)` and `sig()` fingerprints on `role:name`. Getting
22
+ * them wrong doesn't throw, it silently splits one element into two selector
23
+ * rows and breaks the one-health-score-per-element property.
24
+ *
25
+ * accname resolved by Playwright's own accessible-name engine
26
+ * against a live element — authoritative
27
+ * script-literal read verbatim out of `getByRole('button', {name: 'Login'})`
28
+ * — codegen already did the accname work, so this is as good
29
+ * unresolved addressed by CSS or test id only; no role/name known
30
+ * statically. The replay stage can upgrade these by looking
31
+ * at the live element.
32
+ */
33
+ export type Resolution = 'accname' | 'script-literal' | 'synthesized' | 'unresolved';
34
+ export interface RawEvent {
35
+ /** Position in the recording. Dense, 0-based, assigned by the source. */
36
+ seq: number;
37
+ /** Milliseconds since recording start. Excluded from the hash. */
38
+ ts: number;
39
+ action: RecordedAction;
40
+ role?: string;
41
+ name?: string;
42
+ /** Exact-match intent for the name, as codegen emits `{ exact: true }`. */
43
+ exact?: boolean;
44
+ /**
45
+ * Literal value typed or selected. NEVER a credential — see valueRef.
46
+ * A password field emits `valueRef`, never `value`, so a recording can be
47
+ * committed, shared, or shipped to Cloud without leaking secrets.
48
+ */
49
+ value?: string;
50
+ valueRef?: string;
51
+ /** Fallback addressing when role+name isn't available. */
52
+ css?: string;
53
+ testId?: string;
54
+ /**
55
+ * Which attribute the test id came from — `data-testid`, `data-test`, …
56
+ *
57
+ * Playwright's getByTestId only looks at `data-testid` unless reconfigured
58
+ * globally. saucedemo uses `data-test`, so a recording that stored the bare
59
+ * value replayed against nothing. Storing the attribute makes the locator
60
+ * self-describing instead of dependent on ambient config.
61
+ */
62
+ testIdAttr?: string;
63
+ /** Matched by id SUFFIX, never exact — iframe ids are often generated. */
64
+ frameHint?: string;
65
+ /** URL at the moment of the event. */
66
+ url: string;
67
+ /**
68
+ * The page fingerprint this step produced WHEN IT WAS RECORDED.
69
+ *
70
+ * Carried so execution can answer "am I where I expected to be?" — the sig is
71
+ * computed after every step anyway, so comparing it to this costs nothing and
72
+ * is the difference between noticing the app changed under you and walking
73
+ * blindly into a page the plan never saw.
74
+ */
75
+ expectedSig?: string;
76
+ resolution: Resolution;
77
+ /** Anything the source knew but the IR has no column for. */
78
+ hints?: Record<string, unknown>;
79
+ }
80
+ /**
81
+ * How a recording gets to its first step — the part deliberately NOT recorded.
82
+ *
83
+ * A recording of "send a message" should not have to contain the login and the
84
+ * intake that precede it. Re-recording them would mint duplicate segments
85
+ * competing for the same bind slot, which is the exact problem slug reuse
86
+ * exists to prevent. So the entry state is DECLARED rather than captured, and
87
+ * replay reproduces it by other means.
88
+ */
89
+ export interface RecordingEntry {
90
+ /**
91
+ * The page fingerprint observed at the moment capture began.
92
+ *
93
+ * An assertion, not a hint: replay checks it before step 0, because a
94
+ * recording whose steps were captured somewhere other than where replay
95
+ * starts is a recording that describes a page nobody is looking at.
96
+ */
97
+ startState?: string;
98
+ /**
99
+ * Step 0 is not a login — replay must restore a saved session first.
100
+ *
101
+ * Set when capture began from an already-authenticated browser, which is the
102
+ * whole point of arming late. Without it, replaying such a recording lands on
103
+ * a login page and fails on a locator that was never going to be there, with
104
+ * nothing explaining why.
105
+ */
106
+ requiresSession?: boolean;
107
+ /**
108
+ * Flow slugs replayed, in order, in the capture context before capture armed.
109
+ *
110
+ * BY REFERENCE, NEVER INLINED STEPS. A saved session can carry a login past
111
+ * replay because login state lives in cookies; wizard progress does not, so
112
+ * the only way to start a recording past an intake is to actually walk it.
113
+ * Copying those steps into the recording would re-record the intake and mint
114
+ * a duplicate segment competing for the same bind slot — the exact problem
115
+ * slug reuse exists to prevent. A reference also means fixing the referenced
116
+ * segment once fixes every recording built on top of it.
117
+ */
118
+ prelude?: string[];
119
+ /**
120
+ * The saved session to restore, by id — set when the Chrome extension
121
+ * captured the signed-in tab it recorded from. Unlike --arm-manually
122
+ * sessions it is tied to no typed credentials, so it is named explicitly.
123
+ */
124
+ session?: string;
125
+ }
126
+ export interface RawRecording {
127
+ /** Bump when the shape changes incompatibly. */
128
+ version: 1;
129
+ source: 'live' | 'script' | 'import';
130
+ /** Where the source came from — a file path, or 'headed-browser'. */
131
+ origin: string;
132
+ appSlug: string;
133
+ startUrl: string;
134
+ createdAt: string;
135
+ /** Distillation cache key. See recordingHash. */
136
+ hash: string;
137
+ /** Absent for a recording that starts from a blank browser at `startUrl`. */
138
+ entry?: RecordingEntry;
139
+ events: RawEvent[];
140
+ }
141
+ /**
142
+ * Cache key for distillation — BUILDING.md's day-one guard, so the expensive
143
+ * model call happens once per distinct recording and never again.
144
+ *
145
+ * Deliberately excludes:
146
+ * ts wall-clock differs on every capture of the same flow
147
+ * seq derivable from position
148
+ * url normalized to a route pattern, so a recording captured against
149
+ * localhost and the same flow captured against staging share a key
150
+ *
151
+ * Values ARE included: filling a different username is a different recording.
152
+ *
153
+ * THE ENTRY CONDITION IS PART OF THE KEY. The same tail steps captured from a
154
+ * restored session and from a cold browser replay differently and are not the
155
+ * same recording — without this they would collide, and `saveRecording` would
156
+ * report `existed: true` and silently keep the first. `startState` is
157
+ * deliberately NOT included: it is an observation that can shift with a banner,
158
+ * and a cache key that moves on cosmetic change is not a cache key.
159
+ *
160
+ * The line that decides is DECLARATION vs OBSERVATION. `requiresSession` and
161
+ * `prelude` are claims the operator made about how to reach step 0, and they
162
+ * change how the recording must be executed. `startState` is something the
163
+ * browser reported. The first kind belongs in the key; the second does not.
164
+ *
165
+ * The prelude is hashed as the ORDERED LIST OF SLUGS, never the referenced
166
+ * flows' steps. So identical tail steps captured after `[log-in]` and after
167
+ * `[log-in, complete-intake]` are correctly different recordings, while later
168
+ * fixing the login segment does not move the hash and does not orphan a
169
+ * distillation that was paid for.
170
+ */
171
+ export declare function recordingHash(events: RawEvent[], entry?: RecordingEntry): string;
172
+ /** Assemble a recording and stamp its hash. */
173
+ export declare function buildRecording(meta: Omit<RawRecording, 'version' | 'hash' | 'createdAt' | 'events'>, events: RawEvent[]): RawRecording;
174
+ /**
175
+ * Decide whether a typed value is a credential.
176
+ *
177
+ * Fails CLOSED: anything that looks secret is redacted to a valueRef. A false
178
+ * positive costs one hard-coded value that the distiller turns into a
179
+ * parameter anyway; a false negative writes a password into a corpus that gets
180
+ * committed to git and pushed to CockroachDB Cloud.
181
+ */
182
+ export declare function redactValue(fieldHint: string, value: string, inputType?: string, secretSignal?: string): {
183
+ value?: string;
184
+ valueRef?: string;
185
+ };
@@ -0,0 +1,100 @@
1
+ /**
2
+ * RawRecording — the contract every recording source produces.
3
+ *
4
+ * This is the seam that makes the input side open. A human clicking in a headed
5
+ * browser, a codegen script, a hand-written Playwright suite, or a JSON file
6
+ * handed to us by something else entirely all reduce to this shape, and
7
+ * everything downstream — replay, tracing, distillation, IR, memory — consumes
8
+ * only this. A new source is a new adapter, never a new pipeline.
9
+ *
10
+ * IT IS DATA, NOT CODE. Playwright and Cypress source are things we PRINT at
11
+ * emit time; they are never an input format. Code is lossy in the direction we
12
+ * care about: you cannot swap a value, diff two steps, or re-target a selector
13
+ * in a string of JavaScript.
14
+ */
15
+ import { createHash } from 'node:crypto';
16
+ import { urlPattern } from './sig.js';
17
+ /**
18
+ * Cache key for distillation — BUILDING.md's day-one guard, so the expensive
19
+ * model call happens once per distinct recording and never again.
20
+ *
21
+ * Deliberately excludes:
22
+ * ts wall-clock differs on every capture of the same flow
23
+ * seq derivable from position
24
+ * url normalized to a route pattern, so a recording captured against
25
+ * localhost and the same flow captured against staging share a key
26
+ *
27
+ * Values ARE included: filling a different username is a different recording.
28
+ *
29
+ * THE ENTRY CONDITION IS PART OF THE KEY. The same tail steps captured from a
30
+ * restored session and from a cold browser replay differently and are not the
31
+ * same recording — without this they would collide, and `saveRecording` would
32
+ * report `existed: true` and silently keep the first. `startState` is
33
+ * deliberately NOT included: it is an observation that can shift with a banner,
34
+ * and a cache key that moves on cosmetic change is not a cache key.
35
+ *
36
+ * The line that decides is DECLARATION vs OBSERVATION. `requiresSession` and
37
+ * `prelude` are claims the operator made about how to reach step 0, and they
38
+ * change how the recording must be executed. `startState` is something the
39
+ * browser reported. The first kind belongs in the key; the second does not.
40
+ *
41
+ * The prelude is hashed as the ORDERED LIST OF SLUGS, never the referenced
42
+ * flows' steps. So identical tail steps captured after `[log-in]` and after
43
+ * `[log-in, complete-intake]` are correctly different recordings, while later
44
+ * fixing the login segment does not move the hash and does not orphan a
45
+ * distillation that was paid for.
46
+ */
47
+ export function recordingHash(events, entry) {
48
+ const normalized = events.map((e) => [
49
+ e.action,
50
+ e.role ?? '',
51
+ e.name ?? '',
52
+ e.value ?? e.valueRef ?? '',
53
+ e.css ?? '',
54
+ e.testId ?? '',
55
+ e.frameHint ?? '',
56
+ urlPattern(e.url),
57
+ ]);
58
+ // Byte-identical to the old form when there is no entry condition, so every
59
+ // recording captured before this existed keeps the hash it already has.
60
+ // ORDER OF INSERTION IS LOAD-BEARING: `requiresSession` first, `prelude` only
61
+ // when non-empty, so a recording that predates preludes still serializes to
62
+ // exactly the bytes it always did. `auth:check` gate 1 rehashes every
63
+ // recording on disk and is what catches a regression here.
64
+ const extras = {};
65
+ if (entry?.requiresSession)
66
+ extras.requiresSession = true;
67
+ if (entry?.prelude?.length)
68
+ extras.prelude = entry.prelude;
69
+ const payload = Object.keys(extras).length
70
+ ? JSON.stringify([normalized, extras])
71
+ : JSON.stringify(normalized);
72
+ return createHash('sha256').update(payload).digest('hex').slice(0, 32);
73
+ }
74
+ /** Assemble a recording and stamp its hash. */
75
+ export function buildRecording(meta, events) {
76
+ return {
77
+ version: 1,
78
+ ...meta,
79
+ createdAt: new Date().toISOString(),
80
+ hash: recordingHash(events, meta.entry),
81
+ events,
82
+ };
83
+ }
84
+ /** Field names that mean "this is a secret" — matched against role/name/css. */
85
+ const SECRET_HINTS = /pass(word|wd)?|secret|token|otp|cvv|ssn|api[-_ ]?key/i;
86
+ /**
87
+ * Decide whether a typed value is a credential.
88
+ *
89
+ * Fails CLOSED: anything that looks secret is redacted to a valueRef. A false
90
+ * positive costs one hard-coded value that the distiller turns into a
91
+ * parameter anyway; a false negative writes a password into a corpus that gets
92
+ * committed to git and pushed to CockroachDB Cloud.
93
+ */
94
+ export function redactValue(fieldHint, value, inputType, secretSignal = fieldHint) {
95
+ if (inputType === 'password' || SECRET_HINTS.test(secretSignal)) {
96
+ const slug = fieldHint.trim().toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_|_$/g, '') || 'secret';
97
+ return { valueRef: `SECRET.${slug}` };
98
+ }
99
+ return { value };
100
+ }