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): run the TDZ bootstrap guard in the deploy build, with a test

nirholas94e398305aec
diff --git a/CLAUDE.md b/CLAUDE.md
index 63b03f588..429564883 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -289,9 +289,9 @@ Remember stop-and-ask gate 2: production deploys need owner approval unless the
1. **Prepare a CLEAN worktree: `npm run prep:worktree -- --apply`.** That is the whole step; it encodes everything below, and running it beats staging by hand. Plan first with a bare `npm run prep:worktree` (writes nothing), `--path <dir>` to stage your own tree instead of colliding with a concurrent agent on the default `/workspaces/.deploy-wt`, `--force` to replace an existing tree (refused if it holds uncommitted work). What it does: `git worktree add --detach <path> HEAD`, then hardlinks THREE artifacts with `cp -al` on the same filesystem (not just the first): `node_modules`, `chat/node_modules`, and `character-studio/build`, plus copies BOTH `.env` and `.env.local`. Omitting either nested one kills the build minutes in: an OOM exit 144 on the avatar-studio rebuild, or `Cannot find package '@sveltejs/vite-plugin-svelte'` on the chat build. A nested artifact that is missing from the source tree is BUILT first (`deps:chat`, `build:avatar-studio`) rather than skipped, which is the failure a hand-run `cp -al` produces on a machine that has never deployed. `.env.local` is the one that carries `DATABASE_URL`, and without it step 3's migration gate cannot read the schema state and refuses to submit. **Remove it when the deploy lands** (`git worktree remove --force <path>`); that is what step 0 exists to clean up after. See `docs/ops/gcp-production.md`.
2. **Build: `npm run build:gcp`.** ORDER IS LOAD-BEARING and `build:gcp` already encodes it. Never hand-run the steps in a different order. The full chain, in order:
- `check:conflicts` → `check:browser-graph` → `ensure:avatar-studio` → `build:info:snapshot` → `build:lib:full` (the UMD lib) → `build:avatar-sdk` → `build:chat` → `build` (the frontend `vite build`) → `publish:lib` → `build:info` → `check:dist` → `check:pages`
+ `check:conflicts` → `check:browser-graph` → `check:tdz-bootstrap` → `ensure:avatar-studio` → `build:info:snapshot` → `build:lib:full` (the UMD lib) → `build:avatar-sdk` → `build:chat` → `build` (the frontend `vite build`) → `publish:lib` → `build:info` → `check:dist` → `check:pages`
- Why the order is load-bearing: `check:conflicts` runs first so an unresolved merge-conflict marker fails in seconds instead of after a full build. `build:lib:full` writes `dist-lib/agent-3d.js`, `build:avatar-sdk` copies that bundle into `avatar-sdk/dist/index.mjs`, and the frontend `vite build` resolves `avatar-sdk/src/agent.js` against it, so both must come BEFORE `build`; skipping them shipped whatever stale `avatar-sdk/dist` the build machine happened to hold, and in a fresh worktree failed the build outright with `Could not resolve "../dist/index.mjs"` (2026-08-17). The frontend `vite build` runs with `emptyOutDir`, so it WIPES `dist/` and everything that writes into `dist/` must come after it: that is why `publish:lib`, which mirrors the UMD lib into `dist/`, follows `build` rather than sitting next to `build:lib:full`, and `check:dist` fails without that bundle present. `ensure:avatar-studio` consumes `character-studio/build` and `build:chat` consumes `chat/node_modules`, which is exactly why step 1 stages worktree artifacts. Do NOT hand-run `build:vercel` as the frontend build: it builds the SDK/lib sub-artifacts, NOT the static HTML pages, so `dist/` ends up without `/`, `/create`, etc. and `check:dist` fails.
+ Why the order is load-bearing: `check:conflicts` runs first so an unresolved merge-conflict marker fails in seconds instead of after a full build. `check:tdz-bootstrap` sits beside it for the same reason: it refuses a browser module whose top-level bootstrap call runs above the `let`s that call writes. JavaScriptCore checks an assignment target's temporal dead zone before evaluating the right-hand side and V8 does not, so that ordering ships green on Chrome and throws "Cannot access uninitialized variable." on every Safari, which is how `/avatars/:id` went dead on iOS and macOS while every desktop check passed. `build:lib:full` writes `dist-lib/agent-3d.js`, `build:avatar-sdk` copies that bundle into `avatar-sdk/dist/index.mjs`, and the frontend `vite build` resolves `avatar-sdk/src/agent.js` against it, so both must come BEFORE `build`; skipping them shipped whatever stale `avatar-sdk/dist` the build machine happened to hold, and in a fresh worktree failed the build outright with `Could not resolve "../dist/index.mjs"` (2026-08-17). The frontend `vite build` runs with `emptyOutDir`, so it WIPES `dist/` and everything that writes into `dist/` must come after it: that is why `publish:lib`, which mirrors the UMD lib into `dist/`, follows `build` rather than sitting next to `build:lib:full`, and `check:dist` fails without that bundle present. `ensure:avatar-studio` consumes `character-studio/build` and `build:chat` consumes `chat/node_modules`, which is exactly why step 1 stages worktree artifacts. Do NOT hand-run `build:vercel` as the frontend build: it builds the SDK/lib sub-artifacts, NOT the static HTML pages, so `dist/` ends up without `/`, `/create`, etc. and `check:dist` fails.
3. **Submit: `npm run deploy:gcp:submit`.** That is `db:check` (exit 4 if any migration is pending) followed by the same `gcloud builds submit --config server/cloudbuild.yaml --region us-central1 --project aerial-vehicle-466722-p5`. Do NOT hand-run the bare `gcloud builds submit`: it is the only step that would have caught new code shipping over an old schema, and skipping it is how production ended up serving handlers that query columns their migration never applied (`column "blocks_behind" does not exist`, live on 2026-08-14). If the gate says migrations are pending, apply them first (`npm run db:status`, then `npm run db:migrate`); if it says `DATABASE_URL is not set`, step 1 did not copy `.env.local`. EVERY cloudbuild config must pin `serviceAccount: .../three-ws-build@...` (the default compute SA was deleted), and manual submits need `--substitutions=SHORT_SHA=manual$(date +%s)` when the config tags images with `$SHORT_SHA`.
4. **Purge CDN: `npm run deploy:gcp:purge-cdn`.** The purge is synchronous on purpose. Do not re-add `--async`, or post-deploy checks read stale edge content and report phantom failures.
5. **Verify the deploy landed.** `curl -s https://three.ws/api/version` returns the live commit SHA + Cloud Run revision, and `npm run smoke:prod` sweeps every page declared in `data/pages.json` against the live site (`deploy:gcp` runs it automatically after the purge).
diff --git a/package.json b/package.json
index 77ac84904..4a6655797 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: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",
+ "gate": "npm run check:conflicts && npm run check:claude && npm run check:vendored && npm run check:tdz-bootstrap && 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",
@@ -212,6 +212,7 @@
"audit:links": "node scripts/audit-links.mjs",
"audit:rig-coverage": "node scripts/audit-rig-coverage.mjs",
"audit:service-wallets": "node --env-file=.env scripts/audit-service-wallets.mjs",
+ "economy:wallets": "node --env-file=.env.local scripts/economy-wallets.mjs",
"audit:wallet-flows": "node --env-file=.env scripts/audit-wallet-flows.mjs",
"audit:llm-metering": "node scripts/audit-llm-metering.mjs",
"check:cron-drift": "node scripts/check-cron-drift.mjs",
@@ -326,7 +327,6 @@
"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",
@@ -338,7 +338,7 @@
"deploy": "npm run build:all && npm run check:dist && vercel --local-config vercel.json --prod",
"build:info": "node scripts/write-build-info.mjs",
"build:info:snapshot": "node scripts/write-build-info.mjs --snapshot",
- "build:gcp": "npm run check:conflicts && npm run check:browser-graph && npm run ensure:avatar-studio && npm run build:info:snapshot && npm run build:lib:full && npm run build:avatar-sdk && npm run build:chat && npm run build && npm run publish:lib && npm run build:info && npm run check:dist && npm run check:pages",
+ "build:gcp": "npm run check:conflicts && npm run check:browser-graph && npm run check:tdz-bootstrap && npm run ensure:avatar-studio && npm run build:info:snapshot && npm run build:lib:full && npm run build:avatar-sdk && npm run build:chat && npm run build && npm run publish:lib && npm run build:info && npm run check:dist && npm run check:pages",
"ensure:avatar-studio": "test -f character-studio/build/index.html || npm run build:avatar-studio",
"deploy:gcp": "npm run check:dist && npm run check:pages && npm run db:check && gcloud builds submit --config server/cloudbuild.yaml --region us-central1 --project aerial-vehicle-466722-p5 && npm run deploy:gcp:purge-cdn && npm run smoke:prod",
"deploy:gcp:full": "npm run build:gcp && npm run deploy:gcp",
@@ -378,6 +378,7 @@
"clean:worktrees": "node scripts/clean-deploy-worktrees.mjs",
"prep:worktree": "node scripts/prepare-deploy-worktree.mjs",
"check:browser-graph": "node scripts/check-browser-graph.mjs",
+ "check:tdz-bootstrap": "node scripts/check-tdz-bootstrap.mjs",
"prove:guards": "node scripts/prove-guards.mjs",
"prove:a2a-spend": "node scripts/a2a-spend-hardening-proof.mjs",
"capture:docs-world": "node scripts/capture-docs-media.mjs",
diff --git a/scripts/check-tdz-bootstrap.mjs b/scripts/check-tdz-bootstrap.mjs
index db786a6a7..dde4e6add 100644
--- a/scripts/check-tdz-bootstrap.mjs
+++ b/scripts/check-tdz-bootstrap.mjs
@@ -50,6 +50,7 @@
import { readFileSync } from 'node:fs';
import { resolve, relative } from 'node:path';
+import { pathToFileURL } from 'node:url';
import { execFileSync } from 'node:child_process';
import { parse } from 'acorn';
@@ -138,7 +139,7 @@ function isNonReference(node, parent) {
// ── the check ─────────────────────────────────────────────────────────
-function analyze(file, src) {
+export function analyze(file, src) {
let ast;
try {
ast = parse(src, { ecmaVersion: 'latest', sourceType: 'module', locations: true });
@@ -250,6 +251,10 @@ function analyze(file, src) {
// ── run ───────────────────────────────────────────────────────────────
+// Importable for tests (`analyze` above); the sweep runs only as a command.
+if (import.meta.url === pathToFileURL(process.argv[1] || '').href) main();
+
+function main() {
const argv = process.argv.slice(2);
const pathsFlag = argv.indexOf('--paths');
const files = pathsFlag !== -1
@@ -291,3 +296,4 @@ declarations, as src/avatar-page.js and src/three-tier-page.js both do:
init().catch(renderError);
`);
process.exit(1);
+}
diff --git a/tests/check-tdz-bootstrap.test.js b/tests/check-tdz-bootstrap.test.js
new file mode 100644
index 000000000..a5fe9a5e1
--- /dev/null
+++ b/tests/check-tdz-bootstrap.test.js
@@ -0,0 +1,146 @@
+/**
+ * scripts/check-tdz-bootstrap.mjs: the guard against a module bootstrapping
+ * itself above the state it writes.
+ *
+ * The three cases below are the ones that actually shipped:
+ * - src/avatar-page.js `avatar = await fetchAvatar(id)` before `let avatar`,
+ * which threw only in JavaScriptCore and took every /avatars/:id page down
+ * in Safari on iOS and macOS while Chrome stayed green.
+ * - src/three-tier-page.js `_styled` read three frames below mount().
+ * - public/forever.js `BTC_USD` read from a top-level render call.
+ *
+ * The "stays quiet" half matters just as much: a checker wired into the deploy
+ * path earns its keep only if it never blocks a correct build.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { analyze } from '../scripts/check-tdz-bootstrap.mjs';
+
+const names = (src) => analyze('t.js', src).map((f) => f.name).sort();
+
+describe('check:tdz-bootstrap catches what shipped', () => {
+ it('flags an assignment to a let declared below the bootstrap (the Safari-only case)', () => {
+ const findings = analyze('avatar-page.js', `
+ init().catch(renderError);
+ async function init() {
+ avatar = await fetchAvatar(id);
+ }
+ let avatar = null;
+ `);
+ expect(findings).toHaveLength(1);
+ expect(findings[0].name).toBe('avatar');
+ expect(findings[0].write).toBe(true);
+ expect(findings[0].kind).toBe('let');
+ });
+
+ it('flags a synchronous read three calls below the bootstrap', () => {
+ const findings = analyze('three-tier-page.js', `
+ mount();
+ function mount() { boot(); }
+ function boot() { injectStyles(); }
+ function injectStyles() { if (_styled) return; }
+ let _styled = false;
+ `);
+ expect(findings.map((f) => f.name)).toEqual(['_styled']);
+ expect(findings[0].write).toBe(false);
+ expect(findings[0].chain).toBe('mount -> boot -> injectStyles');
+ });
+
+ it('flags a read of a const declared below the bootstrap', () => {
+ expect(names(`
+ renderFeeEstimate();
+ function renderFeeEstimate() { return BTC_USD * 2; }
+ const BTC_USD = 100;
+ `)).toEqual(['BTC_USD']);
+ });
+
+ it('flags a class declared below the bootstrap', () => {
+ expect(names(`
+ boot();
+ function boot() { return new Engine(); }
+ class Engine {}
+ `)).toEqual(['Engine']);
+ });
+
+ it('reports the call site and both line numbers so the fix is obvious', () => {
+ const [f] = analyze('t.js', 'init();\nfunction init() { avatar = 1; }\nlet avatar;');
+ expect(f).toMatchObject({ callName: 'init', callLine: 1, useLine: 2, declLine: 3 });
+ });
+});
+
+describe('check:tdz-bootstrap stays quiet on correct code', () => {
+ it('accepts the bootstrap moved below the declarations (the fix)', () => {
+ expect(names(`
+ let avatar = null;
+ async function init() { avatar = await fetchAvatar(id); }
+ init().catch(renderError);
+ `)).toEqual([]);
+ });
+
+ it('accepts a reference that only runs after an await', () => {
+ expect(names(`
+ init();
+ async function init() {
+ const rec = await fetchAvatar(id);
+ avatar = rec;
+ }
+ let avatar = null;
+ `)).toEqual([]);
+ });
+
+ it('accepts a deferred bootstrap, because the callback runs after evaluation', () => {
+ expect(names(`
+ document.addEventListener('DOMContentLoaded', () => init());
+ function init() { avatar = 1; }
+ let avatar = null;
+ `)).toEqual([]);
+ });
+
+ it('accepts var and function declarations, which are hoisted and initialized', () => {
+ expect(names(`
+ init();
+ function init() { avatar = 1; return helper(); }
+ var avatar = null;
+ function helper() { return 1; }
+ `)).toEqual([]);
+ });
+
+ it('does not confuse a local that shadows a module binding', () => {
+ expect(names(`
+ init();
+ function init() { let avatar = 1; return avatar; }
+ let avatar = null;
+ `)).toEqual([]);
+ });
+
+ it('does not confuse a property that shares a binding name', () => {
+ expect(names(`
+ init();
+ function init() { return rec.avatar + obj[0].avatar; }
+ let avatar = null;
+ `)).toEqual([]);
+ });
+
+ it('does not flag a binding declared above the bootstrap', () => {
+ expect(names(`
+ let avatar = null;
+ init();
+ function init() { avatar = 1; }
+ `)).toEqual([]);
+ });
+
+ it('does not flag a body that only runs when the function is called later', () => {
+ expect(names(`
+ export function init() { avatar = 1; }
+ let avatar = null;
+ `)).toEqual([]);
+ });
+});
+
+describe('the shipped browser modules stay clean', () => {
+ it('reports nothing for the studio page that regressed', async () => {
+ const { readFileSync } = await import('node:fs');
+ const src = readFileSync(new URL('../src/avatar-page.js', import.meta.url), 'utf8');
+ expect(analyze('src/avatar-page.js', src)).toEqual([]);
+ });
+});