@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
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,167 @@
1
- # Temporary Holding Version
1
+ # Understudy
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ End-to-end tests for your own web apps, without clicking through every flow by
4
+ hand. Record a flow once; Understudy remembers it, replays it as a test, notices
5
+ when the app changes, and can run goals you describe in words — including goals
6
+ that need pieces of several recordings.
7
+
8
+ It works on its own from the command line, and it plugs into an AI agent
9
+ (Claude Code, Codex, Cursor) over MCP. The agent is optional; with one,
10
+ Understudy never calls a model itself — the agent is the model.
11
+
12
+ ## What it does
13
+
14
+ ```
15
+ record → save → replay / run → findings
16
+ ```
17
+
18
+ - **record** — click through a flow in your own browser, with the
19
+ [Understudy recorder](https://chromewebstore.google.com/detail/understudy-recorder/mdobdjogkgimabdpmbmhhcdeoahoapjf) extension from the Chrome Web Store. Passwords
20
+ are never stored: a password field is kept as
21
+ a reference like `SECRET.password`, and you supply the value when replaying.
22
+ - **save** — the recording is replayed headless first. It is kept only if every
23
+ step passes, so memory only holds flows known to work.
24
+ - **replay / run** — `replay` runs a flow by name; `run` finds the flow that
25
+ does a goal you describe ("go to my basket") and runs it. Matching is by
26
+ meaning if you configure an embedding model, by name if you don't.
27
+ - **findings** — every run checks for console errors, failed requests, error
28
+ responses, values that didn't stick, and whether the flow took a different
29
+ path through the app than last time. Each problem is reported once, with a
30
+ count, not once per run.
31
+
32
+ With an agent attached it also splits recordings into reusable segments (a
33
+ login cut out of a checkout, say), plans a goal across segments of different
34
+ recordings, and writes down what it learns as facts and lessons that apply to
35
+ every future run.
36
+
37
+ ## Set up (about five minutes)
38
+
39
+ You need **Node 22+** and a **MongoDB** with vector search — a free
40
+ [Atlas](https://www.mongodb.com/atlas) cluster (nothing to install), or MongoDB
41
+ Community Edition with `mongot` running locally.
42
+
43
+ ```bash
44
+ npm install -g @jeffawe/understudy
45
+ npx playwright install --only-shell chromium
46
+
47
+ understudy config set MONGODB_URI="mongodb+srv://…" EMBED_KEY="…"
48
+ ```
49
+
50
+ That writes `~/.understudy/understudy.env`, readable only by you. `EMBED_KEY` is
51
+ a [Voyage](https://www.voyageai.com) API key (200M free tokens); it's optional —
52
+ without one, goals match flow names instead of meaning.
53
+
54
+ Already keep your settings in an env file? Point at it instead:
55
+
56
+ ```bash
57
+ understudy config --env-file ~/secrets/understudy.env
58
+ ```
59
+
60
+ To record, install the [Understudy recorder](https://chromewebstore.google.com/detail/understudy-recorder/mdobdjogkgimabdpmbmhhcdeoahoapjf) from the Chrome Web Store.
61
+ Not using Chrome or another Chromium browser? See
62
+ [extension/README.md](extension/README.md).
63
+
64
+ | Setting | What it's for |
65
+ |---|---|
66
+ | `MONGODB_URI` | your Atlas `mongodb+srv://…` string, or local Community |
67
+ | `EMBED_KEY` | optional: a Voyage key, to match goals by meaning (`voyage-4-lite`). Using another model? See below. |
68
+ | `UNDERSTUDY_<REF>` | login values. A recording never stores a password: the field is kept as a name like `SECRET.password`, and at replay Understudy reads the value from `UNDERSTUDY_SECRET_PASSWORD`. Or pass it per run (`--value SECRET.password=…`, or `values` from an agent). Not set? The terminal asks for it (hidden) and offers to save it; an agent is told which line to add to your env file. |
69
+
70
+ ### Using a different embedding model
71
+
72
+ Voyage is the default, so a key is all it needs. For any other model, also set
73
+ `EMBED_URL` and `EMBED_MODEL` — any endpoint that speaks the OpenAI
74
+ `/v1/embeddings` format works (OpenAI, Mistral, Together, Ollama…) — and
75
+ `EMBED_DIMS` if its vectors aren't 1024 numbers long. Free and offline, with
76
+ [Ollama](https://ollama.com):
77
+
78
+ ```bash
79
+ ollama pull mxbai-embed-large
80
+ understudy config set EMBED_URL=http://localhost:11434/v1/embeddings EMBED_MODEL=mxbai-embed-large EMBED_DIMS=1024
81
+ ```
82
+
83
+ Two things to know: one database holds one model's vectors, so switching later
84
+ means `understudy reembed`; and the line between "a flow I know" and "close,
85
+ but not it" was calibrated on Voyage — other models score differently, so check
86
+ a few goals with `understudy recall` first.
87
+
88
+ ## Use it
89
+
90
+ ```bash
91
+ understudy record myapp # record in your own browser, with the extension
92
+ understudy save <hash> "log in as a member" # prove it by replaying, then keep it
93
+ # --no-verify keeps it without a replay (unproven)
94
+ # --force keeps it even if the replay fails
95
+ understudy flows myapp # what it knows how to do
96
+ understudy replay myapp log-in-as-a-member # run one flow
97
+ understudy run myapp "sign in" # find the flow for a goal, and run it
98
+ understudy findings myapp # what looked broken
99
+ understudy emit myapp log-in-as-a-member # print it as a Playwright (or Cypress) test
100
+ understudy app myapp --placeholder email # keep email addresses out of memory (moves them to your env file)
101
+ ```
102
+
103
+ An unproven flow is marked as such in `flows` and recall; the first run of
104
+ it that passes proves it. `understudy --help` lists everything. A flow that commits something real — a
105
+ purchase, a deletion — is marked destructive and refused unless you pass
106
+ `--allow-purchases`.
107
+
108
+ **On Safari, or prefer a fresh browser over your own?** Record in a browser
109
+ Understudy opens instead. It needs one extra download, the full Chromium
110
+ browser (about 350 MB, once):
111
+
112
+ ```bash
113
+ npx playwright install chromium
114
+ understudy record myapp --new-browser --url https://your-app.example
115
+ ```
116
+
117
+ Click through the flow in the window that opens, then close it to stop.
118
+
119
+ ## Where your data goes
120
+
121
+ Everything stays with you. Understudy has no server, no account and no
122
+ telemetry.
123
+
124
+ - **Recordings** are files on your machine. The Chrome extension sends what it
125
+ records only to Understudy on `127.0.0.1`.
126
+ - **Saved flows, notes and findings** go to the MongoDB you configured.
127
+ - **Your embedding model** (Voyage by default, if you set a key) receives only
128
+ the short texts used for search — flow names and descriptions, facts and
129
+ lessons, the goals you ask for — never steps, typed values or cookies.
130
+ - **Passwords** are never stored; signed-in sessions and your env file are
131
+ local files only you can read.
132
+ - **Your agent**, if you use one, sees what Understudy's tools return to it.
133
+
134
+ The recorder extension's privacy policy: [understudy.jeffawe.dev/privacy.html](https://understudy.jeffawe.dev/privacy.html).
135
+
136
+ ## With an agent
137
+
138
+ Add the MCP server to your agent. It starts and stops with the agent's session;
139
+ settings come from the env file you point it at, so keys never go in the
140
+ agent's config or the chat:
141
+
142
+ ```bash
143
+ claude mcp add understudy -- npx -y -p @jeffawe/understudy understudy-mcp --env-file ~/.understudy/understudy.env
144
+ ```
145
+
146
+ ```json
147
+ { "mcpServers": { "understudy": {
148
+ "command": "npx",
149
+ "args": ["-y", "-p", "@jeffawe/understudy", "understudy-mcp", "--env-file", "~/.understudy/understudy.env"]
150
+ } } }
151
+ ```
152
+
153
+ Ten tools: `recall`, `run`, `answer`, `record`, `save`, `distill`,
154
+ `save_distilled`, `remember`, `findings`, `app`. The server tells the agent how to use
155
+ them when it connects; [REASONER.md](REASONER.md) is the full version — how to
156
+ split a goal, when to answer a question and when to say "I don't know", and
157
+ what to write down.
158
+
159
+ ## Learn more
160
+
161
+ - [understudy.jeffawe.dev](https://understudy.jeffawe.dev) — the one-page overview
162
+ - [REASONER.md](REASONER.md) — how an agent should use it
163
+ - [extension/README.md](extension/README.md) — the Chrome recorder
164
+
165
+ ## License
166
+
167
+ Apache-2.0 — see [LICENSE](LICENSE).
package/REASONER.md ADDED
@@ -0,0 +1,67 @@
1
+ # Using Understudy
2
+
3
+ Understudy runs end-to-end tests against the user's web apps from flows it
4
+ remembers. You supply the judgement; it never calls a model.
5
+
6
+ ## Rules
7
+
8
+ - **Memory first.** `understudy_recall` is free and runs nothing. For a known
9
+ flow it returns the steps and the login values they need, so you can drive it
10
+ yourself if that's better.
11
+ - **Reach the goal however works** — `understudy_run`, or your own browser —
12
+ and **say which you used**. Never imply Understudy ran something you drove.
13
+ - **Never ask the user to paste a password into chat.** Recordings store names
14
+ like `SECRET.password`; Understudy reads the value from the user's settings
15
+ (`UNDERSTUDY_SECRET_PASSWORD`), or you pass one you fetched yourself in
16
+ `values`.
17
+ - **Destructive flows** (purchases, deletions) are refused unless
18
+ `allowPurchases`. Start runs with `dryRun: true`.
19
+
20
+ ## The two questions a run can ask
21
+
22
+ Runs plan before any browser opens.
23
+
24
+ - **decompose** → `{"subGoals": [...]}`: what must happen, **in the order the
25
+ app does it**, phrased in the words of the app's flows (listed with the
26
+ question). Include prerequisites the user left out, like logging in. One
27
+ sub-goal naming a whole recorded flow beats several naming its parts. Tell
28
+ the user the sub-goals.
29
+ - **seam** → `{"steps": [one click or goto]}` to get from one flow to the next,
30
+ or `{"steps": []}` **unless you actually know** — an answer is saved and
31
+ reused forever.
32
+
33
+ ## Growing memory
34
+
35
+ - **The app doesn't have a flow?** Ask the user to record it
36
+ (`understudy_record`, then `understudy_save` once they've stopped), or drive
37
+ it yourself and save the Playwright script (`understudy_save` with `script`;
38
+ read passwords from `process.env`). Saving replays it first and keeps it only
39
+ if every step passes — or pass `verify: false` (with a `note`) when you know
40
+ why the replay can't pass; it's kept as unproven until a run passes. Save what the user would want tested again; a one-off
41
+ is enough as facts and lessons. Saving needs no permission.
42
+ - **Distilling** names a flow and splits it into reusable segments. **Ask the
43
+ user before each one**; any flow may be distilled. Refer to steps by index
44
+ only; preconditions are exactly `"authenticated"` or `"not authenticated"`;
45
+ reuse existing segment slugs rather than inventing synonyms.
46
+ - **Learned something?** Keep a list and put it to the user at a natural pause,
47
+ then write the approved items in one `understudy_remember`:
48
+ a **fact** changes plans ("order history is at `/past-invoices`");
49
+ a **lesson** changes one step, matched by an exact trigger
50
+ (`url_pattern` / `action` / `role` / `name`, never empty);
51
+ a **finding** says the app is broken.
52
+ Reached a goal without `understudy_run`? Record it there as `reached`.
53
+ - **Findings**: `understudy_findings` lists what looked broken; triage each as
54
+ `issue`, `lesson` or `noise`.
55
+ - **Emails out of memory**: `understudy_app` with `placeholders: ["email"]`
56
+ makes email fields placeholders and moves the addresses to the user's env file.
57
+
58
+ ## Traps
59
+
60
+ - **File uploads can't be recorded** — write a Playwright script instead.
61
+ - **Don't save anything irreversible** (a real order): saving replays it.
62
+ - **Logins are often rate-limited**; a missing login value stops a run before
63
+ it opens a browser, so check `needs` from recall first. The answer names the
64
+ env file line to add: ask the user to add it, then call again.
65
+ - **"Matched no elements" isn't always a bad selector** — check the page
66
+ rendered at all.
67
+ - **On Atlas, a just-saved flow takes a few seconds to be searchable.**
@@ -0,0 +1,186 @@
1
+ // Understudy recorder — background service worker.
2
+ //
3
+ // Holds the one recording in progress (which tab, which token), injects the
4
+ // recorder into that tab after every page load, and forwards each action to
5
+ // the `understudy record <app>` process on this machine, in order.
6
+ // The extension stores nothing about the page itself.
7
+
8
+ const DEFAULT_PORT = 7397;
9
+
10
+ async function cliUrl() {
11
+ const { port = DEFAULT_PORT } = await chrome.storage.local.get('port');
12
+ return `http://127.0.0.1:${port}`;
13
+ }
14
+
15
+ /** Is `understudy record <app>` running, and for which app? */
16
+ async function hello() {
17
+ let res;
18
+ try {
19
+ res = await fetch(`${await cliUrl()}/hello`);
20
+ } catch {
21
+ throw new Error('Understudy is not waiting. In a terminal, run: understudy record <app>');
22
+ }
23
+ if (!res.ok) throw new Error(`Understudy answered ${res.status}`);
24
+ return res.json();
25
+ }
26
+
27
+ async function post(path, body) {
28
+ let res;
29
+ try {
30
+ res = await fetch(`${await cliUrl()}${path}`, {
31
+ method: 'POST',
32
+ headers: { 'content-type': 'application/json' },
33
+ body: JSON.stringify(body),
34
+ });
35
+ } catch {
36
+ throw new Error('Understudy is no longer running in the terminal. Run: understudy record <app>');
37
+ }
38
+ const data = await res.json().catch(() => ({}));
39
+ if (!res.ok) throw new Error(data.error || `Understudy answered ${res.status}`);
40
+ return data;
41
+ }
42
+
43
+ async function current() {
44
+ return (await chrome.storage.session.get('rec')).rec;
45
+ }
46
+
47
+ async function inject(tabId, frameIds) {
48
+ await chrome.scripting.executeScript({
49
+ target: frameIds ? { tabId, frameIds } : { tabId, allFrames: true },
50
+ files: ['recorder.js'],
51
+ });
52
+ }
53
+
54
+ /** This tab's cookies and local storage, in the shape Playwright restores. */
55
+ async function captureSession(tab) {
56
+ const sameSite = { no_restriction: 'None', lax: 'Lax', strict: 'Strict', unspecified: 'Lax' };
57
+ const cookies = (await chrome.cookies.getAll({ url: tab.url })).map((c) => ({
58
+ name: c.name, value: c.value, domain: c.domain, path: c.path,
59
+ expires: c.session ? -1 : c.expirationDate ?? -1,
60
+ httpOnly: c.httpOnly, secure: c.secure, sameSite: sameSite[c.sameSite] ?? 'Lax',
61
+ }));
62
+ const [{ result: entries = [] } = {}] = await chrome.scripting.executeScript({
63
+ target: { tabId: tab.id },
64
+ func: () => Object.entries(localStorage),
65
+ });
66
+ const origin = new URL(tab.url).origin;
67
+ return { cookies, origins: [{ origin, localStorage: entries.map(([name, value]) => ({ name, value })) }] };
68
+ }
69
+
70
+ // The tab's sign-in is always sent. Ticked "I'm signed in here": the flow starts
71
+ // signed in, full stop. Unticked: Understudy works it out when you save (it
72
+ // proves the recording without the sign-in first) and deletes it if unneeded.
73
+ let starting = null;
74
+ function startRecording(tabId, opts = {}) {
75
+ // One start at a time: the popup and the permission-granted handler below can
76
+ // both ask, and the second must wait for, not repeat, the first.
77
+ return (starting ??= doStart(tabId, opts).finally(() => { starting = null; }));
78
+ }
79
+
80
+ async function doStart(tabId, { signedIn = false, save = true } = {}) {
81
+ if (await current()) throw new Error('Already recording — stop that one first.');
82
+ const { app, token, started, savedBy = 'terminal' } = await hello();
83
+ if (started) throw new Error('That Understudy recording has already started. Run the command again for a new one.');
84
+ const tab = await chrome.tabs.get(tabId);
85
+ const storageState = await captureSession(tab);
86
+ await post('/start', { token, url: tab.url, storageState, signedIn });
87
+ await chrome.storage.session.set({ rec: { tabId, token, app, origin: new URL(tab.url).origin, save, savedBy } });
88
+ await inject(tabId);
89
+ await chrome.action.setBadgeText({ tabId, text: 'REC' });
90
+ await chrome.action.setBadgeBackgroundColor({ tabId, color: '#c62828' });
91
+ return { app };
92
+ }
93
+
94
+ // --- starting right after the user allows a site -----------------------------
95
+ //
96
+ // Chrome closes the popup when its "allow this site?" dialog appears, so the
97
+ // click on "Record from this page" would be lost and nothing would start. The
98
+ // popup leaves a note first; once the permission is granted, this worker —
99
+ // which outlives the popup — starts the recording itself.
100
+
101
+ const PENDING_MS = 2 * 60 * 1000;
102
+
103
+ async function noteFailure(tabId, message) {
104
+ await chrome.storage.session.set({ lastError: message });
105
+ await chrome.action.setBadgeText({ tabId, text: '!' }).catch(() => {});
106
+ await chrome.action.setBadgeBackgroundColor({ tabId, color: '#ef6c00' }).catch(() => {});
107
+ }
108
+
109
+ async function onPermissionAdded({ origins = [] }) {
110
+ const { pending } = await chrome.storage.session.get('pending');
111
+ if (!pending || Date.now() - pending.at > PENDING_MS) return;
112
+ // Only for the site that was asked about (the pattern is `<origin>/*`).
113
+ if (!origins.some((o) => o.replace(/\/\*$/, '') === pending.origin)) return;
114
+ await chrome.storage.session.remove('pending');
115
+ try {
116
+ await startRecording(pending.tabId, { signedIn: pending.signedIn, save: pending.save !== false });
117
+ } catch (e) {
118
+ if (!/Already recording/.test(e.message)) await noteFailure(pending.tabId, e.message);
119
+ }
120
+ }
121
+ chrome.permissions.onAdded.addListener(onPermissionAdded);
122
+
123
+ /** Stop. `name` (when the user ticked "Save as a flow when I stop"): the terminal proves and saves it under that name. */
124
+ async function stopRecording({ name } = {}) {
125
+ const rec = await current();
126
+ if (!rec) return { stopped: false };
127
+ // A field still being typed in hasn't been sent yet; flush it.
128
+ await chrome.scripting
129
+ .executeScript({ target: { tabId: rec.tabId, allFrames: true }, func: () => window.__understudyFlush && window.__understudyFlush() })
130
+ .catch(() => {});
131
+ await new Promise((r) => setTimeout(r, 300));
132
+ await queue;
133
+ await chrome.storage.session.remove('rec');
134
+ await chrome.action.setBadgeText({ tabId: rec.tabId, text: '' }).catch(() => {});
135
+ const saving = Boolean(name) && rec.save && rec.savedBy !== 'agent';
136
+ const { events, hash } = await post('/stop', { token: rec.token, ...(saving ? { name } : {}) });
137
+ return { stopped: true, events, hash, saving, savedBy: rec.savedBy };
138
+ }
139
+
140
+ // Events go out one at a time, in the order they happened.
141
+ let queue = Promise.resolve();
142
+ function forward(event) {
143
+ queue = queue.then(async () => {
144
+ const rec = await current();
145
+ if (rec) await post('/event', { token: rec.token, event }).catch(() => {});
146
+ });
147
+ }
148
+
149
+ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
150
+ if (sender.id !== chrome.runtime.id) return false;
151
+ if (msg.type === 'understudy:event') {
152
+ current().then((rec) => {
153
+ if (rec && sender.tab && sender.tab.id === rec.tabId) forward(msg.event);
154
+ });
155
+ return false;
156
+ }
157
+ const handlers = {
158
+ 'understudy:status': async () => {
159
+ // A start that failed after the popup closed: say so once, then forget it.
160
+ const { lastError } = await chrome.storage.session.get('lastError');
161
+ await chrome.storage.session.remove('lastError');
162
+ return { rec: (await current()) ?? null, lastError: lastError ?? null, cli: await hello().catch((e) => ({ error: e.message })) };
163
+ },
164
+ 'understudy:start': () => startRecording(msg.tabId, { signedIn: Boolean(msg.signedIn), save: msg.save !== false }),
165
+ 'understudy:stop': () => stopRecording({ name: msg.name }),
166
+ };
167
+ const handler = handlers[msg.type];
168
+ if (!handler) return false;
169
+ handler().then((r) => sendResponse({ ok: true, ...r }), (e) => sendResponse({ ok: false, error: e.message }));
170
+ return true; // answering asynchronously
171
+ });
172
+
173
+ // A click that loads a new page loses the recorder; put it back. Pages on a
174
+ // site you haven't allowed (a payment provider, say) can't be recorded.
175
+ chrome.webNavigation.onDOMContentLoaded.addListener(async ({ tabId, frameId }) => {
176
+ const rec = await current();
177
+ if (rec && rec.tabId === tabId) await inject(tabId, [frameId]).catch(() => {});
178
+ });
179
+
180
+ chrome.tabs.onRemoved.addListener(async (tabId) => {
181
+ const rec = await current();
182
+ if (rec && rec.tabId === tabId) await stopRecording().catch(() => {});
183
+ });
184
+
185
+ // For tests and the console: drive it without the popup.
186
+ self.understudy = { startRecording, stopRecording, current, onPermissionAdded };