project-brain 0.24.0 → 0.26.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 (61) hide show
  1. package/README.md +1 -1
  2. package/package.json +6 -6
  3. package/templates/project.claude.md +1 -1
  4. package/templates/skills/brain-audit/SKILL.md +17 -7
  5. package/templates/skills/brain-audit/references/abuse.md +36 -11
  6. package/templates/skills/brain-audit/references/accessibility.md +50 -22
  7. package/templates/skills/brain-audit/references/ai.md +39 -15
  8. package/templates/skills/brain-audit/references/analytics.md +34 -11
  9. package/templates/skills/brain-audit/references/api.md +38 -13
  10. package/templates/skills/brain-audit/references/backend.md +41 -9
  11. package/templates/skills/brain-audit/references/browser.md +146 -0
  12. package/templates/skills/brain-audit/references/complexity.md +22 -12
  13. package/templates/skills/brain-audit/references/concurrency.md +36 -18
  14. package/templates/skills/brain-audit/references/consistency.md +32 -9
  15. package/templates/skills/brain-audit/references/contract-drift.md +34 -16
  16. package/templates/skills/brain-audit/references/cost.md +45 -23
  17. package/templates/skills/brain-audit/references/cross-surface-parity.md +38 -11
  18. package/templates/skills/brain-audit/references/database.md +43 -17
  19. package/templates/skills/brain-audit/references/dependencies-licensing.md +27 -12
  20. package/templates/skills/brain-audit/references/design-system.md +40 -17
  21. package/templates/skills/brain-audit/references/devops.md +32 -17
  22. package/templates/skills/brain-audit/references/documentation.md +38 -16
  23. package/templates/skills/brain-audit/references/failure.md +40 -18
  24. package/templates/skills/brain-audit/references/feature-flags.md +31 -15
  25. package/templates/skills/brain-audit/references/flow-integrity.md +42 -10
  26. package/templates/skills/brain-audit/references/frontend.md +40 -12
  27. package/templates/skills/brain-audit/references/functional.md +31 -11
  28. package/templates/skills/brain-audit/references/future.md +28 -7
  29. package/templates/skills/brain-audit/references/goal.md +15 -6
  30. package/templates/skills/brain-audit/references/i18n.md +30 -8
  31. package/templates/skills/brain-audit/references/idempotency.md +46 -24
  32. package/templates/skills/brain-audit/references/infrastructure.md +43 -13
  33. package/templates/skills/brain-audit/references/mobile.md +37 -15
  34. package/templates/skills/brain-audit/references/multi-tenancy.md +41 -12
  35. package/templates/skills/brain-audit/references/numeric.md +33 -16
  36. package/templates/skills/brain-audit/references/observability.md +43 -19
  37. package/templates/skills/brain-audit/references/packaging.md +39 -13
  38. package/templates/skills/brain-audit/references/performance.md +43 -13
  39. package/templates/skills/brain-audit/references/privacy.md +38 -15
  40. package/templates/skills/brain-audit/references/product.md +29 -10
  41. package/templates/skills/brain-audit/references/prompt-spec-gap.md +34 -10
  42. package/templates/skills/brain-audit/references/reachability.md +38 -18
  43. package/templates/skills/brain-audit/references/repo-history.md +23 -16
  44. package/templates/skills/brain-audit/references/runtime.md +48 -10
  45. package/templates/skills/brain-audit/references/scalability.md +37 -10
  46. package/templates/skills/brain-audit/references/security.md +46 -22
  47. package/templates/skills/brain-audit/references/state-model.md +44 -15
  48. package/templates/skills/brain-audit/references/supply-chain.md +42 -13
  49. package/templates/skills/brain-audit/references/temporal.md +37 -14
  50. package/templates/skills/brain-audit/references/testing.md +38 -14
  51. package/templates/skills/brain-audit/references/tooling-baseline.md +34 -18
  52. package/templates/skills/brain-audit/references/type-safety.md +38 -19
  53. package/templates/skills/brain-audit/references/usability.md +78 -0
  54. package/templates/skills/brain-audit/references/versioning-compatibility.md +34 -12
  55. package/templates/skills/brain-audit/references/visual-design.md +38 -12
  56. package/templates/skills/brain-audit/references/web-metadata.md +47 -19
  57. package/templates/skills/brain-record/SKILL.md +297 -0
  58. package/templates/skills/brain-record/assets/build-video.sh +142 -0
  59. package/templates/skills/brain-record/assets/record.mjs +283 -0
  60. package/templates/skills/brain-record/references/pitfalls.md +233 -0
  61. package/templates/skills/brain-worktree/SKILL.md +103 -0
