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
perf(agents): halve the per-session CLAUDE.md load by moving deploy, playbook, docs and standards detail into on-demand skills, and trim subagent and read costs
nirholas03cba0287013
diff --git a/.claude/settings.json b/.claude/settings.jsonindex b03e55a17..7379764d8 100644--- a/.claude/settings.json+++ b/.claude/settings.json@@ -4,6 +4,15 @@"Bash(node --check *)","Bash(npx vitest run *)","Bash(npx prettier --check *)"+ ],+ "deny": [+ "Read(./dist/**)",+ "Read(./dist-lib/**)",+ "Read(./node_modules/**)",+ "Read(./**/node_modules/**)",+ "Read(./package-lock.json)",+ "Read(./**/*.glb)",+ "Read(./.claude/worktrees/**)"]},"enabledPlugins": {@@ -23,7 +32,9 @@"autoCompactWindow": 200000,"env": {"BASH_MAX_OUTPUT_LENGTH": "20000",- "CLAUDE_CODE_SUBAGENT_MODEL": "sonnet"+ "CLAUDE_CODE_SUBAGENT_MODEL": "sonnet",+ "CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION": "false",+ "CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS": "20000"},"model": "sonnet"}diff --git a/.claude/skills/changelog-and-docs/SKILL.md b/.claude/skills/changelog-and-docs/SKILL.mdnew file mode 100644index 000000000..ee9e695be--- /dev/null+++ b/.claude/skills/changelog-and-docs/SKILL.md@@ -0,0 +1,38 @@+---+name: changelog-and-docs+description: Rules for the user-visible changelog entry and the feature documentation every change ships with (pages.json, READMEs, STRUCTURE.md, docs/, specs/, audit:docs).+when_to_use: When finishing any feature, fix, SDK or page that users or developers will notice, and before claiming a task done.+---++# Changelog: every user-visible change gets an entry++The three.ws community follows the public changelog (three.ws/changelog, RSS, JSON, Telegram). Keep it alive:++- **New page?** Nothing extra: the `added` date in `data/pages.json` feeds the changelog automatically.+- **Everything else users would notice** (feature, improvement, fix, SDK release, security work): append an entry to `data/changelog.json` with date, community-readable title + summary (plain language, no commit jargon), and tags from: feature, improvement, fix, sdk, infra, docs, security. Optional `link` must be a live page path.+- `npm run build:pages` regenerates CHANGELOG.md, public/changelog.json, and public/changelog.xml. It also validates your entry and fails the build on a malformed one.+- **Delivery to the community is automatic.** `/api/cron/changelog-push` (Cloud Scheduler, every 20 min) reads the feed baked into the running image, diffs it against DB state (`app_settings`), and posts anything new to two lanes: the community Telegram channel (`TELEGRAM_CHANGELOG_CHAT_ID`, @three_ws) gets every entry, and a reply thread on @trythreews (`pushXLane`) gets every entry that passes `data/changelog-x-filter.json`. That filter keeps a public, unattended feed free of wallet and payment internals, keys, outages, security work, other coins, and bare fixes; extend it there, with a reason, rather than in code. X was retired on 2026-07-18 and turned back on by the owner on 2026-09-24. The three reviewed feature posts a day are a separate pipeline (`docs/x-content-pipeline.md`). An entry goes out on its own shortly after the deploy that ships it; there is no manual push step. Credentials live on the Cloud Run service. Do NOT run `npm run changelog:push` / `changelog:push:x` for routine releases anymore: their file-based state (`data/changelog-*-state.json`) is separate from the cron's DB state, so a manual push double-posts. The scripts remain for `--dry-run` previews and owner-directed backfills only.+- Internal-only chores (CI, lockfiles, refactors with no visible effect) do NOT get entries.++## Documentation: every feature ships with its docs++We have strong product-level docs (README, STRUCTURE.md, changelog) but feature-level docs have drifted: half-built features land with no doc explaining what they are or how to use them. That stops now. **Documentation is part of the feature, not a follow-up.** A feature is not done until someone who didn't build it could find it, understand what it does, and use it from the docs alone.++Match the doc to the kind of work. Do every layer that applies, skip the ones that don't:++- **New page or public route** → add it to `data/pages.json` (path, title, description, `added` date). This feeds the sitemap, `llms.txt`, `features.json`, and the changelog automatically. This is the one mandatory step for anything user-reachable.+- **New SDK, package, worker, service, or top-level directory** → a `README.md` *in that directory* is required: what it does, how to install/use it, its public API/exports, and one runnable example. New package under `packages/*`, new `workers/<name>/`, new SDK: no exceptions. Coverage under `packages/`, `workers/`, and `services/` is 100%, every directory carrying a README, and it has stayed there while all three grew (the counts quoted here previously went stale within weeks, so verify rather than trust a number: `for d in packages workers services; do for x in $d/*/; do [ -f "$x/README.md" ] || echo "$x"; done; done` prints nothing when the standard holds). That is a standard to hold, not a stat to admire: the next directory that lands without one breaks it.+- **New product surface or directory** → add a row to `STRUCTURE.md` mapping it to its location and status. Nothing enforces this in CI, so it's on you. If you moved or graduated a surface, update its existing row.+- **New developer-facing capability** (API endpoint, MCP tool, protocol, integration, CLI) → add or update the relevant file in `docs/` (`docs/api-reference.md`, `docs/mcp.md`, `docs/tutorials/*`, etc.). Follow the format of the neighboring docs in that folder. A genuinely new subsystem gets its own `docs/<feature>.md` linked from `docs/start-here.md`.+- **New load-bearing contract or wire format** (manifest schema, on-chain interface, embed protocol, permission model) → write or update the spec in `specs/`. Specs are contracts other code depends on, not tutorials.+- **Always** → add the `data/changelog.json` entry per the Changelog section above. Use the `docs` tag when the change *is* documentation.++Rules:+- **Public, non-obvious surfaces get a doc.** Internal refactors, one-off scripts, and changes with no user- or developer-visible effect do not. Don't manufacture filler docs for them.+- **Write for the reader who has zero context.** No commit jargon, no "see the code." Explain the why, show a working example, link to related surfaces (`STRUCTURE.md`, the page, the spec).+- **Docs are real implementations too.** The no-mocks, no-placeholders, no-stubs rules apply. Every code sample must actually run. Every link must resolve to a live path. A deferred-docs marker in place of real documentation is a failed feature, not a doc.+- **Update, don't duplicate.** If a doc already covers the area, extend it. Read the neighboring docs before adding a new file so you match their structure and depth.+- **If you touched a feature and its existing docs are now wrong, fix them in the same change.** Stale docs are worse than none.+- **Verify with `npm run audit:docs` before claiming a docs task done.** It mechanically catches dead relative links, site links that match no route, commands naming a script that no longer exists, and `packages/*`/`workers/*` directories missing a README. Renaming, moving, or deleting a file is exactly when it earns its keep. It is not wired into the deploy path, so nothing runs it for you.++---diff --git a/.claude/skills/deploy-runbook/SKILL.md b/.claude/skills/deploy-runbook/SKILL.mdnew file mode 100644index 000000000..58bf7ad11--- /dev/null+++ b/.claude/skills/deploy-runbook/SKILL.md@@ -0,0 +1,24 @@+---+name: deploy-runbook+description: The exact three.ws production deploy runbook (clean worktree, build:gcp chain, submit gates, cron sync, CDN purge, verify). Load before any deploy.+when_to_use: Any production deploy, a deploy that died mid-build, or a question about build:gcp order and deploy gates.+---++# Deploy runbook (API/frontend)++Remember stop-and-ask gate 2: production deploys need owner approval unless the owner's current instruction is itself the approval. Full runbook incl. LB/DNS/TLS/env/rollback/recovery: `docs/ops/gcp-production.md`. GPU workers deploy from their own `workers/<name>/cloudbuild.yaml`.++0. **Reclaim disk first: `npm run clean:worktrees` (add `--apply` to act).** Deploy worktrees are created by every deploy and removed by nobody. On 2026-08-04 ten had accumulated and filled the 126 GB disk to 100%, which fails in a way that reads like a different bug entirely: `git worktree add` dies mid-checkout with `No space left on device` and leaves a half-written tree behind. The script only reclaims a linked worktree that is detached, clean, and idle past `--min-age-hours` (default 2, so a concurrent agent's live build is never deleted); anything with uncommitted work is reported and kept. It applies the same rules to the subagent worktrees under `.claude/worktrees/`, which additionally must have their `worktree-agent-*` branch already merged into HEAD; the merged branch is deleted with `git branch -d` (on 2026-10-08 nine of those held 31 GB).+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 every artifact in the `ARTIFACTS` list of `scripts/prepare-deploy-worktree.mjs` with `cp -al` on the same filesystem (not just the first). Three of them are build-critical, `node_modules`, `chat/node_modules` and `character-studio/build`; the optional ones (`walk-sdk/dist`, `multiplayer/node_modules`, `animation-sources`) are what let the worktree also run the repo's own test suite, so a pre-ship `npm test` can be taken at the exact commit being shipped instead of in the shared tree. It then 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` → `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. `publish:lib` writes only the moving channels (`latest`, `1`, `1.5`) from the fresh build; every released version directory is downloaded from the write-once archive `gs://three-ws-lib-releases` and checked against `data/agent-3d-releases.json`, so the build needs network access to storage.googleapis.com, and it fails if `package.json` names a version that was never cut. A versioned URL is immutable and SRI-pinned by embedders, so it must never change bytes: cut a new version with `npm run release:lib` after bumping `package.json`, never by rebuilding an old one (2026-10-01: rebuilding 1.5.2 on every deploy broke every published SRI pin). `check:dist` also fails when a documented SRI pin disagrees with the ledger; `npm run check:sri-pins -- --fix` rewrites stale pins. `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 `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. **Sync new crons, then purge CDN: `npm run deploy:gcp:sync-crons`, then `npm run deploy:gcp:purge-cdn`.** The sync creates a Cloud Scheduler job for every cron in `vercel.json` that has none and touches no existing job; without it a new cron never fires (four sat dead for up to three weeks until 2026-10-08). 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).++The whole build + submit + purge in one command: `npm run deploy:gcp:full`.++---diff --git a/.claude/skills/engineering-standards/SKILL.md b/.claude/skills/engineering-standards/SKILL.mdnew file mode 100644index 000000000..ada921efc--- /dev/null+++ b/.claude/skills/engineering-standards/SKILL.md@@ -0,0 +1,51 @@+---+name: engineering-standards+description: three.ws engineering excellence checklist: architecture, open-source-first search order, UI/UX standards, innovation standard.+when_to_use: When designing or building any non-trivial feature or UI, before writing code.+---++# Engineering excellence++### Architecture+- **Read before you write.** Before adding code, understand the existing patterns. Use the same naming conventions, file organization, and abstractions already established. Consistency compounds.+- **Think in systems, not files.** A feature touches routing, data fetching, state management, UI rendering, and error handling. Trace the full path before you start. Wire every connection.+- **Eliminate dead paths.** If a button exists, it must work. If a link exists, it must go somewhere. If a state exists, there must be a way to reach it. Audit your own work for unreachable or broken paths.+- **Design data flow first.** Where does the data come from? How does it transform? Where does it render? Solve this before writing UI code.+- **Small functions, clear boundaries.** Each function does one thing. If you need a comment to explain what a block does, extract it into a named function.+- **Delete aggressively.** Dead code, unused imports, vestigial features: remove them. Less code is better code.+- **Performance by default.** Lazy-load heavy modules. Debounce user input handlers. Paginate large lists. Use `will-change` and `transform` for animations. Don't ship jank.++### Open source first++Before writing a single line of new code for any non-trivial capability, search for an existing solution. The open-source ecosystem is vast, battle-tested, and maintained by people who have already solved most problems you will encounter. Using it is not laziness, it is engineering judgment. Reinventing what already exists is waste; building on what exists multiplies it.++**The search order:**+1. **NPM** for any JavaScript/Node utility, parser, client library, codec, or algorithm. `npm search`, `npmjs.com`, or a web search scoped to `site:npmjs.com`. Evaluate weekly downloads, last publish date, open issues, and license before adopting.+2. **GitHub** for tools, CLIs, APIs, demos, reference implementations, and anything npm doesn't cover. Search by topic, language, and stars. Read the README and the issue tracker, not just the star count.+3. **Existing workspace dependencies**: check `package.json` first. We may already have a package installed that solves the problem. Never add a dependency that duplicates one already present.++**How to decide:**+- A well-maintained OSS package with >1 k weekly downloads and an active maintainer beats a from-scratch implementation 9 times out of 10. Use it.+- A package with known CVEs, no updates in 2+ years, or a license incompatible with the project (GPL in a commercial product, etc.) does not qualify. Document why and build the thin wrapper or alternative yourself.+- For one-line utilities (e.g. `clamp(n, min, max)`), write it inline. Don't pull a dependency for three statements.+- When adopting an OSS package, pin a semver range (`^x.y.0`), not a commit hash or `latest`. Log the rationale in the commit message if the choice is non-obvious.++**The ecosystem mindset:**+We are not consumers extracting value from open source, we are participants growing it. When an OSS package solves 90% of the problem but misses the last 10%, prefer contributing upstream (open an issue, submit a PR) over forking or working around it in-house. When we build something genuinely reusable, extract it into a publishable package. The rising tide lifts all boats. The more we give back, the more the ecosystem has to offer the next time we go looking.++**Never reinvent:** HTTP clients, date/time parsing, cryptographic primitives, schema validation, markdown rendering, diff algorithms, color manipulation, UUID generation, deep equality checks, path resolution, MIME detection, or any other solved problem with a well-adopted library. Writing your own is a liability, not a feature.++### UI/UX standards+- **Every state is designed.** Loading, empty, error, populated, overflow: all of them. A page with no data should tell the user what to do next, not show a blank void.+- **Transitions matter.** Elements should enter and exit with intention. No jarring pops. CSS transitions on opacity and transform at minimum.+- **Responsive by default.** Test at 320px, 768px, and 1440px mentally. Use relative units. Flex/grid over fixed widths.+- **Accessibility is not optional.** Semantic HTML. ARIA labels on interactive elements. Keyboard navigation. Sufficient color contrast. Focus indicators.+- **Microinteractions signal quality.** Hover states, active states, focus rings, subtle animations on state change. These are not polish, they are the product.+- **Consistent spacing and typography.** Use the existing design tokens / CSS variables. If none exist, establish them and use them everywhere.++### Innovation standard+- **Don't just implement the feature. Improve the platform.** If you're adding a list view and notice the existing list views lack sorting, add sorting to yours and note the gap. Think about what features *should* exist adjacent to what you're building.+- **Cross-pollinate.** When building feature A, consider: does this data/capability unlock something in feature B? Wire the connection. The best platforms feel like everything is linked.+- **Surprise with quality.** Add the keyboard shortcut. Add the tooltip. Add the empty state illustration. Add the subtle gradient. The accumulation of small quality decisions is what separates great products from adequate ones.++---diff --git a/.claude/skills/maintain-claude-md/SKILL.md b/.claude/skills/maintain-claude-md/SKILL.mdnew file mode 100644index 000000000..0ea788c81--- /dev/null+++ b/.claude/skills/maintain-claude-md/SKILL.md@@ -0,0 +1,30 @@+---+name: maintain-claude-md+description: How CLAUDE.md and the .claude/agents and skills it references are kept true (check:claude, check:rules, agent maintenance).+when_to_use: When editing CLAUDE.md, a .claude/agents definition, or a load-bearing script CLAUDE.md names.+---++# Specialized agents and keeping CLAUDE.md true++Three subagents live in `.claude/agents/` and encode checklists you would otherwise rebuild from scratch. Use them; they exist because each of these failures happened more than once:++- **`completionist`** audits changed files against these operating rules at the end of a feature task. It reports violations, it does not fix them. One exception, and it is absolute: when the user asks to commit or push, that IS the approval. Do not run the completionist (or tests, audits, or diff reviews) first. Ship it.+- **`deploy-preflight`** verifies a production deploy is safe BEFORE `gcloud builds submit`: build order, worktree artifacts, service-account pins, changelog wiring. Run it before any deploy, or when a deploy died mid-build. It does not deploy; deploys stay owner-gated.+- **`x402-economy-triage`** diagnoses x402 outages against the known failure map. Run it before concluding "the wallets are dry", which is usually wrong: settle-floor starvation and capital dispersion look identical from the outside and have completely different fixes.++**Evolve** (`npm run evolve:start`, `scripts/evolve.mjs`, runbook `docs/ops/evolve.md`), the unattended development loop and not the product's trading Autopilot, runs headless Claude Code sessions around the clock in its own worktree beside the repo, on branch `evolve`: it works the `prompts/finish/` queue, writes new scouted orders into the `400` band, and sweeps production, then fast-forwards finished commits into local `main`. Its sessions are denied every owner-gated action. If you are hand-running an order, evolve leaves it alone for 6 hours after you last touched it; `npm run evolve:pause` frees the subscription for interactive work.++`.claude/workflows/` holds two workflow scripts: `docs-drift.js` sweeps documentation drift across the repo, and `docs-freshness.js` re-verifies the docs the freshness report marks stale.++**Maintaining these agents.** An agent definition is executed verbatim, exactly like this file, so it is held to the same standard and `npm run check:claude` enforces it: every `npm run` script and repo path it names must exist, it must never send the agent to a per-machine memory file (auto-memory under `~/.claude` is invisible to a fresh clone or a cloud session; put the knowledge in `docs/` and link it), and it must read changeable facts (build chains, artifact lists, env-var locations) from their source of truth instead of restating them. When the same multi-step diagnosis has been rebuilt from scratch twice, that is the signal to add an agent for it. Subagents launched with `isolation: "worktree"` leave a tree under `.claude/worktrees/`; `npm run clean:worktrees` reclaims each one once its branch is merged and it holds no uncommitted work.++## Keeping this file true++This file is the operating brain for every agent here, and agents execute what it says verbatim. A stale line in it does not read as stale, it reads as an instruction, and the cost is a wasted session per drift. Treat it as load-bearing code:++- **`npm run check:rules` enforces the hard rules on the lines you changed** (`scripts/check-rules.mjs`). It reads added lines only, so your change is held to the rules while the legacy around it is left alone: em-dashes, TODO/FIXME comments, not-implemented throws, commented-out code, and `sampleFoo = [...]` fallback arrays all fail it. Because concurrent agents share this worktree, scope it to your own work: `npm run check:rules -- --paths <files you touched>`. It also reads brand-new untracked files, which a bare `git diff` cannot see. Generated output is excluded, including the compiled Marketplace Action under `satellites/glb-quality-gate/dist/`; its authored source remains scanned. It is also enforced mechanically at push time: the pre-push hook (installed into `.git/hooks` by `scripts/setup-git-hooks.mjs`, which `postinstall` runs on every `npm install`) runs it with `--base <remote sha> --head <local sha>` per pushed ref, so it judges exactly the commits leaving the machine and never the shared working tree. In that push-scoped mode it also lints every pushed commit's subject line against the "Commit messages" rules in the Git section, so a `chore: sync working tree` never lands again. A pre-commit hook runs the same check on the staged lines (`--staged`), so violations are stopped before they become a commit; plumbing commits (`git commit-tree` + `update-ref`) skip hooks, so run `node scripts/check-rules.mjs --staged` against the private index before `commit-tree`. Emergency bypass: `SKIP_PUSH_CHECKS=1 git push` (or `git commit`). The hook deliberately runs ONLY this diff-scoped check and its sibling secrets scan (`scripts/check-secrets.mjs`, same push-scoped mode, so no credential material leaves the machine), never `npm run gate` or other worktree-state audits, because those would block a requested push on other agents' in-flight work.+- **`npm run check:claude` guards it** (`scripts/check-claude-md.mjs`, wired into `npm run gate`). It re-derives the checkable claims from their source of truth on every run: every npm script and repo path named here or in `.claude/agents/` must exist, the cron count must match `vercel.json`, the deploy runbook must list the real `build:gcp` chain in the real order, the `db:migrate` warning must match what the script actually does, the README-coverage standard must hold, the remotes documented below must be the ones actually configured (a `git push <remote> main` instruction that does not resolve fails exactly when the owner asked to ship), and the em-dash ban must be honored by this file itself. Run it after editing this file.+- **If you change a load-bearing script, update this file in the same change.** Renaming a script, reordering `build:gcp`, adding a cron, or flipping a default is a documentation change too. The guard will catch most of it; do not make it do your job.+- **Never add a claim here you have not verified.** Numbers, dates, and "X is automatic" statements are the ones that rot. If a claim cannot be checked mechanically, prefer wording that stays true (name the source of truth instead of quoting a number from it).++---diff --git a/.claude/skills/self-unblock-playbook/SKILL.md b/.claude/skills/self-unblock-playbook/SKILL.mdnew file mode 100644index 000000000..9cf51afee--- /dev/null+++ b/.claude/skills/self-unblock-playbook/SKILL.md@@ -0,0 +1,22 @@+---+name: self-unblock-playbook+description: Table of blockers (missing env var, QA login, GCP access, database, quota, API down, failing tests) with the resolution to run instead of asking the owner.+when_to_use: Before stopping to ask a question, when a credential, database, GCP, migration or test blocker appears.+---++# Self-unblock playbook++| Blocker | Resolution (do this, don't ask) |+|---|---|+| Missing env var / credential | Look in `.env` and `.env.local`, then the Cloud Run service. Since 2026-09-02 every credential on that service is a Secret Manager reference, so `describe` shows `valueFrom` where the value used to be: read one with `node scripts/read-service-env.mjs '^NAME$' --raw`, which resolves literals and references alike (`--names` lists which is which). Never trust `vercel env pull` (returns empty for secrets). Update single vars with `--update-env-vars` (merges); `--set-env-vars` REPLACES the whole set, so never use it for one key. If a credential truly exists nowhere, build the feature fully wired behind the env var, prove it with a mock-free dry run, and list the single missing var in your report. |+| A QA login for authed page testing | `AUDIT_EMAIL` / `AUDIT_PASSWORD` in `.env` are a real production QA account. If they are missing from `.env` (a fresh clone has no `.env` at all), `npm run audit:web:provision` creates a new one through the real `/register` page and writes both vars back; no server-side code reads them, so the Cloud Run env does not need them. Unauthenticated sweep: `npm run audit:web`. Authed sweep: `npm run audit:web:login` to mint the session, then `npm run audit:web`, which replays it. Details: `docs/ops/page-audit.md`. |+| GCP access / project facts | Already authenticated in this workspace. Project `aerial-vehicle-466722-p5`, region `us-central1`. Fleet + quota + pre-approved scaling: `docs/ops/gcp-credits-plan.md`. Full production runbook (LB/DNS/TLS/env/rollback): `docs/ops/gcp-production.md`. Logs: `gcloud logging read 'resource.type="cloud_run_revision" resource.labels.service_name="three-ws-api" textPayload:"<term>"' --freshness=24h`. |+| The database | `DATABASE_URL` in `.env.local` (Neon); `.env` currently holds only the QA audit login, so a script that loads `.env` alone dies on `missing required env var: DATABASE_URL`. Production's authoritative copy is on the Cloud Run service env. Migrations: `npm run db:status` previews pending ones, `npm run db:check` is the deploy gate (exit 4 if pending), and **`npm run db:migrate` APPLIES immediately, with no dry run** (the npm script hardcodes `--apply`). Read `db:status` before you ever run `db:migrate`; it applies every pending migration in `api/_lib/migrations/`, not just yours. If `db:status` reports `[drift]` because an applied migration's *comments* were edited (the banned-dash rule does this), `npm run db:restamp` re-records its hash after recovering the applied bytes from git and confirming not one statement changed; a real statement change is refused and needs a NEW migration. `forge_creations` carries per-generation backend/status/error/prompt: the fastest ground truth for generation issues. |+| GCP quota hit | File the increase request immediately (`gcloud` or console link in your report), then route around it: lower minScale on an idle service, use another region, or queue behind existing capacity. Never park the task on the quota. |+| Third-party API down / throttled | Every lane has a failover chain (forge lanes, LLM chain, RPC providers). Use it. If a chain is missing a rung, adding one is part of the task. |+| Ambiguous product decision | Pick the option that is most reversible and closest to existing platform patterns, implement it, and record the decision + alternative in your report. A shipped reasonable default beats a stalled question. |+| Build/test failure in code you didn't touch | Fix it if it blocks your verification path (root-cause it, don't mask it); otherwise note it and continue. Never let someone else's red stop your green. |+| Whether tests pass | `npm test`; do NOT pipe through `tail` (masks exit codes); a vitest failure gates the whole Playwright stage. |+| Model weights / assets missing | Stage them from `gs://three-ws-model-weights` or the worker README's source. Staging weights is part of deploying a worker, not a reason to stop. |+| Where a feature lives | `STRUCTURE.md` maps every surface to its directory. |+| How to deploy | Follow the "Deploy runbook" section below, exactly and in order. |diff --git a/.gitignore b/.gitignoreindex e3671d841..3fe4d9649 100644--- a/.gitignore+++ b/.gitignore@@ -25,7 +25,13 @@ character-studio/public/loot-assets.mcp.json.claude/worktrees/# Auto-created symlinks → .agents/skills/* by scripts/setup-claude-skills.mjs-.claude/skills/+.claude/skills/*+# Repo-owned operating skills live here for real (not symlinks); keep them tracked.+!.claude/skills/deploy-runbook/+!.claude/skills/self-unblock-playbook/+!.claude/skills/changelog-and-docs/+!.claude/skills/maintain-claude-md/+!.claude/skills/engineering-standards/# Local env files.env.xspacediff --git a/CLAUDE.md b/CLAUDE.mdindex ed0b4315d..b82f57624 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -29,20 +29,7 @@ Everything not listed here: proceed, then report.Agents stopping mid-task to ask a question is a failure mode the owner explicitly called out. A turn that ends with a question, a plan, or "let me know if…" is an unfinished task. If you genuinely made a judgment call the owner might want to reverse, state it in one line of your final report; do not convert it into a question that halts work. Before you ever consider stopping, run this table. Nearly every historical stall had an answer already on this machine:-| Blocker | Resolution (do this, don't ask) |-|---|---|-| Missing env var / credential | Look in `.env` and `.env.local`, then the Cloud Run service. Since 2026-09-02 every credential on that service is a Secret Manager reference, so `describe` shows `valueFrom` where the value used to be: read one with `node scripts/read-service-env.mjs '^NAME$' --raw`, which resolves literals and references alike (`--names` lists which is which). Never trust `vercel env pull` (returns empty for secrets). Update single vars with `--update-env-vars` (merges); `--set-env-vars` REPLACES the whole set, so never use it for one key. If a credential truly exists nowhere, build the feature fully wired behind the env var, prove it with a mock-free dry run, and list the single missing var in your report. |-| A QA login for authed page testing | `AUDIT_EMAIL` / `AUDIT_PASSWORD` in `.env` are a real production QA account. If they are missing from `.env` (a fresh clone has no `.env` at all), `npm run audit:web:provision` creates a new one through the real `/register` page and writes both vars back; no server-side code reads them, so the Cloud Run env does not need them. Unauthenticated sweep: `npm run audit:web`. Authed sweep: `npm run audit:web:login` to mint the session, then `npm run audit:web`, which replays it. Details: `docs/ops/page-audit.md`. |-| GCP access / project facts | Already authenticated in this workspace. Project `aerial-vehicle-466722-p5`, region `us-central1`. Fleet + quota + pre-approved scaling: `docs/ops/gcp-credits-plan.md`. Full production runbook (LB/DNS/TLS/env/rollback): `docs/ops/gcp-production.md`. Logs: `gcloud logging read 'resource.type="cloud_run_revision" resource.labels.service_name="three-ws-api" textPayload:"<term>"' --freshness=24h`. |-| The database | `DATABASE_URL` in `.env.local` (Neon); `.env` currently holds only the QA audit login, so a script that loads `.env` alone dies on `missing required env var: DATABASE_URL`. Production's authoritative copy is on the Cloud Run service env. Migrations: `npm run db:status` previews pending ones, `npm run db:check` is the deploy gate (exit 4 if pending), and **`npm run db:migrate` APPLIES immediately, with no dry run** (the npm script hardcodes `--apply`). Read `db:status` before you ever run `db:migrate`; it applies every pending migration in `api/_lib/migrations/`, not just yours. If `db:status` reports `[drift]` because an applied migration's *comments* were edited (the banned-dash rule does this), `npm run db:restamp` re-records its hash after recovering the applied bytes from git and confirming not one statement changed; a real statement change is refused and needs a NEW migration. `forge_creations` carries per-generation backend/status/error/prompt: the fastest ground truth for generation issues. |-| GCP quota hit | File the increase request immediately (`gcloud` or console link in your report), then route around it: lower minScale on an idle service, use another region, or queue behind existing capacity. Never park the task on the quota. |-| Third-party API down / throttled | Every lane has a failover chain (forge lanes, LLM chain, RPC providers). Use it. If a chain is missing a rung, adding one is part of the task. |-| Ambiguous product decision | Pick the option that is most reversible and closest to existing platform patterns, implement it, and record the decision + alternative in your report. A shipped reasonable default beats a stalled question. |-| Build/test failure in code you didn't touch | Fix it if it blocks your verification path (root-cause it, don't mask it); otherwise note it and continue. Never let someone else's red stop your green. |-| Whether tests pass | `npm test`; do NOT pipe through `tail` (masks exit codes); a vitest failure gates the whole Playwright stage. |-| Model weights / assets missing | Stage them from `gs://three-ws-model-weights` or the worker README's source. Staging weights is part of deploying a worker, not a reason to stop. |-| Where a feature lives | `STRUCTURE.md` maps every surface to its directory. |-| How to deploy | Follow the "Deploy runbook" section below, exactly and in order. |+Before stopping to ask anything, load the `self-unblock-playbook` skill (`.claude/skills/self-unblock-playbook/SKILL.md`): it maps every historical blocker (credentials, QA login, GCP, database/migrations, quota, API outage, failing tests, missing assets) to the resolution to run. Its two hardest-won rules: `npm run db:migrate` APPLIES immediately with no dry run (read `npm run db:status` first), and `gcloud run services update --set-env-vars` REPLACES the whole env set (use `--update-env-vars`).**Standing resource approvals (so you never ask):** the owner has approved spending the Google Cloud credits (Google for Startups Web3 grant, up to $200k over 2 years with metered monthly issuance; terms and burn rules in `docs/ops/gcp-credits-plan.md`, project `aerial-vehicle-466722-p5`) freely for quality, reliability, and UX: GPU workers, Vertex AI (Gemini/Imagen), Cloud Run scale, Cloud Build, storage. Prefer GCP over any paid third-party API, and never downgrade quality to save credits. Do NOT onboard new external paid APIs without approval; GCP surfaces are pre-approved.@@ -104,49 +91,7 @@ Before writing a single line of code, answer these questions internally:## Engineering excellence-### Architecture-- **Read before you write.** Before adding code, understand the existing patterns. Use the same naming conventions, file organization, and abstractions already established. Consistency compounds.-- **Think in systems, not files.** A feature touches routing, data fetching, state management, UI rendering, and error handling. Trace the full path before you start. Wire every connection.-- **Eliminate dead paths.** If a button exists, it must work. If a link exists, it must go somewhere. If a state exists, there must be a way to reach it. Audit your own work for unreachable or broken paths.-- **Design data flow first.** Where does the data come from? How does it transform? Where does it render? Solve this before writing UI code.-- **Small functions, clear boundaries.** Each function does one thing. If you need a comment to explain what a block does, extract it into a named function.-- **Delete aggressively.** Dead code, unused imports, vestigial features: remove them. Less code is better code.-- **Performance by default.** Lazy-load heavy modules. Debounce user input handlers. Paginate large lists. Use `will-change` and `transform` for animations. Don't ship jank.--### Open source first--Before writing a single line of new code for any non-trivial capability, search for an existing solution. The open-source ecosystem is vast, battle-tested, and maintained by people who have already solved most problems you will encounter. Using it is not laziness, it is engineering judgment. Reinventing what already exists is waste; building on what exists multiplies it.--**The search order:**-1. **NPM** for any JavaScript/Node utility, parser, client library, codec, or algorithm. `npm search`, `npmjs.com`, or a web search scoped to `site:npmjs.com`. Evaluate weekly downloads, last publish date, open issues, and license before adopting.-2. **GitHub** for tools, CLIs, APIs, demos, reference implementations, and anything npm doesn't cover. Search by topic, language, and stars. Read the README and the issue tracker, not just the star count.-3. **Existing workspace dependencies**: check `package.json` first. We may already have a package installed that solves the problem. Never add a dependency that duplicates one already present.--**How to decide:**-- A well-maintained OSS package with >1 k weekly downloads and an active maintainer beats a from-scratch implementation 9 times out of 10. Use it.-- A package with known CVEs, no updates in 2+ years, or a license incompatible with the project (GPL in a commercial product, etc.) does not qualify. Document why and build the thin wrapper or alternative yourself.-- For one-line utilities (e.g. `clamp(n, min, max)`), write it inline. Don't pull a dependency for three statements.-- When adopting an OSS package, pin a semver range (`^x.y.0`), not a commit hash or `latest`. Log the rationale in the commit message if the choice is non-obvious.--**The ecosystem mindset:**-We are not consumers extracting value from open source, we are participants growing it. When an OSS package solves 90% of the problem but misses the last 10%, prefer contributing upstream (open an issue, submit a PR) over forking or working around it in-house. When we build something genuinely reusable, extract it into a publishable package. The rising tide lifts all boats. The more we give back, the more the ecosystem has to offer the next time we go looking.--**Never reinvent:** HTTP clients, date/time parsing, cryptographic primitives, schema validation, markdown rendering, diff algorithms, color manipulation, UUID generation, deep equality checks, path resolution, MIME detection, or any other solved problem with a well-adopted library. Writing your own is a liability, not a feature.--### UI/UX standards-- **Every state is designed.** Loading, empty, error, populated, overflow: all of them. A page with no data should tell the user what to do next, not show a blank void.-- **Transitions matter.** Elements should enter and exit with intention. No jarring pops. CSS transitions on opacity and transform at minimum.-- **Responsive by default.** Test at 320px, 768px, and 1440px mentally. Use relative units. Flex/grid over fixed widths.-- **Accessibility is not optional.** Semantic HTML. ARIA labels on interactive elements. Keyboard navigation. Sufficient color contrast. Focus indicators.-- **Microinteractions signal quality.** Hover states, active states, focus rings, subtle animations on state change. These are not polish, they are the product.-- **Consistent spacing and typography.** Use the existing design tokens / CSS variables. If none exist, establish them and use them everywhere.--### Innovation standard-- **Don't just implement the feature. Improve the platform.** If you're adding a list view and notice the existing list views lack sorting, add sorting to yours and note the gap. Think about what features *should* exist adjacent to what you're building.-- **Cross-pollinate.** When building feature A, consider: does this data/capability unlock something in feature B? Wire the connection. The best platforms feel like everything is linked.-- **Surprise with quality.** Add the keyboard shortcut. Add the tooltip. Add the empty state illustration. Add the subtle gradient. The accumulation of small quality decisions is what separates great products from adequate ones.-----+Read before you write; match existing patterns; wire every path end to end (routing, data, state, UI, errors); delete dead code; search npm/GitHub/`package.json` before writing anything non-trivial; design every UI state (loading, empty, error, populated, overflow) with accessibility and responsive behavior; improve the adjacent platform, not just the ticket. Load the `engineering-standards` skill (`.claude/skills/engineering-standards/SKILL.md`) before building any non-trivial feature or UI.## Definition of done@@ -184,61 +129,15 @@ Fix every issue found. Then report complete.- Track any task with 3+ steps in the harness's task list (TodoWrite or its equivalent; the tool name differs between harnesses). Mark items complete in real time.- Communication: short. State what you did, what's next. No trailing recaps.-## Specialized agents in this repo--Three subagents live in `.claude/agents/` and encode checklists you would otherwise rebuild from scratch. Use them; they exist because each of these failures happened more than once:--- **`completionist`** audits changed files against these operating rules at the end of a feature task. It reports violations, it does not fix them. One exception, and it is absolute: when the user asks to commit or push, that IS the approval. Do not run the completionist (or tests, audits, or diff reviews) first. Ship it.-- **`deploy-preflight`** verifies a production deploy is safe BEFORE `gcloud builds submit`: build order, worktree artifacts, service-account pins, changelog wiring. Run it before any deploy, or when a deploy died mid-build. It does not deploy; deploys stay owner-gated.-- **`x402-economy-triage`** diagnoses x402 outages against the known failure map. Run it before concluding "the wallets are dry", which is usually wrong: settle-floor starvation and capital dispersion look identical from the outside and have completely different fixes.--**Evolve** (`npm run evolve:start`, `scripts/evolve.mjs`, runbook `docs/ops/evolve.md`), the unattended development loop and not the product's trading Autopilot, runs headless Claude Code sessions around the clock in its own worktree beside the repo, on branch `evolve`: it works the `prompts/finish/` queue, writes new scouted orders into the `400` band, and sweeps production, then fast-forwards finished commits into local `main`. Its sessions are denied every owner-gated action. If you are hand-running an order, evolve leaves it alone for 6 hours after you last touched it; `npm run evolve:pause` frees the subscription for interactive work.--`.claude/workflows/` holds two workflow scripts: `docs-drift.js` sweeps documentation drift across the repo, and `docs-freshness.js` re-verifies the docs the freshness report marks stale.+## Specialized agents and keeping this file true-**Maintaining these agents.** An agent definition is executed verbatim, exactly like this file, so it is held to the same standard and `npm run check:claude` enforces it: every `npm run` script and repo path it names must exist, it must never send the agent to a per-machine memory file (auto-memory under `~/.claude` is invisible to a fresh clone or a cloud session; put the knowledge in `docs/` and link it), and it must read changeable facts (build chains, artifact lists, env-var locations) from their source of truth instead of restating them. When the same multi-step diagnosis has been rebuilt from scratch twice, that is the signal to add an agent for it. Subagents launched with `isolation: "worktree"` leave a tree under `.claude/worktrees/`; `npm run clean:worktrees` reclaims each one once its branch is merged and it holds no uncommitted work.--## Keeping this file true--This file is the operating brain for every agent here, and agents execute what it says verbatim. A stale line in it does not read as stale, it reads as an instruction, and the cost is a wasted session per drift. Treat it as load-bearing code:--- **`npm run check:rules` enforces the hard rules on the lines you changed** (`scripts/check-rules.mjs`). It reads added lines only, so your change is held to the rules while the legacy around it is left alone: em-dashes, TODO/FIXME comments, not-implemented throws, commented-out code, and `sampleFoo = [...]` fallback arrays all fail it. Because concurrent agents share this worktree, scope it to your own work: `npm run check:rules -- --paths <files you touched>`. It also reads brand-new untracked files, which a bare `git diff` cannot see. Generated output is excluded, including the compiled Marketplace Action under `satellites/glb-quality-gate/dist/`; its authored source remains scanned. It is also enforced mechanically at push time: the pre-push hook (installed into `.git/hooks` by `scripts/setup-git-hooks.mjs`, which `postinstall` runs on every `npm install`) runs it with `--base <remote sha> --head <local sha>` per pushed ref, so it judges exactly the commits leaving the machine and never the shared working tree. In that push-scoped mode it also lints every pushed commit's subject line against the "Commit messages" rules in the Git section, so a `chore: sync working tree` never lands again. Emergency bypass: `SKIP_PUSH_CHECKS=1 git push`. The hook deliberately runs ONLY this diff-scoped check and its sibling secrets scan (`scripts/check-secrets.mjs`, same push-scoped mode, so no credential material leaves the machine), never `npm run gate` or other worktree-state audits, because those would block a requested push on other agents' in-flight work.-- **`npm run check:claude` guards it** (`scripts/check-claude-md.mjs`, wired into `npm run gate`). It re-derives the checkable claims from their source of truth on every run: every npm script and repo path named here or in `.claude/agents/` must exist, the cron count must match `vercel.json`, the deploy runbook must list the real `build:gcp` chain in the real order, the `db:migrate` warning must match what the script actually does, the README-coverage standard must hold, the remotes documented below must be the ones actually configured (a `git push <remote> main` instruction that does not resolve fails exactly when the owner asked to ship), and the em-dash ban must be honored by this file itself. Run it after editing this file.-- **If you change a load-bearing script, update this file in the same change.** Renaming a script, reordering `build:gcp`, adding a cron, or flipping a default is a documentation change too. The guard will catch most of it; do not make it do your job.-- **Never add a claim here you have not verified.** Numbers, dates, and "X is automatic" statements are the ones that rot. If a claim cannot be checked mechanically, prefer wording that stays true (name the source of truth instead of quoting a number from it).+Subagents in `.claude/agents/`: `completionist` (audit against these rules at the end of a feature task; never run it when the user asks to commit/push, that IS the approval), `deploy-preflight` (before any deploy), `x402-economy-triage` (before concluding "the wallets are dry"). Evolve (`npm run evolve:start`, runbook `docs/ops/evolve.md`) is the unattended dev loop on branch `evolve`; its sessions are denied every owner-gated action. Workflow scripts live in `.claude/workflows/`. Run `npm run check:rules -- --paths <files you touched>` on your own work and `npm run check:claude` after editing this file or any script it names. Full maintenance rules: `maintain-claude-md` skill (`.claude/skills/maintain-claude-md/SKILL.md`).----## Changelog: every user-visible change gets an entry--The three.ws community follows the public changelog (three.ws/changelog, RSS, JSON, Telegram). Keep it alive:--- **New page?** Nothing extra: the `added` date in `data/pages.json` feeds the changelog automatically.-- **Everything else users would notice** (feature, improvement, fix, SDK release, security work): append an entry to `data/changelog.json` with date, community-readable title + summary (plain language, no commit jargon), and tags from: feature, improvement, fix, sdk, infra, docs, security. Optional `link` must be a live page path.-- `npm run build:pages` regenerates CHANGELOG.md, public/changelog.json, and public/changelog.xml. It also validates your entry and fails the build on a malformed one.-- **Delivery to the community is automatic.** `/api/cron/changelog-push` (Cloud Scheduler, every 20 min) reads the feed baked into the running image, diffs it against DB state (`app_settings`), and posts anything new to two lanes: the community Telegram channel (`TELEGRAM_CHANGELOG_CHAT_ID`, @three_ws) gets every entry, and a reply thread on @trythreews (`pushXLane`) gets every entry that passes `data/changelog-x-filter.json`. That filter keeps a public, unattended feed free of wallet and payment internals, keys, outages, security work, other coins, and bare fixes; extend it there, with a reason, rather than in code. X was retired on 2026-07-18 and turned back on by the owner on 2026-09-24. The three reviewed feature posts a day are a separate pipeline (`docs/x-content-pipeline.md`). An entry goes out on its own shortly after the deploy that ships it; there is no manual push step. Credentials live on the Cloud Run service. Do NOT run `npm run changelog:push` / `changelog:push:x` for routine releases anymore: their file-based state (`data/changelog-*-state.json`) is separate from the cron's DB state, so a manual push double-posts. The scripts remain for `--dry-run` previews and owner-directed backfills only.-- Internal-only chores (CI, lockfiles, refactors with no visible effect) do NOT get entries.--## Documentation: every feature ships with its docs--We have strong product-level docs (README, STRUCTURE.md, changelog) but feature-level docs have drifted: half-built features land with no doc explaining what they are or how to use them. That stops now. **Documentation is part of the feature, not a follow-up.** A feature is not done until someone who didn't build it could find it, understand what it does, and use it from the docs alone.+## Changelog and documentation-Match the doc to the kind of work. Do every layer that applies, skip the ones that don't:--- **New page or public route** → add it to `data/pages.json` (path, title, description, `added` date). This feeds the sitemap, `llms.txt`, `features.json`, and the changelog automatically. This is the one mandatory step for anything user-reachable.-- **New SDK, package, worker, service, or top-level directory** → a `README.md` *in that directory* is required: what it does, how to install/use it, its public API/exports, and one runnable example. New package under `packages/*`, new `workers/<name>/`, new SDK: no exceptions. Coverage under `packages/`, `workers/`, and `services/` is 100%, every directory carrying a README, and it has stayed there while all three grew (the counts quoted here previously went stale within weeks, so verify rather than trust a number: `for d in packages workers services; do for x in $d/*/; do [ -f "$x/README.md" ] || echo "$x"; done; done` prints nothing when the standard holds). That is a standard to hold, not a stat to admire: the next directory that lands without one breaks it.-- **New product surface or directory** → add a row to `STRUCTURE.md` mapping it to its location and status. Nothing enforces this in CI, so it's on you. If you moved or graduated a surface, update its existing row.-- **New developer-facing capability** (API endpoint, MCP tool, protocol, integration, CLI) → add or update the relevant file in `docs/` (`docs/api-reference.md`, `docs/mcp.md`, `docs/tutorials/*`, etc.). Follow the format of the neighboring docs in that folder. A genuinely new subsystem gets its own `docs/<feature>.md` linked from `docs/start-here.md`.-- **New load-bearing contract or wire format** (manifest schema, on-chain interface, embed protocol, permission model) → write or update the spec in `specs/`. Specs are contracts other code depends on, not tutorials.-- **Always** → add the `data/changelog.json` entry per the Changelog section above. Use the `docs` tag when the change *is* documentation.--Rules:-- **Public, non-obvious surfaces get a doc.** Internal refactors, one-off scripts, and changes with no user- or developer-visible effect do not. Don't manufacture filler docs for them.-- **Write for the reader who has zero context.** No commit jargon, no "see the code." Explain the why, show a working example, link to related surfaces (`STRUCTURE.md`, the page, the spec).-- **Docs are real implementations too.** The no-mocks, no-placeholders, no-TODO rules apply. Every code sample must actually run. Every link must resolve to a live path. A `// TODO: document` is a failed feature, not a doc.-- **Update, don't duplicate.** If a doc already covers the area, extend it. Read the neighboring docs before adding a new file so you match their structure and depth.-- **If you touched a feature and its existing docs are now wrong, fix them in the same change.** Stale docs are worse than none.-- **Verify with `npm run audit:docs` before claiming a docs task done.** It mechanically catches dead relative links, site links that match no route, commands naming a script that no longer exists, and `packages/*`/`workers/*` directories missing a README. Renaming, moving, or deleting a file is exactly when it earns its keep. It is not wired into the deploy path, so nothing runs it for you.+Every user-visible change appends an entry to `data/changelog.json` (then `npm run build:pages`); every new page goes in `data/pages.json`; every new package/worker/service/SDK gets a README in its directory; new surfaces get a `STRUCTURE.md` row; new developer-facing capabilities update `docs/`; verify with `npm run audit:docs`. Changelog delivery is automatic via the cron, so never run `npm run changelog:push` for routine releases. Details and rules: `changelog-and-docs` skill (`.claude/skills/changelog-and-docs/SKILL.md`).---@@ -293,20 +192,7 @@ The root `vercel.json` filename is legacy but the file is still load-bearing: th## Deploy runbook (API/frontend)-Remember stop-and-ask gate 2: production deploys need owner approval unless the owner's current instruction is itself the approval. Full runbook incl. LB/DNS/TLS/env/rollback/recovery: `docs/ops/gcp-production.md`. GPU workers deploy from their own `workers/<name>/cloudbuild.yaml`.--0. **Reclaim disk first: `npm run clean:worktrees` (add `--apply` to act).** Deploy worktrees are created by every deploy and removed by nobody. On 2026-08-04 ten had accumulated and filled the 126 GB disk to 100%, which fails in a way that reads like a different bug entirely: `git worktree add` dies mid-checkout with `No space left on device` and leaves a half-written tree behind. The script only reclaims a linked worktree that is detached, clean, and idle past `--min-age-hours` (default 2, so a concurrent agent's live build is never deleted); anything with uncommitted work is reported and kept. It applies the same rules to the subagent worktrees under `.claude/worktrees/`, which additionally must have their `worktree-agent-*` branch already merged into HEAD; the merged branch is deleted with `git branch -d` (on 2026-10-08 nine of those held 31 GB).-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 every artifact in the `ARTIFACTS` list of `scripts/prepare-deploy-worktree.mjs` with `cp -al` on the same filesystem (not just the first). Three of them are build-critical, `node_modules`, `chat/node_modules` and `character-studio/build`; the optional ones (`walk-sdk/dist`, `multiplayer/node_modules`, `animation-sources`) are what let the worktree also run the repo's own test suite, so a pre-ship `npm test` can be taken at the exact commit being shipped instead of in the shared tree. It then 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` → `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. `publish:lib` writes only the moving channels (`latest`, `1`, `1.5`) from the fresh build; every released version directory is downloaded from the write-once archive `gs://three-ws-lib-releases` and checked against `data/agent-3d-releases.json`, so the build needs network access to storage.googleapis.com, and it fails if `package.json` names a version that was never cut. A versioned URL is immutable and SRI-pinned by embedders, so it must never change bytes: cut a new version with `npm run release:lib` after bumping `package.json`, never by rebuilding an old one (2026-10-01: rebuilding 1.5.2 on every deploy broke every published SRI pin). `check:dist` also fails when a documented SRI pin disagrees with the ledger; `npm run check:sri-pins -- --fix` rewrites stale pins. `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 `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. **Sync new crons, then purge CDN: `npm run deploy:gcp:sync-crons`, then `npm run deploy:gcp:purge-cdn`.** The sync creates a Cloud Scheduler job for every cron in `vercel.json` that has none and touches no existing job; without it a new cron never fires (four sat dead for up to three weeks until 2026-10-08). 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).--The whole build + submit + purge in one command: `npm run deploy:gcp:full`.+Production deploys need owner approval (gate 2) unless the current instruction is the approval. Load the `deploy-runbook` skill (`.claude/skills/deploy-runbook/SKILL.md`) and follow it exactly and in order; never hand-run `build:gcp` steps or a bare `gcloud builds submit`. One command: `npm run deploy:gcp:full`. Full runbook: `docs/ops/gcp-production.md`.---diff --git a/scripts/check-claude-md.mjs b/scripts/check-claude-md.mjsindex 377a1ff81..ca47ab2b8 100644--- a/scripts/check-claude-md.mjs+++ b/scripts/check-claude-md.mjs@@ -32,7 +32,11 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');-const md = readFileSync(path.join(root, 'CLAUDE.md'), 'utf8');+const claudeMd = readFileSync(path.join(root, 'CLAUDE.md'), 'utf8');+// Operating detail that was split out of CLAUDE.md to keep every session's base+// context small. These skills are part of the brain, so they are held to the same claims.+const operatingSkills = ['deploy-runbook', 'self-unblock-playbook', 'changelog-and-docs', 'maintain-claude-md', 'engineering-standards'];+const md = [claudeMd, ...operatingSkills.map((n) => readFileSync(path.join(root, '.claude/skills', n, 'SKILL.md'), 'utf8'))].join('\n');const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));const scripts = pkg.scripts || {};@@ -86,7 +90,7 @@ for (const raw of missingPaths(md)) failures.push(`path \`${raw}\` is referenced// 3. Typography: the ban applies to the file that declares it. Only the lines// that name the banned characters may contain them.-md.split('\n').forEach((line, i) => {+claudeMd.split('\n').forEach((line, i) => {if (/[—–]/.test(line) && !/em-dash|en-dash/.test(line)) {failures.push(`line ${i + 1} contains an em/en-dash, which CLAUDE.md itself bans`);}