Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

feat(perf): phase 0 perceived-performance gate and migration baseline

Abdurrahman Fakhrulc795f0bcd5a4
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 11b8e184..2f514c11 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,25 +8,14 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh
**Added**
-- `cli` close the opencode parity gap on run/session/stats/pair/doctor --json/completion
-
-**Changed**
-
-- `agent` drop the inert thinking option from the one-shot turn
-
-**Tests**
-
-- `cli` keep offline-update and private-state fixtures in sync with the new CLI slices
+- `perf` phase 0 perceived-performance gate and migration baseline
+- `cli` close the opencode parity gap on run/session/stats/pair/doctor --json/completion (#165)
**Docs**
- `agents` refresh AGENTS.md and add .mso/KNOWLEDGE.md for #154-#162 (#164)
- `antislop` design direction, agent pointer, and the R-10 glass audit (#163)
-**Other**
-
-- `cli` drop em dashes from the new copy (antislop R-02)
-
## 2026-10-27
**Added**
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index 7ef6e580..8a749de6 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -80,6 +80,31 @@ browser journey checks all five shells, absence of graph/editor/terminal/ONNX
runtime chunks on cold startup, delayed first-open/close/reopen Search, eager
clipboard capture, and retained Inspector tab state. It uses synthetic stores.
+### Perceived-performance measurement
+
+Bundle bytes are deterministic; the numbers a person actually feels are not, so
+they live in a separate, deliberately weaker gate.
+
+| Command | What it does | Gates a push |
+|---|---|---|
+| `bun run perf:probe` | Cold load at 4G + 4× CPU against a synthetic fixture (or `--base=`), writes `perf-report.json` | no |
+| `bun run perf:check` | Enforces `scripts/perf-budget.json` against a report | **yes** |
+| `bun run perf:tasks` | CDP-trace attribution of every long task to the script that owns it | no |
+| `bun run perf:apps` | Per-app open latency, fetched chunks and long tasks caused | no |
+
+`perf:check` fails hard on first-load JS bytes and on a missing measurement — a
+silent zero is how a perf gate dies. Timings only fail on a 2× blowup against
+`scripts/perf-baseline.json`, because this box also serves production and a
+wall-clock gate that flakes gets muted. Targets in that budget file
+(`tbtMs 150`, `lcpMs 2500`, `initialGzipBytes 256000`) are the post-migration goal
+from `docs/MSO-MIGRATION.md`; they are printed as advisory and never enforced,
+since holding today's Next build to a Svelte target would just make the gate
+permanently red.
+
+Regenerate the baseline with `node scripts/perf-probe.mjs --json` and commit the
+runs. Do that deliberately after a real improvement, not to silence a failure.
+
+
The report deduplicates eager catch-all entry chunks plus the framework runtime.
It lists `nomodule` polyfills separately: charging them to modern browsers would
overstate first-load bytes. Gzip/Brotli values are compression estimates, not
diff --git a/docs/MSO-MIGRATION.md b/docs/MSO-MIGRATION.md
new file mode 100644
index 00000000..d41c4d2d
--- /dev/null
+++ b/docs/MSO-MIGRATION.md
@@ -0,0 +1,592 @@
+# MSO migration plan — Svelte / Bun / Rust
+
+Status: **open plan, not implemented.** Measurement-first. Nothing here is approved to
+start until §3 gate is signed off with fresh numbers from the target host.
+
+Baseline commit: `1c74603` (2026-10-27), app `0.2.23`.
+Measurement host: ASUS laptop, WSL Ubuntu, node `26.7.0`, bun `1.4.2`, Next `16.4.2`.
+Measured: 2026-10-28.
+
+Live instances that must stay green during any phase: three of them — the local laptop
+instance, a second host running the same build, and the VPS instance that is treated as
+the source of truth. Their hostnames are deliberately not recorded here; see the
+operator's private deployment notes.
+
+---
+
+## 0. Code inventory (static)
+
+| Area | Files | LOC | Portability |
+|---|---|---|---|
+| `lib/` | 1,200 | 98,942 | 1,177 files (96,437 LOC) import neither `react` nor `next/*` → already framework-agnostic |
+| `frontend/slices/` | 943 | 74,176 | React-coupled; 32 slices; `appshell` alone is 20,028 |
+| `app/` (pages + routes) | 223 | 14,774 | 4 pages, 1 layout, 117 `route.ts` (6,305 LOC) |
+| `components/ui/` | 23 | 1,558 | Radix wrappers — the only `@radix-ui/*` consumers |
+| `scripts/` | 153 | 9,974 | already partly Bun |
+| tests | 858 files | 5,583 assertions | vitest |
+
+Next-specific surface actually used:
+
+```
+next/server 162 files (NextRequest 122, NextResponse 744)
+next/headers 4
+next/navigation 3
+next/link 1
+next/font/local 1
+next/og 1
+"use client" 481 files
+"use server" 1 file
+```
+
+Radix usage is concentrated: 11 packages, 13 files. No monaco, no react-three.
+Heavy optional engines: xterm + onnxruntime (`@imgly/background-removal`).
+
+`node:` builtin usage across `lib/` + `app/` + `components/` (482 files):
+
+```
+node:path 356 node:fs 267 node:os 259 node:crypto 155
+node:fs/promises 68 node:child_process 43 node:net 15
+node:util 14 node:events 6 node:http 5 node:zlib 4 node:stream 4
+```
+
+React surface in `frontend/` + `app/` + `components/`: `useState` 239 files,
+`useEffect` 147, `useMemo`/`useCallback` 106, `createContext` 16, `forwardRef`/`React.*` 113.
+
+Slice sizes and appshell coupling (risk ordering input):
+
+| Slice | LOC | files importing `@/features/appshell` |
+|---|---|---|
+| `appshell` | 20,028 | — (it is the shell) |
+| `os-settings` | 8,915 | 0 (`"use client"` in 76/78 files) |
+| `image-editor` | 6,966 | 0 |
+| `reel-editor` | 6,539 | 3/62 |
+| `assistant` | 5,430 | 0 |
+| `managed-apps` | 3,080 | 0 |
+| `files-manager` | 2,809 | 0 |
+| `icon-picker` | 2,766 | 1/32 |
+| `app-store` | 2,196 | 4 |
+| `code-editor` | 1,782 | 0 |
+| `workflows` | 1,734 | 0 |
+| `os-terminal` | 1,482 | 4/15 |
+| `auth` | 1,406 | 2/19 |
+| `media-viewer` | 1,363 | 1 |
+| `os-shell` | 955 | 5 |
+| `organization` | 889 | 2 |
+| `system-monitor` | 759 | 4/14 |
+| `image-picker` | 683 | 1/13 |
+| `memory-graph` | 536 | 3/9 |
+| `camoufox-browser` | 470 | 1/7 |
+| `channels` | 462 | 3/7 |
+| `agent-group` | 450 | 3/7 |
+| `agent-vault` | 409 | 4/11 |
+| `media-studio` | 332 | 3/5 |
+| `create-app` | 312 | 2/5 |
+| `integrations` | 299 | 1/6 |
+| `shell-settings` | 285 | 0/7 (fully decoupled) |
+| `extensions` | 278 | 1/11 |
+| `docs` | 220 | 3/4 |
+| `infrastructure` | 130 | 1/2 |
+| `n8n` | 128 | 2/4 |
+| `quicklinks` | 83 | 2/3 |
+
+Cross-slice import counts (barrel discipline): `appshell` 23, `os-settings` 6,
+`os-shell` 5, `app-store` 4, `agent-group` 4, `extensions` 3, `channels` 3,
+`organization` 2, `auth` 2, `assistant` 2, `os-terminal` 1, `media-viewer` 1.
+Every slice except `infrastructure` already has an `index.ts` barrel — the strangler
+boundary is already written down.
+
+Architecture ratchets currently enforced (`architecture.boundaries.json`):
+`structuralCycles 0`, `crossDomainCycles 0`, `crossProtocolCycles 0`,
+`serverFrontendImports 0`, `filesOver500 0`, `filesOver220 43`, `cliEntrypointLines 220`,
+`installerCoreLines 450`. Any migration must keep these at equal-or-lower values.
+
+---
+
+## 1. Measurements (2026-10-28, commit `1c74603`)
+
+### 1.1 Build
+
+`mso build` runs three stages: isolated Next build → Playwright runtime → mandatory
+release E2E. Timed end to end with `/usr/bin/time -v`.
+
+| Metric | Value |
+|---|---|
+| **`mso build` total** | **322 s (5:22)**, peak RSS 2.31 GB |
+| ├ Next compile (Turbopack) | 8.6 s |
+| ├ `tsc --noEmit` | 16.2 s, 1.19 GB RSS |
+| └ E2E + bundle-budget verify | ~296 s (**92 %** of build) |
+| `tsc --noEmit` alone | 8.4 s wall, 1.19 GB RSS |
+| SvelteKit minimal baseline (`vite build`, same box) | **1.85 s**, 658 MB RSS |
+| SvelteKit minimal `bun install` (56 pkgs) | 1.88 s |
+
+Bundle budget gate output inside the build:
+
+```
+bundle initial: 882.0 KiB raw / 281.0 KiB gzip (18 files)
+bundle entry: 448.3 KiB raw / 151.5 KiB gzip (13 files)
+bundle css: 184.1 KiB raw / 30.0 KiB gzip (2 files)
+bundle fonts: 68.0 KiB raw / 68.1 KiB gzip (1 file)
+```
+
+`scripts/bundle-budget.json` currently allows `initial 307200 gzip`, `entry 163840`,
+`css 30720`, fonts `81920`. Actual initial is 281 KB against a 300 KB ceiling.
+
+**Conclusion: compilation is 2.7 % of build time. A Svelte rewrite cannot fix build
+time. The 5-minute build is the Playwright release gate.**
+
+### 1.2 Test
+
+| Runner | Result |
+|---|---|
+| `vitest run` (full) | 41.4 s wall, 5,583 pass / 0 fail, 858 workers, 567 MB RSS |
+| `vitest run lib/mcp` | 6.14 s wall, 20 files |
+| `bun test lib/mcp` | 5.99 s wall, **243 pass / 98 fail / 23 errors** |
+
+Vitest itself reports: 858 workers spawned at ~122 ms each, `isolate:false` would save
+~6.84 s (16 %). That is available today without any framework change.
+
+Bun's runner is ~1.1 s faster on the same 85-file subset and does not run the suite as
+written. Observed blockers: `vi.mock("server-only", …)`, jsdom environment, `localStorage`
+flag assumptions. Not a drop-in.
+
+`bun install` of this repo's own `package.json` **fails** outside the existing tree:
+
+```
+> Rebuilding because directory node_modules/node-pty/prebuilds/linux-x64 does not exist
+/usr/bin/bash: node-gyp: command not found
+error: install script from "node-pty" exited with 127
+```
+
+Install portability is currently npm/node-gyp-shaped. This blocks Bun as a stack choice.
+
+### 1.3 Client bundle
+
+Route `/[[...slug]]` is the entire shell, so its first-load set is the product's
+first-load set.
+
+| Metric | Value |
+|---|---|
+| First-load JS | 897 KB raw, 20 chunks |
+| Initial (eager shell budget) | 882 KB raw / **281 KB gzip** |
+| Entry chunk | 448 KB raw / 151.5 KB gzip |
+| CSS | 184 KB raw / 30 KB gzip |
+| Fonts | 68 KB |
+| All chunks shipped | 5.51 MB raw / **1.59 MB gzip** |
+| `react-dom` first-load chunk | **230 KB** |
+| Deferred (not first-load) | onnxruntime-web 2 × 380 KB, xterm 322 KB |
+
+Per-chunk first-load breakdown (largest first):
+
+```
+230 KB react-dom 2uq1r5nfrxpmw.js
+155 KB app code 17m6xheheb8d-.js
+ 71 KB app code 15vf0xb5yvhvg.js
+ 62 KB app code 0juouw7m1iugm.js
+ 61 KB app code 239mdbdf4esdv.js
+ 41 KB app code 2n5sb_sdwp_j_.js
+ 35 KB app code 0w53v9augwoup.js
+ 32 KB radix 2yrl7mnjm--25.js
+ 30 KB app code (×2)
+ 27 KB 25 KB 23 KB 14 KB 11 KB 8 KB 5 KB 5 KB 1 KB
+TOTAL 897 KB / 20 chunks
+```
+
+Route-level stats (`route-bundle-stats.json`, only 5 routes exist):
+
+| Route | First-load JS |
+|---|---|
+| `/[[...slug]]` | 897 KB |
+| `/login` | 810 KB |
+| `/oauth/authorize` | 497 KB |
+| `/install` | 476 KB |
+| `/_not-found` | 453 KB |
+
+`node_modules` is 1.2 GB (373 packages), of which `next` alone is 210 MB.
+
+### 1.4 Server runtime (live instance, `127.0.0.1:4005`)
+
+| Metric | Value |
+|---|---|
+| HTML TTFB (root) | 10–14 ms |
+| API TTFB (`/api/status`) | 4–8 ms |
+| API TTFB (`/api/v1/apps`, 401 path) | 5–7 ms |
+| Server RSS total | 284 MB (`next-server` 110 MB + `scripts/server.mjs` wrapper 174 MB) |
+| Boot network requests | 129 total, **2 API calls** (`/api/auth/me`, `/api/prefs`) |
+| Root HTML size | 20,765 B (desktop), 7,115 B (deep link) |
+| DOM nodes after hydration | 870 desktop / 1,165 mobile |
+
+Server RSS budget enforced in E2E is only "streaming growth < 128 MiB", not absolute.
+
+### 1.5 Perceived performance (Playwright, Slow 4G emulation + 4× CPU throttle)
+
+Measured with `PerformanceObserver` (`longtask`, `largest-contentful-paint`,
+`layout-shift`) injected via `addInitScript`, network shaped by CDP to
+150 ms RTT / 1.6 Mbps down / 750 kbps up (Lighthouse "Slow 4G"), CPU throttled 4×.
+Reproducible with `bun run perf:probe`.
+
+Two earlier numbers in this document were wrong and are corrected here:
+
+- The first pass used 200 kbps down (Slow **3G**). The 900 KB shell then needs ~37 s to
+ arrive, which measures the network, not the shell. Re-measured at Slow 4G.
+- The first pass reported TBT as the **raw sum of long-task durations**. TBT by
+ definition is the sum of `max(0, duration − 50 ms)` per long task. The corrected
+ number is roughly a third of the old one.
+
+| Metric | Desktop 1440×900 | Mobile 390×844 |
+|---|---|---|
+| FCP | 1,180 ms | 1,166 ms |
+| **LCP** | **3,222 ms** | **3,054 ms** |
+| **TBT** | **164 ms** | **132 ms** |
+| Long tasks | 4 | 4 |
+| Max single long task | 126 ms | 126 ms |
+| CLS | 0.001 | 0 |
+| DOM nodes after hydration | 870 | 1,165 |
+
+Values are the median of 3 runs against the synthetic `releaseFixture` (the path CI
+takes), with the first run of a session discarded as warm-up: a cold disk cache inflated
+TBT to 418 ms against 164 ms warm, a 2.5× error that would have failed the gate on every
+fresh runner. Observed spread across stable runs: desktop TBT 150–184 ms, mobile
+69–148 ms, LCP 2.98–3.22 s. Host load moves these by ±25 %, which is why the gate
+enforces a 2× blowup rather than an absolute cap.
+
+Same page, unthrottled local, cold cache:
+
+```
+desktop DCL 52 ms load 124 ms FCP 64 ms 20 JS files 285 KB JS 384 KB transfer
+mobile DCL 49 ms load 97 ms FCP 56 ms same
+```
+
+Warm cache (second visit):
+
+```
+TTFB 11 ms DCL 64 ms load 236 ms 75/77 resources from cache
+```
+
+Deep link `/files` cold: 1,816 ms wall, 7,115 B HTML — server renders per-route title +
+session, then the client shell takes over.
+
+Opening an app window inside the running shell at 4× CPU (`bun run perf:apps`, one cold
+context per app so the cost is attributable):
+
+```
+Image Editor window visible ~550-600 ms +8 chunks ~600 ms long task
+Video Editor ~450-470 ms +4 ~300 ms
+System Monitor ~230 ms +2 ~75 ms
+Terminal ~190 ms +3 ~60 ms
+```
+
+Image Editor and Video Editor each pull editor chunks and pay 300–600 ms of main-thread
+time — those two are the per-slice measurement that matters, and they are also the two
+places where a framework swap would show up first.
+
+**Conclusion: server and in-shell navigation are already good. The remaining
+user-visible cost is LCP ~3.1 s on throttled mobile; TBT is 164 ms desktop / 132 ms
+mobile, i.e. already at or near the 150 ms post-migration target, before any migration.**
+
+That last fact materially changes §3: the Svelte case can no longer be "TBT 443 → 150",
+because TBT is effectively there already. What is left to buy is **LCP**, and LCP on this
+shell is dominated by first paint (CSS + wallpaper art), not by the JS bundle.
+
+
+---
+
+## 2. What each piece of the proposed stack can and cannot deliver
+
+### 2.1 Svelte / SvelteKit
+
+Delivers:
+- ~180–230 KB gzip less first-load JS (`react-dom` 230 KB raw + Next router runtime).
+ Realistic post-migration initial: 281 KB gzip → **~90–110 KB gzip**.
+- Less main-thread work at startup. Measured attribution (`bun run perf:tasks`) puts
+ ~280 ms of ~355 ms total long-task self time on the `react-dom` chunk — so removing
+ it removes real work, but TBT is already 164 ms, which means most of that 280 ms
+ overlaps idle time rather than blocking interaction. Expect TBT to move from 164 ms
+ toward ~60–90 ms, not from 443 ms.
+- `next/server` 162 imports and 117 route handlers collapse to `+server.ts` functions.
+- One mental model (no RSC/hydration split). Faster `svelte-check` than full-repo `tsc`
+ (8.4 s today for 202 k LOC).
+- Smaller `node_modules`: `next` alone is 210 MB of the 1.2 GB.
+
+Does not deliver:
+- Build time (§1.1: compile is 2.7 % of the build).
+- Server RSS: SvelteKit SSR is still Node/Bun. It does not shrink the 110 MB process.
+- The LCP win that would matter most. LCP is 3.1 s and is set by first paint — CSS and
+ the wallpaper artwork — not by the JS bundle. A Svelte rewrite keeps both. Expect
+ maybe 200–400 ms, not 1 s.
+- Anything for `lib/`: 96 % of it is already portable, so rewriting it is pure cost.
+
+Costs:
+- 74,176 LOC of React components + 14,774 LOC of app layer re-expressed.
+- 11 Radix packages across 13 files → bits-ui / melt-ui. `@imgly/background-removal`
+ has no Svelte-native equivalent (keep it as a framework-agnostic island).
+ Phosphor has a Svelte build; Radix does not.
+- 858 test files: most touch React/Next APIs. Re-write, not port.
+- Three live instances must stay green. The real cost is maintaining two stacks during
+ the transition, not the coding.
+- `frontend/slices/appshell` (20,028 LOC, config-driven registry with `ReactNode` and
+ `ComponentType` in its public types) is the single hardest piece and cannot be a
+ "small first step".
+
+### 2.2 Bun (runtime)
+
+Delivers:
+- Faster install, `bun test` (marginal here: ~1.1 s on the measured subset).
+- Single-binary distribution eventually.
+- One less toolchain in scripts (roughly half of `scripts/*` already runs under Bun).
+
+Does not deliver today:
+- Next.js under Bun is not first-class. Bun only becomes relevant **after** Next is gone.
+- 482 files use `node:` builtins. `node:child_process` appears 43 times; process/pty
+ semantics is exactly where Bun diverges and exactly where `lib/orchestration` lives —
+ the most dangerous place to discover a difference.
+- `bun install` currently fails on `node-pty` postinstall (§1.2).
+
+### 2.3 Rust
+
+Justified only for: `proxy.ts` (354 LOC) plus its 3 test files — host→managed-app
+rewrite, CSRF depth-2, per-request CSP nonce, websocket upgrade detection.
+Also plausible: filesystem scanning, hashing in `lib/security`.
+
+Not justified as: a rewrite of 202 k LOC TS with 33 runtime dependencies (anthropic sdk,
+mcp, nakama parity, xterm, onnxruntime) across three live deployments. That is not a
+migration, it is a new product.
+
+If server RSS matters: `next-server` 110 MB → a Rust HTTP core could plausibly land near
+15–25 MB. That is a **hosting cost** win, not a **user speed** win. Do not sell it as UX.
+
+Never port `lib/orchestration` to Rust; `child_process`/pty semantics are the product's
+entire failure surface.
+
+---
+
+## 3. Decision gate — do this before any rewrite
+
+**The gate now fails on its own terms.** §1.5 measures TBT at 164 ms desktop / 132 ms
+mobile, against a post-migration target of 150 ms. Desktop is within 10 % of the number
+the Svelte rewrite was going to buy; mobile already beats it. The remaining user-visible
+cost is LCP 3.1 s, and LCP is set by first paint (CSS + wallpaper artwork), which a
+framework swap does not change.
+
+So the honest sequencing is: fix LCP cheaply first, then re-decide.
+
+Cheaper fixes, in the order the measurements say to do them:
+
+1. **Attack LCP, which is the real number.** 3.1 s to largest paint on Slow 4G with a
+ 1,168 ms FCP means ~2 s is spent after first paint on the element that ends up
+ largest — measured as an `IMG.shell-artwork` on mobile. Concretely: check whether the
+ wallpaper is fetched at full resolution for the viewport, whether it is in the
+ critical path of first paint, and whether a CSS gradient placeholder would let the
+ real art arrive after paint without being the LCP element. This is the single
+ highest-value piece of work available and it requires no migration.
+2. **Tighten the eager shell budget.** `scripts/bundle-budget.json` allows 300 KB gzip
+ initial; actual is 281 KB. The ceiling is not doing any work. Lower it to 250 KB and
+ fix what breaks. (Same for entry: 151.5 KB actual against a 160 KB ceiling.)
+3. **Attribute and shrink the 4 long tasks.** `bun run perf:tasks` already attributes
+ them: ~280 ms of 355 ms of self time is the `react-dom` chunk. Since TBT is only
+ 164 ms, that work mostly overlaps idle time — so the win here is smaller than the
+ raw attribution suggests. Do not spend a quarter on it after LCP is fixed.
+4. **Turn on vitest `isolate:false` where safe.** 6.84 s of the 41.4 s is worker startup.
+ Pure dev-loop win, zero user risk.
+
+Gate criteria to proceed past §3 — all three required:
+
+- LCP on Slow 4G + 4× CPU is still > 2.5 s after (1) and (2), **and**
+- a named slice proves Svelte parity in a real browser at equal-or-better LCP, **and**
+- build time is addressed separately (it is an E2E problem, not a framework problem).
+
+Note what is *not* in that list any more: TBT. Gating on it would be gating on a number
+the current build already meets.
+
+---
+
+## 4. Phased migration (only if §3 gate passes)
+
+Rule for every phase: **no user-visible UX change, no second login, no second cookie
+domain, no dropped deep link.** Rollback at every step is a config flip, not a revert.
+Every phase keeps the architecture ratchets in §0 at equal-or-lower values.
+
+### Phase 0 — Instrumentation (DONE, 2026-10-28)
+
+Shipped:
+
+| Command | Purpose | Gate |
+|---|---|---|
+| `bun run perf:probe` | Cold load, Slow 4G + 4× CPU, → `perf-report.json` | no |
+| `bun run perf:check` | Enforces `scripts/perf-budget.json` | **yes** |
+| `bun run perf:tasks` | CDP trace → long task → owning script | no |
+| `bun run perf:apps` | Per-app open latency, chunks, long tasks | no |
+
+Files: `scripts/perf-probe.mjs`, `scripts/check-perf.mjs`, `scripts/perf-longtasks.mjs`,
+`scripts/perf-app-open.mjs`, `scripts/lib/perf-report.mjs` (+ vitest),
+`scripts/perf-budget.json`, `scripts/perf-baseline.json`.
+
+Gate policy: bytes are already gated deterministically by `check-bundle.mjs` from build
+output, so the perf gate does **not** re-gate browser-measured bytes (they count deferred
+chunks and are noisy). It gates the 2× TBT blowup against the committed baseline, and
+fails on a *missing* TBT rather than passing it — a null measurement is an instrumentation
+failure, not a fast page.
+
+Phase 0 findings that changed the plan: §1.5 corrections (Slow 4G, not 200 kbps; TBT
+definition), and the resulting conclusion in §3 that TBT is already at target and LCP is
+the real number.
+
+Exit criteria met: numbers in §1.4/§1.5 reproducible with one command on any host, median
+of 3 runs committed as baseline.
+
+
+### Phase 1 — Bun for tooling only (2–4 days, zero product change)
+
+- Keep Next on Node. Keep vitest.
+- Move remaining `scripts/*.mjs` that are still npm/node-shaped to Bun where tests
+ already pass under Bun.
+- Fix the install portability blocker: `node-pty` prebuild or a Bun-compatible
+ postinstall. Until that is fixed, Bun is a dev convenience, not a stack choice.
+- Optional and independent: `isolate:false` for vitest.
+
+Exit criteria: `bun install` succeeds from a clean clone; all `scripts/*` green under
+Bun; `next` still on Node; build time unchanged or better.
+
+### Phase 2 — Framework-agnostic core (2–3 weeks, zero product change)
+
+The largest durable win and the cheapest real work, because 96 % of `lib/` needs nothing.
+
+- Formalize the boundary: `lib/` exports plain request/response types; nothing in `lib/`
+ may import `next/*`. Two files violate this today — remove them.
+- Convert the 117 `route.ts` handlers into thin adapters: one shared
+ `NextRequest → { request, ctx }` shim, all logic in `lib/`. Handlers become 3–5 lines.
+ (`NextResponse` 744 usages, `NextRequest` 122 — the shim is the whole job.)
+- Extract session/auth/CSP into a typed `HttpContext` module so the same code can serve
+ SvelteKit `+server.ts` later without edits.
+- Keep `proxy.ts` as-is; it is ported in Phase 6, not here.
+
+Exit criteria: zero `next/*` imports in `lib/`; every route handler ≤ 15 LOC; ratchets
+unchanged; full suite green.
+
+Value even if the migration dies here: the backend becomes portable and testable without
+a framework. Worth doing on its own.
+
+### Phase 3 — One low-risk slice as a Svelte island (3–4 weeks)
+
+Pick from the bottom of the risk table in §0. `quicklinks` (83 LOC) is too small to prove
+anything; `n8n` (128 LOC, 2/4 appshell imports, separate surface and embed) is the
+right first target, with `infrastructure` (130 LOC) as second.
+
+Method (strangler, no shell rewrite):
+- Build the Svelte component as a static island bundle (Vite lib mode), mount it inside
+ the existing React shell at exactly one route.
+- The React shell keeps ownership of window chrome, auth, cookies, deep links.
+- Ship behind the existing URL. No new origin, no new host header.
+- Gate on Phase 0 metrics: the island must not regress shell TBT or first-load bytes.
+- Rollback: remove one mount point.
+
+Exit criteria: the slice live for real users for 2 weeks, zero rollback, metrics equal or
+better.
+
+**If one island is not clearly better after 2 weeks, stop the migration here** and keep
+the Phase 2 portable core. That is a good outcome, not a failure.
+
+### Phase 4 — Slice by slice (ongoing, ~1 slice / 2–3 weeks)
+
+- Order by the §0 risk table, cheapest independent slices first.
+- `os-settings` (8,915 LOC, `"use client"` in 76/78 files, zero appshell imports) is the
+ real test: pure UI, heavy Radix, no data logic.
+- One slice at a time, each behind a flag, each measured, each reversible.
+- Freeze new React slice work only when > 50 % of `frontend/slices` bytes are Svelte.
+
+Exit criteria: > 60 % of slice bytes are Svelte, `appshell` is the only large React
+surface left, and no slice has regressed its Phase 0 baseline.
+
+### Phase 5 — Shell swap (the only irreversible-feeling step)
+
+- Only after Phase 4 exit criteria.
+- SvelteKit takes over routing. The 4 pages + 1 layout are trivial; `appshell`
+ (20,028 LOC, registry with `SlotRegion`, `FeatureDescriptor`, `ShellManifest`) is the work.
+- Run both shells in parallel behind a host-level flag for at least one release cycle.
+- Rollback = flip the flag back to the Next image. No database change, no cookie change.
+
+Exit criteria: one full release cycle on SvelteKit with per-instance health green,
+`proxy.ts` still in front (host rewrite, CSP, CSRF unchanged), and TBT measured at the
+§3 target.
+
+### Phase 6 — Rust sidecar (optional, independent of Phases 1–5)
+
+- Port `proxy.ts` only (354 LOC + 3 test files). Measure with the Phase 0 harness.
+- Prerequisite: prove proxy is a measurable share of CPU or TBT. It is not today
+ (server TTFB 4–14 ms).
+- Deliver as a sidecar/subprocess first, not a replacement — the CSP nonce path must stay
+ byte-identical or the XSS containment layer breaks.
+- Never port `lib/orchestration`.
+
+### Rust HTTP core (speculative, separate decision)
+
+Only if the 110 MB `next-server` RSS becomes a real hosting cost across three instances.
+Then the Rust core serves Phase 2's portable handlers and SvelteKit becomes static assets
+plus thin SSR. Do not attempt before Phase 2 lands.
+
+---
+
+## 5. Cost summary
+
+| Path | Engineering | Risk to live users | Measured upside |
+|---|---|---|---|
+| Phase 0 (done) | 1 day | none | makes everything else falsifiable |
+| **LCP fix (§3 item 1), no migration** | **2–5 days** | low | **the actual user-visible win** |
+| + Phase 1 (Bun tooling) | +2–4 days | none | dev velocity; `bun install` portability |
+| + Phase 2 (portable core) | +2–3 weeks | none | maintainability, framework freedom |
+| + Phase 3 (one island) | +3–4 weeks | low, flag-gated | proves or disproves the whole thesis |
+| Full Svelte (all phases) | **6–9 months solo** | medium | initial JS −60 %, TBT 164 → ~70–95 ms |
+| Rust rewrite of shell + server | **> 1 year** | high | nothing user-visible |
+
+The single honest sentence: **TBT is already at the post-migration target; the number
+still worth fixing is LCP, it is a few days of work, and it needs no migration at all.**
+
+After the LCP fix, Phases 1–2 are still worth doing on their own merits (maintainability,
+`bun install` portability, a framework-free backend). Phase 3 remains the honest test of
+the Svelte thesis, but its expected payoff has shrunk from "TBT −70 %" to "bundle bytes
+−60 % with TBT already fine", which is a maintenance argument, not a speed argument.
+
+
+---
+
+## 6. How to reproduce these numbers
+
+Perceived performance (steps 4 and 6 below) is now committed as Phase 0 scripts. The
+rest are one-shot commands, kept here because the migration doc must be auditable, not
+because they should be automated.
+
+Perceived performance and per-app cost:
+
+```
+bun run perf:probe --base=http://127.0.0.1:4005 # table to stderr
+node scripts/perf-probe.mjs --json > /tmp/perf.json # machine-readable
+bun run perf:check --report=/tmp/perf.json # enforce budget
+bun run perf:tasks --base=http://127.0.0.1:4005 --min-ms=40
+bun run perf:apps --base=http://127.0.0.1:4005
+```
+
+Without `--base=` each script starts its own synthetic `releaseFixture()`, so the gate is
+runnable on a machine with no live instance.
+
+Everything else:
+
+1. `mso build` under `/usr/bin/time -v` (refuses to build in-place while the live runtime
+ owns the checkout; it builds out of tree, so run it from outside the repo).
+ → total wall time and peak RSS in §1.1.
+2. `npx tsc --noEmit`, `npx vitest run`, `npx vitest run lib/mcp`, `bun test lib/mcp`.
+3. `.next/diagnostics/route-bundle-stats.json` + `scripts/check-bundle.mjs --report-only`
+ for the bundle table.
+4. `curl -w` against `/`, `/api/status`, `/api/v1/apps` for TTFB.
+5. `ps -eo rss` over the `next-server` + `scripts/server.mjs` processes for RSS.
+
+Measurement pitfalls found while building Phase 0, kept because each one produced a
+wrong number first:
+
+- 200 kbps is Slow **3G**; the shell then takes ~37 s to arrive and you measure the
+ network. Lighthouse Slow 4G is 1.6 Mbps down / 750 kbps up / 150 ms RTT.
+- `#main-content` exists in the server-rendered skeleton, so waiting for it measures an
+ 82-node pre-hydration frame. Wait for `#main-content[data-shell]`.
+- `data-shell` is `macos` on desktop and `ios` on mobile; a hardcoded value hangs the
+ mobile run.
+- LCP arrives ~3 s in. A "settle when nothing changes for 1 s" loop exits too early and
+ reports `lcpMs: null`.
+- TBT is `Σ max(0, duration − 50)`, not the raw sum of long-task durations.
diff --git a/docs/README.md b/docs/README.md
index cbf7f151..efea6bc3 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -119,6 +119,7 @@ source comments. They are **not current implementation contracts**.
| [`SHELL-FIDELITY-PLAN.md`](./SHELL-FIDELITY-PLAN.md) | Historical design backlog/baseline; current shell design lives in code + architecture |
| [`DRAWER-MENU-BYOK-PLAN.md`](./DRAWER-MENU-BYOK-PLAN.md) | Historical implementation plan; phases A–C and OpenAI Codex D1 shipped; remaining ideas are not promises |
| [`OS-SETTINGS-ICON-UPDATE-DEVICE-PLAN.md`](./OS-SETTINGS-ICON-UPDATE-DEVICE-PLAN.md) | **Open plan, not implemented**: auto-update opt-in, stable channel, Devices/Server merge, account icon picker, upload→WebP/ICO pipeline |
+| [`MSO-MIGRATION.md`](./MSO-MIGRATION.md) | **Open plan, not implemented**: measured baseline plus phased Next→Svelte/Bun/Rust migration with a decision gate before any rewrite |
## Marketing/demo collateral
diff --git a/package.json b/package.json
index ae3c05e0..6d9420e5 100644
--- a/package.json
+++ b/package.json
@@ -54,6 +54,10 @@
"e2e:release": "node scripts/e2e/release.mjs",
"bundle:report": "node scripts/check-bundle.mjs --report-only",
"bundle:check": "node scripts/check-bundle.mjs",
+ "perf:probe": "node scripts/perf-probe.mjs",
+ "perf:check": "node scripts/check-perf.mjs",
+ "perf:apps": "node scripts/perf-app-open.mjs",
+ "perf:tasks": "node scripts/perf-longtasks.mjs",
"ci:plan": "node scripts/ci/run.mjs --plan",
"ci:verify": "node scripts/ci/run.mjs --profile verify",
"ci:security": "node scripts/ci/run.mjs --profile security",
diff --git a/scripts/check-perf.mjs b/scripts/check-perf.mjs
new file mode 100644
index 00000000..05daf829
--- /dev/null
+++ b/scripts/check-perf.mjs
@@ -0,0 +1,89 @@
+#!/usr/bin/env node
+// Perf gate. Companion to check-bundle.mjs: that one reads build output from disk and
+// is deterministic; this one needs a browser and is therefore advisory on timing.
+//
+// Why the split: bytes decide whether a regression shipped, timings decide whether
+// anyone notices. Gating hard on wall-clock numbers on a box that also serves
+// production produces flakes that get muted, and a muted gate is worse than none.
+// So: bytes fail the run, timings only fail on a 2x blowup against the committed
+// baseline, and targets are printed but never enforced.
+import fs from "node:fs";
+import path from "node:path";
+import { spawnSync } from "node:child_process";
+import { parseArgs } from "node:util";
+import { parsePerfReport, summarize, perfViolations, formatTable } from "./lib/perf-report.mjs";
+
+const ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..");
+
+function readJson(file, label) {
+ try {
+ return JSON.parse(fs.readFileSync(file, "utf8"));
+ } catch (error) {
+ throw new Error(`cannot read ${label} at ${file}: ${error instanceof Error ? error.message : String(error)}`);
+ }
+}
+
+function measure() {
+ const result = spawnSync(process.execPath, [path.join(ROOT, "scripts/perf-probe.mjs"), "--json"], {
+ cwd: ROOT, encoding: "utf8", maxBuffer: 16 * 1024 * 1024,
+ });
+ if (result.status !== 0) {
+ throw new Error(`perf probe failed (exit ${result.status}): ${(result.stderr || "").trim()}`);
+ }
+ return result.stdout;
+}
+
+try {
+ const { values } = parseArgs({
+ options: {
+ report: { type: "string" },
+ "report-only": { type: "boolean", default: false },
+ json: { type: "boolean", default: false },
+ },
+ strict: true,
+ allowPositionals: false,
+ });
+
+ const budget = readJson(path.join(ROOT, "scripts/perf-budget.json"), "perf budget");
+ // A missing baseline is not an error: the first run after a deliberate reset has
+ // nothing to compare against, and inventing a zero baseline would fail every run.
+ let baseline = null;
+ try {
+ baseline = JSON.parse(fs.readFileSync(path.join(ROOT, "scripts/perf-baseline.json"), "utf8"));
+ } catch (error) {
+ if (error?.code !== "ENOENT") throw error;
+ }
+
+ const report = parsePerfReport(values.report ? fs.readFileSync(values.report, "utf8") : measure());
+
+ if (values.json) {
+ console.log(JSON.stringify({ budget, baseline, report, summary: summarize(report) }, null, 2));
+ } else {
+ console.log(formatTable(report));
+ const targets = budget.targets ?? {};
+ for (const run of summarize(report)) {
+ const misses = [];
+ if (Number.isFinite(targets.tbtMs) && Number.isFinite(run.tbtMs) && run.tbtMs > targets.tbtMs) misses.push(`tbt ${run.tbtMs}ms > ${targets.tbtMs}ms`);
+ if (Number.isFinite(targets.lcpMs) && Number.isFinite(run.lcpMs) && run.lcpMs > targets.lcpMs) misses.push(`lcp ${run.lcpMs}ms > ${targets.lcpMs}ms`);
+ // Reported, never enforced: the target is the post-migration goal in
+ // docs/MSO-MIGRATION.md §3, and holding today's Next build to it would just
+ // make the gate permanently red and therefore ignored.
+ if (misses.length) console.log(`perf ${run.label}: above target — ${misses.join(", ")} (advisory)`);
+ }
+ }
+
+ if (values["report-only"]) {
+ console.log("perf: report only, budget not enforced.");
+ } else {
+ const failures = perfViolations(report, budget, baseline);
+ if (failures.length) {
+ for (const failure of failures) console.error(`perf: ${failure}`);
+ process.exitCode = 1;
+ } else {
+ console.log("perf: within budget.");
+ }
+ }
+} catch (error) {
+ console.error(`perf: ${error instanceof Error ? error.message : String(error)}`);
+ process.exitCode = 1;
+}
diff --git a/scripts/lib/browser-metrics.mjs b/scripts/lib/browser-metrics.mjs
new file mode 100644
index 00000000..ecebdc66
--- /dev/null
+++ b/scripts/lib/browser-metrics.mjs
@@ -0,0 +1,72 @@
+// Browser-side measurement primitives shared by perf-probe and perf-app-open.
+// Kept out of the CLI files so the "what counts as a measurement" decisions live in one
+// place: the same TBT formula, the same shell-ready selector, the same throttle profile.
+//
+// Two traps this file exists to prevent:
+// `#main-content` exists in the server-rendered skeleton, so it is not "the shell".
+// `data-shell` is set on mount, and its value differs per surface (macos vs ios).
+
+export const SHELL_READY = "#main-content[data-shell]";
+
+// Lighthouse "Slow 4G": 150 ms RTT, 1.6 Mbps down, 750 kbps up. CDP takes bytes/second.
+// 200 kbps is Slow 3G — at that rate the ~900 KB shell needs ~37 s to arrive and the
+// measurement becomes a network benchmark instead of a shell benchmark.
+export const SLOW_4G = { latency: 150, downloadThroughput: 204800, uploadThroughput: 93750 };
+
+// Runs in the page before any document script. Collected here so every entry point
+// observes the same entry types with the same buffering.
+export function installPerfObservers() {
+ localStorage.setItem("sv:shell", JSON.stringify({ desktop: "macos", mobile: "ios" }));
+ localStorage.setItem("mso:onboarding:v1", "done");
+
+ window.__perfLongTasks = [];
+ window.__perfLCP = null;
+ window.__perfCLS = 0;
+ window.__perfResetLongTasks = () => {
+ window.__perfLongTasks = [];
+ };
+
+ try {
+ new PerformanceObserver((list) => {
+ for (const entry of list.getEntries()) window.__perfLongTasks.push({ duration: entry.duration, startTime: entry.startTime });
+ }).observe({ type: "longtask", buffered: true });
+ } catch {}
+
+ try {
+ new PerformanceObserver((list) => {
+ const last = list.getEntries().pop();
+ if (last) window.__perfLCP = last.renderTime || last.loadTime || last.startTime;
+ }).observe({ type: "largest-contentful-paint", buffered: true });
+ } catch {}
+
+ try {
+ new PerformanceObserver((list) => {
+ for (const entry of list.getEntries()) if (!entry.hadRecentInput) window.__perfCLS += entry.value;
+ }).observe({ type: "layout-shift", buffered: true });
+ } catch {}
+}
+
+// Evaluated in the page. Same definitions the gate reports, so a number taken by hand
+// with the devtools console matches the number in the report.
+export function readPerfMetrics() {
+ const paint = performance.getEntriesByType("paint").find((e) => e.name === "first-contentful-paint");
+ const longTasks = window.__perfLongTasks ?? [];
+ const resources = performance.getEntriesByType("resource");
+ const js = resources.filter((e) => e.name.includes("/_next/static/") && new URL(e.name).pathname.endsWith(".js"));
+
+ return {
+ fcpMs: paint ? Math.round(paint.startTime) : null,
+ lcpMs: window.__perfLCP == null ? null : Math.round(window.__perfLCP),
+ // TBT clamps each task at 50 ms. Summing raw durations is a different, much larger
+ // number and is not TBT — that mistake produced the retracted figures in
+ // docs/MSO-MIGRATION.md §1.5.
+ tbtMs: Math.round(longTasks.reduce((sum, task) => sum + Math.max(0, task.duration - 50), 0)),
+ cls: Number((window.__perfCLS ?? 0).toFixed(4)),
+ longTasks: longTasks.length,
+ maxLongTaskMs: Math.round(longTasks.reduce((max, task) => Math.max(max, task.duration), 0)),
+ firstLoadJsBytes: js.reduce((sum, r) => sum + r.decodedBodySize, 0),
+ firstLoadJsFiles: js.length,
+ transferBytes: resources.reduce((sum, r) => sum + (r.encodedBodySize || 0), 0),
+ domNodes: document.querySelectorAll("*").length,
+ };
+}
diff --git a/scripts/lib/perf-report.d.ts b/scripts/lib/perf-report.d.ts
new file mode 100644
index 00000000..b28ef638
--- /dev/null
+++ b/scripts/lib/perf-report.d.ts
@@ -0,0 +1,56 @@
+// Types for perf-report.mjs. Kept in a .d.ts so the implementation stays under the
+// repo's 220-line ratchet and the shapes are visible to the TypeScript side (allowJs).
+//
+// `tbtMs` is nullable on purpose: null means "the probe did not observe one", which the
+// gate treats as a violation when a baseline exists. It must never be coerced to 0.
+
+export type PerfRun = {
+ label: string;
+ viewport?: { width: number; height: number };
+ fcpMs: number | null;
+ lcpMs: number | null;
+ tbtMs: number | null;
+ cls: number | null;
+ longTasks?: number;
+ maxLongTaskMs: number | null;
+ firstLoadJsBytes: number | null;
+ firstLoadJsFiles?: number;
+ transferBytes?: number;
+ domNodes?: number;
+};
+
+export type PerfReport = {
+ schemaVersion: number;
+ createdAt?: string;
+ commit?: string | null;
+ host?: { platform: string; cpus: number; node: string; totalMemMb: number };
+ profile?: { name: string; latencyMs: number; downlinkKbps: number; uplinkKbps: number; cpuRate: number };
+ runs: PerfRun[];
+};
+
+export type PerfSummary = {
+ label: string;
+ fcpMs: number | null;
+ lcpMs: number | null;
+ tbtMs: number | null;
+ cls: number | null;
+ firstLoadJsBytes: number | null;
+ maxLongTaskMs: number | null;
+};
+
+export type PerfBudget = {
+ schemaVersion?: number;
+ note?: string;
+ enforce: { firstLoadJsBytes?: Record<string, number>; tbtMsBlowupFactor?: number };
+ targets?: { initialGzipBytes?: number; tbtMs?: number; lcpMs?: number };
+ targetsEnforced?: boolean;
+};
+
+export function parsePerfReport(json: unknown): PerfReport;
+export function summarize(report: PerfReport | { runs?: Array<Record<string, unknown>> } | string): PerfSummary[];
+export function perfViolations(
+ report: PerfReport | { runs?: Array<Record<string, unknown>> } | string,
+ budget: PerfBudget | null | undefined,
+ baseline?: PerfReport | { runs?: Array<Record<string, unknown>> } | Record<string, unknown> | null,
+): string[];
+export function formatTable(report: PerfReport | { runs?: Array<Record<string, unknown>> } | string): string;
diff --git a/scripts/lib/perf-report.fixtures.ts b/scripts/lib/perf-report.fixtures.ts
new file mode 100644
index 00000000..464b79fd
--- /dev/null
+++ b/scripts/lib/perf-report.fixtures.ts
@@ -0,0 +1,57 @@
+// Shared fixtures for the perf-report tests. Kept out of the test files so each test file
+// stays under the repo's 220-physical-line ratchet, and so the sample numbers exist once.
+//
+// The numbers mirror scripts/perf-baseline.json (Slow 4G, 4x CPU, median of 3 runs at
+// commit 1c74603). They are deliberately realistic: a fixture with a 0 tbt would let a
+// broken TBT formula pass.
+
+export const validRunDesktop = {
+ label: "desktop",
+ viewport: { width: 1440, height: 900 },
+ fcpMs: 1168,
+ lcpMs: 3168,
+ tbtMs: 146,
+ cls: 0.001,
+ longTasks: 4,
+ maxLongTaskMs: 126,
+ firstLoadJsBytes: 964362,
+ firstLoadJsFiles: 20,
+ transferBytes: 393216,
+ domNodes: 870,
+};
+
+export const validRunMobile = {
+ label: "mobile",
+ viewport: { width: 390, height: 844 },
+ fcpMs: 1156,
+ lcpMs: 3096,
+ tbtMs: 142,
+ cls: 0,
+ longTasks: 4,
+ maxLongTaskMs: 126,
+ firstLoadJsBytes: 947790,
+ firstLoadJsFiles: 20,
+ transferBytes: 350000,
+ domNodes: 1165,
+};
+
+export const validReport = {
+ schemaVersion: 1,
+ createdAt: "2026-10-28T15:04:05.000Z",
+ commit: "1c74603",
+ runs: [validRunDesktop, validRunMobile],
+};
+
+export const sampleBudget = {
+ schemaVersion: 1,
+ enforce: { tbtMsBlowupFactor: 2.0 },
+ targets: { initialGzipBytes: 256000, tbtMs: 150, lcpMs: 2500 },
+ targetsEnforced: false,
+};
+
+export const sampleBaseline = {
+ runs: [
+ { label: "desktop", tbtMs: 146 },
+ { label: "mobile", tbtMs: 142 },
+ ],
+};
diff --git a/scripts/lib/perf-report.gate.test.ts b/scripts/lib/perf-report.gate.test.ts
new file mode 100644
index 00000000..3369a6ec
--- /dev/null
+++ b/scripts/lib/perf-report.gate.test.ts
@@ -0,0 +1,85 @@
+import { describe, expect, it } from "vitest";
+import { formatTable, perfViolations } from "./perf-report.mjs";
+import { sampleBaseline, sampleBudget, validReport, validRunDesktop, validRunMobile } from "./perf-report.fixtures";
+
+const run = (overrides: Record<string, unknown>) => ({ ...validRunDesktop, ...overrides });
+
+describe("perfViolations", () => {
+ it("passes a report that matches its baseline", () => {
+ expect(perfViolations(validReport, sampleBudget, sampleBaseline)).toEqual([]);
+ });
+
+ it("fails on a tbt blowup past the factor, naming the run and both numbers", () => {
+ const violations = perfViolations({ runs: [run({ tbtMs: 850 }), validRunMobile] }, sampleBudget, sampleBaseline);
+ expect(violations).toContain("desktop: tbtMs 850ms > 2x baseline 146ms");
+ });
+
+ it("does not fail a run whose tbt is inside the factor", () => {
+ const violations = perfViolations({ runs: [run({ tbtMs: 280 }), validRunMobile] }, sampleBudget, sampleBaseline);
+ expect(violations).toEqual([]);
+ });
+
+ it("skips the tbt check entirely when no baseline exists", () => {
+ // First run after a deliberate reset has nothing to compare against. Inventing a
+ // zero baseline would fail every run, so absence means skip.
+ const slow = { runs: [run({ tbtMs: 5000 }), validRunMobile] };
+ expect(perfViolations(slow, sampleBudget, null)).toEqual([]);
+ expect(perfViolations(slow, sampleBudget, undefined)).toEqual([]);
+ });
+
+ it("treats a null tbt as a violation when a baseline exists", () => {
+ // A painted shell with no attributable long task means the probe broke, not that the
+ // page got fast. Passing this is how a perf gate silently stops gating.
+ const violations = perfViolations({ runs: [run({ tbtMs: null }), validRunMobile] }, sampleBudget, sampleBaseline);
+ expect(violations).toContain("desktop: missing tbtMs measurement");
+ expect(violations.some((v) => v.startsWith("mobile:"))).toBe(false);
+ });
+
+ it("fails a missing tbt for a label present in the baseline", () => {
+ const { tbtMs: _drop, ...withoutTbt } = validRunDesktop;
+ expect(() => perfViolations({ runs: [withoutTbt] }, sampleBudget, sampleBaseline)).not.toThrow();
+ });
+
+ it("never turns an advisory target miss into a violation", () => {
+ // Both runs blow past the tbtMs 150 target and sit exactly on their baseline; the
+ // target exists to describe the post-migration goal, not to fail today's build.
+ const atBaseline = { runs: [run({ tbtMs: 146, lcpMs: 9000 }), validRunMobile] };
+ expect(perfViolations(atBaseline, sampleBudget, sampleBaseline)).toEqual([]);
+ });
+
+ it("fails on a first-load byte cap even when timings are fine", () => {
+ const budget = { ...sampleBudget, enforce: { ...sampleBudget.enforce, firstLoadJsBytes: { desktop: 900000 } } };
+ expect(perfViolations({ runs: [run({}), validRunMobile] }, budget, sampleBaseline))
+ .toContain(`desktop: firstLoadJsBytes 964362 > 900000`);
+ });
+
+ it("fails on a non-finite byte measurement rather than scoring it as zero", () => {
+ const budget = { ...sampleBudget, enforce: { ...sampleBudget.enforce, firstLoadJsBytes: { desktop: 900000 } } };
+ const violations = perfViolations({ runs: [run({ firstLoadJsBytes: Number.NaN })] }, budget, sampleBaseline);
+ expect(violations).toContain("desktop: missing measurement");
+ });
+});
+
+describe("formatTable", () => {
+ it("aligns columns to the widest cell and keeps every run on its own line", () => {
+ const text = formatTable(validReport);
+ const lines = text.split("\n");
+ expect(lines).toHaveLength(3);
+ expect(lines[0]).toMatch(/^label\s+fcp\s+lcp\s+tbt\s+cls\s+maxTask\s+jsKB$/);
+ expect(lines[1]).toContain("desktop");
+ expect(lines[2]).toContain("mobile");
+ // Every data line ends with the byte count converted to KB.
+ expect(lines[1].trim().endsWith("941.8KB")).toBe(true);
+ expect(lines[2].trim().endsWith("925.6KB")).toBe(true);
+ });
+
+ it("renders a null metric as n/a instead of 0", () => {
+ const text = formatTable({ runs: [run({ lcpMs: null })] });
+ expect(text).toContain("n/a");
+ expect(text).not.toMatch(/\s0ms/);
+ });
+
+ it("returns an empty string for a report with no runs", () => {
+ expect(formatTable({ runs: [] })).toBe("");
+ });
+});
diff --git a/scripts/lib/perf-report.mjs b/scripts/lib/perf-report.mjs
new file mode 100644
index 00000000..43642c98
--- /dev/null
+++ b/scripts/lib/perf-report.mjs
@@ -0,0 +1,206 @@
+// ESM only. Pure functions for parsing, summarizing, checking, and formatting perf reports.
+// Shapes live in perf-report.d.ts; this file stays implementation-only.
+
+
+const REQUIRED_TIMING_FIELDS = [
+ "fcpMs",
+ "lcpMs",
+ "tbtMs",
+ "cls",
+ "maxLongTaskMs",
+ "firstLoadJsBytes",
+];
+
+/**
+ * Validates and parses a performance report JSON or object.
+ * Requires schemaVersion === 1, non-empty runs array, and every run to have
+ * a valid string label and numeric-or-null timing fields.
+ * Fails closed on missing fields instead of silently coercing to zero.
+ *
+ * @param {unknown} json - Raw JSON string or parsed object
+ * @returns {PerfReport} Validated report object
+ */
+export function parsePerfReport(json) {
+ let report = json;
+ if (typeof json === "string") {
+ try {
+ report = JSON.parse(json);
+ } catch (err) {
+ throw new Error(`Invalid JSON for perf report: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ }
+
+ if (!report || typeof report !== "object" || Array.isArray(report)) {
+ throw new Error("Report must be a non-null object");
+ }
+
+ if (report.schemaVersion !== 1) {
+ throw new Error(`Invalid or missing schemaVersion: expected 1, received ${report.schemaVersion}`);
+ }
+
+ if (!Array.isArray(report.runs) || report.runs.length === 0) {
+ throw new Error("Report missing valid runs: expected non-empty array");
+ }
+
+ for (let index = 0; index < report.runs.length; index++) {
+ const run = report.runs[index];
+ if (!run || typeof run !== "object" || Array.isArray(run)) {
+ throw new Error(`Run at index ${index} must be a non-null object`);
+ }
+
+ if (!("label" in run) || typeof run.label !== "string" || !run.label.trim()) {
+ throw new Error(`Run at index ${index} missing valid string label`);
+ }
+
+ for (const field of REQUIRED_TIMING_FIELDS) {
+ if (!(field in run) || run[field] === undefined) {
+ throw new Error(`Run "${run.label}" missing required field: ${field}`);
+ }
+ const val = run[field];
+ if (val !== null && (typeof val !== "number" || !Number.isFinite(val))) {
+ throw new Error(`Run "${run.label}" field "${field}" must be a finite number or null`);
+ }
+ }
+ }
+
+ return report;
+}
+
+/**
+ * Returns a compact summary projection of all runs in the report.
+ *
+ * @param {{ runs?: Array<Record<string, unknown>> }|string} report - The performance report
+ * @returns {PerfSummary[]}
+ */
+export function summarize(report) {
+ const data = typeof report === "string" ? JSON.parse(report) : report;
+ if (!data?.runs || !Array.isArray(data.runs)) {
+ return [];
+ }
+ return data.runs.map((run) => ({
+ label: run.label,
+ fcpMs: run.fcpMs,
+ lcpMs: run.lcpMs,
+ tbtMs: run.tbtMs,
+ cls: run.cls,
+ firstLoadJsBytes: run.firstLoadJsBytes,
+ maxLongTaskMs: run.maxLongTaskMs,
+ }));
+}
+
+/**
+ * Helper to resolve baseline tbtMs for a run label.
+ * Supports map keyed by label { [label]: { tbtMs } } or { [label]: number },
+ * as well as report shape { runs: [{ label, tbtMs }] }.
+ */
+function getBaselineTbt(baseline, label) {
+ if (!baseline || typeof baseline !== "object") return null;
+ const direct = baseline[label];
+ if (typeof direct === "number" && Number.isFinite(direct)) {
+ return direct;
+ }
+ if (direct && typeof direct.tbtMs === "number" && Number.isFinite(direct.tbtMs)) {
+ return direct.tbtMs;
+ }
+ if (Array.isArray(baseline.runs)) {
+ const run = baseline.runs.find((r) => r?.label === label);
+ if (run && typeof run.tbtMs === "number" && Number.isFinite(run.tbtMs)) {
+ return run.tbtMs;
+ }
+ }
+ return null;
+}
+
+/**
+ * Evaluates performance violations against budget and optional baseline.
+ *
+ * Note: Contract text in Phase 0 specifies two arguments (report, budget), but
+ * baseline is accepted as the third argument to keep the function pure and
+ * dependency-free as specified in the contract ownership rules.
+ *
+ * @param {{ runs?: Array<Record<string, unknown>> }|string} report - The performance report (partial reports are valid input: the point is to report what is missing)
+ * @param {any} budget - The performance budget
+ * @param {any|null} [baseline] - Optional baseline measurements
+ * @returns {string[]} List of human-readable violation messages
+ */
+export function perfViolations(report, budget, baseline = null) {
+ const failures = [];
+ const data = typeof report === "string" ? JSON.parse(report) : report;
+ const runs = Array.isArray(data?.runs) ? data.runs : [];
+ const runByLabel = new Map(runs.map((r) => [r?.label, r]));
+
+ // 1. Enforce firstLoadJsBytes caps per label
+ const enforcedBytes = budget?.enforce?.firstLoadJsBytes;
+ if (enforcedBytes && typeof enforcedBytes === "object") {
+ for (const [label, cap] of Object.entries(enforcedBytes)) {
+ const run = runByLabel.get(label);
+ const actual = run?.firstLoadJsBytes;
+ if (actual === null || actual === undefined || !Number.isFinite(actual)) {
+ failures.push(`${label}: missing measurement`);
+ } else if (Number.isFinite(cap) && actual > cap) {
+ failures.push(`${label}: firstLoadJsBytes ${actual} > ${cap}`);
+ }
+ }
+ }
+
+ // 2. Enforce TBT blowup factor against baseline
+ // Baseline absent or null skips the check entirely (no baseline is not a violation).
+ const blowupFactor = budget?.enforce?.tbtMsBlowupFactor;
+ if (baseline && blowupFactor !== null && blowupFactor !== undefined && Number.isFinite(blowupFactor)) {
+ for (const run of runs) {
+ if (!run?.label) continue;
+ const baseTbt = getBaselineTbt(baseline, run.label);
+ if (baseTbt !== null && Number.isFinite(baseTbt)) {
+ if (run.tbtMs === null || run.tbtMs === undefined || !Number.isFinite(run.tbtMs)) {
+ // A null tbtMs means the probe never attributed a long task, which on a
+ // shell that has already painted is a measurement bug, not a fast page.
+ // Passing it would turn the gate off precisely when instrumentation
+ // breaks, so it is a violation rather than a skip.
+ failures.push(`${run.label}: missing tbtMs measurement`);
+ } else if (run.tbtMs > baseTbt * blowupFactor) {
+ failures.push(`${run.label}: tbtMs ${run.tbtMs}ms > ${blowupFactor}x baseline ${baseTbt}ms`);
+ }
+ }
+ }
+ }
+
+ // Targets (budget.targets) are advisory and never produce violations
+ return failures;
+}
+
+/**
+ * Formats report runs into a table with stable fixed-width aligned columns.
+ * Produces pure string output without ANSI color escapes.
+ *
+ * @param {{ runs?: Array<Record<string, unknown>> }|string} report - The performance report
+ * @returns {string} Fixed-width aligned table text
+ */
+export function formatTable(report) {
+ const data = typeof report === "string" ? JSON.parse(report) : report;
+ const runs = Array.isArray(data?.runs) ? data.runs : [];
+ if (runs.length === 0) return "";
+
+ const headers = ["label", "fcp", "lcp", "tbt", "cls", "maxTask", "jsKB"];
+ const rows = runs.map((run) => [
+ String(run.label ?? "n/a"),
+ run.fcpMs != null ? `${run.fcpMs}ms` : "n/a",
+ run.lcpMs != null ? `${run.lcpMs}ms` : "n/a",
+ run.tbtMs != null ? `${run.tbtMs}ms` : "n/a",
+ typeof run.cls === "number" ? run.cls.toFixed(3) : "n/a",
+ run.maxLongTaskMs != null ? `${run.maxLongTaskMs}ms` : "n/a",
+ run.firstLoadJsBytes != null ? `${(run.firstLoadJsBytes / 1024).toFixed(1)}KB` : "n/a",
+ ]);
+
+ const allRows = [headers, ...rows];
+ const colWidths = headers.map((_, colIdx) =>
+ Math.max(...allRows.map((row) => row[colIdx].length))
+ );
+
+ return allRows
+ .map((row) =>
+ row
+ .map((cell, colIdx) => (colIdx === row.length - 1 ? cell : cell.padEnd(colWidths[colIdx])))
+ .join(" ")
+ )
+ .join("\n");
+}
diff --git a/scripts/lib/perf-report.parse.test.ts b/scripts/lib/perf-report.parse.test.ts
new file mode 100644
index 00000000..84165dd5
--- /dev/null
+++ b/scripts/lib/perf-report.parse.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from "vitest";
+import { parsePerfReport, summarize } from "./perf-report.mjs";
+import { validReport, validRunDesktop, validRunMobile } from "./perf-report.fixtures";
+
+describe("parsePerfReport", () => {
+ it("accepts a valid report and returns it unchanged", () => {
+ const parsed = parsePerfReport(validReport);
+ expect(parsed.schemaVersion).toBe(1);
+ expect(parsed.runs).toHaveLength(2);
+ expect(parsed.runs[0].label).toBe("desktop");
+ });
+
+ it("accepts a JSON string as well as an object", () => {
+ expect(parsePerfReport(JSON.stringify(validReport)).runs).toHaveLength(2);
+ });
+
+ it("rejects invalid JSON with a parse message", () => {
+ expect(() => parsePerfReport("{ nope")).toThrow(/Invalid JSON/);
+ });
+
+ it("rejects missing or invalid schemaVersion naming the field", () => {
+ expect(() => parsePerfReport({ ...validReport, schemaVersion: 2 })).toThrow(/schemaVersion/);
+ const { schemaVersion: _drop, ...withoutVersion } = validReport;
+ expect(() => parsePerfReport(withoutVersion)).toThrow(/schemaVersion/);
+ });
+
+ it("rejects non-array and empty runs naming the field", () => {
+ expect(() => parsePerfReport({ ...validReport, runs: {} })).toThrow(/runs/);
+ expect(() => parsePerfReport({ ...validReport, runs: [] })).toThrow(/runs/);
+ });
+
+ it("rejects a run without a label naming the offending index", () => {
+ expect(() => parsePerfReport({ ...validReport, runs: [{ ...validRunDesktop, label: " " }] })).toThrow(/index 0.*label/);
+ });
+
+ it("rejects a missing timing field without coercing it to zero", () => {
+ // The whole point: a dropped metric must fail loudly, not be scored as a fast page.
+ const { tbtMs: _drop, ...withoutTbt } = validRunDesktop;
+ expect(() => parsePerfReport({ ...validReport, runs: [withoutTbt] })).toThrow(/desktop.*tbtMs/);
+ });
+
+ it("rejects a non-finite timing value", () => {
+ expect(() => parsePerfReport({ ...validReport, runs: [{ ...validRunDesktop, lcpMs: Number.NaN }] })).toThrow(/lcpMs/);
+ expect(() => parsePerfReport({ ...validReport, runs: [{ ...validRunMobile, fcpMs: "1168" }] })).toThrow(/fcpMs/);
+ });
+
+ it("permits an explicit null timing value (unobserved, not zero)", () => {
+ const parsed = parsePerfReport({ ...validReport, runs: [{ ...validRunMobile, lcpMs: null }] });
+ expect(parsed.runs[0].lcpMs).toBeNull();
+ });
+});
+
+describe("summarize", () => {
+ it("projects only the fields the table and the gate read", () => {
+ const rows = summarize(validReport);
+ expect(rows).toHaveLength(2);
+ expect(Object.keys(rows[0]).sort()).toEqual(["cls", "fcpMs", "firstLoadJsBytes", "label", "lcpMs", "maxLongTaskMs", "tbtMs"]);
+ expect(rows[1].label).toBe("mobile");
+ });
+
+ it("returns an empty list for a report with no runs", () => {
+ expect(summarize({ runs: [] })).toEqual([]);
+ });
+});
diff --git a/scripts/lib/trace-longtasks.mjs b/scripts/lib/trace-longtasks.mjs
new file mode 100644
index 00000000..0d2e5342
--- /dev/null
+++ b/scripts/lib/trace-longtasks.mjs
@@ -0,0 +1,165 @@
+// Pure trace analysis: turn a raw DevTools trace into "which script owned which long
+// task". No browser, no CDP, no filesystem — so it can be tested against a recorded
+// trace without a running instance.
+//
+// Why attribution at all: "TBT is 146 ms" is a symptom. Without naming the chunk that
+// owns the time, the only available fix is "rewrite everything", which is what
+// docs/MSO-MIGRATION.md exists to avoid.
+
+const CANDIDATE_NAMES = new Set(["FunctionCall", "EvaluateScript", "v8.compile"]);
+const ANCESTOR_NAMES = new Set(["ParseScriptOnBackground", "v8.run", "EvaluateScript", "FunctionCall", "v8.compile"]);
+
+export function getBasename(url) {
+ try {
+ const parts = new URL(url).pathname.split("/").filter(Boolean);
+ return parts.length > 0 ? parts[parts.length - 1] : new URL(url).hostname;
+ } catch {
+ return String(url).split("/").pop() || String(url);
+ }
+}
+
+function urlOf(event) {
+ const direct = event.args?.data?.url || event.args?.url || event.args?.fileName;
+ return typeof direct === "string" && direct.trim() !== "" ? direct.trim() : null;
+}
+
+export function resolveScriptUrl(candidate, allEvents) {
+ const own = urlOf(candidate);
+ if (own) return own;
+
+ const ancestors = allEvents
+ .filter((e) => e !== candidate && e.ts <= candidate.ts && e.ts + (e.dur || 0) >= candidate.ts + (candidate.dur || 0))
+ // Nearest enclosing event first, then the tightest one.
+ .sort((a, b) => b.ts - a.ts || (a.dur || 0) - (b.dur || 0));
+
+ for (const ancestor of ancestors) {
+ if (ANCESTOR_NAMES.has(ancestor.name)) {
+ const url = urlOf(ancestor);
+ if (url) return url;
+ }
+ }
+ for (const ancestor of ancestors) {
+ const url = urlOf(ancestor);
+ if (url) return url;
+ }
+ return null;
+}
+
+// Renderer main thread only: a task on another thread did not block input, so charging
+// it to TBT would overstate the page.
+function mainThreadEvents(events) {
+ const thread = events.find((e) => e.name === "thread_name" && e.args?.name === "CrRendererMain");
+ const process = events.find((e) => e.name === "process_name" && e.args?.name === "Renderer");
+ const pid = thread?.pid ?? process?.pid;
+ const tid = thread?.tid ?? pid;
+ if (pid === undefined || tid === undefined) return events;
+ return events.filter((e) => e.pid === pid && e.tid === tid);
+}
+
+function navigationOrigin(events) {
+ const starts = events.filter((e) => e.name === "navigationStart" && e.args?.data?.isLoadingMainFrame);
+ const target =
+ starts.find((n) => typeof n.args?.data?.documentLoaderURL === "string" && n.args.data.documentLoaderURL.startsWith("http")) ||
+ starts[starts.length - 1];
+ return target ? target.ts : (events[0]?.ts ?? 0);
+}
+
+const isTask = (e) => (e.name === "RunTask" || e.name === "ThreadControllerImpl::RunTask") && typeof e.dur === "number";
+
+function outermost(tasks) {
+ return tasks.filter(
+ (task) =>
+ !tasks.some((other) => other !== task && other.ts <= task.ts && other.ts + other.dur >= task.ts + task.dur),
+ );
+}
+
+// Self time = duration minus the duration of its direct children. That is the number
+// that tells you which script is expensive, as opposed to which script merely calls.
+function selfTime(candidate, candidates) {
+ const inside = candidates.filter(
+ (child) => child !== candidate && child.ts >= candidate.ts && child.ts + child.dur <= candidate.ts + candidate.dur,
+ );
+ const direct = inside.filter(
+ (child) => !inside.some((other) => other !== child && other.ts <= child.ts && other.ts + other.dur >= child.ts + child.dur),
+ );
+ return Math.max(0, candidate.dur - direct.reduce((sum, child) => sum + child.dur, 0));
+}
+
+export function attributeLongTasks(rawEvents, { minMs = 40 } = {}) {
+ const events = Array.isArray(rawEvents) ? rawEvents : (rawEvents?.traceEvents ?? []);
+ const main = mainThreadEvents(events);
+ const originTs = navigationOrigin(events);
+ const minUs = minMs * 1000;
+
+ const tasks = outermost(main.filter(isTask))
+ .filter((task) => task.dur >= minUs && (originTs === 0 || task.ts >= originTs))
+ .sort((a, b) => a.ts - b.ts)
+ .map((task) => {
+ const candidates = main.filter(
+ (e) =>
+ CANDIDATE_NAMES.has(e.name) &&
+ e.ph === "X" &&
+ typeof e.dur === "number" &&
+ e.dur > 0 &&
+ e.ts >= task.ts &&
+ e.ts + e.dur <= task.ts + task.dur,
+ );
+
+ const byUrl = new Map();
+ for (const candidate of candidates) {
+ const url = resolveScriptUrl(candidate, main);
+ const selfDur = selfTime(candidate, candidates);
+ const key = url || "(unattributed)";
+ const entry = byUrl.get(key) ?? { url, totalSelfDur: 0, topItem: null };
+ entry.totalSelfDur += selfDur;
+ if (!entry.topItem || selfDur > entry.topItem.selfDur) {
+ entry.topItem = { selfDur, functionName: candidate.args?.data?.functionName };
+ }
+ byUrl.set(key, entry);
+ }
+
+ let winner = null;
+ for (const entry of byUrl.values()) if (!winner || entry.totalSelfDur > winner.totalSelfDur) winner = entry;
+
+ const durationMs = Math.round(task.dur / 1000);
+ if (!winner) return { startMs: Math.round((task.ts - originTs) / 1000), durationMs, selfMs: durationMs, scriptFrame: "(unattributed)" };
+
+ const fnHint = winner.topItem?.functionName?.trim();
+ return {
+ startMs: Math.round((task.ts - originTs) / 1000),
+ durationMs,
+ selfMs: Math.round(winner.totalSelfDur / 1000),
+ scriptFrame: winner.url ? (fnHint && fnHint !== "anonymous" ? `${getBasename(winner.url)} (${fnHint})` : getBasename(winner.url)) : "(unattributed)",
+ };
+ });
+
+ const grouped = new Map();
+ for (const row of tasks) {
+ const entry = grouped.get(row.scriptFrame) ?? { scriptFrame: row.scriptFrame, selfMs: 0, tasks: 0 };
+ entry.selfMs += row.selfMs;
+ entry.tasks += 1;
+ grouped.set(row.scriptFrame, entry);
+ }
+
+ return { tasks, byScript: [...grouped.values()].sort((a, b) => b.selfMs - a.selfMs || b.tasks - a.tasks) };
+}
+
+function table(headers, rows, rightAlign) {
+ const widths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => String(r[i]).length)));
+ const pad = (s, w) => (rightAlign ? String(s).padStart(w) : String(s).padEnd(w));
+ return [
+ headers.map((h, i) => pad(h, widths[i])).join(" "),
+ widths.map((w) => "-".repeat(w)).join(" "),
+ ...rows.map((row) => row.map((cell, i) => pad(cell, widths[i])).join(" ")),
+ ];
+}
+
+export function formatLongTasks({ tasks, byScript }, minMs) {
+ if (tasks.length === 0) return `No long tasks found (>= ${minMs} ms).`;
+ const lines = table(["startMs", "durationMs", "selfMs", "scriptFrame"], tasks.map((t) => [t.startMs, t.durationMs, t.selfMs, t.scriptFrame]), false);
+ if (byScript.length) {
+ lines.push("", "Summary by script frame (descending selfMs):");
+ lines.push(...table(["scriptFrame", "selfMs", "tasks"], byScript.map((b) => [b.scriptFrame, b.selfMs, b.tasks]), true));
+ }
+ return lines.join("\n");
+}
diff --git a/scripts/perf-app-open.mjs b/scripts/perf-app-open.mjs
new file mode 100644
index 00000000..2877674d
--- /dev/null
+++ b/scripts/perf-app-open.mjs
@@ -0,0 +1,120 @@
+#!/usr/bin/env node
+// Per-app open cost inside the running shell: how long until the window appears, which
+// chunks that pulled, and how much main-thread time it cost. This is the number a slice
+// migration moves, so it is measured per slice rather than as a page average.
+//
+// Local compute only: network is NOT throttled here. The question is "what does opening
+// this app cost this machine", not "how fast does it download".
+import fs from "node:fs";
+import path from "node:path";
+import { parseArgs } from "node:util";
+import { chromium } from "@playwright/test";
+import { releaseFixture } from "./e2e/release-fixture.mjs";
+import { SHELL_READY, installPerfObservers } from "./lib/browser-metrics.mjs";
+
+const { values } = parseArgs({
+ options: {
+ base: { type: "string" },
+ apps: { type: "string" },
+ output: { type: "string" },
+ json: { type: "boolean", default: false },
+ },
+ strict: true,
+ allowPositionals: false,
+});
+
+const DEFAULTS = ["Image Editor", "Terminal", "System Monitor", "Video Editor"];
+const apps = values.apps ? values.apps.split(",").map((s) => s.trim()).filter(Boolean) : DEFAULTS;
+
+// The shell renders every active window as a [data-window] container; counting them is
+// how an open is detected without depending on any app's internal markup.
+//
+// aria-label only, on purpose. A role/name lookup also matches the macOS menu-bar title
+// that displays the focused app's name, so `getByRole("button", { name: "System Monitor" })`
+// silently clicks the menu bar and the window never opens.
+const findIcon = (page, name) =>
+ page.locator(`[aria-label="${name}"], [aria-label="${name} (running)"]`).first();
+
+async function measureApp(page, name) {
+ const icon = findIcon(page, name);
+ if ((await icon.count()) === 0) return { app: name, openMs: null, error: "icon not found", newResources: 0, newResourceFiles: [], longTaskMs: 0 };
+
+ const windowsBefore = await page.locator("[data-window]").count();
+ const resourcesBefore = await page.evaluate(() => performance.getEntriesByType("resource").length);
+ await page.evaluate(() => window.__perfResetLongTasks());
+
+ const started = Date.now();
+ await icon.click({ noWaitAfter: true });
+ let openMs = null;
+ let error;
+ try {
+ await page.waitForFunction((n) => document.querySelectorAll("[data-window]").length > n, windowsBefore, { timeout: 15000 });
+ openMs = Date.now() - started;
+ } catch {
+ error = "window did not open";
+ }
+
+ // Window mounting is not the whole cost: the content chunk evaluates after it. Waiting
+ // 2 s and reading the tasks accumulated since the reset captures that.
+ await page.waitForTimeout(2000);
+ const longTaskMs = await page.evaluate(() => Math.round((window.__perfLongTasks ?? []).reduce((sum, t) => sum + t.duration, 0)));
+ const newResourceFiles = await page.evaluate((from) =>
+ performance.getEntriesByType("resource").slice(from)
+ .map((e) => { try { return new URL(e.name, location.href).pathname.split("/").pop() || null; } catch { return null; } })
+ .filter(Boolean), resourcesBefore);
+
+ return { app: name, openMs, ...(error ? { error } : {}), newResources: newResourceFiles.length, newResourceFiles, longTaskMs };
+}
+
+function printTable(rows) {
+ const cells = rows.map((r) => [r.app, r.openMs ?? r.error ?? "n/a", String(r.newResources), String(r.longTaskMs), r.newResourceFiles.slice(0, 3).join(", ") + (r.newResourceFiles.length > 3 ? ` (+${r.newResourceFiles.length - 3})` : "")]);
+ const headers = ["App", "Open (ms)", "Resources", "Long Task (ms)", "Chunks"];
+ const widths = headers.map((h, i) => Math.max(h.length, ...cells.map((r) => r[i].length)));
+ const pad = (s, w) => String(s).padEnd(w);
+ console.log(headers.map((h, i) => pad(h, widths[i])).join(" "));
+ console.log(widths.map((w) => "-".repeat(w)).join(" "));
+ for (const row of cells) console.log(row.map((c, i) => pad(c, widths[i])).join(" "));
+}
+
+let fixture;
+let browser;
+try {
+ const base = values.base ?? (fixture = await releaseFixture()).base;
+ browser = await chromium.launch({ headless: true });
+
+ // One fresh context per app. Reusing a page means the second click happens with the
+ // first app's window already open — the window count does not increase, and a window
+ // that happens to cover the dock makes the next icon unclickable. A cold context per
+ // app also keeps the measured cost attributable to that app instead of to whatever the
+ // previous one left in memory.
+ const rows = [];
+ for (const name of apps) {
+ const context = await browser.newContext({ viewport: { width: 1440, height: 900 } });
+ try {
+ await context.addInitScript(installPerfObservers);
+ const page = await context.newPage();
+ const cdp = await context.newCDPSession(page);
+ await cdp.send("Emulation.setCPUThrottlingRate", { rate: 4 });
+ await page.goto(base, { waitUntil: "load", timeout: 60000 });
+ await page.locator(SHELL_READY).waitFor({ state: "visible", timeout: 60000 });
+ await page.waitForTimeout(1500);
+ rows.push(await measureApp(page, name));
+ } finally {
+ await context.close();
+ }
+ }
+
+ const report = { schemaVersion: 1, createdAt: new Date().toISOString(), throttle: { cpuRate: 4 }, apps: rows };
+ if (values.output) {
+ fs.mkdirSync(values.output, { recursive: true, mode: 0o700 });
+ fs.writeFileSync(path.join(values.output, "perf-app-open.json"), JSON.stringify(report, null, 2), { mode: 0o600 });
+ }
+ if (values.json) console.log(JSON.stringify(report, null, 2));
+ else printTable(rows);
+} catch (error) {
+ console.error(`perf-app-open: ${error instanceof Error ? error.message : String(error)}`);
+ process.exitCode = 1;
+} finally {
+ await browser?.close();
+ await fixture?.close();
+}
diff --git a/scripts/perf-baseline.json b/scripts/perf-baseline.json
new file mode 100644
index 00000000..920a5da9
--- /dev/null
+++ b/scripts/perf-baseline.json
@@ -0,0 +1,40 @@
+{
+ "schemaVersion": 1,
+ "note": "Committed measured baseline for the catch-all shell, Slow 4G + 4x CPU, commit 1c74603 (2026-10-28). Values are the median of 3 runs against the synthetic releaseFixture (the path CI takes); the first run of a session is discarded as warm-up because a cold page cache inflates TBT by ~2x. Observed spread across the stable runs: desktop TBT 150-184 ms, mobile 99-148 ms, LCP 3.02-3.22 s, so host load moves these by roughly +/-25%. Only the 2x blowup guard reads them, which is why they are allowed to be approximate; bundle bytes are gated deterministically elsewhere (check-bundle.mjs). Regenerate with: node scripts/perf-probe.mjs --json. TBT here is the standard definition: sum over long tasks of max(0, duration - 50ms), NOT the raw sum of task durations.",
+ "commit": "1c74603",
+ "profile": {
+ "name": "cold-slow4g-4xcpu",
+ "latencyMs": 150,
+ "downlinkKbps": 1600,
+ "uplinkKbps": 750,
+ "cpuRate": 4
+ },
+ "runs": [
+ {
+ "label": "desktop",
+ "viewport": { "width": 1440, "height": 900 },
+ "fcpMs": 1180,
+ "lcpMs": 3222,
+ "tbtMs": 164,
+ "cls": 0.001,
+ "longTasks": 4,
+ "maxLongTaskMs": 128,
+ "firstLoadJsBytes": 964362,
+ "firstLoadJsFiles": 21,
+ "domNodes": 870
+ },
+ {
+ "label": "mobile",
+ "viewport": { "width": 390, "height": 844 },
+ "fcpMs": 1166,
+ "lcpMs": 3054,
+ "tbtMs": 132,
+ "cls": 0,
+ "longTasks": 4,
+ "maxLongTaskMs": 126,
+ "firstLoadJsBytes": 947790,
+ "firstLoadJsFiles": 21,
+ "domNodes": 1165
+ }
+ ]
+}
diff --git a/scripts/perf-budget.json b/scripts/perf-budget.json
new file mode 100644
index 00000000..fdfa1987
--- /dev/null
+++ b/scripts/perf-budget.json
@@ -0,0 +1,13 @@
+{
+ "schemaVersion": 1,
+ "note": "Timing numbers drift with host load, so this file only enforces a 2x blowup against scripts/perf-baseline.json. Bundle bytes are already gated deterministically by scripts/check-bundle.mjs (gzip, from build output, no browser); enforcing a browser-measured byte count here would be both redundant and flaky, since it counts every JS chunk the shell fetched during the window including deferred ones. targets are the post-migration goal from docs/MSO-MIGRATION.md and are printed, never enforced.",
+ "enforce": {
+ "tbtMsBlowupFactor": 2.0
+ },
+ "targets": {
+ "initialGzipBytes": 256000,
+ "tbtMs": 150,
+ "lcpMs": 2500
+ },
+ "targetsEnforced": false
+}
diff --git a/scripts/perf-longtasks.mjs b/scripts/perf-longtasks.mjs
new file mode 100644
index 00000000..6f438db2
--- /dev/null
+++ b/scripts/perf-longtasks.mjs
@@ -0,0 +1,87 @@
+#!/usr/bin/env node
+// Read-only diagnostic: attribute each long task on first load to the script that owns it.
+// Not a gate — a finding here is information, not a failure (see check-perf.mjs for the gate).
+import { writeFileSync, mkdirSync } from "node:fs";
+import path from "node:path";
+import { parseArgs } from "node:util";
+import { chromium } from "@playwright/test";
+import { releaseFixture } from "./e2e/release-fixture.mjs";
+import { attributeLongTasks, formatLongTasks } from "./lib/trace-longtasks.mjs";
+
+const { values } = parseArgs({
+ options: {
+ base: { type: "string" },
+ "min-ms": { type: "string", default: "40" },
+ output: { type: "string" },
+ json: { type: "boolean", default: false },
+ },
+ strict: true,
+ allowPositionals: false,
+});
+
+const parsed = Number(values["min-ms"]);
+const minMs = Number.isFinite(parsed) && parsed >= 0 ? parsed : 40;
+
+const CATEGORIES = [
+ "devtools.timeline",
+ "disabled-by-default-devtools.timeline",
+ "v8.execute",
+ "blink.user_timing",
+ "disabled-by-default-v8.cpu_profiler",
+].join(",");
+
+let fixture;
+let browser;
+try {
+ const base = values.base ?? (fixture = await releaseFixture()).base;
+ browser = await chromium.launch({ headless: true });
+ const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, reducedMotion: "reduce" });
+ await context.addInitScript(() => {
+ localStorage.setItem("sv:shell", JSON.stringify({ desktop: "macos", mobile: "ios" }));
+ localStorage.setItem("mso:onboarding:v1", "done");
+ });
+
+ const page = await context.newPage();
+ const cdp = await context.newCDPSession(page);
+ await cdp.send("Network.enable");
+ // Slow 4G (Lighthouse): 150 ms RTT, 1.6 Mbps down, 750 kbps up. Tracing an
+ // unthrottled load finds different tasks than the ones the gate measures.
+ await cdp.send("Network.emulateNetworkConditions", { offline: false, latency: 150, downloadThroughput: 204800, uploadThroughput: 93750 });
+ await cdp.send("Emulation.setCPUThrottlingRate", { rate: 4 });
+
+ const complete = new Promise((resolve) => cdp.once("Tracing.tracingComplete", resolve));
+ await cdp.send("Tracing.start", { categories: CATEGORIES, transferMode: "ReturnAsStream" });
+
+ await page.goto(base, { waitUntil: "load", timeout: 60000 });
+ // The pre-hydration skeleton also has #main-content; data-shell means the shell mounted.
+ await page.locator("#main-content[data-shell]").waitFor({ state: "visible", timeout: 60000 });
+ // Deferred panels arrive after mount and are still part of the load cost.
+ await page.waitForTimeout(3000);
+
+ await cdp.send("Tracing.end");
+ const { stream } = await complete;
+ if (!stream) throw new Error("Tracing did not return a stream");
+
+ let json = "";
+ for (let eof = false; !eof; ) {
+ const chunk = await cdp.send("IO.read", { handle: stream });
+ json += chunk.data;
+ eof = chunk.eof;
+ }
+ await cdp.send("IO.close", { handle: stream }).catch(() => {});
+
+ const result = attributeLongTasks(JSON.parse(json), { minMs });
+ const report = { schemaVersion: 1, createdAt: new Date().toISOString(), minMs, ...result };
+
+ if (values.output) {
+ mkdirSync(values.output, { recursive: true, mode: 0o700 });
+ writeFileSync(path.join(values.output, "perf-longtasks.json"), JSON.stringify(report, null, 2), { mode: 0o600 });
+ }
+ console.log(values.json ? JSON.stringify(report, null, 2) : formatLongTasks(result, minMs));
+} catch (error) {
+ console.error(`perf-longtasks: ${error instanceof Error ? error.message : String(error)}`);
+ process.exitCode = 1;
+} finally {
+ await browser?.close();
+ await fixture?.close();
+}
diff --git a/scripts/perf-probe.mjs b/scripts/perf-probe.mjs
new file mode 100644
index 00000000..42963d8a
--- /dev/null
+++ b/scripts/perf-probe.mjs
@@ -0,0 +1,120 @@
+#!/usr/bin/env node
+// Cold-load perceived performance, measured the way the gate measures it.
+// Emits perf-report.json: FCP / LCP / TBT / CLS / first-load JS for desktop + mobile.
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { execFileSync } from "node:child_process";
+import { parseArgs } from "node:util";
+import { chromium } from "@playwright/test";
+import { releaseFixture } from "./e2e/release-fixture.mjs";
+import { formatTable } from "./lib/perf-report.mjs";
+import { SHELL_READY, SLOW_4G, installPerfObservers, readPerfMetrics } from "./lib/browser-metrics.mjs";
+
+const { values } = parseArgs({
+ options: {
+ base: { type: "string" },
+ output: { type: "string" },
+ json: { type: "boolean", default: false },
+ },
+ strict: true,
+ allowPositionals: false,
+});
+
+const RUNS = [
+ { label: "desktop", viewport: { width: 1440, height: 900 } },
+ { label: "mobile", viewport: { width: 390, height: 844 } },
+];
+
+function commit() {
+ try {
+ return execFileSync("git", ["rev-parse", "--short", "HEAD"], { cwd: path.resolve("."), encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
+ } catch {
+ return null;
+ }
+}
+
+async function measure(browser, base, { label, viewport }) {
+ const context = await browser.newContext({ viewport, reducedMotion: "reduce" });
+ try {
+ await context.addInitScript(installPerfObservers);
+ const page = await context.newPage();
+ const cdp = await context.newCDPSession(page);
+ await cdp.send("Network.enable");
+ await cdp.send("Network.emulateNetworkConditions", { offline: false, ...SLOW_4G });
+ await cdp.send("Emulation.setCPUThrottlingRate", { rate: 4 });
+
+ await page.goto(base, { waitUntil: "load", timeout: 60000 });
+ await page.locator(SHELL_READY).waitFor({ state: "visible", timeout: 60000 });
+
+ // LCP lands ~3 s in, well after hydration. Waiting only for "nothing changed for 1 s"
+ // exits at ~1.2 s and reports lcpMs null; wait for the entry itself.
+ await page.waitForFunction(() => window.__perfLCP != null, null, { timeout: 30000 }).catch(() => {});
+ // Then let the post-LCP deferred chunks finish so their tasks are charged to this load.
+ let last = -1;
+ for (let stable = 0, deadline = Date.now() + 10000; Date.now() < deadline; ) {
+ const count = await page.evaluate(() => window.__perfLongTasks?.length ?? 0);
+ if (count !== last) {
+ last = count;
+ stable = 0;
+ } else if (++stable >= 10) {
+ break;
+ }
+ await page.waitForTimeout(100);
+ }
+
+ return { label, viewport, ...(await page.evaluate(readPerfMetrics)) };
+ } finally {
+ await context.close();
+ }
+}
+
+let fixture;
+let browser;
+try {
+ const base = values.base ?? (fixture = await releaseFixture()).base;
+ browser = await chromium.launch({ headless: true });
+
+ // Warm-up boot, discarded. The first cold load of a session pays disk-cache misses for
+ // ~900 KB of chunks and measured TBT 418 ms against 164 ms once warm — a 2.5x error that
+ // would fail the gate on every fresh CI runner. Not reported, not counted.
+ const warm = await browser.newContext({ viewport: RUNS[0].viewport });
+ try {
+ await warm.addInitScript(installPerfObservers);
+ const page = await warm.newPage();
+ await page.goto(base, { waitUntil: "load", timeout: 60000 });
+ await page.locator(SHELL_READY).waitFor({ state: "visible", timeout: 60000 });
+ } finally {
+ await warm.close();
+ }
+
+ const runs = [];
+ for (const config of RUNS) runs.push(await measure(browser, base, config));
+
+ const report = {
+ schemaVersion: 1,
+ createdAt: new Date().toISOString(),
+ commit: commit(),
+ host: {
+ platform: process.platform,
+ cpus: os.cpus().length,
+ node: process.version.replace(/^v/, ""),
+ totalMemMb: Math.round(os.totalmem() / 1024 / 1024),
+ },
+ profile: { name: "cold-slow4g-4xcpu", latencyMs: SLOW_4G.latency, downlinkKbps: 1600, uplinkKbps: 750, cpuRate: 4 },
+ runs,
+ };
+
+ if (values.output) {
+ fs.mkdirSync(values.output, { recursive: true, mode: 0o700 });
+ fs.writeFileSync(path.join(values.output, "perf-report.json"), JSON.stringify(report, null, 2), { mode: 0o600 });
+ }
+ if (values.json) process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
+ else process.stderr.write(`${formatTable(report)}\n`);
+} catch (error) {
+ console.error(`perf-probe: ${error instanceof Error ? error.message : String(error)}`);
+ process.exitCode = 1;
+} finally {
+ await browser?.close();
+ await fixture?.close();
+}