@@ -0,0 +1,297 @@
1
+ ---
2
+ name: brain-record
3
+ description: "Trigger: record a demo, graba el flujo, demo del branch, gif de la feature, video del PR, evidence video for PR, ticket attachment video, swagger walkthrough recording, record this flow, video del ticket, grabar evidencia, screen recording of this work. Records the full flow a ticket or branch touches — frontend through the browser, backend through Swagger UI — at a true, real-time-paced 30fps with a drawn pointer overlay, as evidence for a PR or ticket attachment."
4
+ license: Apache-2.0
5
+ metadata:
6
+ author: jcsoftdev
7
+ version: "2.0"
8
+ generator: project-brain
9
+ ---
10
+
11
+ <!--
12
+ `generator: project-brain` is an ownership marker, not decoration.
13
+ `project-brain setup` overwrites this directory only when it finds that line;
14
+ without it, setup treats the directory as hand-written and leaves it alone.
15
+ Strip it and you pin this copy forever — no upgrade will ever reach it.
16
+ -->
17
+
18
+ ## Why this engine, not screen capture
19
+
20
+ The previous engine drove the browser through the Chrome MCP and captured the SCREEN
21
+ with `ffmpeg -f avfoundation`. That cannot work, and this was verified live, not
22
+ reasoned: the Chrome MCP drives a tab that is NOT frontmost, so the page reports
23
+ `visibilityState: "hidden"`, `hasFocus: false`, and therefore `outerWidth: 0,
24
+ outerHeight: 0, screenX: 0, screenY: 0` — an instruction to "read the window rect from
25
+ the page" returns zeros. Worse, screen capture records the FOREGROUND, which is a
26
+ different tab entirely; capturing one frame of every attached display confirmed the
27
+ automated page was on neither. Screen capture and a background-tab driver are
28
+ structurally incompatible.
29
+
30
+ This engine drives the browser AND captures it over the same channel: Chrome DevTools
31
+ Protocol. `assets/record.mjs` connects to a Chrome instance's CDP endpoint with
32
+ `playwright-core`, drives every beat itself (click, fill, scroll), and captures with
33
+ `Page.startScreencast`, which captures the PAGE regardless of foreground state or tab
34
+ visibility. There is no more Chrome MCP involvement in the recorded take at all — see
35
+ Execution Steps for where Chrome MCP still helps (page inspection only, never the take
36
+ itself) and where it does not appear.
37
+
38
+ One consequence worth stating plainly: this engine has no macOS dependency. The old one
39
+ needed `avfoundation`, which is macOS-only. This one needs Chrome, Node, and ffmpeg —
40
+ available on any platform that runs project-brain.
41
+
42
+ ## Activation Contract
43
+
44
+ Apply when asked to record a video of the full flow a ticket or branch touches, as
45
+ evidence for a PR review or a ticket attachment — a frontend flow driven in the
46
+ browser, a backend flow driven through Swagger UI, or both in one take.
47
+
48
+ This skill owns BOTH weights of that job. A handful of states is not a different skill,
49
+ it is the light gate below: `gif_creator` needs no worktree, no ffmpeg, no node and no
50
+ playwright. Choosing between them is a Decision Gate, not a hand-off.
51
+
52
+ Do not apply when: the branch has no user-visible flow to show (a refactor that touches
53
+ no route or endpoint); or no Chrome binary is reachable and the user cannot enable
54
+ remote debugging on any Chrome instance — say so and stop, do not attempt a degraded
55
+ capture.
56
+
57
+ ## Hard Rules
58
+
59
+ - Never drive the recorded take through the Chrome MCP. Verified live: a tab under
60
+ `computer`/`navigate` control is not frontmost, reports `visibilityState: "hidden"`
61
+ and a zeroed window rect, and a screen-capture engine built on that data captures the
62
+ wrong tab. Always drive the take through `assets/record.mjs`, connected directly to a
63
+ Chrome instance's CDP endpoint, and capture with `Page.startScreencast` — it captures
64
+ the PAGE, so foreground and tab visibility never matter. Chrome MCP tools
65
+ (`navigate`, `read_page`, `find`) may still be used to INSPECT the app while deriving
66
+ beats — that exploration is never part of the recording.
67
+ - Never run `assets/record.mjs` under `bun`. Measured: `chromium.connectOverCDP` from
68
+ Bun hangs at the websocket upgrade and dies at the 30s timeout, while the identical
69
+ script under `node` connects instantly. Always `node assets/record.mjs ...` — see
70
+ Decision Gates and `references/pitfalls.md`.
71
+ - Never assume `NODE_PATH` or `npx --package=playwright-core` makes `import { chromium }
72
+ from "playwright-core"` resolve. Measured: both fail with `ERR_MODULE_NOT_FOUND`,
73
+ because Node's ESM resolver walks up `node_modules` from the FILE doing the import,
74
+ not from `cwd` or `PATH`. Always run `record.mjs` from inside (copied into, or
75
+ symlinked under) the scratch directory that owns `node_modules/playwright-core` — see
76
+ Execution Steps.
77
+ - Never accept a consent/cookie overlay on the user's behalf. Sweep it away GENERICALLY
78
+ (any `position: fixed|sticky` element with `z-index > 1000` covering more than 25% of
79
+ the viewport, excluding the pointer) — never by a vendor selector. Two runs against
80
+ the SAME url served two different consent libraries. REMOVE, never ACCEPT: clicking
81
+ "allow all" is consent this tool has no standing to give, and it would be recorded as
82
+ if the user had agreed. Re-run the sweep after every scroll.
83
+ - Never press a button that writes real data unless the user explicitly asked for that
84
+ beat to be real. Prefer read paths, cancel confirmations before they submit, or a
85
+ sandbox/staging environment when a beat would otherwise mutate real data.
86
+ - Never ship a GIF. Measured: a GIF of the same take is LARGER than the H.264 MP4 while
87
+ carrying fewer frames, lower resolution and 256 colours. One output, one format —
88
+ `build-video.sh` writes it. Drag the MP4 into the pull request; GitHub renders a
89
+ player.
90
+ - Never hardcode the app's own port. Acquire it with `port_acquire` using the
91
+ `project`/`worktree` pair `project-brain worktree status --json` reports — two agents
92
+ that both assume 3000 collide, and it looks like a broken app. The CDP port is a
93
+ different concern (which Chrome instance to attach to, not which port the app under
94
+ test binds) — see Decision Gates for how it is chosen.
95
+ - Never default the connection mode to "live". `project-brain setup` records a
96
+ preference (`~/.project-brain/record-config.json`), and it defaults to "fresh" and
97
+ stays there unless the user explicitly opted in with `--record-connection-live`.
98
+ Chrome's own warning on the toggle "live" requires is the honest cost — see Decision
99
+ Gates.
100
+ - Derive beats in the MAIN checkout; record in the WORKTREE. `.project-brain/` only
101
+ resolves in the main checkout — deriving beats from an uninitialized worktree returns
102
+ nothing.
103
+ - Delete raw frames (`frames/`) and any scratch concat file once the final MP4 is
104
+ built. A take is tens of megabytes of JPEGs.
105
+
106
+ ## What has actually been recorded, and what has not
107
+
108
+ Stated because a skill that hides its own coverage costs its first user an afternoon.
109
+
110
+ VERIFIED end to end on real hardware: the backend path. A Swagger UI flow driven over
111
+ CDP — expand an operation, Try it out, fill a required parameter, Execute — recorded to a
112
+ 1280x800 constant-30fps MP4 whose last frame carries the request URL and a 200. Fresh
113
+ throwaway profile.
114
+
115
+ NOT YET VERIFIED, in this order of risk:
116
+ - The FRONTEND path. Same engine and same beats, but no real application flow with
117
+ navigation, forms and state has been recorded through it. Treat the first frontend take
118
+ as a shakedown: check the file before promising it to a reviewer.
119
+ - Connection mode "live". Wired and documented, never run against a logged-in Chrome.
120
+ - The light `gif_creator` gate, inherited from `branch-demo` rather than re-measured here.
121
+
122
+ ## Decision Gates
123
+
124
+ | Situation | Do |
125
+ |---|---|
126
+ | Fewer than ~8 states worth showing, and none of them is motion (a scroll, a transition, a drag) | Light path: `gif_creator`. Discrete screenshots, no worktree, no ffmpeg, no node. See the cap and the overlay settings in `references/pitfalls.md` before using it |
127
+ | Anything with motion, or more than ~8 states | Full path: `record.mjs` + `build-video.sh`. `gif_creator` physically cannot show motion — one frame per action — and caps at 50 frames SILENTLY |
128
+ | Flow is pure frontend (routes/components changed) | Beats target the app directly |
129
+ | Flow is pure backend (handler/controller/route changed, no UI) | Beats target Swagger UI (`/api-docs`, `/swagger`, or whatever the project serves) against the same endpoint |
130
+ | Flow touches both | One take, ordered the way the ticket describes it — e.g. the frontend action, then the backend call it triggers in Swagger UI |
131
+ | No worktree yet, or `worktree status` reports `indexed: false` | Defer to `brain-worktree` to create and index it — never `git worktree add` by hand |
132
+ | A beat would mutate real data | Confirm with the user first, or record up to the confirming dialog and stop there |
133
+ | No connection-mode preference recorded yet | Read `~/.project-brain/record-config.json` (written by `project-brain setup`); if absent, default to `{ mode: "fresh", cdpPort: 9222 }` — never assume "live" |
134
+ | Connection mode is "fresh" | Launch a throwaway Chrome (`--remote-debugging-port=<cdpPort> --user-data-dir=<tempdir>`), poll `/json/version` until it answers, record, then kill that Chrome process and delete its temp profile |
135
+ | Connection mode is "live" | The USER opens `chrome://inspect/#remote-debugging` in their own Chrome and toggles "Allow remote debugging for this browser instance" themselves — never automate that toggle. Surface Chrome's own warning before proceeding (quoted in full in Execution Steps). Never launch or kill the user's Chrome process |
136
+ | `record.mjs` throws a click-guard error (`"<label>": "<X>" is on top at <x>,<y> — a click here would hit that, not the target`) | Stop. Do not retry blindly — either the beat's selector needs a different scroll target, or a new kind of overlay needs investigating (never hardcode it into the sweep by vendor) |
137
+ | The CDP port is unreachable, or `/json/version` answers but the flow's tab is not there | Ask the user, or pick a different `--record-cdp-port` — never silently reuse a port that might be a stray Chrome from a previous take |
138
+
139
+ ## Execution Steps
140
+
141
+ ### Phase 0 — Ask exactly one thing, and only when you must
142
+
143
+ Infer everything you can; ask only what the repository cannot tell you.
144
+
145
+ Inferable from the diff, so never ask: frontend or backend (routes and components mean
146
+ the app, handlers and endpoints mean Swagger UI), light or full path (count the states
147
+ worth showing, and whether any of them is motion), which base branch to diff against.
148
+
149
+ NOT inferable, so this is the one question: **does the flow need a logged-in session?**
150
+ A flow behind auth needs connection mode "live" — the user's own Chrome, with their
151
+ cookies. Everything else records on a throwaway profile. Nothing in the diff answers
152
+ that, and guessing "live" wrongly means asking someone to expose their whole browser.
153
+
154
+ Ask it as one question, phrased for a decision and not for a menu, and only when the
155
+ recorded config does not already answer it. Then stop and wait. Do not stack a second
156
+ question onto it, and do not ask at all when the flow is plainly public — a Swagger UI
157
+ served by the branch's own dev server needs no session.
158
+
159
+ ### Phase 1 — Derive beats (run in the MAIN checkout)
160
+
161
+ 1. Resolve the ticket/branch: use the argument if given, else the current branch
162
+ (`git branch --show-current`).
163
+ 2. Read what it touches: `git diff <base>...<branch> --stat`, then the full diff for the
164
+ changed symbols. Use whichever base the repo actually branches from (`main`,
165
+ `develop`, …).
166
+ 3. Map files to user-visible surface with project-brain, from the MAIN checkout — this is
167
+ why phase 1 cannot run from the worktree, `.project-brain/` only resolves here:
168
+ - Frontend files → `find_callers`/`trace_path` to the route/page that renders them, or
169
+ `search_context` for "route for `<component>`" when the mapping isn't obvious from
170
+ the path alone.
171
+ - Backend files → `find_symbol` on the changed handler/controller to get its exact
172
+ HTTP method + path — that is the operation to drive in Swagger UI.
173
+ 4. Write the beats as an ordered list of concrete actions, not vague states. Each beat
174
+ names a URL or Swagger operation, an interaction, and what proves it worked:
175
+ ```
176
+ 1. Navigate to /login, sign in as the demo user
177
+ 2. Navigate to /orders/new, fill quantity=3, submit
178
+ 3. Swagger UI: POST /api/orders — show the 201 response body with the new order id
179
+ 4. Navigate to /orders, show the new order in the list
180
+ ```
181
+ 5. Keep this list in context as the shot list for phase 2 — nothing here needs to survive
182
+ to disk. The same session carries it across the working-directory switch.
183
+
184
+ ### Phase 2 — Record (run in the WORKTREE)
185
+
186
+ 6. Ensure the worktree exists and is indexed — follow `brain-worktree`'s own steps rather
187
+ than reimplementing worktree creation or `project-brain init`/`sync` here. Use
188
+ `EnterWorktree` (or the `using-git-worktrees` skill) to enter it.
189
+ 7. Acquire the port(s) the beats need: read `project-brain worktree status --json` for
190
+ the `project`/`worktree` pair, then `port_acquire(project, worktree, technology)` once
191
+ per service (e.g. `frontend`, `backend`). Start the app(s) bound to the acquired
192
+ ports — never a hardcoded one.
193
+ 8. Find each beat's selector. Navigate the running app with Chrome MCP
194
+ (`mcp__claude-in-chrome__navigate`, `read_page`, `find`) purely to INSPECT it — prefer
195
+ an id, a `data-testid`, or a stable ARIA role/name over a structural CSS path. This
196
+ exploration never touches CDP directly and is not part of the recording; close or
197
+ ignore that tab once every beat has a selector.
198
+ 9. Write `flow.json` (anywhere in the worktree's scratch area) from phase 1's shot list,
199
+ translated into `record.mjs`'s beat shapes:
200
+ ```json
201
+ {
202
+ "startUrl": "http://localhost:<port>/orders/new",
203
+ "viewport": { "width": 1280, "height": 800 },
204
+ "beats": [
205
+ { "action": "click", "label": "expand GET /pet/findByStatus", "selector": "#operations-pet-findPetsByStatus .opblock-summary-control" },
206
+ { "action": "click", "label": "Try it out", "selector": "#operations-pet-findPetsByStatus .try-out__btn" },
207
+ { "action": "fill", "label": "choose status=available", "selector": "#operations-pet-findPetsByStatus select", "value": "available" },
208
+ { "action": "click", "label": "Execute", "selector": "#operations-pet-findPetsByStatus .execute" },
209
+ { "action": "wait", "ms": 1600 },
210
+ { "action": "centre", "label": "show the response", "selector": "#operations-pet-findPetsByStatus .live-responses-table", "ms": 900 }
211
+ ]
212
+ }
213
+ ```
214
+ The clickable header of a Swagger operation is the summary CONTROL, not the whole
215
+ `opblock` — the `opblock`'s box centre falls below the header once it expands, so a
216
+ click at its centre misses. A backend-only beat sequence targets the Swagger UI URL
217
+ as `startUrl` instead of the app's own route.
218
+ 10. Resolve the connection mode and CDP endpoint per the Decision Gates row:
219
+ - **Fresh** (default, safe — what this engine was verified against):
220
+ ```
221
+ PORT=<cdpPort from record-config.json, default 9222>
222
+ PROFILE=$(mktemp -d)
223
+ "<Chrome binary>" --remote-debugging-port=$PORT --user-data-dir="$PROFILE" \
224
+ --no-first-run --no-default-browser-check about:blank &
225
+ until curl -s -o /dev/null http://127.0.0.1:$PORT/json/version; do sleep 0.05; done
226
+ ```
227
+ Poll `/json/version` rather than sleeping a fixed guess — measured ~0.7s on one
228
+ machine for a headless launch, but do not assume that number holds everywhere; see
229
+ `references/pitfalls.md`. `--headless=new` is optional: drop it to watch the take
230
+ live, keep it on a machine with no display. No logins, no cookies, no history — a
231
+ throwaway profile is inherently safe to record.
232
+ - **Live**: the USER — never this skill — opens `chrome://inspect/#remote-debugging`
233
+ in their own already-running Chrome and toggles "Allow remote debugging for this
234
+ browser instance" themselves. Before asking them to, surface Chrome's own warning
235
+ verbatim, because it is the honest cost of this mode: it "allows external apps to
236
+ request full control of this browser. This includes read access to your saved
237
+ data, cookies and site data, and the ability to navigate to any URL." Confirm the
238
+ user understands that before using this mode, even if `record-config.json` already
239
+ says `"mode": "live"` — a stored preference is not a renewed consent for THIS take.
240
+ Use the CDP port Chrome itself reports once the toggle is on; it does not have to
241
+ match `record-config.json`'s stored default.
242
+ 11. Resolve `playwright-core` without adding it as a project-brain dependency. Cache the
243
+ install once, globally, and run `record.mjs` from inside that cache directory —
244
+ verified this is required, not optional, per the Hard Rules item on `NODE_PATH`:
245
+ ```
246
+ SCRATCH="$HOME/.project-brain/record-scratch"
247
+ mkdir -p "$SCRATCH"
248
+ [ -d "$SCRATCH/node_modules/playwright-core" ] || npm install --prefix "$SCRATCH" --no-save playwright-core
249
+ cp assets/record.mjs "$SCRATCH/record.mjs"
250
+ ```
251
+ 12. Run the take:
252
+ ```
253
+ node "$SCRATCH/record.mjs" <outdir> <flow.json path> http://127.0.0.1:$PORT
254
+ ```
255
+ in the FOREGROUND — unlike the old engine, there is no separate capture process to
256
+ interleave `computer` calls with. `record.mjs` drives every beat itself and only
257
+ returns once the whole flow is complete, printing `beat: ...` lines as it goes and a
258
+ final `frames=N span=Xs` line. A non-zero exit means a beat failed (most likely the
259
+ click guard) — read the error, fix the flow, and re-run rather than trying to salvage
260
+ a partial take.
261
+ 13. Build the deliverable:
262
+ ```
263
+ bash assets/build-video.sh <outdir>/frames <outdir>/stamps.json <out.mp4>
264
+ ```
265
+ 14. Sample the finished file across its length and look at it. `build-video.sh` prints a
266
+ ready-made sampling command in its own output — scoring is not the same as watching
267
+ what shipped.
268
+ 15. Clean up: delete `frames/` and `stamps.json`. In fresh mode, kill the Chrome process
269
+ launched in step 10 and delete its temp profile directory — in live mode, leave the
270
+ user's Chrome exactly as it was, just stop connecting to it. `port_release` the
271
+ app's leased ports and tear down the worktree per `brain-worktree`'s own teardown
272
+ step, unless the user wants it left open for another pass.
273
+
274
+ ## Output Contract
275
+
276
+ Report: the beats recorded (from phase 1, and the selectors phase 2 resolved them to);
277
+ the worktree used and whether it was created or reused; the app port(s) leased and their
278
+ technology; the connection mode used (fresh or live) and the CDP port; if fresh, that the
279
+ throwaway profile and Chrome process were cleaned up; if live, that the user (not this
280
+ skill) enabled and will disable remote debugging; `record.mjs`'s own `frames=N span=Xs`
281
+ line; the output file's path, size, and duration; and whether `frames/`/`stamps.json`
282
+ were deleted. If any beat could not be captured cleanly — a click-guard failure, a button
283
+ that would have mutated real data, a connection that never came up — say so explicitly
284
+ rather than shipping a take with the caveat buried in prose.
285
+
286
+ ## References
287
+
288
+ - `assets/record.mjs` — connects to a Chrome CDP endpoint with `playwright-core`, drives
289
+ a `flow.json`'s beats (click/fill/centre/wait) with a drawn pointer overlay and a
290
+ generic consent-overlay sweep, and captures via `Page.startScreencast` — writing
291
+ `frames/NNNNN.jpg` and `stamps.json` (per-frame real timestamps). Run with `node`,
292
+ never `bun`; see its own header comment for why.
293
+ - `assets/build-video.sh` — turns `stamps.json` into an ffmpeg concat file with a
294
+ per-frame `duration`, then encodes a constant fps=30 H.264 MP4. No browser-chrome crop
295
+ — the screencast never contained one.
296
+ - `references/pitfalls.md` — traps to read before the first take, each labelled measured
297
+ or derived.
@@ -0,0 +1,142 @@
1
+ #!/bin/zsh
2
+ # Build the deliverable MP4 from record.mjs's screencast frames + real timestamps.
3
+ #
4
+ # There is no browser-chrome crop here — that only ever existed because the
5
+ # prior engine captured the OS WINDOW with avfoundation, tab strip and all.
6
+ # record.mjs captures the PAGE itself over CDP (`Page.startScreencast`), so no
7
+ # tab strip, URL bar, or "started debugging" banner is ever in the frames to
8
+ # begin with. There is also no crop_y, no device match, no HiDPI math: none of
9
+ # it applies to a page-level capture.
10
+ #
11
+ # WHY A CONCAT FILE INSTEAD OF `-framerate $FPS -i frames/%05d.jpg`:
12
+ #
13
+ # The screencast is VARIABLE-rate — Page.startScreencast only emits a frame
14
+ # when the page actually repaints, so idle time between beats produces NO
15
+ # frames. Encoding the raw sequence at a flat input framerate would be wrong
16
+ # twice over: it plays back FASTER than real time across any idle gap, and it
17
+ # throws away the only record of how long each frame was actually on screen.
18
+ # record.mjs writes that record as stamps.json — one CDP
19
+ # `Page.screencastFrame` `metadata.timestamp` per frame, in seconds, the first
20
+ # one normalised to 0. This script turns consecutive timestamp deltas into a
21
+ # per-frame `duration` in an ffmpeg concat file, then re-encodes THAT at a
22
+ # constant fps=$FPS, so the shipped file is a normal, seekable,
23
+ # constant-frame-rate video whose pacing matches what was actually recorded.
24
+ #
25
+ # WHY H.264 AND NOT A GIF, AND NOT AV1 EITHER — measured, not assumed.
26
+ #
27
+ # A GIF cannot carry this. 256 colours per frame and no real interframe
28
+ # prediction means a screen recording either bands visibly or balloons, and it
29
+ # has to drop framerate and resolution to stay embeddable at all. Measured on
30
+ # one 191-frame take: the GIF at 12fps / 900px wide / 256 colours came to 260K,
31
+ # while H.264 at 30fps / 1200x700 / full colour and VMAF 97.0 came to 149K.
32
+ # Better on every axis AND 43% smaller. So there is no GIF output here.
33
+ #
34
+ # Against the modern codecs, at MATCHED quality on the same source (VMAF via
35
+ # ffmpeg's libvmaf, against a lossless FFV1 reference of the same frames):
36
+ #
37
+ # static screen take, VMAF ~97 motion take (synthesised scroll), VMAF ~90
38
+ # h264 crf18 149,067 B h264 crf18 206,889 B
39
+ # h265 crf20 150,000 B h265 crf21 179,425 B
40
+ # av1 crf30 286,450 B av1 crf32 290,857 B
41
+ # vp9 crf24 283,369 B vp9 crf26 270,715 B
42
+ #
43
+ # AV1 and VP9 LOSE on both, roughly 2x. These takes are short — seconds, not
44
+ # minutes — so the long-GOP efficiency those codecs are famous for never gets
45
+ # paid back against their container and keyframe overhead. H.265 wins the
46
+ # motion case by ~13%, and is not used here anyway: Chrome and Firefox will not
47
+ # reliably decode HEVC in MP4, and this file exists to be opened by a reviewer
48
+ # who is not you. Universal playback beats 13%.
49
+ #
50
+ # Also unchanged from the prior engine, still true: FLUIDITY COSTS BITRATE.
51
+ # Measured on the same flow: 199 frames / 226,017 bytes with jump-cut scrolling
52
+ # versus 609 frames / 1,509,635 bytes with eased scrolling. That is the trade
53
+ # record.mjs's eased rAF scroll makes on purpose, not a regression to fix.
54
+ #
55
+ # Usage: build-video.sh <framedir> <stamps.json> <out.mp4> [play_fps]
56
+ #
57
+ # <framedir> and <stamps.json> are record.mjs's own outputs: <outdir>/frames
58
+ # and <outdir>/stamps.json. Default play_fps is 30 — real time, matching what
59
+ # stamps.json already encodes. Lower it to slow down a fast interaction for
60
+ # legibility, or raise it to compress a long take with a lot of dead air
61
+ # between beats (the concat file's per-frame durations already own the actual
62
+ # pacing either way — this only resamples the constant-rate output).
63
+
64
+ set -e
65
+ DIR=${1:?framedir}; STAMPS=${2:?stamps.json}; OUT=${3:?out.mp4}
66
+ FPS=${4:-30}
67
+
68
+ if [ ! -f "$STAMPS" ]; then
69
+ echo "stamps file not found: $STAMPS" >&2
70
+ exit 1
71
+ fi
72
+
73
+ CONCAT="$DIR/../concat.txt"
74
+ GEN="$DIR/../gen-concat.mjs"
75
+
76
+ # A small node generator, not inline zsh: building a duration-annotated
77
+ # ffconcat list needs real JSON parsing and float arithmetic, and node is
78
+ # already a hard requirement for assets/record.mjs — see its header. Written
79
+ # to a scratch file rather than passed via `node -e` because the ffconcat
80
+ # `file '...'` lines need literal single quotes, which is painful to escape
81
+ # correctly inside a zsh single-quoted `-e` argument.
82
+ cat > "$GEN" <<'JS'
83
+ import { readFileSync, writeFileSync, readdirSync } from "node:fs";
84
+ import { resolve } from "node:path";
85
+
86
+ const [, , framedir, stampsPath, concatPath] = process.argv;
87
+ const stamps = JSON.parse(readFileSync(stampsPath, "utf8"));
88
+ const frames = readdirSync(framedir).filter((f) => f.endsWith(".jpg")).sort();
89
+
90
+ if (frames.length !== stamps.length) {
91
+ console.error(`frame count ${frames.length} != stamp count ${stamps.length} — is stamps.json from a different take?`);
92
+ process.exit(1);
93
+ }
94
+ if (frames.length === 0) {
95
+ console.error(`no frames in ${framedir}`);
96
+ process.exit(1);
97
+ }
98
+
99
+ const lines = ["ffconcat version 1.0"];
100
+ for (let i = 0; i < frames.length; i++) {
101
+ const abs = resolve(framedir, frames[i]);
102
+ const dur =
103
+ i + 1 < stamps.length ? stamps[i + 1] - stamps[i] :
104
+ i > 0 ? stamps[i] - stamps[i - 1] : 1 / 30;
105
+ // Never a zero/negative duration: a repaint burst can stamp two frames at
106
+ // (near) the same instant, and ffmpeg rejects a non-positive duration line.
107
+ lines.push(`file '${abs}'`);
108
+ lines.push(`duration ${Math.max(dur, 1 / 120).toFixed(6)}`);
109
+ }
110
+ // ffmpeg's concat demuxer silently ignores the FINAL duration line unless the
111
+ // last file is listed once more without one — undocumented, but load-bearing:
112
+ // skip this and the last frame never appears in playback at all.
113
+ lines.push(`file '${resolve(framedir, frames[frames.length - 1])}'`);
114
+ writeFileSync(concatPath, lines.join("\n") + "\n");
115
+ console.log(`concat: ${frames.length} frames, span=${(stamps.at(-1) - stamps[0]).toFixed(2)}s`);
116
+ JS
117
+
118
+ node "$GEN" "$DIR" "$STAMPS" "$CONCAT"
119
+ rm -f "$GEN"
120
+
121
+ # scale only DOWN, never up: `scale='min(1440,iw)':-2` on a 1200-wide capture
122
+ # upscales, which spends bytes inventing pixels that carry no information.
123
+ # crf 18, not 22: measured VMAF 97.0 against a lossless reference of the same
124
+ # frames, for 149K on a 191-frame take. Screen content is cheap to encode —
125
+ # there is no reason to spend quality here.
126
+ ffmpeg -y -loglevel error \
127
+ -f concat -safe 0 -i "$CONCAT" \
128
+ -vf "fps=$FPS,scale='min(1440,iw)':-2:flags=lanczos" \
129
+ -c:v libx264 -preset slow -crf 18 -pix_fmt yuv420p -movflags +faststart \
130
+ "$OUT"
131
+
132
+ rm -f "$CONCAT"
133
+
134
+ ffprobe -v error -show_entries format=duration:stream=width,height -of default=nw=1 "$OUT"
135
+ ls -lh "$OUT"
136
+
137
+ # Sample across the finished file and LOOK at the result. Scoring frames (as
138
+ # the prior engine's filter-frames.py did) is not the same as watching what
139
+ # shipped — and there is no foreign-window filtering step any more: a page
140
+ # screencast cannot contain a frame of another window, so that whole class of
141
+ # defect no longer exists.
142
+ echo "sample it: for t in 3 25 50 75 100; do ffmpeg -y -ss \$t -i $OUT -frames:v 1 -vf scale=460:-2 v_\$t.jpg; done && magick v_*.jpg -append check.jpg"