Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(gate): refuse to ship a browser module that bootstraps before its state

nirholas1f884a199a78
diff --git a/docs/oracle-trading-mcp-plan.md b/docs/oracle-trading-mcp-plan.md
new file mode 100644
index 000000000..ddf62e9dc
--- /dev/null
+++ b/docs/oracle-trading-mcp-plan.md
@@ -0,0 +1,247 @@
+# Plan: ship Oracle and the autonomous trading agents as MCP servers
+
+**Status:** planned, not started. Written 2026-08-19.
+**Goal:** make [Oracle](https://three.ws/oracle) and the autonomous trading agents first-class,
+discoverable MCP servers, publish them to the official MCP registry
+(`registry.modelcontextprotocol.io`), document them, and announce them in one plain-language X post.
+
+This document is the build order. Everything in "What already exists" was verified against the
+tree and the live registry on 2026-08-19, so the plan starts from facts, not assumptions.
+
+---
+
+## Why this is worth doing
+
+Oracle is the best thing we run and almost nobody can find it from an agent client.
+
+Its four MCP tools (`oracle_top_plays`, `oracle_coin`, `oracle_arm_watch`, `oracle_watch_status`)
+live inside the main `https://three.ws/api/mcp` server, buried among 40+ avatar, model, animation,
+sign-language, memory, and market tools. In the registry that server is listed as
+"3D avatars, embeds, glTF tools, agent memory, and on-chain agent identity". An agent looking for
+a conviction signal on a new launch has no way to find it, and a human browsing the registry has
+no reason to click.
+
+The same is true of the autonomous side. `oracle_arm_watch` is the single most interesting write
+tool on the platform (it arms an agent to trade a live conviction stream inside a spend leash), and
+it is discoverable only by reading a 40-tool list on an avatar server.
+
+The fix is not new capability. It is **packaging**: two focused servers, named for what they do,
+listed under their own registry entries.
+
+---
+
+## What already exists (verified 2026-08-19)
+
+### Oracle
+
+| Layer | Location | State |
+|---|---|---|
+| Conviction engine | `api/_lib/oracle/` + `conviction-model.json` | Live, fitted model, AUC 0.879 on holdout |
+| Public API | `api/oracle/*.js` (26 endpoints) | Live: `feed`, `coin`, `signal`, `stats`, `backtest`, `calibration`, `leaderboard`, `wins`, `movers`, `categories`, `search`, `history`, `market`, `social`, `trades`, `wallet`, `watch`, `agent-stats`, `action-stream`, `activity`, `follow`, `batch`, `stream`, and more |
+| Pages | `/oracle`, `/oracle/docs`, `/oracle/arm` (in `data/pages.json`) | Live |
+| Reference doc | `docs/oracle.md` | Complete, long-form |
+| MCP tools | `api/_mcp/tools/oracle.js`, 4 tools | Live, but only inside the main server |
+| Dedicated MCP server | none | **This is the gap** |
+
+### Autonomous trading agents
+
+| Surface | Location | Registry state |
+|---|---|---|
+| Sniper engine (library + CLI + MCP + x402 API) | `packages/agent-sniper`, `workers/agent-sniper` | `io.github.nirholas/agent-sniper` @ 0.1.5 published; local `server.json` is 0.1.6, so a bump is pending |
+| Autopilot control plane | `packages/autopilot-mcp` | `io.github.nirholas/autopilot-mcp` @ 0.2.0 published |
+| Copy-trade follows | `packages/copy-mcp` | published @ 0.1.1 |
+| Signal marketplace | `packages/signals-mcp` | published @ 0.1.1 |
+| Portfolio + PnL | `packages/portfolio-mcp` | published @ 0.1.1 |
+| Market intel | `packages/intel-mcp`, `packages/kol-mcp` | published |
+| Oracle-armed agent loop | `api/oracle/watch.js`, `api/oracle/action-stream.js`, `api/oracle/agent-stats.js` | **No dedicated server. Only the two tools inside `/api/mcp`.** |
+
+61 distinct servers are already published under the `io.github.nirholas` namespace, so the
+publishing path is proven and boring. `scripts/publish-mcp-servers.mjs` (`npm run publish:mcp`)
+handles npm plus registry, idempotently, and skips anything already at the target version.
+
+### The publishing machinery (already built, do not rebuild)
+
+- `scripts/publish-mcp-servers.mjs`: npm publish, then registry publish, per server. Auth resolves
+ `MCP_REGISTRY_TOKEN`, then the owner's GitHub PAT from git config or `~/.git-credentials`, then
+ `GITHUB_TOKEN`.
+- `npm run audit:mcp` / `audit:mcp-golden` / `audit:mcp-safety` / `audit:mcp-catalog`: manifest,
+ golden-transcript, safety-annotation, and catalog checks. All four are in `npm run gate`.
+- `npm run smoke:mcp`: hits the hosted remotes for real.
+- `public/.well-known/mcp.json`: the hand-maintained hosted-server directory (7 entries today).
+- `public/mcp-catalog.json` + `/mcp-tools` page: the human-facing catalog, built by
+ `scripts/build-mcp-catalog.mjs`.
+
+---
+
+## The plan
+
+Five phases. Phases 1 and 2 are independent and can run in parallel; 3 depends on both; 4 and 5
+close it out.
+
+### Phase 1: `@three-ws/oracle-mcp` and the hosted Oracle remote
+
+Two faces of one server, mirroring the pattern already used for 3D Studio
+(`packages/*` stdio package plus `api/mcp-3d.js` remote plus `server-3d.json`).
+
+**1a. Hosted remote: `api/mcp-oracle.js` + `server-oracle.json`**
+
+Copy the structure of `api/mcp-3d.js` exactly: Streamable HTTP, shared OAuth/x402 plumbing from
+`api/_mcp/auth.js` and `api/_mcp/payments.js`, per-IP rate limits, SSE on GET, terminate on DELETE.
+Registry name `io.github.nirholas/threews-oracle`, URL `https://three.ws/api/mcp-oracle`.
+
+Route it in `vercel.json` (both the handler entry and the
+`/api/mcp-oracle/.well-known/oauth-protected-resource` route, matching the `/api/mcp` precedent at
+`vercel.json:525`), and add the entry to `public/.well-known/mcp.json`.
+
+**1b. stdio package: `packages/oracle-mcp`**
+
+Read-only, public, no key, no signer, no payment, over the live public API. This is the one people
+will actually install, so it has to be free and instant. Model it on `packages/intel-mcp`, which is
+already exactly this shape.
+
+**Tool surface (both faces).** The four existing tools stay, and the rest are thin wrappers over
+endpoints that are already live and public:
+
+| Tool | Backing endpoint | Auth |
+|---|---|---|
+| `oracle_getting_started` | local, static | free |
+| `oracle_top_plays` | `/api/oracle/signal` | free |
+| `oracle_coin` | `/api/oracle/coin`, `/api/oracle/signal?mint=` | free |
+| `oracle_feed` | `/api/oracle/feed` | free |
+| `oracle_search` | `/api/oracle/search` | free |
+| `oracle_movers` | `/api/oracle/movers` | free |
+| `oracle_wins` | `/api/oracle/wins` | free |
+| `oracle_backtest` | `/api/oracle/backtest` | free |
+| `oracle_calibration` | `/api/oracle/calibration` | free |
+| `oracle_leaderboard` | `/api/oracle/leaderboard` | free |
+| `oracle_wallet` | `/api/oracle/wallet` | free |
+| `oracle_stats` | `/api/oracle/stats` | free |
+| `oracle_arm_watch` | `POST /api/oracle/watch` | account-scoped (hosted remote only) |
+| `oracle_watch_status` | `GET /api/oracle/watch` | account-scoped (hosted remote only) |
+
+The two write tools ship on the hosted remote only. The stdio package advertises them as
+"available on the hosted server" in its getting-started text rather than shipping a half-wired
+auth path locally.
+
+**Honesty requirements, non-negotiable, already enforced by the existing tests in
+`tests/api/mcp-oracle-tools.test.js`:** a degraded feed or intel store reports as transient, never
+as an empty market, and an unknown coin is distinguished from an outage. Any new tool inherits
+that rule and gets a case in that test file.
+
+**Backwards compatibility:** the four tools stay in the main `/api/mcp` catalog. Nothing that works
+today stops working. `api/_mcp/tools/oracle.js` becomes the shared definition both catalogs import.
+
+### Phase 2: `@three-ws/agent-trader-mcp`, the autonomous trading control plane
+
+One server that answers "arm my agent on Oracle, then show me what it did and let me stop it."
+Today that story is split across `oracle_arm_watch`, the sniper package, autopilot, and the
+portfolio server, so no single entry in the registry tells it.
+
+Registry name `io.github.nirholas/threews-agent-trader`, npm `@three-ws/agent-trader-mcp`, stdio,
+authenticated with a three.ws API key. Model it on `packages/autopilot-mcp`, which already has the
+right posture for a write-heavy, real-money server.
+
+| Tool | Backing surface | Kind |
+|---|---|---|
+| `trader_getting_started` | local, static | free |
+| `agent_arm` | `POST /api/oracle/watch` | write, guarded |
+| `agent_disarm` | `POST /api/oracle/watch` (`armed:false`) | write, the kill switch |
+| `agent_status` | `GET /api/oracle/watch` | read |
+| `agent_actions` | `/api/oracle/action-stream`, `/api/oracle/activity` | read |
+| `agent_performance` | `/api/oracle/agent-stats` | read |
+| `agent_positions` | portfolio API | read |
+| `agent_guardrails` | agent guards / spend-envelope API | write, guarded |
+
+**Safety posture, copied from `packages/autopilot-mcp` because it is correct:**
+
+- `mode` defaults to `simulate`. Live spend is opt-in, per call, never sticky by accident.
+- Every boundary (scopes, per-trade SOL, daily SOL cap, max open positions) is enforced
+ server-side. The MCP server cannot widen a leash the backend refuses.
+- `agent_disarm` is documented as the kill switch and must work with only an agent id, no other
+ arguments, because that is what someone types when something is going wrong.
+- The `README` and `server.json` description both say, in the first two lines, that this server can
+ move real SOL.
+- Arming live still routes through the platform's existing owner-confirmation path. This server
+ does not become a way around the spend gate in `CLAUDE.md`.
+
+### Phase 3: publish to the registry
+
+Nothing new to build here. In order:
+
+```bash
+npm run audit:mcp # manifest validation
+npm run audit:mcp-safety # tool annotation / safety audit
+npm run audit:mcp-golden # golden transcripts
+npm run audit:mcp-catalog # catalog is in sync
+npm run test:mcp # every MCP server's own tests
+npm run publish:mcp:dry # report exactly what would publish, publish nothing
+npm run publish:mcp # npm, then registry, idempotent
+npm run smoke:mcp # hit the hosted remotes for real
+```
+
+Also in this phase, because they are one-line fixes that are currently drifted:
+
+- Bump `packages/agent-sniper` to publish 0.1.6 (registry has 0.1.5, the tree has 0.1.6).
+- Add both new remotes to `public/.well-known/mcp.json` (7 entries today, 8 after Phase 1).
+- Add both new server keys to the `SERVERS` array in `scripts/publish-mcp-servers.mjs`. A server
+ that is not in that array is invisible to the publisher, which is the single easiest way for
+ this whole plan to silently ship nothing.
+
+Verify after publishing:
+
+```bash
+curl -s "https://registry.modelcontextprotocol.io/v0/servers?search=threews-oracle" | jq '.servers[].server.name'
+```
+
+### Phase 4: documentation
+
+Per the documentation rules in `CLAUDE.md`, all of these apply and none are optional:
+
+- `packages/oracle-mcp/README.md` and `packages/agent-trader-mcp/README.md`: what it does, install,
+ full tool table, one runnable example each. Package README coverage is currently 100% and this
+ plan must not be what breaks it.
+- `docs/mcp.md`: update the server count (it currently says 44) and add both servers to the hosted
+ and install-and-run lists.
+- `docs/oracle.md`: expand the existing "the MCP path" section into a real quickstart with the new
+ server name and a copy-pasteable client config.
+- `docs/agent-trading-mcp.md`: new. The autonomous trading story end to end, linked from
+ `docs/start-here.md`.
+- `STRUCTURE.md`: rows for both new package directories.
+- `data/pages.json`: only if a new public page lands. No new page is planned.
+- `data/changelog.json`: one entry, tags `feature` and `sdk`. Holder-readable, no commit jargon.
+ Something like "Oracle is now its own MCP server: any AI agent can pull live conviction scores,
+ and arm a trading agent, without touching the website."
+
+### Phase 5: the X post
+
+Draft lives at [`docs/oracle-trading-mcp-x-post.md`](oracle-trading-mcp-x-post.md). Written before
+the work ships so the announcement shapes the scope rather than the reverse: if a claim in that
+post is not true when the phases are done, the phases are not done.
+
+Post it only after `npm run smoke:mcp` passes against the live remotes and both registry entries
+resolve. Announcing an MCP server nobody can connect to is the one failure mode that costs more
+than shipping late.
+
+---
+
+## Definition of done
+
+- [ ] `https://three.ws/api/mcp-oracle` responds to `initialize` and `tools/list` unauthenticated.
+- [ ] `npx @three-ws/oracle-mcp` connects from a clean machine with no key and returns a live score.
+- [ ] `npx @three-ws/agent-trader-mcp` arms an agent in simulate mode and disarms it.
+- [ ] Both servers resolve in `registry.modelcontextprotocol.io`.
+- [ ] `npm run gate` passes (all four MCP audits are inside it).
+- [ ] `npm run smoke:mcp` passes.
+- [ ] Every doc in Phase 4 is written, and `npm run audit:docs` is clean.
+- [ ] The changelog entry is in and `npm run build:pages` accepts it.
+- [ ] The X post claims nothing that is not live.
+
+## Risks and how they get handled
+
+| Risk | Handling |
+|---|---|
+| Registry publish 403s on the wrong account | Known trap, documented in the publish script: the git PAT outranks `GITHUB_TOKEN` because a Codespace token can belong to a different account. If it 403s, check `npm whoami` and the PAT source before touching anything else. |
+| Tool sprawl makes the new servers as unfindable as the old one | Hard cap: Oracle ships at most 14 tools, agent-trader at most 8. A tool that does not earn its place in the getting-started text does not ship. |
+| Someone arms live spend from an MCP client by accident | `simulate` default, server-side leash, per-call opt-in, kill switch that takes one argument. Same posture as `packages/autopilot-mcp`. |
+| The X post outruns the deploy | Post gated on `smoke:mcp` plus both registry lookups resolving. |
+| The main `/api/mcp` server loses the Oracle tools in the refactor | The four tool definitions stay in `api/_mcp/tools/oracle.js` and both catalogs import them. `tests/api/mcp-oracle-tools.test.js` already covers them and must stay green. |
diff --git a/docs/oracle-trading-mcp-x-post.md b/docs/oracle-trading-mcp-x-post.md
new file mode 100644
index 000000000..250ddf23f
--- /dev/null
+++ b/docs/oracle-trading-mcp-x-post.md
@@ -0,0 +1,134 @@
+# X post: Oracle and our trading agents become MCP servers
+
+Draft copy for announcing that [Oracle](https://three.ws/oracle) and the three.ws autonomous
+trading agents are published as Model Context Protocol servers in
+[Anthropic's official MCP registry](https://registry.modelcontextprotocol.io/?q=io.github.nirholas),
+so any AI assistant can use them directly.
+
+Build plan this announces: [`docs/oracle-trading-mcp-plan.md`](oracle-trading-mcp-plan.md).
+
+**Do not post until:** `npm run smoke:mcp` passes against the live remotes, and both
+`io.github.nirholas/threews-oracle` and `io.github.nirholas/threews-agent-trader` resolve in the
+registry. Every claim below has to be true at post time.
+
+## Rules for this one
+
+1. **Explain it to someone who has never heard of MCP.** The audience is not protocol people. It
+ is traders who use Claude and builders who have heard the acronym and never installed one.
+ One sentence of plain English up top, jargon only after the reader is already interested.
+2. **Lead with the thing, not the plumbing.** Nobody wakes up wanting an MCP server. They want the
+ score before the candle. Open on that.
+3. **One outbound link in the main post.** Threads can carry more.
+4. **Claim only what is live.** We publish to the registry, we do not "partner with Anthropic".
+ Do not imply endorsement.
+5. **No price talk, no predictions, no moon language.** This is a capability post.
+6. **$THREE is the only coin named**, and only if it is naturally relevant. Do not force it in.
+
+---
+
+## 1. Main post (recommended)
+
+> Your AI can now trade with our eyes.
+>
+> Oracle scores every new pump.fun coin 0 to 100 in the first seconds, from the creator's history,
+> who is buying, and how clean the supply is.
+>
+> It is now an MCP server. One line of setup and Claude reads it live.
+>
+> https://three.ws/oracle
+
+Why this one: the first line is the whole product in six words, the second line explains it with
+zero jargon, and MCP shows up only after the reader already wants it.
+
+## 2. Alternate main post (builder-facing)
+
+> We turned our conviction engine into an MCP server.
+>
+> `npx @three-ws/oracle-mcp`
+>
+> Free, no key, no signup. Your agent gets a live 0-100 score on every new launch, the reasoning
+> behind it, and the track record so it can decide how much to trust it.
+>
+> Now in Anthropic's MCP registry.
+
+## 3. Thread (use if the main post lands)
+
+**1/**
+> Your AI can now trade with our eyes.
+>
+> Oracle scores every new pump.fun coin 0 to 100 in its first seconds. It is now an MCP server, so
+> Claude can read it live.
+>
+> Here is what that actually means. 🧵
+
+**2/**
+> MCP is a plug for AI assistants. Instead of copy-pasting data into a chat, you connect a tool
+> once and the AI can use it whenever it needs to.
+>
+> Anthropic built it. There is an official registry of them. We just published two.
+
+**3/**
+> Server one is Oracle.
+>
+> Ask your AI "what is worth looking at right now" and it pulls the live board: score, tier, the
+> plain-language reasoning, and the honest track record.
+>
+> Free. No key. No account.
+
+**4/**
+> Server two is the trading agent.
+>
+> Same conversation, next step: "arm my agent on anything scoring 80+, half a SOL a day, simulate
+> first."
+>
+> It runs. You can check what it did and stop it in one sentence.
+
+**5/**
+> Simulate is the default. Real spend is opt-in every time, and the per-trade and daily limits are
+> enforced on our side, not in the client.
+>
+> An AI cannot talk its way past them. That is the point.
+
+**6/**
+> Why it matters: the first minutes of a new coin are the most lopsided market there is. The people
+> with an edge have context you do not.
+>
+> Oracle is that context, as a number, delivered fast enough to act on.
+
+**7/**
+> Both servers are in the official MCP registry now, alongside the rest of ours.
+>
+> registry.modelcontextprotocol.io/?q=io.github.nirholas
+>
+> Docs: https://three.ws/oracle/docs
+
+## 4. Reply to attach to whichever post lands
+
+> The scoring model is fitted on our own labeled outcomes, not hand-tuned vibes, and the holdout
+> numbers are published on the docs page including the ones that make us look worse.
+>
+> If you are going to let an agent act on a number, you should get to audit the number.
+
+## 5. If someone asks "what is MCP" in the replies
+
+> It is a standard way to plug a tool into an AI assistant. Connect it once and Claude can use it
+> whenever it is relevant, instead of you pasting data in by hand. Anthropic made it and it is
+> open. Ours takes one line to add.
+
+---
+
+## Facts a reply might need
+
+Pull the live numbers from https://three.ws/oracle/docs before posting. As of 2026-08-19 the
+docs report holdout AUC 0.879, top-decile good-rate 62.5 percent against an 11.7 percent base rate,
+and Prime tier at 72.7 percent. **Re-read those from the page at post time.** The model is refit as
+labels accumulate, and quoting a stale number in a post about being auditable is the worst possible
+place to be wrong.
+
+## What not to say
+
+- Anything implying Anthropic endorses, reviewed, or partnered with us. We published to a public
+ registry. That is all.
+- "Guaranteed", "alpha", "printer", "financial advice" in any direction.
+- A win-rate number without the base rate next to it.
+- Anything about the agent being unsupervised. Simulate is the default and the limits are real.
diff --git a/package.json b/package.json
index df4ebd55b..77ac84904 100644
--- a/package.json
+++ b/package.json
@@ -194,7 +194,7 @@
"audit:route-shadowing": "node scripts/audit-route-shadowing.mjs",
"audit:handlers": "node scripts/audit-empty-handlers.mjs",
"audit:x402-catalog": "node scripts/audit-x402-catalog.mjs",
- "gate": "npm run check:conflicts && npm run check:claude && npm run check:vendored && npm run check:event && npm run check:cron-syntax && npm run check:studio-openapi && npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:mcp-safety && npm run audit:mcp-catalog && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:links && npm run audit:docs && npm run check:tutorials && npm run audit:hidden-guard && npm run audit:inline-handlers && npm run audit:x402-catalog && npm run audit:tokens && npm run audit:guards && npm run audit:tour-atlas",
+ "gate": "npm run check:conflicts && npm run check:claude && npm run check:vendored && npm run check:tdz && npm run check:event && npm run check:cron-syntax && npm run check:studio-openapi && npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:mcp-safety && npm run audit:mcp-catalog && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:links && npm run audit:docs && npm run check:tutorials && npm run audit:hidden-guard && npm run audit:inline-handlers && npm run audit:x402-catalog && npm run audit:tokens && npm run audit:guards && npm run audit:tour-atlas",
"test:gate-3d": "vitest run tests/glb-canonicalize.test.js tests/animation-retarget.test.js tests/animation-retarget-rest-pollution.test.js tests/viewer-framing.test.js",
"audit:mcp-golden": "node scripts/audit-mcp-golden.mjs",
"audit:mcp-safety": "node scripts/audit-mcp-safety.mjs",
@@ -266,6 +266,8 @@
"publish:lib": "node scripts/publish-lib.mjs",
"publish:packages": "node scripts/publish-packages.mjs",
"publish:packages:dry": "node scripts/publish-packages.mjs --dry-run",
+ "publish:queue:dry": "node scripts/publish-npm-queue.mjs",
+ "publish:queue": "node scripts/publish-npm-queue.mjs --publish",
"publish:mcp": "node scripts/publish-mcp-servers.mjs",
"publish:mcp:dry": "node scripts/publish-mcp-servers.mjs --dry-run",
"sync:repos": "node scripts/sync-standalone-repos.mjs --execute",
@@ -324,6 +326,7 @@
"verify:erc8004-validation": "node scripts/erc8004/verify-validation-registry.mjs",
"check:rules": "node scripts/check-rules.mjs",
"check:vendored": "node scripts/check-vendored-workers.mjs",
+ "check:tdz": "node scripts/check-tdz-bootstrap.mjs",
"check:secrets": "node scripts/check-secrets.mjs",
"check:gcloudignore": "node scripts/check-gcloudignore.mjs",
"check:evm-rpc": "node --env-file=.env scripts/probe-evm-rpc.mjs --chain 1 --ens",
diff --git a/scripts/audit-docs.mjs b/scripts/audit-docs.mjs
index 2f3d8dec0..9fd8e2d17 100644
--- a/scripts/audit-docs.mjs
+++ b/scripts/audit-docs.mjs
@@ -298,6 +298,8 @@ const UNPUBLISHED_DOCS = new Map([
['money-map', 'internal: revenue-share and treasury routing'],
['native-launchpad', 'owner-gated: names a crypto project other than $THREE'],
['news-archive-x-post', 'internal: paste-ready X copy for the news archive, drafted for the owner to post'],
+ ['oracle-trading-mcp-plan', 'internal: build order for the Oracle and trading-agent MCP servers, not a reader-facing product doc'],
+ ['oracle-trading-mcp-x-post', 'internal: paste-ready X copy for the MCP launch, drafted for the owner to post'],
['nvidia-apps-catalog-listing', 'internal: paste-ready listing copy and portal steps for the NVIDIA Inception catalog'],
['nvidia-apps-catalog-request', 'internal: outbound email asking NVIDIA to publish the catalog listing'],
['nvidia-visibility-map', 'internal: outreach priorities and unclaimed program benefits across every NVIDIA surface'],
diff --git a/scripts/check-tdz-bootstrap.mjs b/scripts/check-tdz-bootstrap.mjs
new file mode 100644
index 000000000..db786a6a7
--- /dev/null
+++ b/scripts/check-tdz-bootstrap.mjs
@@ -0,0 +1,293 @@
+#!/usr/bin/env node
+/**
+ * Refuse to ship a browser module whose bootstrap runs BEFORE the state it touches.
+ *
+ * Why this exists
+ * ---------------
+ * A module that calls its own entry point at top level, above the `let`s that
+ * entry point writes, is reading bindings that are still in their temporal dead
+ * zone. Whether that throws depends on the engine, so it ships green and breaks
+ * in the field:
+ *
+ * init(); // runs during module evaluation
+ * async function init() {
+ * avatar = await fetchAvatar(id); // `avatar` is still uninitialized
+ * }
+ * let avatar = null; // ...declared down here
+ *
+ * JavaScriptCore checks an assignment target's dead zone EAGERLY, before it
+ * evaluates the right-hand side, so Safari throws before the `await` is even
+ * reached. V8 defers the same check until after the await, by which point module
+ * evaluation has finished and the binding exists, so Chrome never notices.
+ *
+ * That exact shape shipped in src/avatar-page.js and took every /avatars/:id page
+ * down in Safari on both iOS and macOS, rendering the engine's raw
+ * "Cannot access uninitialized variable." into the page where the 3D stage
+ * belongs. Chrome, Edge and Firefox were all fine, so it survived review, the
+ * page audit, and a production smoke sweep.
+ *
+ * A synchronous READ of a later-declared binding is worse: that one throws in
+ * every engine. src/three-tier-page.js (`_styled`) and public/forever.js
+ * (`BTC_USD`) both hit it and both carry a hand-written comment begging the next
+ * person not to reorder the file. This check enforces what those comments ask.
+ *
+ * The rule
+ * --------
+ * For every call made during module evaluation, walk the callee's SYNCHRONOUS
+ * prefix (everything up to its first `await`) and flag any reference to a
+ * module-level `let`/`const`/`class` declared after that call site. `var` and
+ * function declarations are hoisted and initialized, so they are exempt.
+ *
+ * The fix is always ordering, never a try/catch: move the bootstrap call below
+ * the declarations (see the "bootstrap (must run last)" blocks in
+ * src/avatar-page.js and src/three-tier-page.js), or move the declarations above
+ * the call. Do not rely on which engine checks when.
+ *
+ * Usage:
+ * node scripts/check-tdz-bootstrap.mjs # exits 1 on any finding
+ * node scripts/check-tdz-bootstrap.mjs --paths a.js b.js
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve, relative } from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { parse } from 'acorn';
+
+const ROOT = resolve(new URL('..', import.meta.url).pathname);
+
+// How deep to follow calls out of the bootstrap before giving up. The real
+// regression in src/three-tier-page.js was three frames down
+// (mount -> boot -> injectStyles), so a depth of 1 would have missed it.
+const MAX_CALL_DEPTH = 4;
+
+function tracked(patterns) {
+ return execFileSync('git', ['ls-files', ...patterns], { cwd: ROOT, encoding: 'utf8' })
+ .split('\n')
+ .filter(Boolean)
+ .map((p) => resolve(ROOT, p));
+}
+
+// ── AST helpers ───────────────────────────────────────────────────────
+
+/** Direct child nodes, in source order, so a traversal sees `a` before `await b` in `a = await b`. */
+function childNodes(node) {
+ const out = [];
+ for (const key of Object.keys(node)) {
+ if (key === 'type' || key === 'start' || key === 'end') continue;
+ const val = node[key];
+ if (Array.isArray(val)) {
+ for (const v of val) if (v && typeof v.type === 'string') out.push(v);
+ } else if (val && typeof val.type === 'string') {
+ out.push(val);
+ }
+ }
+ return out.sort((a, b) => a.start - b.start);
+}
+
+const FN_TYPES = new Set(['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression']);
+
+/** Every identifier a pattern binds (params, destructured locals). */
+function patternNames(node, into) {
+ if (!node) return into;
+ switch (node.type) {
+ case 'Identifier': into.add(node.name); break;
+ case 'ObjectPattern': for (const p of node.properties) patternNames(p.value || p.argument, into); break;
+ case 'ArrayPattern': for (const e of node.elements) patternNames(e, into); break;
+ case 'AssignmentPattern': patternNames(node.left, into); break;
+ case 'RestElement': patternNames(node.argument, into); break;
+ default: break;
+ }
+ return into;
+}
+
+/**
+ * Names declared inside a function body (its own scope). Approximated at
+ * function granularity rather than block granularity: a local that shadows a
+ * module binding suppresses the finding, which errs toward silence rather than
+ * toward a false accusation.
+ */
+function localNames(fn) {
+ const names = new Set();
+ for (const p of fn.params || []) patternNames(p, names);
+ if (fn.id?.name) names.add(fn.id.name);
+ const walk = (n) => {
+ for (const c of childNodes(n)) {
+ if (FN_TYPES.has(c.type)) {
+ if (c.id?.name) names.add(c.id.name);
+ continue; // a nested function's own locals belong to its scope
+ }
+ if (c.type === 'VariableDeclarator') patternNames(c.id, names);
+ if (c.type === 'ClassDeclaration' && c.id?.name) names.add(c.id.name);
+ walk(c);
+ }
+ };
+ walk(fn.body || fn);
+ return names;
+}
+
+/** True when this identifier is a name rather than a value reference (`o.avatar`, `{avatar: 1}`). */
+function isNonReference(node, parent) {
+ if (!parent) return false;
+ if (parent.type === 'MemberExpression' && parent.property === node && !parent.computed) return true;
+ if (parent.type === 'Property' && parent.key === node && !parent.computed) return true;
+ if (parent.type === 'MethodDefinition' && parent.key === node && !parent.computed) return true;
+ if (parent.type === 'LabeledStatement' || parent.type === 'BreakStatement' || parent.type === 'ContinueStatement') return true;
+ if (FN_TYPES.has(parent.type) && parent.id === node) return true;
+ return false;
+}
+
+// ── the check ─────────────────────────────────────────────────────────
+
+function analyze(file, src) {
+ let ast;
+ try {
+ ast = parse(src, { ecmaVersion: 'latest', sourceType: 'module', locations: true });
+ } catch {
+ return []; // not an ES module we can read; other checks own syntax errors
+ }
+
+ // Module-level lexical bindings (`let`/`const`/`class`). `var` and function
+ // declarations are hoisted AND initialized, so they can never be in a dead zone.
+ const lexical = new Map(); // name -> { start, line, kind }
+ // Module-level functions, so a bootstrap call can be followed into its body.
+ const functions = new Map(); // name -> fn node
+ for (const stmt of ast.body) {
+ const node = stmt.type === 'ExportNamedDeclaration' || stmt.type === 'ExportDefaultDeclaration'
+ ? stmt.declaration
+ : stmt;
+ if (!node) continue;
+ if (node.type === 'VariableDeclaration' && node.kind !== 'var') {
+ for (const d of node.declarations) {
+ for (const name of patternNames(d.id, new Set())) {
+ lexical.set(name, { start: node.start, line: node.loc.start.line, kind: node.kind });
+ }
+ }
+ for (const d of node.declarations) {
+ if (d.init && FN_TYPES.has(d.init.type) && d.id.type === 'Identifier') functions.set(d.id.name, d.init);
+ }
+ }
+ if (node.type === 'ClassDeclaration' && node.id?.name) {
+ lexical.set(node.id.name, { start: node.start, line: node.loc.start.line, kind: 'class' });
+ }
+ if (node.type === 'FunctionDeclaration' && node.id?.name) functions.set(node.id.name, node);
+ }
+ if (!lexical.size || !functions.size) return [];
+
+ const findings = [];
+
+ /**
+ * Walk a function's synchronous prefix: everything evaluated before its first
+ * `await`. Returns once an await is reached, because module evaluation has
+ * completed by the time the continuation runs and every binding is live.
+ */
+ function scanSync(fn, callSite, depth, seen, chain) {
+ if (depth > MAX_CALL_DEPTH || seen.has(fn)) return;
+ seen.add(fn);
+ const locals = localNames(fn);
+ let stopped = false;
+
+ const walk = (node, parent) => {
+ if (stopped) return;
+ if (node.type === 'AwaitExpression') { stopped = true; return; }
+ // A nested function body is not part of this synchronous prefix; it runs
+ // whenever its callback fires, long after module evaluation.
+ if (FN_TYPES.has(node.type) && node !== fn) return;
+
+ if (node.type === 'Identifier' && !isNonReference(node, parent) && !locals.has(node.name)) {
+ const decl = lexical.get(node.name);
+ if (decl && decl.start > callSite.start) {
+ const write = parent?.type === 'AssignmentExpression' && parent.left === node;
+ findings.push({
+ file,
+ name: node.name,
+ kind: decl.kind,
+ useLine: node.loc.start.line,
+ declLine: decl.line,
+ callLine: callSite.loc.start.line,
+ callName: callSite.name,
+ write,
+ chain: chain.join(' -> '),
+ });
+ }
+ }
+
+ for (const c of childNodes(node)) {
+ if (stopped) return;
+ walk(c, node);
+ // Follow a synchronous call into a module-level function.
+ if (c.type === 'CallExpression' && c.callee.type === 'Identifier' && !locals.has(c.callee.name)) {
+ const target = functions.get(c.callee.name);
+ if (target) scanSync(target, callSite, depth + 1, seen, [...chain, c.callee.name]);
+ }
+ }
+ };
+ walk(fn.body || fn, null);
+ seen.delete(fn);
+ }
+
+ // Every call made during module evaluation, i.e. at the top level of the
+ // module body rather than inside a function.
+ for (const stmt of ast.body) {
+ if (FN_TYPES.has(stmt.type) || stmt.type === 'ImportDeclaration') continue;
+ const collect = (node) => {
+ if (FN_TYPES.has(node.type)) return; // deferred, not module-evaluation time
+ if (node.type === 'CallExpression' && node.callee.type === 'Identifier') {
+ const fn = functions.get(node.callee.name);
+ if (fn) {
+ scanSync(fn, { start: node.start, loc: node.loc, name: node.callee.name }, 1, new Set(), [node.callee.name]);
+ }
+ }
+ for (const c of childNodes(node)) collect(c);
+ };
+ collect(stmt);
+ }
+
+ // One finding per binding per file; the first use is the one to fix.
+ const byName = new Map();
+ for (const f of findings) if (!byName.has(f.name)) byName.set(f.name, f);
+ return [...byName.values()];
+}
+
+// ── run ───────────────────────────────────────────────────────────────
+
+const argv = process.argv.slice(2);
+const pathsFlag = argv.indexOf('--paths');
+const files = pathsFlag !== -1
+ ? argv.slice(pathsFlag + 1).filter((a) => !a.startsWith('--')).map((p) => resolve(ROOT, p))
+ : tracked(['src/**/*.js', 'public/**/*.js']);
+
+const all = [];
+for (const file of files) {
+ let src;
+ try { src = readFileSync(file, 'utf8'); } catch { continue; }
+ if (!src.includes('let ') && !src.includes('const ')) continue;
+ all.push(...analyze(relative(ROOT, file), src));
+}
+
+if (!all.length) {
+ console.log(`check:tdz-bootstrap: no bootstrap-before-state ordering in ${files.length} browser module(s)`);
+ process.exit(0);
+}
+
+console.error(`\ncheck:tdz-bootstrap: ${all.length} module-evaluation reference(s) to a binding declared later:\n`);
+for (const f of all) {
+ const how = f.write ? 'assigns' : 'reads';
+ console.error(` ${f.file}:${f.useLine} ${how} \`${f.name}\` (${f.kind} declared at line ${f.declLine})`);
+ console.error(` reached synchronously from ${f.callName}() at line ${f.callLine} [${f.chain}]`);
+}
+console.error(`
+Each of these runs during module evaluation, while the binding is still in its
+temporal dead zone. A synchronous READ throws in every engine. An ASSIGNMENT
+throws only in JavaScriptCore, which checks the target's dead zone before it
+evaluates the right-hand side, so the page dies in Safari on iOS and macOS while
+Chrome and Firefox stay green.
+
+Fix by ordering, not by catching. Move the bootstrap call below the
+declarations, as src/avatar-page.js and src/three-tier-page.js both do:
+
+ let avatar = null; // every binding the entry point writes
+
+ // ── bootstrap (must run last) ──
+ init().catch(renderError);
+`);
+process.exit(1);