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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(deploy): import every API module before submitting, so a load-time throw fails the deploy instead of 500ing a route
nirholasc6108b0546d8
diff --git a/CLAUDE.md b/CLAUDE.mdindex 3143229a9..8010e0009 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -298,7 +298,7 @@ Remember stop-and-ask gate 2: production deploys need owner approval unless the`check:conflicts` → `check:browser-graph` → `check:tdz-bootstrap` → `ensure:avatar-studio` → `build:info:snapshot` → `docs:freshness` → `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. `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. `docs:freshness` measures documentation drift against git history and writes `public/docs-freshness.json` plus its summary, so it must run before `build` copies `public/` into `dist/`; running it here is what keeps `/docs/freshness` and every docs-page freshness badge describing the commit actually deployed instead of whenever someone last ran it by hand. 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), then `check:gcloudignore`, then `audit:deploy` (no committed symlinks, no unsatisfied peer deps, no undeclared `api/` imports, decoder assets present, and an installed `node_modules` that matches `package-lock.json`), then the same `gcloud builds submit --config server/cloudbuild.yaml --region us-central1 --project aerial-vehicle-466722-p5`. `check:gcloudignore` simulates the upload and fails when a file the server imports at runtime would be excluded from the build context: an omitted `services/home-relay/src/token.js` shipped revision 00412 answering `/api/healthz` with `ERR_MODULE_NOT_FOUND` on every request (2026-09-04). The lockfile match exists because the image installs from the lockfile while every local test, and every deploy worktree that hardlinks this `node_modules`, runs whatever is on disk: a dependency bump nobody reinstalled shipped `@x402/extensions` 2.25.0 untested and every paid x402 route answered 500 on import (2026-09-17). If it fails, run `npm install`, then `npm test`, before deploying. 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`.+3. **Submit: `npm run deploy:gcp:submit`.** That is `db:check` (exit 4 if any migration is pending), then `check:gcloudignore`, then `audit:deploy` (no committed symlinks, no unsatisfied peer deps, no undeclared `api/` imports, decoder assets present, and an installed `node_modules` that matches `package-lock.json`), then `check:api-imports` (imports every module under `api/` and fails on any that throws while loading, since the server imports a handler on first hit and a load-time throw is a 500 on every request to that route rather than a build error), then the same `gcloud builds submit --config server/cloudbuild.yaml --region us-central1 --project aerial-vehicle-466722-p5`. `check:gcloudignore` simulates the upload and fails when a file the server imports at runtime would be excluded from the build context: an omitted `services/home-relay/src/token.js` shipped revision 00412 answering `/api/healthz` with `ERR_MODULE_NOT_FOUND` on every request (2026-09-04). The lockfile match exists because the image installs from the lockfile while every local test, and every deploy worktree that hardlinks this `node_modules`, runs whatever is on disk: a dependency bump nobody reinstalled shipped `@x402/extensions` 2.25.0 untested and every paid x402 route answered 500 on import (2026-09-17). If it fails, run `npm install`, then `npm test`, before deploying. 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/docs/ops/gcp-production.md b/docs/ops/gcp-production.mdindex cf17977a2..fe1fbef3c 100644--- a/docs/ops/gcp-production.md+++ b/docs/ops/gcp-production.md@@ -268,6 +268,27 @@ npm run db:check # what deploy:gcp and deploy:gcp:submit run: exits 4 if anybehind the code by exactly that list until the failing file is fixed with aNEW migration and the run drains the rest.+**Dependency and import gates.** `deploy:gcp:submit` runs two more checks after+`db:check`, both added after the 2026-09-18 outage, when two merged dependency+bumps took the paid x402 surface down on import:++```bash+npm run audit:deploy # includes: installed node_modules must match package-lock.json+npm run check:api-imports # imports every module under api/, fails on any that throws while loading+```++- The image installs from `package-lock.json`, but local tests and every deploy+ worktree (which hardlinks `node_modules`) run whatever is on disk. If the two+ differ, a green `npm test` says nothing about what production will boot. When+ `audit:deploy` reports drift, run `npm install`, then `npm test`.+- The server imports a handler the first time its route is hit, so a module+ that throws while loading is not a build error. It is a 500 on every request+ to that route. `check:api-imports` needs no environment and groups failures+ by error, so one broken shared module reads as one finding. Scope it with a+ path while debugging: `node scripts/check-api-imports.mjs api/x402`.+- A dependency bump that changes an API is fixed in code or pinned back in+ `package.json` and held in `.github/dependabot.yml`. It is never waved through.+- Lockfile unchanged → layer cache skips the workspace `npm ci`: **~3–5 min**.- Lockfile changed → full install: **~12 min**.- If the pipeline's deploy step fails on IAM (see above), deploy the pusheddiff --git a/package.json b/package.jsonindex 1f2591eff..d6fd79b0b 100644--- a/package.json+++ b/package.json@@ -395,6 +395,7 @@"check:model-viewer": "node scripts/check-model-viewer-version.mjs","check:secrets": "node scripts/check-secrets.mjs","check:gcloudignore": "node scripts/check-gcloudignore.mjs",+ "check:api-imports": "node scripts/check-api-imports.mjs","check:home-voice": "node scripts/check-home-voice.mjs","check:evm-rpc": "node --env-file=.env scripts/probe-evm-rpc.mjs --chain 1 --ens","awal:pin": "node scripts/update-awal-version.mjs",@@ -415,7 +416,7 @@"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 deploy:gcp:submit && npm run deploy:gcp:purge-cdn && npm run smoke:prod","deploy:gcp:full": "npm run build:gcp && npm run deploy:gcp",- "deploy:gcp:submit": "npm run db:check && npm run check:gcloudignore && npm run audit:deploy && gcloud builds submit --config server/cloudbuild.yaml --region us-central1 --project aerial-vehicle-466722-p5",+ "deploy:gcp:submit": "npm run db:check && npm run check:gcloudignore && npm run audit:deploy && npm run check:api-imports && gcloud builds submit --config server/cloudbuild.yaml --region us-central1 --project aerial-vehicle-466722-p5","deploy:gcp:purge-cdn": "gcloud compute url-maps invalidate-cdn-cache three-ws-lb --path '/*' --project aerial-vehicle-466722-p5","postversion": "git push threews HEAD && git push threews --tags","validate:cards": "node scripts/validate-agent-cards.mjs",diff --git a/scripts/check-api-imports.mjs b/scripts/check-api-imports.mjsnew file mode 100644index 000000000..0ac13ac03--- /dev/null+++ b/scripts/check-api-imports.mjs@@ -0,0 +1,116 @@+#!/usr/bin/env node+/**+ * API import sweep: does every module under api/ load?+ *+ * Why this exists+ * ---------------+ * The Cloud Run server imports a handler the first time its route is hit, so a+ * module that throws while loading is not a build error and not a boot error.+ * It is a 500 on every request to that route, found later in stderr. One bad+ * shared module takes down everything that imports it:+ *+ * · 2026-09-18: @x402/extensions 2.25.0 made `origin` a required option and+ * throws at construction without it. api/_lib/siwx-server.js built the+ * extension at module load, so every paidEndpoint() route, /api/mcp, the+ * facilitator and /.well-known/x402 answered 500.+ * · Same day, same dependabot batch: @bnb-chain/mpp 0.7.0 dropped its+ * './b402/server' export, so api/_lib/bnb/mpp-server.js failed with+ * ERR_PACKAGE_PATH_NOT_EXPORTED and the BSC rail went with it.+ *+ * Both were invisible to a test suite running on a stale node_modules, and both+ * are caught here in under a minute regardless of cause: a renamed export, a+ * deleted file, a dependency that changed shape, a top-level throw.+ *+ * What it does+ * ------------+ * Imports every api/**∕*.js (tests and vitest configs excluded) in this process+ * and reports each one that throws, grouped by error so one root cause reads as+ * one finding. Handlers read their configuration per request, not at load, so+ * this needs no environment: it passes with no `.env` at all, and a module that+ * starts demanding env at import time is itself a finding.+ *+ * Usage:+ * node scripts/check-api-imports.mjs # whole api/ tree+ * node scripts/check-api-imports.mjs api/x402 # one subtree+ *+ * Exit code 0 when everything loads, 1 otherwise. Wired into+ * `npm run deploy:gcp:submit` ahead of the Cloud Build upload.+ */+import { globSync } from 'glob';+import { dirname, relative, resolve } from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';++const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');++export function listApiModules({ root = ROOT, subtree = 'api' } = {}) {+ return globSync('**/*.js', {+ cwd: resolve(root, subtree),+ absolute: true,+ ignore: ['**/*.test.js', '**/vitest.config.js', '**/node_modules/**'],+ }).sort();+}++function describeFailure(err) {+ const label = err?.code || err?.name || 'Error';+ const firstLine = String(err?.message ?? err).split('\n')[0];+ return `${label}: ${firstLine}`;+}++/**+ * Imports each file and returns the failures grouped by error text:+ * `[{ error, files: [...] }]`, most widespread first.+ */+export async function findBrokenImports(files, { root = ROOT } = {}) {+ const byError = new Map();+ for (const file of files) {+ try {+ await import(pathToFileURL(file).href);+ } catch (err) {+ const error = describeFailure(err);+ if (!byError.has(error)) byError.set(error, []);+ byError.get(error).push(relative(root, file));+ }+ }+ return [...byError.entries()]+ .map(([error, failed]) => ({ error, files: failed }))+ .sort((a, b) => b.files.length - a.files.length);+}++const isMain = process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url);+if (isMain) {+ const start = Date.now();+ const subtree = process.argv[2] || 'api';+ const files = listApiModules({ subtree });+ if (!files.length) {+ console.error(`[check:api-imports] FAIL: no modules found under ${subtree}/`);+ process.exit(1);+ }++ // Modules log while loading. Keep that out of the report so a failure is the+ // only thing on screen.+ const quiet = () => {};+ const original = { log: console.log, info: console.info, warn: console.warn, error: console.error };+ Object.assign(console, { log: quiet, info: quiet, warn: quiet, error: quiet });+ const broken = await findBrokenImports(files);+ Object.assign(console, original);++ const elapsed = ((Date.now() - start) / 1000).toFixed(1);+ if (broken.length) {+ const total = broken.reduce((sum, group) => sum + group.files.length, 0);+ console.error(+ `[check:api-imports] FAIL: ${total} of ${files.length} module(s) under ${subtree}/ throw while loading. Each one is a 500 on every request to its route:`,+ );+ for (const { error, files: failed } of broken) {+ console.error(`\n ${failed.length}x ${error}`);+ for (const file of failed.slice(0, 8)) console.error(` ${file}`);+ if (failed.length > 8) console.error(` ... and ${failed.length - 8} more`);+ }+ console.error(+ `\n[check:api-imports] failed in ${elapsed}s. A dependency error usually means node_modules is behind package-lock.json (run \`npm install\`) or a bump changed an API.`,+ );+ process.exit(1);+ }+ console.log(`[check:api-imports] clean in ${elapsed}s: all ${files.length} module(s) under ${subtree}/ load`);+ // Loaded modules can hold timers and sockets open; the verdict is in, so leave.+ process.exit(0);+}diff --git a/tests/check-api-imports.test.js b/tests/check-api-imports.test.jsnew file mode 100644index 000000000..3c26d537d--- /dev/null+++ b/tests/check-api-imports.test.js@@ -0,0 +1,72 @@+// Guards the import sweep that gates `npm run deploy:gcp:submit`. A module that+// throws while loading is a 500 on every request to its route, not a build+// error: that is how @x402/extensions 2.25.0 and @bnb-chain/mpp 0.7.0 took the+// paid x402 surface down on 2026-09-18 while the build stayed green.++import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { describe, it, expect, afterEach } from 'vitest';+import { listApiModules, findBrokenImports } from '../scripts/check-api-imports.mjs';++const scratchDirs = [];+function scratchTree(files) {+ const root = mkdtempSync(join(tmpdir(), 'check-api-imports-'));+ scratchDirs.push(root);+ for (const [path, source] of Object.entries(files)) {+ mkdirSync(join(root, path, '..'), { recursive: true });+ writeFileSync(join(root, path), source);+ }+ return root;+}+afterEach(() => {+ while (scratchDirs.length) rmSync(scratchDirs.pop(), { recursive: true, force: true });+});++describe('listApiModules', () => {+ it('lists handlers and shared modules but not tests or vitest configs', () => {+ const root = scratchTree({+ 'api/echo.js': 'export default 1;\n',+ 'api/_lib/shared.js': 'export default 1;\n',+ 'api/_lib/shared.test.js': 'export default 1;\n',+ 'api/vitest.config.js': 'export default {};\n',+ });+ const listed = listApiModules({ root }).map((f) => f.slice(root.length + 1));+ expect(listed).toEqual(['api/_lib/shared.js', 'api/echo.js']);+ });+});++describe('findBrokenImports', () => {+ it('passes a tree where every module loads', async () => {+ const root = scratchTree({ 'api/ok.js': 'export const ok = true;\n' });+ expect(await findBrokenImports(listApiModules({ root }), { root })).toEqual([]);+ });++ it('reports a module that throws at load, and every module that imports it, as one finding', async () => {+ const root = scratchTree({+ 'api/_lib/extension.js': "throw new Error('Invalid origin: \"undefined\" is not a valid URL');\n",+ 'api/paid-a.js': "import './_lib/extension.js';\nexport default 1;\n",+ 'api/paid-b.js': "import './_lib/extension.js';\nexport default 1;\n",+ 'api/free.js': 'export default 1;\n',+ });+ const broken = await findBrokenImports(listApiModules({ root }), { root });+ expect(broken).toEqual([+ {+ error: 'Error: Invalid origin: "undefined" is not a valid URL',+ files: ['api/_lib/extension.js', 'api/paid-a.js', 'api/paid-b.js'],+ },+ ]);+ });++ it('reports an import of a package subpath that no longer exists', async () => {+ const root = scratchTree({+ 'api/rail.js': "import 'vitest/this-subpath-was-removed';\nexport default 1;\n",+ });+ const broken = await findBrokenImports(listApiModules({ root }), { root });+ expect(broken).toHaveLength(1);+ expect(broken[0].files).toEqual(['api/rail.js']);+ // Node reports ERR_PACKAGE_PATH_NOT_EXPORTED; vitest's resolver words the+ // same failure as "is not exported". Either way the subpath is named.+ expect(broken[0].error).toMatch(/this-subpath-was-removed/);+ });+});