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: implement garment forge pipeline with image generation and mesh processing

nirholasea28e853e923
diff --git a/.gitignore b/.gitignore
index b182f8a63..dff19fada 100644
--- a/.gitignore
+++ b/.gitignore
@@ -408,3 +408,6 @@ SECURITY-AUDIT.md
/workers/avatar-reconstruction/eval/reports/
# local Python venv for the eval harness — thousands of files, always regenerable
/workers/avatar-reconstruction/.venv-eval/
+
+# Scratch harnesses for local 3D/pose debugging — never committed.
+scripts/.scratch/
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5ded0e9cd..acef98eb0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,9 +10,12 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **The Story So Far** (`/timeline`) — three.ws's history as an explorable 3D scene: every launch, partnership, listing, and milestone laid out along a path you can orbit in 360° or walk end to end, with a synced scrubber and source links.
- **three.ws is an OpenAI Select Partner** (`/openai`) — three.ws is an OpenAI Select Partner in the OpenAI Partner Network. Connect the free three.ws 3D Studio MCP server to ChatGPT and turn a prompt into an interactive, riggable, AR-ready 3D model inline in the conversation.
- **three.ws Named an OpenAI Select Partner** (`/blog/three-ws-openai-select-partner`) — three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. What we ship on OpenAI surfaces today: a free 3D Studio MCP connector for ChatGPT, custom GPT Actions, the open Spatial MCP response shape, and one-tap AR.
+- **Dress any avatar: the wardrobe now adds clothes, not just recolours them** — Until now the wardrobe could only recolour or hide the clothes an avatar was generated with. It can now put NEW clothes on: the avatar editor's Wardrobe tab gained a Closet with racks of catalog pieces (tops, bottoms, footwear, outerwear, hair, headwear, glasses, accessories). Click a piece and it binds to your avatar's skeleton and moves with every animation, whatever generator the avatar came from: forge characters, selfie reconstructions and uploaded models all work, because garments are fitted to the skeleton at wear-time instead of being authored for one specific body. The body is masked under whatever you wear so skin never pokes through the cloth, a piece that cannot fit a particular skeleton politely refuses instead of deforming into spaghetti, and every download is integrity-checked against the catalog before it touches your avatar. Saved outfits persist: the downloadable and embedded versions of your avatar come out dressed too. (`/avatar-edit`) `[feature]`
- **The KOL Tracker is now reachable, and its numbers are real** — The KOL Tracker page shipped listed in the sitemap but with no route behind it, so three.ws/tracker returned a 404 for everyone who followed the link, and the API behind it was answering with three placeholder rows left over from a test fixture. Both are fixed. The page is served, and it now ranks real Solana traders from the live kolscan board: realized profit, win rate and trade count for the 24h, 7d and 30d windows, enriched with our own on-chain FIFO profit calculation wherever we have the trades for a wallet. Every row states where its number came from, and when a source is unreachable the board shows an honest empty state instead of inventing traders. A new test blocks the whole class of mistake: any page advertised in the site index that has no route, or that never gets built, now fails the suite before it can reach production. (`/tracker`) `[fix, feature]`
+- **The signing avatar's arm now sits where a signer's arm sits, and it signs real words** — The signing avatar had a broken arm. Its handshapes were right, but the arm carrying them swung out to the side and behind the body, and the clip also dragged the avatar about a metre down through the floor, so you were watching correct fingerspelling performed somewhere over the avatar's shoulder. The cause was that the arm was posed with rotations written against a skeleton convention our reference avatar does not use. Arms are now solved instead of guessed: the code measures the actual skeleton (which way each bone points, how long it is, which way each palm faces) and then runs real inverse kinematics to put the wrist at a specific point in front of the body, with the elbow hanging where an elbow hangs. Fingerspelling now happens where signers do it, in front of the dominant shoulder at jaw height with the palm facing you, and the letters themselves are unchanged, to the digit. Because a hand can now be sent to a place on the body, the avatar also has a real sign vocabulary for the first time: thirty-two everyday words including hello, thank you, please, sorry, yes, no, happy, help, love, want, welcome, name, y'all and finish, two-handed where the sign is two-handed. Type a sentence and the words with signs are signed while the rest is fingerspelled, in one continuous motion, and the page tells you which was which. There is a new section on the sign-language page listing every word it can sign, each one playable. Both arms are now posed throughout, the idle hand rests at the side instead of hanging oddly, the avatar breathes during long holds, and the camera crops closer so you can actually see the hands. (`/sign-language`) `[improvement, fix]`
- **The Spatial MCP reference renderer actually renders again** — Spatial MCP is our open, public-domain shape for handing back a live 3D scene as an AI tool result instead of a link, and three.ws/spatial-mcp is the page that proves it works. It has been showing two empty frames. The demo code asked for its renderer with a path relative to the page, and because the page is served both with and without a trailing slash, that path pointed at the site root on one of them and came back as a 404, so the renderer never loaded and neither scene appeared. The demo now loads as its own module file, which resolves correctly on either address and in local development, where the same page had been failing to build at all. Both frames are live again: you can orbit and zoom a real model on the left and, on the right, the same viewer displaying a model that arrived from a completely different server in a completely different format, converted by a six-line adapter shown as JSON underneath. That side-by-side is the whole argument for the standard, so it is worth having it work. The left frame is now a genuine model from our free text-to-3D lane rather than a borrowed sample, and the sample the page used to point at had itself gone dead upstream, which is why it also stayed blank once the renderer was fixed. (`/spatial-mcp`) `[fix]`
- **The trading fleet never sells 100% of a winner again** — New rule across every autonomous trading strategy: once a position has earned back what it cost, we never sell all of it. Any exit taken in profit now sells just enough to recover the original stake (or banks the gain down to a floor if the stake is already home) and keeps the rest, which then rides indefinitely. The logic is simple: after the cost is recovered the leftover position is free, so it is worth nothing at worst and has no ceiling at best. Selling that last slice to lock in a few thousandths of a SOL gives up every large outcome for a rounding error, and large outcomes are the entire reason to hold. Concretely: a position that ran to 1.4x and then hit its trailing stop used to be dumped completely for about +0.003 SOL; it now sells 71% to return the stake and keeps 29% riding at zero cost. Losses are unchanged and still exit completely, because nothing is free until the stake is back, and the hard stop-loss still overrides everything while real money is at risk. Held positions are booked as closed for accounting the moment the profit is banked, so they never occupy a slot that would stop a strategy from taking its next trade. Each strategy's held bags and their current value are now shown on the experiments board, tracked separately from realized profit since nothing counts as profit until it is sold. This also repairs the take-initials ladder, which could never actually fire: the exit settings lived on the strategy but were missing from the query the position loop reads, so every position silently fell back to selling everything no matter how it was configured. (`/sniper/experiments`) `[feature, fix]`
+- **The trading postmortem's findings are now enforced in code** — Our published audit of the fleet's first 90 real trades ended with a list of fixes, and four of them are now live code instead of intentions. First, the overconfidence ceiling: the audit showed AI judge verdicts at 0.7 confidence performed best while verdicts above 0.9 went winless, so each AI-judged strategy now carries a confidence ceiling next to its floor, and a screaming-confident verdict is recorded but never funded. Second, named-model integrity: during the audit most calls to the named models were actually answered by cheaper fallback models, muddying the model-vs-model comparison, so the Grok and Claude strategies are now strict and will pause rather than trade on a fallback's judgment. Third, the liquidity-decay exit: a coin nobody is trading at all now gets sold after five quiet minutes instead of squatting on a trading slot for the full half-hour timeout, and this only applies underwater, so quiet winners still ride. Fourth, and most important operationally: the audit found two of the fleet's learning loops had been silently dead for two days behind green health checks, so a new hourly watchdog now asks every learning loop when it last actually wrote a row, and pages us when any answer is too old. A loop that has never written a row counts as the worst finding, not a pass. (`/docs/trading-experiment`) `[improvement, fix, infra]`
- **three.ws is an OpenAI Select Partner** — three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. A new page at /openai lays out everything the platform already ships on OpenAI surfaces: the free, keyless 3D Studio MCP connector for ChatGPT with nine tools (text to 3D, avatars, auto-rigging, conversational refinement, and a living agent body), the custom GPT Actions surface for plans without connectors, one-tap AR on iOS and Android, and Spatial MCP, the open CC0 shape for returning a live 3D scene as a tool result. The partner directory at /partners was also rewritten to list only the programs three.ws is actually enrolled in today, with NVIDIA correctly described as Inception membership. (`/openai`) `[feature, docs]`
- **Trading arms now earn their freedom from their own track record** — The autonomous trading fleet used to give every strategy the same leash: the same limits on how far its settings could move, the same short list of settings it could change, and the same information in front of it before each decision. A strategy that had been making money for weeks was kept in exactly the same box as one that had never had a winning day. Now each arm is graded on its own real, on-chain results and placed in one of four tiers. A profitable arm gets a wider range to work in, moves faster, unlocks settings a losing arm can't touch (which launches it hunts, how confident it needs to be before buying, and the take-initials exit that banks your stake at 2x and lets the rest ride), takes a bigger share of the fleet's fixed daily budget, and is shown far more evidence before it decides: how often launches actually succeed, which signals genuinely predict a winner, its own trading history, and how well its own past calls turned out. A bleeding arm is held tighter instead. Grading is on realized profit rather than win rate, so an arm that wins only a third of its trades but makes real money is rewarded, while one that wins most of its trades and still loses money is not. Every tier is re-earned continuously, so an arm that stops paying loses the extra rope automatically. None of it can touch the safety limits: the trade firewall, the daily loss cap, position limits, and a hard stop-loss apply at every tier, no matter how well an arm is doing. Each arm's tier and the evidence behind it are visible on the experiments board. (`/sniper/experiments`) `[feature, improvement]`
diff --git a/STRUCTURE.md b/STRUCTURE.md
index b1de709c4..31c4fc388 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -78,12 +78,13 @@ bottom.
| Avatar fidelity evaluation (selfie → avatar, scored) | [workers/avatar-reconstruction/eval/](workers/avatar-reconstruction/eval) | In-repo · gates every reconstruction change | **Identity Shape Error (ISE)** — does the reconstructed avatar have *this person's* face shape? Texture-blind, pose- and scale-invariant, dimensionless: MediaPipe's 468 landmarks and the avatar's corresponding head vertices are both Umeyama-aligned onto the neutral canonical face over a stable identity subset (no eyes/lips, so a smile is not scored as identity), then compared. A pipeline cannot score better by resizing or tilting the head — only by matching shape, a property pinned in [eval/test_identity_eval.py](workers/avatar-reconstruction/eval/test_identity_eval.py) alongside monotonicity. [`run_eval.py`](workers/avatar-reconstruction/eval/run_eval.py) scores a whole reference set against a live worker and diffs two revisions, surfacing per-face regressions a mean would hide. Reference photos are never committed (gitignored; mirrored via `gs://three-ws-avatar-reconstructions/eval-refs/`). Docs: [eval/README.md](workers/avatar-reconstruction/eval/README.md), program plan [docs/avatar-fidelity-program.md](docs/avatar-fidelity-program.md) |
| Avatar Composer (modular studio generation) | [api/_lib/avatar-composer/](api/_lib/avatar-composer) | In-repo · wired into the studio seed lane | Assembles a rigged, ARKit-expression-ready GLB by mixing skinned parts (hair / top / bottom / footwear / glasses) across the RPM base bodies onto **one shared 67-joint skeleton**, then recolors each part and scales the rig — the Ready-Player-Me / Avaturn "one skeleton, many parts" architecture in pure JS on `@gltf-transform`, no GPU or external service. Replaces the recolor-one-of-five-bodies studio lane so two draws almost never look alike. Borrowed parts keep their own inverse binds but remap onto the identity skeleton; mixing is restricted to a base's rest-pose group so parts always fit. Consumed by [api/cron/avaturn-seed-cron.js](api/cron/avaturn-seed-cron.js) (legacy [studio-avatar.js](api/_lib/studio-avatar.js) recolor is the fallback) and the one-click [api/avatars/surprise.js](api/avatars/surprise.js) endpoint (instant avatar, previewed in [public/gallery/surprise.js](public/gallery/surprise.js)). Docs: [api/_lib/avatar-composer/README.md](api/_lib/avatar-composer/README.md). Tests: [tests/avatar-composer.test.js](tests/avatar-composer.test.js) |
| Auto-rigging worker (Mixamo skeleton + ARKit-52 blendshapes) | [workers/rig/](workers/rig) | Code-complete · deploy pending (asset staging + Cloud Build, see its README) | Make-It-Animatable engine (MIT) predicts the 52-bone Mixamo skeleton + weights; [workers/rig/rig_glb.py](workers/rig/rig_glb.py) grafts them into the original GLB (textures untouched); ICT-FaceKit (MIT) ARKit-52 expression transfer for emotions/lipsync. Contract-compatible replacement for the retired `unirig` service behind `GCP_UNIRIG_URL`; cutover is one env-var update. Canonicalization proof: `rig worker skeleton` cases in [tests/glb-canonicalize.test.js](tests/glb-canonicalize.test.js) |
+| Additive wardrobe (dress any avatar from the catalog) | Runtime [src/avatar-garment.js](src/avatar-garment.js) + taxonomy [src/garment-taxonomy.js](src/garment-taxonomy.js) + catalog [src/garment-catalog.js](src/garment-catalog.js) + closet UI [src/garment-closet.js](src/garment-closet.js) (in the `/avatar-edit` Wardrobe tab), bake pass [api/_lib/bake-garments.js](api/_lib/bake-garments.js), contract [specs/GARMENT_MANIFEST.md](specs/GARMENT_MANIFEST.md) | Live in the avatar editor · catalog seeding in progress | The wardrobe's additive half: catalog garments (top/bottom/footwear/outerwear/hair/headwear/glasses/accessory) are skinned onto ANY loaded humanoid at wear-time — skin indices rewritten to the avatar's bone order via [glb-canonicalize](src/glb-canonicalize.js) canonical names, garment inverse-binds kept where skeletons correspond (divergent rest poses reconcile), body culled under declared `occludes` regions so skin never clips through cloth, ≥60% weight-coverage gate refuses unbindable pieces. Saved outfits persist in `appearance.garments` and the server bake re-runs the same rebind on @gltf-transform so exports/embeds are dressed. Catalog: public GCS `three-ws-garments` bucket, sha256-verified per download, licence-gated (CC0/CC-BY/MIT/Apache/BSD only). Docs: [docs/avatar-wardrobe.md](docs/avatar-wardrobe.md). Tests: [tests/avatar-garment.test.js](tests/avatar-garment.test.js), [tests/garment-catalog.test.js](tests/garment-catalog.test.js), [tests/bake-garments.test.js](tests/bake-garments.test.js) |
| Parametric avatar base (change-everything sliders) | Baker [scripts/build-parametric-base.mjs](scripts/build-parametric-base.mjs) → [public/avatars/parametric-base.glb](public/avatars), CC0 source data [avatar-sources/anny/](avatar-sources/anny), studio wiring [src/avatar-studio.js](src/avatar-studio.js) (`?base=parametric`) + [src/avatar-sculpt.js](src/avatar-sculpt.js) | Live in Avatar Studio (Base switcher) | One canonical humanoid whose identity is **122 baked morph-target sliders** (nose/ears/mouth/eyes/jaw/cheeks/head shape/neck plus gender, muscle, weight, age, height, torso, hips, limbs), built from the CC0 MakeHuman/MPFB2 body vendored via [naver/anny](https://github.com/naver/anny). 52-bone `mixamorig:*` skeleton, so the full clip library retargets onto every slider combination. Sparse-accessor morphs keep the GLB at ~4 MB. Roadmap to conforming hair/garments + sculpt brush: [prompts/roadmap/avatar-parametric-editor.md](prompts/roadmap/avatar-parametric-editor.md). Tests: [tests/parametric-base.test.js](tests/parametric-base.test.js) |
| Animation gallery | [pages/animations.html](pages/animations.html) + [src/animations-gallery.js](src/animations-gallery.js) | Live at `/animations` | 2,100+ clips with poster thumbnails ([scripts/build-animation-thumbnails.mjs](scripts/build-animation-thumbnails.mjs)), derived categories ([src/animation-categories.js](src/animation-categories.js)), shared live-preview engine ([src/animations-live-preview.js](src/animations-live-preview.js)) · see [docs/animations.md](docs/animations.md) |
| Character Library | [pages/character-library.html](pages/character-library.html) + [src/character-library.js](src/character-library.js) → `/character-library`, API [api/avatars/library.js](api/avatars/library.js) | Live at `/character-library` | 106 professionally rigged Mixamo characters (skinned GLB + thumbnails on R2, `avatars/mixamo/`), each drives the full animation library. Pipeline: [scripts/fetch-mixamo-avatars.mjs](scripts/fetch-mixamo-avatars.mjs) → [scripts/convert-mixamo-avatars.mjs](scripts/convert-mixamo-avatars.mjs) → [scripts/fetch-mixamo-avatar-thumbnails.mjs](scripts/fetch-mixamo-avatar-thumbnails.mjs) → [scripts/build-mixamo-avatar-library.mjs](scripts/build-mixamo-avatar-library.mjs) publishes `avatars/library/manifest.json`. Cards deep-link into the 3D viewer (`/app#model=`), Widget Studio (`/studio?model=`), and Animation Studio (`/pose?src=`). Mirrors the animation-library R2-manifest pattern (no DB). See [public/avatars/mixamo/README.md](public/avatars/mixamo/README.md) |
| Object Library | [pages/objects.html](pages/objects.html) + [src/objects-library.js](src/objects-library.js) → `/objects`, API [api/objects/library.js](api/objects/library.js) | Live at `/objects` | Hundreds of CC0 (public-domain) 3D props from Poly Haven (packed to GLB on R2, `objects/polyhaven/`). Pipeline: [scripts/fetch-polyhaven-objects.mjs](scripts/fetch-polyhaven-objects.mjs) (glTF→GLB via @gltf-transform) → [scripts/render-glb-thumbnails.mjs](scripts/render-glb-thumbnails.mjs) → [scripts/build-object-library.mjs](scripts/build-object-library.mjs) publishes `objects/library/manifest.json`. Same R2-manifest pattern as the Character/animation libraries (no DB). Cards preview in the 3D viewer (`/app#model=`), place into AR Studio (`/ar/studio?src=`), and download the GLB directly (CC0). AR Studio's tray also has an Objects tab over the same manifest. |
| Motion Swap (avatar body-swap in video) | [pages/motion-swap.html](pages/motion-swap.html) `→ /motion-swap` + [src/motion-swap.js](src/motion-swap.js), API [api/motion-swap.js](api/motion-swap.js), worker [workers/model-video2motion/](workers/model-video2motion) | Live | Upload a video of one person, get it back with a 3D avatar performing their motion. The worker (CPU Cloud Run, MediaPipe pose + selfie segmentation, both Apache-2.0) tracks 33 world landmarks per frame, solves them onto the canonical Wolf3D skeleton with an in-house bend-plane IK solver ([pose_solver.py](workers/model-video2motion/pose_solver.py), pure NumPy, unit-tested), and emits a standard `AnimationClip.toJSON()` + person-mask video + per-frame screen anchors. The browser composites in one WebGL scene: footage on a shader quad with the subject pixelated under the mask, avatar retargeted via [src/animation-retarget.js](src/animation-retarget.js) and pinned to the subject's anchor each frame, MediaRecorder export with original audio. Provider mode `video2motion` (`GCP_VIDEO2MOTION_URL`) in [api/_providers/gcp.js](api/_providers/gcp.js). Docs: [docs/motion-swap.md](docs/motion-swap.md). Tests: [workers/model-video2motion/test_pose_solver.py](workers/model-video2motion/test_pose_solver.py). |
-| Sign Language (feature home) | [pages/sign-language.html](pages/sign-language.html) `→ /sign-language` + [src/sign-language-page.js](src/sign-language-page.js) | Live | The front door for signing avatars: a live avatar signing on arrival (PoseStage + [src/sign-speech.js](src/sign-speech.js) SignSpeaker, portrait-framed), an input that fingerspells any word or number, the three ASL capabilities explained, and an embedded webcam sign-recognition demo. Engines: [src/fingerspelling.js](src/fingerspelling.js) (26 letters + 0–9 handshapes), [src/sign-speech.js](src/sign-speech.js) (text→one signing clip, dictionary + fingerspell fallback), [src/sign-input.js](src/sign-input.js) (browser Holistic landmarks → text). Docs: [docs/sign-language.md](docs/sign-language.md). Tests: `tests/{fingerspelling,sign-speech,sign-input}.test.js`. |
+| Sign Language (feature home) | [pages/sign-language.html](pages/sign-language.html) `→ /sign-language` + [src/sign-language-page.js](src/sign-language-page.js) | Live | The front door for signing avatars: a live avatar signing on arrival (PoseStage + [src/sign-speech.js](src/sign-speech.js) SignSpeaker, portrait-framed), an input that signs or spells anything you type (reporting which words were which), a playable vocabulary of every word with a real sign, and an embedded webcam sign-recognition demo. Engines: [src/sign-rig.js](src/sign-rig.js) (skeleton measured from the bind pose → forward kinematics + two-bone arm IK, so a sign is authored as a place in signing space, not as joint angles), [src/sign-handshapes.js](src/sign-handshapes.js) (A–Z, 0–9, and the named shapes), [src/sign-clip.js](src/sign-clip.js) (resting signer, phase poser, eased timeline → clip JSON), [src/sign-dictionary.js](src/sign-dictionary.js) (the lexical vocabulary, one- and two-handed), [src/fingerspelling.js](src/fingerspelling.js) (the manual alphabet), [src/sign-speech.js](src/sign-speech.js) (text→one signing clip, signs where they exist and spelling for the rest), [src/sign-input.js](src/sign-input.js) (browser Holistic landmarks → text). Docs: [docs/sign-language.md](docs/sign-language.md). Tests: `tests/{sign-rig,sign-dictionary,fingerspelling,sign-speech,sign-input}.test.js`. |
| ASL recognition (webcam signing → text) | worker [workers/model-asl-recognition/](workers/model-asl-recognition), API [api/asl-recognition.js](api/asl-recognition.js) (`GCP_ASL_RECOGNITION_URL`) | Live | The reverse direction of [sign speech](docs/sign-language.md): the browser extracts MediaPipe landmarks from the webcam (video never leaves the device) and the worker transcribes continuous ASL fingerspelling to text on CPU via LiteRT, with a decode-confidence score and an LLM cleanup pass on the API. Model: Kaggle 2023 ASLFR 1st-place (Apache-2.0 code + weights, FSboard CC BY 4.0 corpus — the license-clean chain most ASL models lack). Cloud Run gen2 + `patchelf --clear-execstack` on the LiteRT .so. Next: word-level signs (PopSign retrain). Tests: [workers/model-asl-recognition/test_decode.py](workers/model-asl-recognition/test_decode.py). |
| Avatar thumbnail coverage | [api/_lib/avatar-thumbs.js](api/_lib/avatar-thumbs.js) + crons [api/cron/avatar-thumbnail-backfill.js](api/cron/avatar-thumbnail-backfill.js) (absent thumbnails, `*/5`) and [api/cron/avatar-thumbnail-render.js](api/cron/avatar-thumbnail-render.js) (stale marketplace thumbnails, `*/10`) | Live | The single owner of `avatars.thumbnail_key`. Enforces the invariant that a thumbnail key is persisted **only after** its R2 object is confirmed to exist — a key pointing at a missing object makes R2 return 404 `text/plain`, which Chrome blocks as `ERR_BLOCKED_BY_ORB` inside an `<img>`. Fills coverage cheapest-first: zero-copy adoption of `forge_creations.preview_key`, then a headless-chromium GLB→PNG render to `thumb/<avatarId>.png` ([api/_lib/render-glb.js](api/_lib/render-glb.js)). Bounded retries via the `avatar_thumbnail_backfill` claim ledger ([migration](api/_lib/migrations/20260709120000_avatar_thumbnail_backfill.sql)), with `isBrowserInfrastructureError()` separating an OOM-killed browser from a genuinely broken model so a crash never retires healthy avatars. Bulk runner: [scripts/backfill-avatar-thumbnails.mjs](scripts/backfill-avatar-thumbnails.mjs) (`--status`, `--adopt-only`, `--loop`, `--reset-infra`). Docs: [docs/avatar-thumbnails.md](docs/avatar-thumbnails.md). Tests: [tests/avatar-thumbs.test.js](tests/avatar-thumbs.test.js), [tests/home-thumbnail-orb.test.js](tests/home-thumbnail-orb.test.js) |
| Forge model categorization | Classifier [api/_lib/forge-classify.js](api/_lib/forge-classify.js), wired at generation in [api/_lib/forge-store.js](api/_lib/forge-store.js) (`createCreation`), backfill [scripts/backfill-forge-categories.mjs](scripts/backfill-forge-categories.mjs), coloured badges in [src/forge-showcase.js](src/forge-showcase.js) + `/forge-studio` twin | Live | Assigns every forge model a `model_category` (avatar/accessory/item/scene/creature/vehicle/other) from its prompt with a deterministic, dependency-free keyword classifier — most-specific-first so "a knight riding a horse" is an avatar, not a creature. Nothing set the category before, so ~99.8% of the corpus was `other` and the category badges, filters, and Forge-Off category dimension were dead; the classifier now runs inline on every generation (all lanes) and reclassifies ~85% of the 9.8k-row back catalogue (dry-run verified). Coloured category pills render across the showcase/gallery/community feed. Tests: [tests/forge-classify.test.js](tests/forge-classify.test.js). |
diff --git a/api/_lib/bake-garments.js b/api/_lib/bake-garments.js
new file mode 100644
index 000000000..d517e3fd9
--- /dev/null
+++ b/api/_lib/bake-garments.js
@@ -0,0 +1,400 @@
+// Server-side additive-garment baker.
+//
+// The runtime counterpart lives in src/avatar-garment.js: it rebinds a garment
+// GLB onto a live three.js skeleton in the editor. This module performs the
+// SAME rebind on a @gltf-transform Document inside bakeAppearance(), so an
+// avatar saved wearing catalog garments serves a fully dressed GLB to every
+// consumer that never runs our runtime — embeds, AR quick-look, external
+// engines, /play.
+//
+// The math is identical (see the skinning contract in avatar-garment.js):
+// 1. rewrite each garment primitive's JOINTS_0 from garment-joint-order into
+// avatar-joint-order via canonical bone names, ancestor-fallback for
+// helper joints, weights zeroed+renormalised when a joint has no home;
+// 2. give the garment a skin whose joints are the avatar's but whose
+// inverseBindMatrices keep the GARMENT's values where the two correspond —
+// that is what reconciles a divergent rest pose;
+// 3. cull body triangles under the garment's declared `occludes` regions so
+// skin never pokes through cloth in the baked output.
+//
+// Failure posture mirrors the client: a garment that cannot bind at
+// MIN_BIND_COVERAGE is skipped with a warning, never baked in mangled. A bake
+// with zero attachable garments is still a valid bake.
+
+import { createHash } from 'node:crypto';
+import { canonicalizeBoneName } from '../../src/glb-canonicalize.js';
+import {
+ REGION_BONES,
+ MIN_BIND_COVERAGE,
+} from '../../src/garment-taxonomy.js';
+import { sanitizeCatalog } from '../../src/garment-catalog.js';
+
+export const GARMENT_CATALOG_URL =
+ 'https://storage.googleapis.com/three-ws-garments/garments/catalog.json';
+
+// Catalog cache: the bake path can be hit in bursts (bulk re-bakes) and the
+// catalog is small and slow-moving.
+let _catalog = null; // { garments, expiresAt }
+const CATALOG_TTL_MS = 5 * 60_000;
+
+async function loadServerCatalog() {
+ if (_catalog && _catalog.expiresAt > Date.now()) return _catalog.garments;
+ const res = await fetch(GARMENT_CATALOG_URL, { headers: { accept: 'application/json' } });
+ if (!res.ok) throw new Error(`garment catalog fetch failed: ${res.status}`);
+ const { garments } = sanitizeCatalog(await res.json());
+ _catalog = { garments, expiresAt: Date.now() + CATALOG_TTL_MS };
+ return garments;
+}
+
+/** Test seam + cache invalidation hook. */
+export function _resetCatalogCache() {
+ _catalog = null;
+}
+
+/* ── document helpers ────────────────────────────────────────────────────── */
+
+/** The avatar's primary skin: the one deforming the most vertices. */
+export function findPrimarySkin(doc) {
+ let best = null;
+ for (const node of doc.getRoot().listNodes()) {
+ const skin = node.getSkin();
+ const mesh = node.getMesh();
+ if (!skin || !mesh) continue;
+ let count = 0;
+ for (const prim of mesh.listPrimitives()) {
+ count += prim.getAttribute('POSITION')?.getCount() || 0;
+ }
+ if (!best || count > best.count) best = { skin, node, mesh, count };
+ }
+ return best;
+}
+
+/** canonical bone name → joint index for a skin. First occurrence wins. */
+function jointIndexByCanonical(skin) {
+ const map = new Map();
+ skin.listJoints().forEach((joint, i) => {
+ const canonical = canonicalizeBoneName(joint.getName() || '');
+ if (canonical && !map.has(canonical)) map.set(canonical, i);
+ });
+ return map;
+}
+
+/** child node → parent node map for ancestor-fallback walks. */
+function parentMap(doc) {
+ const map = new Map();
+ for (const node of doc.getRoot().listNodes()) {
+ for (const child of node.listChildren()) map.set(child, node);
+ }
+ return map;
+}
+
+/**
+ * Map garment joint indices onto avatar joint indices (canonical name match,
+ * nearest-mapped-ancestor fallback, -1 when unresolvable).
+ */
+export function buildJointRemap(garmentSkin, avatarSkin, parents) {
+ const avatarIndex = jointIndexByCanonical(avatarSkin);
+ const joints = garmentSkin.listJoints();
+ const jointSet = new Set(joints);
+ const remap = new Int32Array(joints.length).fill(-1);
+
+ joints.forEach((joint, i) => {
+ for (let node = joint; node && jointSet.has(node); node = parents.get(node)) {
+ const canonical = canonicalizeBoneName(node.getName() || '');
+ if (canonical && avatarIndex.has(canonical)) {
+ remap[i] = avatarIndex.get(canonical);
+ return;
+ }
+ }
+ });
+ return remap;
+}
+
+/** Share of skin weight that survives the remap, across all of a mesh's prims. */
+function bindCoverageOfMesh(mesh, remap) {
+ let total = 0;
+ let kept = 0;
+ for (const prim of mesh.listPrimitives()) {
+ const joints = prim.getAttribute('JOINTS_0');
+ const weights = prim.getAttribute('WEIGHTS_0');
+ if (!joints || !weights) continue;
+ const j = joints.getArray();
+ const w = weights.getArray();
+ for (let i = 0; i < w.length; i++) {
+ if (w[i] <= 0) continue;
+ total += w[i];
+ if (remap[j[i]] >= 0) kept += w[i];
+ }
+ }
+ return total > 0 ? kept / total : 0;
+}
+
+/** Rewrite JOINTS_0/WEIGHTS_0 of every primitive into avatar joint order. */
+function remapMeshSkinAttributes(mesh, remap) {
+ for (const prim of mesh.listPrimitives()) {
+ const joints = prim.getAttribute('JOINTS_0');
+ const weights = prim.getAttribute('WEIGHTS_0');
+ if (!joints || !weights) continue;
+ const j = joints.getArray();
+ const w = weights.getArray();
+ const outJ = new Uint16Array(j.length);
+ const outW = new Float32Array(w.length);
+ for (let v = 0; v < j.length; v += 4) {
+ let sum = 0;
+ for (let c = 0; c < 4; c++) {
+ const mapped = remap[j[v + c]];
+ if (mapped >= 0 && w[v + c] > 0) {
+ outJ[v + c] = mapped;
+ outW[v + c] = w[v + c];
+ sum += w[v + c];
+ }
+ }
+ if (sum > 0 && Math.abs(sum - 1) > 1e-6) {
+ for (let c = 0; c < 4; c++) outW[v + c] /= sum;
+ }
+ }
+ joints.setArray(outJ);
+ weights.setArray(outW);
+ }
+}
+
+/**
+ * A skin for the rebound garment: avatar joints, garment inverseBindMatrices
+ * where a garment joint claimed that avatar joint, avatar IBMs elsewhere.
+ */
+function buildReboundSkin(doc, garmentSkin, avatarSkin, remap, label) {
+ const avatarJoints = avatarSkin.listJoints();
+ const avatarIbm = avatarSkin.getInverseBindMatrices()?.getArray();
+ const garmentIbm = garmentSkin.getInverseBindMatrices()?.getArray();
+ const out = new Float32Array(avatarJoints.length * 16);
+ if (avatarIbm) out.set(avatarIbm.subarray(0, out.length));
+
+ const claimed = new Set();
+ for (let g = 0; g < remap.length; g++) {
+ const a = remap[g];
+ if (a < 0 || claimed.has(a) || !garmentIbm) continue;
+ claimed.add(a);
+ out.set(garmentIbm.subarray(g * 16, g * 16 + 16), a * 16);
+ }
+
+ const buffer = doc.getRoot().listBuffers()[0] || doc.createBuffer();
+ const ibmAccessor = doc
+ .createAccessor(`${label}:ibm`)
+ .setType('MAT4')
+ .setArray(out)
+ .setBuffer(buffer);
+
+ const skin = doc.createSkin(label).setInverseBindMatrices(ibmAccessor);
+ for (const joint of avatarJoints) skin.addJoint(joint);
+ const skeleton = avatarSkin.getSkeleton();
+ if (skeleton) skin.setSkeleton(skeleton);
+ return skin;
+}
+
+/* ── occlusion ───────────────────────────────────────────────────────────── */
+
+/**
+ * Drop body triangles fully covered by the garments' declared regions — the
+ * bake-time equivalent of cullSkinByBones in avatar-garment.js. Same seam
+ * policy: a triangle survives unless every corner is covered.
+ */
+export function cullBodyRegions(bodyMesh, avatarSkin, regions, threshold = 0.5) {
+ const wanted = new Set();
+ for (const region of regions) {
+ for (const b of REGION_BONES[region] || []) wanted.add(b);
+ }
+ if (!wanted.size) return 0;
+
+ const jointIndices = new Set();
+ avatarSkin.listJoints().forEach((joint, i) => {
+ if (wanted.has(canonicalizeBoneName(joint.getName() || ''))) jointIndices.add(i);
+ });
+ if (!jointIndices.size) return 0;
+
+ let droppedTotal = 0;
+ for (const prim of bodyMesh.listPrimitives()) {
+ const indexAccessor = prim.getIndices();
+ const joints = prim.getAttribute('JOINTS_0');
+ const weights = prim.getAttribute('WEIGHTS_0');
+ if (!indexAccessor || !joints || !weights) continue;
+
+ const j = joints.getArray();
+ const w = weights.getArray();
+ const vertCount = joints.getCount();
+ const covered = new Uint8Array(vertCount);
+ for (let v = 0; v < vertCount; v++) {
+ let sum = 0;
+ for (let c = 0; c < 4; c++) {
+ if (jointIndices.has(j[v * 4 + c])) sum += w[v * 4 + c];
+ }
+ covered[v] = sum >= threshold ? 1 : 0;
+ }
+
+ const src = indexAccessor.getArray();
+ const kept = [];
+ let dropped = 0;
+ for (let i = 0; i < src.length; i += 3) {
+ if (covered[src[i]] && covered[src[i + 1]] && covered[src[i + 2]]) { dropped++; continue; }
+ kept.push(src[i], src[i + 1], src[i + 2]);
+ }
+ if (dropped) {
+ indexAccessor.setArray(
+ vertCount > 65535 ? new Uint32Array(kept) : new Uint16Array(kept),
+ );
+ droppedTotal += dropped;
+ }
+ }
+ return droppedTotal;
+}
+
+/* ── main entry ──────────────────────────────────────────────────────────── */
+
+/**
+ * Merge every wearable in `garmentRefs` ({slot, id}[]) into `doc`, rebinding
+ * each onto the avatar's primary skin, then cull occluded body regions.
+ *
+ * @param {import('@gltf-transform/core').NodeIO} io
+ * @param {import('@gltf-transform/core').Document} doc
+ * @param {Array<{slot: string, id: string}>} garmentRefs
+ * @param {(doc: any, srcDoc: any) => void} mergeDocumentsFn passed in from
+ * bake.js so this module doesn't duplicate the gltf-transform import
+ * surface bake.js already manages.
+ * @param {object} [opts] test seams
+ * @param {object[]} [opts.catalog] bypass the live catalog fetch
+ * @param {(manifest: object) => Promise<ArrayBuffer>} [opts.fetchBytes]
+ * @returns {Promise<{ attached: string[], skipped: Array<{id: string, reason: string}> }>}
+ */
+export async function applyGarments(io, doc, garmentRefs, mergeDocumentsFn, opts = {}) {
+ const attached = [];
+ const skipped = [];
+ if (!Array.isArray(garmentRefs) || !garmentRefs.length) return { attached, skipped };
+
+ const primary = findPrimarySkin(doc);
+ if (!primary) {
+ return {
+ attached,
+ skipped: garmentRefs.map((r) => ({ id: r.id, reason: 'avatar has no skin to bind against' })),
+ };
+ }
+
+ let catalog;
+ try {
+ catalog = opts.catalog || (await loadServerCatalog());
+ } catch (err) {
+ return {
+ attached,
+ skipped: garmentRefs.map((r) => ({ id: r.id, reason: `catalog unavailable: ${err.message}` })),
+ };
+ }
+ const byKey = new Map(catalog.map((g) => [`${g.slot}/${g.id}`, g]));
+
+ const scene = doc.getRoot().getDefaultScene() || doc.getRoot().listScenes()[0];
+ const occludeRegions = new Set();
+
+ for (const ref of garmentRefs) {
+ const manifest = byKey.get(`${ref.slot}/${ref.id}`);
+ if (!manifest) {
+ skipped.push({ id: ref.id, reason: 'not in catalog' });
+ continue;
+ }
+
+ let bytes;
+ try {
+ bytes = await (opts.fetchBytes || fetchGarmentBytes)(manifest);
+ } catch (err) {
+ skipped.push({ id: ref.id, reason: err.message });
+ continue;
+ }
+
+ const garmentDoc = await io.readBinary(new Uint8Array(bytes));
+
+ // Tag the garment's scene roots so we can find them after the merge
+ // (mergeDocuments disconnects source refs — same trick as the accessory
+ // path in bake.js).
+ const gScene =
+ garmentDoc.getRoot().getDefaultScene() || garmentDoc.getRoot().listScenes()[0];
+ const roots = gScene
+ ? [...gScene.listChildren()]
+ : garmentDoc.getRoot().listNodes().filter((n) => !n.listParents().some((p) => p.propertyType === 'Node'));
+ const tag = `__garment_${ref.slot}_${ref.id}`;
+ roots.forEach((node, i) => node.setName(`${tag}_${i}`));
+
+ mergeDocumentsFn(doc, garmentDoc);
+
+ const mergedRoots = doc.getRoot().listNodes().filter((n) => (n.getName() || '').startsWith(tag));
+ // Collect every mesh-bearing node under the merged roots.
+ const meshNodes = [];
+ const stack = [...mergedRoots];
+ while (stack.length) {
+ const node = stack.pop();
+ if (node.getMesh()) meshNodes.push(node);
+ stack.push(...node.listChildren());
+ }
+
+ const parents = parentMap(doc);
+ let attachedAny = false;
+ for (const node of meshNodes) {
+ const gSkin = node.getSkin();
+ if (gSkin) {
+ const remap = buildJointRemap(gSkin, primary.skin, parents);
+ const coverage = bindCoverageOfMesh(node.getMesh(), remap);
+ if (coverage < MIN_BIND_COVERAGE) {
+ skipped.push({
+ id: ref.id,
+ reason: `binds ${(coverage * 100).toFixed(0)}% of skin weight (need ${MIN_BIND_COVERAGE * 100}%)`,
+ });
+ continue;
+ }
+ remapMeshSkinAttributes(node.getMesh(), remap);
+ node.setSkin(buildReboundSkin(doc, gSkin, primary.skin, remap, `garment:${ref.id}`));
+ // Per glTF 2.0 the transform of a skinned mesh node is ignored —
+ // parking it at the scene root is spec-correct.
+ for (const s of doc.getRoot().listScenes()) s.removeChild(node);
+ const parent = parents.get(node);
+ if (parent) parent.removeChild(node);
+ scene.addChild(node);
+ attachedAny = true;
+ } else {
+ // Rigid piece: parent to the manifest's attach bone, keeping the
+ // authored offset (matches the runtime's rigid path).
+ const boneName = canonicalizeBoneName(manifest.rig?.attachBone || 'Head') || 'Head';
+ const target = primary.skin
+ .listJoints()
+ .find((jn) => canonicalizeBoneName(jn.getName() || '') === boneName);
+ if (!target) continue;
+ const parent = parents.get(node);
+ if (parent) parent.removeChild(node);
+ for (const s of doc.getRoot().listScenes()) s.removeChild(node);
+ target.addChild(node);
+ attachedAny = true;
+ }
+ }
+
+ // Drop the garment's own skeleton/scene scaffolding; prune() reclaims it.
+ for (const root of mergedRoots) {
+ for (const s of doc.getRoot().listScenes()) s.removeChild(root);
+ }
+
+ if (attachedAny) {
+ attached.push(ref.id);
+ for (const region of manifest.occludes || []) occludeRegions.add(region);
+ }
+ }
+
+ if (occludeRegions.size) {
+ cullBodyRegions(primary.mesh, primary.skin, [...occludeRegions]);
+ }
+
+ return { attached, skipped };
+}
+
+async function fetchGarmentBytes(manifest) {
+ const res = await fetch(manifest.model.uri);
+ if (!res.ok) throw new Error(`garment download failed: ${res.status}`);
+ const bytes = await res.arrayBuffer();
+ const hex = createHash('sha256').update(Buffer.from(bytes)).digest('hex');
+ if (hex !== manifest.model.sha256) {
+ throw new Error('garment bytes failed integrity check');
+ }
+ return bytes;
+}
diff --git a/api/_lib/bake.js b/api/_lib/bake.js
index 655a973cd..3b29f68d7 100644
--- a/api/_lib/bake.js
+++ b/api/_lib/bake.js
@@ -176,6 +176,26 @@ export async function bakeAppearance(baseGlbBytes, appearance) {
}
}
+ // 2b) Additive catalog garments: skinned wearables rebound onto the avatar's
+ // skeleton (specs/GARMENT_MANIFEST.md). Skips — not fails — any garment
+ // that can't bind, so the bake always lands.
+ if (Array.isArray(appearance?.garments) && appearance.garments.length > 0) {
+ try {
+ const { applyGarments } = await import('./bake-garments.js');
+ const { attached, skipped } = await applyGarments(io, doc, appearance.garments, mergeDocuments);
+ if (skipped.length) {
+ console.warn(
+ `[bake] garments skipped: ${skipped.map((s) => `${s.id} (${s.reason})`).join(', ')}`,
+ );
+ }
+ if (attached.length) {
+ console.log(`[bake] garments baked: ${attached.join(', ')}`);
+ }
+ } catch (err) {
+ console.warn(`[bake] garment pass failed, baking without garments: ${err.message}`);
+ }
+ }
+
// 3) Tag + clean.
const asset = doc.getRoot().getAsset();
asset.generator =
diff --git a/api/_lib/sniper-loops-health.js b/api/_lib/sniper-loops-health.js
new file mode 100644
index 000000000..8a50dc00d
--- /dev/null
+++ b/api/_lib/sniper-loops-health.js
@@ -0,0 +1,105 @@
+// "Count rows, not status codes."
+//
+// The July 2026 fleet audit's hardest operational lesson: two of the fleet's
+// autonomous learning loops ran DEAD for two days while every health check they
+// had returned green. The crons fired, the handlers returned 200, and no rows
+// were written. Autonomy without audited side effects is theater.
+//
+// This module is the pure half of the fix. Each loop the fleet depends on is
+// declared here with the QUESTION THAT CANNOT LIE: the freshest row it should
+// have produced, and the maximum age that row may reach before the loop is
+// declared stale. The cron (api/cron/sniper-loops-health.js) runs the queries
+// and alerts on what this classifier returns; nothing in the alert path trusts
+// a status code.
+//
+// Max ages are cadence * ~4 + slack: late enough to never page on one slow or
+// skipped run, early enough that "dead for two days" can never happen again.
+
+/**
+ * Every autonomous loop the fleet's learning depends on. `table`/`column` name
+ * the freshest-row probe (the cron builds `select max(column) from table`
+ * with an optional network filter); `maxAgeMs` is the staleness verdict line.
+ */
+export const LOOPS = [
+ {
+ name: 'intel-weight-training',
+ table: 'pump_intel_weights',
+ column: 'trained_at',
+ networkColumn: 'network',
+ maxAgeMs: 2 * 3600_000, // cron every 15 min
+ why: 'The scorer trades on these weights; stale weights mean every intel entry is judged by an old market.',
+ },
+ {
+ name: 'outcome-labeling',
+ table: 'pump_coin_outcomes',
+ column: 'labeled_at',
+ networkColumn: null, // mainnet-only table
+ maxAgeMs: 2 * 3600_000, // labeling runs with intel-learn every 15 min
+ why: 'Ground truth. Every learning loop downstream (weights, Oracle, evolution fitness) starves without new labels.',
+ },
+ {
+ name: 'llm-judging',
+ table: 'sniper_llm_verdicts',
+ column: 'created_at',
+ networkColumn: 'network',
+ maxAgeMs: 2 * 3600_000, // continuous while the firehose runs
+ why: 'The LLM arms are the experiment. No new verdicts while the feed is live means the judge chain is down.',
+ },
+ {
+ name: 'optimizer',
+ table: 'agent_sniper_optimizer_runs',
+ column: 'created_at',
+ networkColumn: 'network',
+ maxAgeMs: 26 * 3600_000, // cron every 6h; a full quiet day is legitimate when no arm has proposals
+ why: 'The intra-arm tuning loop. This is one of the two loops that silently died in the audit window.',
+ },
+ {
+ name: 'evolution',
+ table: 'sniper_evolution_log',
+ column: 'created_at',
+ networkColumn: 'network',
+ maxAgeMs: 26 * 3600_000, // cron every 12h
+ why: 'The budget-reallocation loop. The other silent death: proposals logged nothing for two days.',
+ },
+ {
+ name: 'oracle-scoring',
+ table: 'oracle_conviction',
+ column: 'scored_at',
+ networkColumn: 'network',
+ maxAgeMs: 30 * 60_000, // cron every 2 min
+ why: 'The conviction score gates entries and the oracle_crossing trigger polls it; a stale table blinds both.',
+ },
+];
+
+/**
+ * Classify each loop's freshest-row age. Pure.
+ *
+ * @param {Array<{name:string, lastAt:string|Date|null}>} probes one per LOOPS entry
+ * @param {number} now epoch ms
+ * @returns {{ ok: Array, stale: Array }} stale entries carry ageMs + the loop's why
+ */
+export function classifyLoopHealth(probes, now) {
+ const byName = new Map(LOOPS.map((l) => [l.name, l]));
+ const ok = [];
+ const stale = [];
+ for (const probe of probes || []) {
+ const loop = byName.get(probe.name);
+ if (!loop) continue;
+ const t = probe.lastAt ? new Date(probe.lastAt).getTime() : null;
+ // A loop with NO rows at all is the worst case of stale, not a pass: it has
+ // never produced a side effect. Report age as Infinity so it sorts first.
+ const ageMs = t == null || !Number.isFinite(t) ? Infinity : now - t;
+ const entry = { name: loop.name, ageMs, maxAgeMs: loop.maxAgeMs, why: loop.why, lastAt: probe.lastAt ?? null };
+ (ageMs > loop.maxAgeMs ? stale : ok).push(entry);
+ }
+ stale.sort((a, b) => b.ageMs - a.ageMs);
+ return { ok, stale };
+}
+
+/** Human line for one stale loop, used in the ops alert body. */
+export function describeStale(entry) {
+ const age = entry.ageMs === Infinity
+ ? 'has NEVER produced a row'
+ : `last row ${Math.round(entry.ageMs / 3600_000 * 10) / 10}h ago (limit ${Math.round(entry.maxAgeMs / 3600_000 * 10) / 10}h)`;
+ return `${entry.name}: ${age}. ${entry.why}`;
+}
diff --git a/api/_lib/validate.js b/api/_lib/validate.js
index 17527bab3..ab3b1cc43 100644
--- a/api/_lib/validate.js
+++ b/api/_lib/validate.js
@@ -57,6 +57,15 @@ export const avatarAppearance = z
message: 'appearance.morphs max 32 keys',
});
}
+ if (val?.garments) {
+ const slots = val.garments.map((g) => g.slot);
+ if (new Set(slots).size !== slots.length) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: 'appearance.garments: one garment per slot',
+ });
+ }
+ }
});
// Avatars are GLB/GLTF models. Lock the content-type allowlist here so both
diff --git a/api/cron/sniper-loops-health.js b/api/cron/sniper-loops-health.js
new file mode 100644
index 000000000..5080ebaf7
--- /dev/null
+++ b/api/cron/sniper-loops-health.js
@@ -0,0 +1,84 @@
+// GET/POST /api/cron/sniper-loops-health: the row-count watchdog over the
+// fleet's autonomous learning loops.
+//
+// Born from the July 2026 audit's ugliest finding: the optimizer and evolution
+// loops ran dead for two days behind green health checks, because every check
+// looked at status codes and none looked at side effects. This cron asks each
+// loop the one question that cannot lie — "when did you last write a row?" —
+// and pages the ops channel (with per-signature dedup) when any answer is too
+// old. The loop declarations and staleness policy are pure and unit-tested in
+// api/_lib/sniper-loops-health.js.
+//
+// A degraded probe (table missing, query error) is reported as its own alert
+// rather than swallowed: an unqueryable ledger is exactly the kind of silence
+// this watchdog exists to catch.
+
+import { error, json, method, wrapCron } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { sql } from '../_lib/db.js';
+import { sendOpsAlert } from '../_lib/alerts.js';
+import { LOOPS, classifyLoopHealth, describeStale } from '../_lib/sniper-loops-health.js';
+
+const NETWORK = 'mainnet';
+
+function requireCron(req, res) {
+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;
+ if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }
+ const auth = req.headers['authorization'] || '';
+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';
+ if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }
+ return true;
+}
+
+// One freshest-row probe per loop. Table/column names come from the static
+// LOOPS declaration (never user input), so the interpolation here is safe; the
+// only runtime value, the network, is parameterized.
+async function probeLoop(loop) {
+ try {
+ const where = loop.networkColumn ? `where ${loop.networkColumn} = $1` : '';
+ const params = loop.networkColumn ? [NETWORK] : [];
+ const rows = await sql.query(
+ `select max(${loop.column}) as last_at from ${loop.table} ${where}`,
+ params,
+ );
+ return { name: loop.name, lastAt: rows?.[0]?.last_at ?? null };
+ } catch (err) {
+ return { name: loop.name, lastAt: null, probeError: err?.message || 'query failed' };
+ }
+}
+
+export default wrapCron(async (req, res) => {
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const probes = await Promise.all(LOOPS.map(probeLoop));
+ const broken = probes.filter((p) => p.probeError);
+ const { ok, stale } = classifyLoopHealth(probes.filter((p) => !p.probeError), Date.now());
+
+ if (stale.length) {
+ // One alert per run covering every stale loop, deduped hourly on a stable
+ // signature so a dead loop pages once an hour until it produces rows again.
+ const body = stale.map(describeStale).join('\n');
+ await Promise.resolve(sendOpsAlert(
+ `🎯 agent-sniper — ${stale.length} learning loop(s) STALE (rows, not status codes)`,
+ body,
+ { signature: 'sniper:loops-stale' },
+ )).catch(() => {});
+ }
+ if (broken.length) {
+ await Promise.resolve(sendOpsAlert(
+ '🎯 agent-sniper — loops-health probe failed',
+ broken.map((b) => `${b.name}: ${b.probeError}`).join('\n'),
+ { signature: 'sniper:loops-probe-failed' },
+ )).catch(() => {});
+ }
+
+ return json(res, 200, {
+ ok: stale.length === 0 && broken.length === 0,
+ checked: probes.length,
+ stale: stale.map((s) => ({ name: s.name, last_at: s.lastAt, age_h: s.ageMs === Infinity ? null : Math.round(s.ageMs / 3600_000 * 10) / 10 })),
+ healthy: ok.map((s) => s.name),
+ probe_errors: broken.map((b) => ({ name: b.name, error: b.probeError })),
+ });
+});
diff --git a/data/changelog.json b/data/changelog.json
index 72fa70141..450a9e33c 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,36 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-07-25",
+ "title": "Dress any avatar: the wardrobe now adds clothes, not just recolours them",
+ "summary": "Until now the wardrobe could only recolour or hide the clothes an avatar was generated with. It can now put NEW clothes on: the avatar editor's Wardrobe tab gained a Closet with racks of catalog pieces (tops, bottoms, footwear, outerwear, hair, headwear, glasses, accessories). Click a piece and it binds to your avatar's skeleton and moves with every animation, whatever generator the avatar came from: forge characters, selfie reconstructions and uploaded models all work, because garments are fitted to the skeleton at wear-time instead of being authored for one specific body. The body is masked under whatever you wear so skin never pokes through the cloth, a piece that cannot fit a particular skeleton politely refuses instead of deforming into spaghetti, and every download is integrity-checked against the catalog before it touches your avatar. Saved outfits persist: the downloadable and embedded versions of your avatar come out dressed too.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/avatar-edit"
+ },
+ {
+ "date": "2026-07-25",
+ "title": "The signing avatar's arm now sits where a signer's arm sits, and it signs real words",
+ "summary": "The signing avatar had a broken arm. Its handshapes were right, but the arm carrying them swung out to the side and behind the body, and the clip also dragged the avatar about a metre down through the floor, so you were watching correct fingerspelling performed somewhere over the avatar's shoulder. The cause was that the arm was posed with rotations written against a skeleton convention our reference avatar does not use. Arms are now solved instead of guessed: the code measures the actual skeleton (which way each bone points, how long it is, which way each palm faces) and then runs real inverse kinematics to put the wrist at a specific point in front of the body, with the elbow hanging where an elbow hangs. Fingerspelling now happens where signers do it, in front of the dominant shoulder at jaw height with the palm facing you, and the letters themselves are unchanged, to the digit. Because a hand can now be sent to a place on the body, the avatar also has a real sign vocabulary for the first time: thirty-two everyday words including hello, thank you, please, sorry, yes, no, happy, help, love, want, welcome, name, y'all and finish, two-handed where the sign is two-handed. Type a sentence and the words with signs are signed while the rest is fingerspelled, in one continuous motion, and the page tells you which was which. There is a new section on the sign-language page listing every word it can sign, each one playable. Both arms are now posed throughout, the idle hand rests at the side instead of hanging oddly, the avatar breathes during long holds, and the camera crops closer so you can actually see the hands.",
+ "tags": [
+ "improvement",
+ "fix"
+ ],
+ "link": "/sign-language"
+ },
+ {
+ "date": "2026-07-25",
+ "title": "The trading postmortem's findings are now enforced in code",
+ "summary": "Our published audit of the fleet's first 90 real trades ended with a list of fixes, and four of them are now live code instead of intentions. First, the overconfidence ceiling: the audit showed AI judge verdicts at 0.7 confidence performed best while verdicts above 0.9 went winless, so each AI-judged strategy now carries a confidence ceiling next to its floor, and a screaming-confident verdict is recorded but never funded. Second, named-model integrity: during the audit most calls to the named models were actually answered by cheaper fallback models, muddying the model-vs-model comparison, so the Grok and Claude strategies are now strict and will pause rather than trade on a fallback's judgment. Third, the liquidity-decay exit: a coin nobody is trading at all now gets sold after five quiet minutes instead of squatting on a trading slot for the full half-hour timeout, and this only applies underwater, so quiet winners still ride. Fourth, and most important operationally: the audit found two of the fleet's learning loops had been silently dead for two days behind green health checks, so a new hourly watchdog now asks every learning loop when it last actually wrote a row, and pages us when any answer is too old. A loop that has never written a row counts as the worst finding, not a pass.",
+ "tags": [
+ "improvement",
+ "fix",
+ "infra"
+ ],
+ "link": "/docs/trading-experiment"
+ },
{
"date": "2026-07-25",
"title": "The Spatial MCP reference renderer actually renders again",
diff --git a/docs/avatar-fidelity-program.md b/docs/avatar-fidelity-program.md
index b614523a0..fbf7ab553 100644
--- a/docs/avatar-fidelity-program.md
+++ b/docs/avatar-fidelity-program.md
@@ -1,8 +1,9 @@
# Avatar fidelity program — owning selfie → avatar end to end
-**Goal:** a selfie-to-avatar engine that beats Avaturn on identity fidelity,
-runs entirely on infrastructure we own, and costs nothing per avatar. Not "good
-enough to avoid a bill" — better than the thing we would have paid for.
+**Goal:** a selfie-to-avatar engine that beats the leading commercial
+selfie-avatar products on identity fidelity, runs entirely on infrastructure we
+own, and costs nothing per avatar. Not "good enough to avoid a bill" — better
+than the thing we would have paid for.
This is the program plan. The subsystem it improves is documented in
[avatar-reconstruction.md](avatar-reconstruction.md); the worker lives in
@@ -10,16 +11,16 @@ This is the program plan. The subsystem it improves is documented in
## Why we are not buying this
-Avaturn sells exactly this capability, and their API is metered per avatar. Two
+Commercial vendors sell exactly this capability, metered per avatar. Two
reasons we build instead:
1. **It is the product.** three.ws is an avatar platform. Renting the step that
turns a person into an avatar means the core of the product is someone
else's, priced by them, rate-limited by them, and deprecable by them.
2. **The architecture is already ours.** The worker fits a person onto a
- pre-rigged fixed-topology template — the same approach Avaturn and Ready
- Player Me use. The output is born rigged with 52 ARKit blendshapes and 15
- visemes. What is missing is fidelity, and fidelity is a compute-and-research
+ pre-rigged fixed-topology template — the same approach the major commercial
+ avatar platforms use. The output is born rigged with 52 ARKit blendshapes
+ and 15 visemes. What is missing is fidelity, and fidelity is a compute-and-research
problem, which is precisely what ~$100k of Google Cloud credits buys.
Every stage is commercial-clean (Apache-2.0 / MIT / BSD / CC0). Holding that
@@ -35,8 +36,9 @@ Every track below is judged by one number, **Identity Shape Error (ISE)** —
texture-blind, pose- and scale-invariant, dimensionless. Full definition and
usage: [`workers/avatar-reconstruction/eval/README.md`](../workers/avatar-reconstruction/eval/README.md).
-Without it, "better than Avaturn" is an opinion and a research track can burn
-GPU-months moving a number nobody measured. With it, every change is a diff:
+Without it, "better than the commercial benchmark" is an opinion and a research
+track can burn GPU-months moving a number nobody measured. With it, every
+change is a diff:
```bash
python -m eval.run_eval --compare eval/reports/v1.json eval/reports/v2.json
diff --git a/docs/avatar-wardrobe.md b/docs/avatar-wardrobe.md
new file mode 100644
index 000000000..0c3cbfa4d
--- /dev/null
+++ b/docs/avatar-wardrobe.md
@@ -0,0 +1,105 @@
+# Additive Wardrobe — dress any avatar from the garment catalog
+
+The wardrobe has two halves. The **subtractive** half has existed for a while:
+recolour or hide the garment layers an avatar's GLB already contains
+(`src/avatar-wardrobe.js`). This document covers the **additive** half: putting
+a garment ON an avatar that was never generated with it — a catalog shirt onto
+a Forge-generated character, a hairstyle onto a selfie reconstruction.
+
+Open any avatar in the editor (`/avatar-edit?id=…`), Wardrobe tab. The layer
+cards for the model's built-in garments render first; the **Closet** renders
+beneath them with one rack per slot (tops, bottoms, footwear, outerwear, hair,
+headwear, glasses, accessories). Click a piece to wear it, click again or "Take
+off" to remove it. Saving the avatar persists what it wears, and the baked GLB
+served to embeds, AR, and external engines includes the garments.
+
+## Why this is not the usual wardrobe
+
+Commercial avatar platforms author every garment against one skeleton they
+control, so "attach" is trivial — and their wardrobe only fits avatars from
+their own generator. Ours binds at runtime instead: a garment authored on its
+own skeleton, with its own bone naming and its own rest pose, is rebound onto
+whatever humanoid is loaded. That works because the platform already
+normalises arbitrary rigs to a canonical bone set
+([`src/glb-canonicalize.js`](../src/glb-canonicalize.js)) — the same machinery
+that lets any humanoid drive the animation clip library.
+
+Concretely, `attachGarment()`:
+
+1. rewrites the garment's skin indices from garment-bone-order into
+ avatar-bone-order by canonical name, with helper/twist joints the avatar
+ lacks falling back to their nearest mapped ancestor;
+2. re-indexes the garment's inverse bind matrices, keeping the **garment's**
+ values where the two skeletons correspond — which is what makes a T-pose
+ garment land correctly on an A-pose avatar;
+3. refuses any garment that binds under 60% of its skin **weight**
+ (`MIN_BIND_COVERAGE`) rather than attaching a mesh that would deform into
+ garbage;
+4. masks the body in the regions the garment declares it covers
+ (`occludes`), so skin never pokes through cloth.
+
+A garment with no skin at all (hat, glasses) is parented to a single joint
+(`rig.attachBone`) instead of deformed.
+
+## The pieces
+
+| Piece | Where | Job |
+|---|---|---|
+| Attachment engine | [`src/avatar-garment.js`](../src/avatar-garment.js) | Skin rebind, occlusion, slot occupancy — the runtime core |
+| Shared taxonomy | [`src/garment-taxonomy.js`](../src/garment-taxonomy.js) | Slots, body regions, region→bone map, coverage gate |
+| Catalog loader | [`src/garment-catalog.js`](../src/garment-catalog.js) | Fetch + validate manifests; drops anything malformed or unlicensed |
+| Closet UI + controller | [`src/garment-closet.js`](../src/garment-closet.js) | Racks/tiles in the editor, attach/detach queue, appearance sync |
+| Editor wiring | [`src/avatar-edit.js`](../src/avatar-edit.js) | Hydrate on load, persist `appearance.garments`, reset/save |
+| Server schema | [`api/_lib/validate.js`](../api/_lib/validate.js) | `appearance.garments` — one garment per slot, catalog-shaped refs |
+| Bake pass | [`api/_lib/bake-garments.js`](../api/_lib/bake-garments.js) | Same rebind on the @gltf-transform document, so exports are dressed |
+| Manifest contract | [`specs/GARMENT_MANIFEST.md`](../specs/GARMENT_MANIFEST.md) | What a wearable must declare to enter the catalog |
+
+## The catalog
+
+One public JSON array of Garment Manifest v1 documents:
+
+```
+https://storage.googleapis.com/three-ws-garments/garments/catalog.json
+```
+
+Assets live under `garments/<slot>/<id>/v<version>/` in the same bucket, one
+immutable directory per version. Every manifest pins its GLB's `sha256`; both
+the client and the baker verify the bytes before attaching, so a swapped or
+truncated download is refused, never worn.
+
+Validation is strict and central (`validateManifest`): unknown spec, unknown
+slot, unknown body region, malformed hash, or a licence outside the approved
+commercial set (CC0, CC-BY, MIT, Apache-2.0, BSD) drops the entry with a
+console warning. A broken manifest becomes a missing tile, not a broken avatar.
+
+## Persistence shape
+
+```json
+"appearance": {
+ "garments": [
+ { "slot": "top", "id": "oxford-shirt-white" },
+ { "slot": "footwear", "id": "low-top-sneakers" }
+ ]
+}
+```
+
+One garment per slot, max 8, enforced by the zod schema. Existence against the
+live catalog is deliberately NOT checked at save time — a garment retired from
+the catalog later degrades to "not worn" on the next load/bake instead of
+bricking the avatar.
+
+## Failure posture
+
+- Garment can't reach the skeleton → refused with the measured coverage in the
+ reason string; the slot keeps its previous occupant.
+- Catalog unreachable → closet shows a retry state; the rest of the editor is
+ unaffected.
+- Bake-time garment failure → logged and skipped; the bake always lands.
+- Non-humanoid model → the closet is withheld (`supportsWardrobe` gate), same
+ policy as the animation library's humanoid gate.
+
+## Related
+
+- [`docs/avatar-reconstruction.md`](avatar-reconstruction.md) — selfie → avatar
+- [`docs/avatar-fidelity-program.md`](avatar-fidelity-program.md) — identity fidelity program
+- [`specs/GARMENT_MANIFEST.md`](../specs/GARMENT_MANIFEST.md) — the wearable contract
diff --git a/docs/sign-language.md b/docs/sign-language.md
index 57bb8bfec..59b91debc 100644
--- a/docs/sign-language.md
+++ b/docs/sign-language.md
@@ -1,6 +1,6 @@
# Sign language: avatars that sign
-three.ws avatars can communicate in American Sign Language. Today that means ASL fingerspelling everywhere an avatar performs, and signed chat replies on the platform's conversational surfaces. The system is built in layers so that real lexical signs (captured from human signers) progressively replace fingerspelling word by word as the sign library grows.
+three.ws avatars can communicate in American Sign Language. Words with a sign are signed, on one or both hands; everything else is fingerspelled. It runs everywhere an avatar performs, including signed chat replies on the platform's conversational surfaces.
> Studio usage (the Spell box, exports, share links) is covered in [Animation Studio](./animation-studio.md). This page covers the system: the engines, the chat integration, and the roadmap.
@@ -14,33 +14,62 @@ three.ws avatars can communicate in American Sign Language. Today that means ASL
```
- **Sign INTO the chat with your camera.** The 🎥 button in the agent chat opens your webcam with a mirrored self-view: fingerspell at the camera, click again, and the transcription lands in the message box for review before sending. Landmarks are extracted in your browser (MediaPipe Holistic), so video never leaves your device — only pose coordinates go to the recognizer ([workers/model-asl-recognition](../workers/model-asl-recognition), the Kaggle-2023 1st-place fingerspelling model; Apache-2.0 weights, CC BY 4.0 corpus). Expect a 10–20% character error rate on webcam fingerspelling; the chat model is robust to it.
-- **Motion capture with hands.** The video-to-motion worker tracks 21 landmarks per hand and solves all 30 finger joints, so a video of a real signer becomes a retargetable animation clip. This is the pipeline that will populate the lexical sign dictionary.
+- **A lexical sign vocabulary.** Common words are SIGNED, not spelled: `HELLO`, `THANK`, `HAPPY`, `SORRY`, `HELP`, `LOVE`, `WANT`, `YALL` and the rest of [`src/sign-dictionary.js`](../src/sign-dictionary.js), two-handed where the sign is two-handed. Browse and play the whole vocabulary at [/sign-language](https://three.ws/sign-language). A word with no sign fingerspells, in the same clip, with no seam.
+- **Motion capture with hands.** The video-to-motion worker tracks 21 landmarks per hand and solves all 30 finger joints, so a video of a real signer becomes a retargetable animation clip — the path for growing the vocabulary from real signers.
## How it works
-Two engines, both dependency-free JavaScript modules:
+Signing is a spatial language. A sign is a handshape, a place on or in front of the body, and a movement between places — never a list of joint angles. The stack is built that way, as dependency-free JavaScript modules:
-- [`src/fingerspelling.js`](../src/fingerspelling.js) — a parametric ASL hand model. Each letter is defined by per-finger curl, splay, a thumb preset, and wrist orientation, compiled to quaternion tracks on the canonical skeleton. `buildFingerspellingClip('HELLO')` returns the same `AnimationClip` JSON document the animation library serves.
+- [`src/sign-rig.js`](../src/sign-rig.js) — kinematics for the canonical skeleton. It **measures** the reference rig (bone axes, bone lengths, each hand's palm and thumb-side directions, the parent chain) from the generated bind pose in `src/animation-canonical-rest.js` rather than assuming a convention, then offers forward kinematics (`Pose`) and a two-bone arm IK (`solveArm`) that puts a wrist at a POINT with a natural elbow. Assuming the convention instead of measuring it is what once left the signing arm pointing behind the avatar's back.
+- [`src/sign-handshapes.js`](../src/sign-handshapes.js) — the handshape catalogue: A–Z, 0–9, and the named shapes with no letter (`CLAW`, `FLAT_O`, `BENT_B`, `OPEN_8`, `ILY`). Each is per-finger curl, splay, and a thumb preset.
+- [`src/sign-clip.js`](../src/sign-clip.js) — the authoring layer: a resting signer to start and end from, `posePhase()` to solve one phase of a sign, and `SignTimeline` to string phases together with eased transitions, a breathing idle, and clip output.
+- [`src/sign-dictionary.js`](../src/sign-dictionary.js) — the vocabulary. Each sign lists its phases; `both:` poses two hands from one description because places and directions are body-relative, so the non-dominant hand mirrors for free.
+- [`src/fingerspelling.js`](../src/fingerspelling.js) — the manual alphabet. The hand sits in front of the dominant shoulder at jaw height, palm to the reader, and only the handshape changes between letters, which is what makes fingerspelling readable. `buildFingerspellingClip('HELLO')` returns the same `AnimationClip` JSON document the animation library serves.
- [`src/sign-speech.js`](../src/sign-speech.js) — the signed counterpart of text-to-speech. `compileUtterance(text, { signs })` splits text into words, resolves each against a sign dictionary (lexical clips), fingerspells the misses, and concatenates everything into one continuous clip. `SignSpeaker` drives an avatar's `AnimationManager` like a TTS engine:
```js
import { SignSpeaker } from './sign-speech.js';
+// The built-in vocabulary is the default: known words sign, the rest spell.
const speaker = new SignSpeaker({ manager: viewer.animationManager });
-await speaker.speak('hello world'); // resolves when the signing ends
+const { signed, spelled } = await speaker.speak('happy to meet you');
+// signed → ['HAPPY', 'MEET', 'YOU']
+// spelled → ['TO']
```
+Pass `signs: null` for spelling only, or your own lookup to override the vocabulary. Every clip is upper-body: signing never writes the root translation, so it can never move the avatar off the floor.
+
+Adding a sign is a data change. Describe its phases and assert where the hands land:
+
+```js
+// src/sign-dictionary.js
+WELCOME: {
+ gloss: 'Open palm sweeps in toward the body, inviting.',
+ phases: [
+ { t: 0.32, right: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.22, up: -0.04, forward: 0.30 },
+ fingers: ['forward', 'out'], palm: 'up' }, head: { turn: -4 } },
+ { t: 0.34, right: { shape: 'FLAT', at: { anchor: 'sternum', out: 0.02, up: -0.06, forward: 0.22 },
+ fingers: ['forward', 'in'], palm: 'up' }, head: { nod: 4 }, hold: 0.18 },
+ ],
+},
+```
+
+Anchors (`forehead`, `nose`, `chin`, `mouth`, `sternum`, `belly`, `shoulder`, `hip`) are measured off the reference skeleton, and offsets are metres: `out` away from the midline, `in` toward it, `forward` toward the person reading. Directions take the same words. Because a sign is described anatomically, the same entry reads correctly on a tall avatar, a short one, and either hand.
+
Chat surfaces integrate through `AgentAvatar.setSignLanguage(true)`: the avatar layer already receives every assistant reply (the protocol `SPEAK` event), so signing rides the same event with no per-surface plumbing. Rigs without finger bones are refused with an explanation rather than signing wrong.
## Honest scope
-Fingerspelling spells English words letter by letter; it is not grammatical ASL, which has its own grammar and non-manual markers (facial expressions carry meaning). The design principle for the lexical layer: signs come from recordings of real signers, captured through the motion pipeline, never synthesized guesses. That is also why the sign dictionary starts empty rather than shipping approximations.
+The vocabulary is a core set of citation-form signs, strung together in English word order. That is signed English, not ASL grammar: real ASL reorders sentences, inflects verbs through space, and carries grammar on the face. The signs here are authored from standard descriptions, not captured from a specific signer, so they read as clear citation forms rather than as any individual's signing. Words with no entry are fingerspelled letter by letter. Non-manual markers are limited to head and torso movement, because the reference avatar carries no facial blendshapes.
+
+None of this replaces a human interpreter. It makes an avatar legible to signers instead of silent.
## Roadmap
-1. **Lexical sign dictionary** — captured clips (commissioned signers, community capture through [Motion Swap](https://three.ws/motion-swap), permissively licensed video) served as a `sign-language` library category and fed to `compileUtterance` so common words are signed, not spelled.
+1. **Captured signs** — clips from real signers (commissioned, community capture through [Motion Swap](https://three.ws/motion-swap), permissively licensed video) replacing authored entries word by word, through the same dictionary interface.
2. **Word-level sign recognition** — the current recognizer reads fingerspelling; a 250-sign vocabulary model (MIT architecture retrained on the CC BY 4.0 PopSign corpus) will let common signs be recognized directly.
-3. **Non-manual markers** — eyebrow and mouth blendshape tracks alongside the hand tracks.
+3. **Non-manual markers** — eyebrow and mouth blendshape tracks alongside the hand tracks, on avatars that carry the morph targets.
4. **Standalone package** — the engines are platform-free by design and will ship as an npm package plus reference integration.
## Related
diff --git a/docs/trading-experiment.md b/docs/trading-experiment.md
index 35564ad35..8e2713d80 100644
--- a/docs/trading-experiment.md
+++ b/docs/trading-experiment.md
@@ -106,6 +106,44 @@ the ladder on by itself and records why. See
all, so the ladder is only ever switched on for a strategy whose record shows it
actually catches runners.
+## The post-audit fixes (from the published fleet postmortem)
+
+The [published audit](https://three.ws/blog/autonomous-trading-experiment) of the
+fleet's first 90 real trades produced three findings that are now code:
+
+**Overconfidence ceiling** (`llm_max_confidence`). The audit's calibration table
+showed judge verdicts in the 0.7 confidence band performed best while 0.9+
+verdicts went winless. Each LLM arm can now carry a confidence CEILING next to
+its floor: a buy verdict at or above it is recorded for calibration but never
+funded. The experiment arms run floor 0.65, ceiling 0.9. Gate:
+`llmVerdictGate` in [workers/agent-sniper/llm-judge.js](../workers/agent-sniper/llm-judge.js).
+
+**Named-model strictness** (`llm_strict_model`). During the audit window the LLM
+failover chain answered most named-model calls, so "Grok vs Claude" was really
+"fallback vs fallback". A strict arm now refuses to trade on any verdict whose
+answering model was a fallback (`fallback:*` tag): the verdict still lands in the
+judgment ledger, but the arm pauses rather than pollutes its own experiment. The
+grok and claude arms are strict; the auto-router arm is not (a fallback IS its
+router pick).
+
+**Liquidity-decay exit** (`liquidity_decay`). A bonding-curve quote only moves
+when someone trades, so a position whose re-quoted value is exactly frozen sweep
+after sweep is a coin nobody is trading. The audit found those squatting on
+concurrency slots until the 30-minute timeout. Now an underwater position whose
+value has not moved at all for `SNIPER_LIQUIDITY_DECAY_S` (default 300s) exits
+early with reason `liquidity_decay` and frees the slot. The clock never runs in
+profit (quiet winners belong to the trailing stop and the moon-bag rule), resets
+on any trade, and a house-money position keeps its moon-bag floor even here.
+
+**Row-count watchdog** (`/api/cron/sniper-loops-health`). The audit's worst
+operational finding: two learning loops ran dead for two days behind green
+health checks. An hourly cron now asks each autonomous loop (weight training,
+outcome labeling, LLM judging, optimizer, evolution, Oracle scoring) the one
+question that cannot lie, "when did you last write a row?", and pages the ops
+channel when any answer exceeds that loop's cadence-derived limit. A loop with
+no rows at all is the worst finding, not an exemption. Policy is pure and
+tested: [api/_lib/sniper-loops-health.js](../api/_lib/sniper-loops-health.js).
+
### No-Mayhem enforcement (`workers/agent-sniper/mayhem-gate.js`)
`isMayhemMode` lives on the pump.fun bonding curve, not the new-mint firehose, so
diff --git a/public/changelog.json b/public/changelog.json
index 1895683cb..58b539add 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-25T09:07:42.742Z",
+ "generated_at": "2026-07-25T09:31:26.690Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -46,6 +46,16 @@
"launch"
]
},
+ {
+ "date": "2026-07-25",
+ "type": "update",
+ "title": "Dress any avatar: the wardrobe now adds clothes, not just recolours them",
+ "summary": "Until now the wardrobe could only recolour or hide the clothes an avatar was generated with. It can now put NEW clothes on: the avatar editor's Wardrobe tab gained a Closet with racks of catalog pieces (tops, bottoms, footwear, outerwear, hair, headwear, glasses, accessories). Click a piece and it binds to your avatar's skeleton and moves with every animation, whatever generator the avatar came from: forge characters, selfie reconstructions and uploaded models all work, because garments are fitted to the skeleton at wear-time instead of being authored for one specific body. The body is masked under whatever you wear so skin never pokes through the cloth, a piece that cannot fit a particular skeleton politely refuses instead of deforming into spaghetti, and every download is integrity-checked against the catalog before it touches your avatar. Saved outfits persist: the downloadable and embedded versions of your avatar come out dressed too.",
+ "link": "/avatar-edit",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-07-25",
"type": "update",
@@ -57,6 +67,17 @@
"feature"
]
},
+ {
+ "date": "2026-07-25",
+ "type": "update",
+ "title": "The signing avatar's arm now sits where a signer's arm sits, and it signs real words",
+ "summary": "The signing avatar had a broken arm. Its handshapes were right, but the arm carrying them swung out to the side and behind the body, and the clip also dragged the avatar about a metre down through the floor, so you were watching correct fingerspelling performed somewhere over the avatar's shoulder. The cause was that the arm was posed with rotations written against a skeleton convention our reference avatar does not use. Arms are now solved instead of guessed: the code measures the actual skeleton (which way each bone points, how long it is, which way each palm faces) and then runs real inverse kinematics to put the wrist at a specific point in front of the body, with the elbow hanging where an elbow hangs. Fingerspelling now happens where signers do it, in front of the dominant shoulder at jaw height with the palm facing you, and the letters themselves are unchanged, to the digit. Because a hand can now be sent to a place on the body, the avatar also has a real sign vocabulary for the first time: thirty-two everyday words including hello, thank you, please, sorry, yes, no, happy, help, love, want, welcome, name, y'all and finish, two-handed where the sign is two-handed. Type a sentence and the words with signs are signed while the rest is fingerspelled, in one continuous motion, and the page tells you which was which. There is a new section on the sign-language page listing every word it can sign, each one playable. Both arms are now posed throughout, the idle hand rests at the side instead of hanging oddly, the avatar breathes during long holds, and the camera crops closer so you can actually see the hands.",
+ "link": "/sign-language",
+ "tags": [
+ "improvement",
+ "fix"
+ ]
+ },
{
"date": "2026-07-25",
"type": "update",
@@ -78,6 +99,18 @@
"fix"
]
},
+ {
+ "date": "2026-07-25",
+ "type": "update",
+ "title": "The trading postmortem's findings are now enforced in code",
+ "summary": "Our published audit of the fleet's first 90 real trades ended with a list of fixes, and four of them are now live code instead of intentions. First, the overconfidence ceiling: the audit showed AI judge verdicts at 0.7 confidence performed best while verdicts above 0.9 went winless, so each AI-judged strategy now carries a confidence ceiling next to its floor, and a screaming-confident verdict is recorded but never funded. Second, named-model integrity: during the audit most calls to the named models were actually answered by cheaper fallback models, muddying the model-vs-model comparison, so the Grok and Claude strategies are now strict and will pause rather than trade on a fallback's judgment. Third, the liquidity-decay exit: a coin nobody is trading at all now gets sold after five quiet minutes instead of squatting on a trading slot for the full half-hour timeout, and this only applies underwater, so quiet winners still ride. Fourth, and most important operationally: the audit found two of the fleet's learning loops had been silently dead for two days behind green health checks, so a new hourly watchdog now asks every learning loop when it last actually wrote a row, and pages us when any answer is too old. A loop that has never written a row counts as the worst finding, not a pass.",
+ "link": "/docs/trading-experiment",
+ "tags": [
+ "improvement",
+ "fix",
+ "infra"
+ ]
+ },
{
"date": "2026-07-25",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index a69e886af..6c9857f70 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -38,6 +38,14 @@
<category>launch</category>
<description>three.ws has been named an OpenAI Select Partner within the OpenAI Partner Network. What we ship on OpenAI surfaces today: a free 3D Studio MCP connector for ChatGPT, custom GPT Actions, the open Spatial MCP response shape, and one-tap AR.</description>
</item>
+ <item>
+ <title>Dress any avatar: the wardrobe now adds clothes, not just recolours them</title>
+ <link>https://three.ws/avatar-edit</link>
+ <guid isPermaLink="false">2026-07-25:Dress any avatar: the wardrobe now adds clothes, not just recolours them</guid>
+ <pubDate>Sat, 25 Jul 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Until now the wardrobe could only recolour or hide the clothes an avatar was generated with. It can now put NEW clothes on: the avatar editor's Wardrobe tab gained a Closet with racks of catalog pieces (tops, bottoms, footwear, outerwear, hair, headwear, glasses, accessories). Click a piece and it binds to your avatar's skeleton and moves with every animation, whatever generator the avatar came from: forge characters, selfie reconstructions and uploaded models all work, because garments are fitted to the skeleton at wear-time instead of being authored for one specific body. The body is masked under whatever you wear so skin never pokes through the cloth, a piece that cannot fit a particular skeleton politely refuses instead of deforming into spaghetti, and every download is integrity-checked against the catalog before it touches your avatar. Saved outfits persist: the downloadable and embedded versions of your avatar come out dressed too.</description>
+ </item>
<item>
<title>The KOL Tracker is now reachable, and its numbers are real</title>
<link>https://three.ws/tracker</link>
@@ -46,6 +54,14 @@
<category>fix</category>
<description>The KOL Tracker page shipped listed in the sitemap but with no route behind it, so three.ws/tracker returned a 404 for everyone who followed the link, and the API behind it was answering with three placeholder rows left over from a test fixture. Both are fixed. The page is served, and it now ranks real Solana traders from the live kolscan board: realized profit, win rate and trade count for the 24h, 7d and 30d windows, enriched with our own on-chain FIFO profit calculation wherever we have the trades for a wallet. Every row states where its number came from, and when a source is unreachable the board shows an honest empty state instead of inventing traders. A new test blocks the whole class of mistake: any page advertised in the site index that has no route, or that never gets built, now fails the suite before it can reach production.</description>
</item>
+ <item>
+ <title>The signing avatar's arm now sits where a signer's arm sits, and it signs real words</title>
+ <link>https://three.ws/sign-language</link>
+ <guid isPermaLink="false">2026-07-25:The signing avatar's arm now sits where a signer's arm sits, and it signs real words</guid>
+ <pubDate>Sat, 25 Jul 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>The signing avatar had a broken arm. Its handshapes were right, but the arm carrying them swung out to the side and behind the body, and the clip also dragged the avatar about a metre down through the floor, so you were watching correct fingerspelling performed somewhere over the avatar's shoulder. The cause was that the arm was posed with rotations written against a skeleton convention our reference avatar does not use. Arms are now solved instead of guessed: the code measures the actual skeleton (which way each bone points, how long it is, which way each palm faces) and then runs real inverse kinematics to put the wrist at a specific point in front of the body, with the elbow hanging where an elbow hangs. Fingerspelling now happens where signers do it, in front of the dominant shoulder at jaw height with the palm facing you, and the letters themselves are unchanged, to the digit. Because a hand can now be sent to a place on the body, the avatar also has a real sign vocabulary for the first time: thirty-two everyday words including hello, thank you, please, sorry, yes, no, happy, help, love, want, welcome, name, y'all and finish, two-handed where the sign is two-handed. Type a sentence and the words with signs are signed while the rest is fingerspelled, in one continuous motion, and the page tells you which was which. There is a new section on the sign-language page listing every word it can sign, each one playable. Both arms are now posed throughout, the idle hand rests at the side instead of hanging oddly, the avatar breathes during long holds, and the camera crops closer so you can actually see the hands.</description>
+ </item>
<item>
<title>The Spatial MCP reference renderer actually renders again</title>
<link>https://three.ws/spatial-mcp</link>
@@ -62,6 +78,14 @@
<category>feature</category>
<description>New rule across every autonomous trading strategy: once a position has earned back what it cost, we never sell all of it. Any exit taken in profit now sells just enough to recover the original stake (or banks the gain down to a floor if the stake is already home) and keeps the rest, which then rides indefinitely. The logic is simple: after the cost is recovered the leftover position is free, so it is worth nothing at worst and has no ceiling at best. Selling that last slice to lock in a few thousandths of a SOL gives up every large outcome for a rounding error, and large outcomes are the entire reason to hold. Concretely: a position that ran to 1.4x and then hit its trailing stop used to be dumped completely for about +0.003 SOL; it now sells 71% to return the stake and keeps 29% riding at zero cost. Losses are unchanged and still exit completely, because nothing is free until the stake is back, and the hard stop-loss still overrides everything while real money is at risk. Held positions are booked as closed for accounting the moment the profit is banked, so they never occupy a slot that would stop a strategy from taking its next trade. Each strategy's held bags and their current value are now shown on the experiments board, tracked separately from realized profit since nothing counts as profit until it is sold. This also repairs the take-initials ladder, which could never actually fire: the exit settings lived on the strategy but were missing from the query the position loop reads, so every position silently fell back to selling everything no matter how it was configured.</description>
</item>
+ <item>
+ <title>The trading postmortem's findings are now enforced in code</title>
+ <link>https://three.ws/docs/trading-experiment</link>
+ <guid isPermaLink="false">2026-07-25:The trading postmortem's findings are now enforced in code</guid>
+ <pubDate>Sat, 25 Jul 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Our published audit of the fleet's first 90 real trades ended with a list of fixes, and four of them are now live code instead of intentions. First, the overconfidence ceiling: the audit showed AI judge verdicts at 0.7 confidence performed best while verdicts above 0.9 went winless, so each AI-judged strategy now carries a confidence ceiling next to its floor, and a screaming-confident verdict is recorded but never funded. Second, named-model integrity: during the audit most calls to the named models were actually answered by cheaper fallback models, muddying the model-vs-model comparison, so the Grok and Claude strategies are now strict and will pause rather than trade on a fallback's judgment. Third, the liquidity-decay exit: a coin nobody is trading at all now gets sold after five quiet minutes instead of squatting on a trading slot for the full half-hour timeout, and this only applies underwater, so quiet winners still ride. Fourth, and most important operationally: the audit found two of the fleet's learning loops had been silently dead for two days behind green health checks, so a new hourly watchdog now asks every learning loop when it last actually wrote a row, and pages us when any answer is too old. A loop that has never written a row counts as the worst finding, not a pass.</description>
+ </item>
<item>
<title>three.ws is an OpenAI Select Partner</title>
<link>https://three.ws/openai</link>
diff --git a/public/features.json b/public/features.json
index b866faf27..4c940250b 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-25T09:07:42.736Z",
+ "generated_at": "2026-07-25T09:31:26.684Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/seed-sniper-experiments.mjs b/scripts/seed-sniper-experiments.mjs
index 1dda7b75d..211440c8b 100644
--- a/scripts/seed-sniper-experiments.mjs
+++ b/scripts/seed-sniper-experiments.mjs
@@ -104,6 +104,10 @@ const ARMS = [
note: 'no shields; Grok judges every launch',
set: {
decision_mode: 'llm', llm_model: 'x-ai/grok-4.3', llm_min_confidence: 0.65,
+ // Audit findings (blog/autonomous-trading-experiment): 0.9+ confidence
+ // verdicts went winless -> ceiling; fallback models answered most named
+ // calls -> strict, this arm trades only on Grok's own judgment.
+ llm_max_confidence: 0.9, llm_strict_model: true,
require_socials: false, min_market_cap_usd: null, max_market_cap_usd: null,
min_oracle_score: null, per_trade_lamports: '10000000', daily_budget_lamports: '50000000',
max_concurrent_positions: 1,
@@ -116,6 +120,9 @@ const ARMS = [
note: 'no shields; Claude Haiku judges every launch',
set: {
decision_mode: 'llm', llm_model: 'anthropic/claude-haiku-4.5', llm_min_confidence: 0.65,
+ // Same audit rationale as llm-grok: confidence ceiling + named-model
+ // strictness. This arm was the one most answered by fallbacks.
+ llm_max_confidence: 0.9, llm_strict_model: true,
require_socials: false, min_market_cap_usd: null, max_market_cap_usd: null,
min_oracle_score: null, per_trade_lamports: '10000000', daily_budget_lamports: '50000000',
max_concurrent_positions: 1,
@@ -128,6 +135,9 @@ const ARMS = [
note: 'no shields; the OpenRouter auto-router picks the judge',
set: {
decision_mode: 'llm', llm_model: 'openrouter/auto', llm_min_confidence: 0.65,
+ // Ceiling applies (overconfidence is model-agnostic); strictness does
+ // NOT: this arm is any-model by design, a fallback IS its router pick.
+ llm_max_confidence: 0.9, llm_strict_model: false,
require_socials: false, min_market_cap_usd: null, max_market_cap_usd: null,
min_oracle_score: null, per_trade_lamports: '10000000', daily_budget_lamports: '50000000',
max_concurrent_positions: 1,
diff --git a/scripts/verify-garment.mjs b/scripts/verify-garment.mjs
new file mode 100644
index 000000000..41160393e
--- /dev/null
+++ b/scripts/verify-garment.mjs
@@ -0,0 +1,120 @@
+// Verify a published garment against the runtime wardrobe contract.
+//
+// Downloads (or reads) a garment manifest, verifies the manifest's sha256
+// against the fetched GLB bytes, loads the garment and a target avatar with
+// three's GLTFLoader, runs the REAL runtime attach path
+// (attachGarment from src/avatar-garment.js), and reports the measured bind
+// coverage plus the skin-occlusion result for the manifest's `occludes`.
+//
+// This is the "definition of done" harness for workers/garment-forge: a
+// garment only counts as shipped when this script attaches it to an avatar
+// at >= MIN_BIND_COVERAGE.
+//
+// Usage:
+// node scripts/verify-garment.mjs <manifest.json url|path> [avatar.glb url|path]
+//
+// The avatar defaults to public/avatars/parametric-base.glb, the platform's
+// canonical body. Pass any other humanoid GLB to prove cross-rig attachment.
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { createHash } from 'node:crypto';
+import { Blob } from 'node:buffer';
+
+// three's GLTFLoader touches DOM globals; same shims as scripts/build-animations.mjs.
+globalThis.self = globalThis;
+globalThis.window = globalThis;
+class FakeImage extends EventTarget {
+ constructor() {
+ super();
+ this._src = '';
+ this.style = {};
+ this.complete = false;
+ this.naturalWidth = 1;
+ this.naturalHeight = 1;
+ }
+ get src() { return this._src; }
+ set src(value) {
+ this._src = value;
+ setTimeout(() => {
+ this.complete = true;
+ this.onload?.({ target: this });
+ this.dispatchEvent(new Event('load'));
+ }, 0);
+ }
+ setAttribute() {}
+}
+globalThis.document = {
+ createElementNS: () => new FakeImage(),
+ createElement: () => new FakeImage(),
+};
+globalThis.Image = FakeImage;
+globalThis.Blob = Blob;
+
+const { GLTFLoader } = await import('three/addons/loaders/GLTFLoader.js');
+const { attachGarment, applySkinOcclusion, MIN_BIND_COVERAGE } =
+ await import('../src/avatar-garment.js');
+
+async function fetchBytes(source) {
+ if (/^https?:\/\//.test(source)) {
+ const res = await fetch(source);
+ if (!res.ok) throw new Error(`${source} -> HTTP ${res.status}`);
+ return Buffer.from(await res.arrayBuffer());
+ }
+ return readFileSync(resolve(process.cwd(), source));
+}
+
+function loadGlb(bytes) {
+ const loader = new GLTFLoader();
+ return new Promise((res, rej) => {
+ loader.parse(
+ bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),
+ '',
+ (gltf) => res(gltf),
+ rej,
+ );
+ });
+}
+
+const [manifestSource, avatarSource = 'public/avatars/parametric-base.glb'] =
+ process.argv.slice(2);
+if (!manifestSource) {
+ console.error('usage: node scripts/verify-garment.mjs <manifest url|path> [avatar url|path]');
+ process.exit(2);
+}
+
+const manifest = JSON.parse((await fetchBytes(manifestSource)).toString('utf8'));
+console.log(`manifest: ${manifest.id} v${manifest.version} slot=${manifest.slot}`);
+
+const glbBytes = await fetchBytes(manifest.model.uri);
+const sha = createHash('sha256').update(glbBytes).digest('hex');
+if (sha !== manifest.model.sha256) {
+ console.error(`FAIL sha256 mismatch: manifest=${manifest.model.sha256} fetched=${sha}`);
+ process.exit(1);
+}
+console.log(`sha256 ok (${glbBytes.length} bytes)`);
+
+const [avatar, garment] = await Promise.all([
+ fetchBytes(avatarSource).then(loadGlb),
+ loadGlb(glbBytes),
+]);
+avatar.scene.updateMatrixWorld(true);
+garment.scene.updateMatrixWorld(true);
+
+const result = attachGarment(avatar.scene, garment.scene, { slot: manifest.slot });
+if (!result.ok) {
+ console.error(`FAIL attachGarment refused: ${result.reason}`);
+ console.error(`coverage=${result.coverage.toFixed(4)} unresolved=${result.unresolved.join(', ')}`);
+ process.exit(1);
+}
+
+const occlusion = applySkinOcclusion(avatar.scene, manifest.occludes);
+
+console.log(`attachGarment: ok slot=${result.slot} meshes=${result.meshes.length}`);
+console.log(`coverage: ${result.coverage.toFixed(4)} (gate ${MIN_BIND_COVERAGE})`);
+if (result.unresolved.length) {
+ console.log(`unresolved bones (ancestor-fallback applied upstream of coverage): ${result.unresolved.join(', ')}`);
+}
+console.log(`occludes: [${manifest.occludes.join(', ')}] -> applied via ${occlusion.method}`
+ + (occlusion.trianglesHidden ? ` (${occlusion.trianglesHidden} triangles hidden)` : ''));
+console.log(`PASS ${manifest.id} binds at ${(result.coverage * 100).toFixed(1)}% >= ${MIN_BIND_COVERAGE * 100}%`);
diff --git a/src/avatar-garment.js b/src/avatar-garment.js
index f236f527e..3b9fa7d93 100644
--- a/src/avatar-garment.js
+++ b/src/avatar-garment.js
@@ -32,18 +32,16 @@
import { Bone, Matrix4, Skeleton, SkinnedMesh, Uint16BufferAttribute } from 'three';
import { canonicalizeBoneName } from './glb-canonicalize.js';
+import {
+ GARMENT_SLOTS,
+ BODY_REGIONS,
+ REGION_BONES,
+ MIN_BIND_COVERAGE,
+} from './garment-taxonomy.js';
-/** Below this share of *weighted* garment bones resolving to avatar bones, the
- * garment cannot deform sanely and we refuse rather than ship a mangled mesh.
- * Mirrors the MIN_COVERAGE gate in src/animation-retarget.js. */
-export const MIN_BIND_COVERAGE = 0.6;
-
-/** Slots a garment may occupy. One garment per slot; attaching to an occupied
- * slot detaches the incumbent. Kept deliberately in step with WARDROBE_SLOTS
- * in src/avatar-wardrobe.js so the two panels describe the same taxonomy. */
-export const GARMENT_SLOTS = Object.freeze([
- 'top', 'bottom', 'footwear', 'outerwear', 'hair', 'headwear', 'glasses', 'accessory',
-]);
+// Shared vocabulary lives in src/garment-taxonomy.js (pure, also consumed by
+// the server-side baker). Re-exported so existing consumers keep one import.
+export { GARMENT_SLOTS, BODY_REGIONS, REGION_BONES, MIN_BIND_COVERAGE };
/* ────────────────────────────────────────────────────────────────────────── *
* Skeleton discovery
@@ -334,16 +332,6 @@ export function occupiedSlots(avatarRoot) {
* Skin occlusion
* ────────────────────────────────────────────────────────────────────────── */
-/**
- * Body regions a garment can claim. A garment declares which it covers, and the
- * body's skin is masked there so it cannot poke through the cloth — the single
- * most visible artefact in any additive wardrobe.
- */
-export const BODY_REGIONS = Object.freeze([
- 'torso', 'upperArms', 'lowerArms', 'hands',
- 'hips', 'upperLegs', 'lowerLegs', 'feet', 'neck', 'scalp',
-]);
-
/**
* Hide the body wherever attached garments cover it.
*
@@ -395,20 +383,6 @@ export function applySkinOcclusion(avatarRoot, regions, opts = {}) {
return { occluded: [...wanted], method: 'bone-cull', trianglesHidden: hidden };
}
-/** Canonical bones that own each body region, for the mask-free fallback. */
-export const REGION_BONES = Object.freeze({
- torso: ['Spine', 'Spine1', 'Spine2'],
- upperArms: ['LeftArm', 'RightArm'],
- lowerArms: ['LeftForeArm', 'RightForeArm'],
- hands: ['LeftHand', 'RightHand'],
- hips: ['Hips'],
- upperLegs: ['LeftUpLeg', 'RightUpLeg'],
- lowerLegs: ['LeftLeg', 'RightLeg'],
- feet: ['LeftFoot', 'RightFoot', 'LeftToeBase', 'RightToeBase'],
- neck: ['Neck'],
- scalp: ['Head'],
-});
-
/**
* Drop triangles whose vertices are predominantly weighted to `boneIndices`.
*
diff --git a/src/avatar-pose.js b/src/avatar-pose.js
index a91e22ca3..981199ccd 100644
--- a/src/avatar-pose.js
+++ b/src/avatar-pose.js
@@ -174,16 +174,17 @@ export class PoseStage {
// Drop the model so its feet sit at y=0, then look at the upper torso.
this.model.position.y -= box.min.y;
- // Portrait framing sits the camera at chest height and pulls in so the
- // raised hand and face fill the frame — the signing is the point. It
- // also centers on the model's true x/z, since a close camera amplifies
+ // Portrait framing crops to the signing space — roughly the waist up,
+ // where every handshape, the face, and both hands live. Signing reads at
+ // the scale of a finger, so a full-body distance throws the detail away.
+ // It also centers on the model's true x/z, since a close camera amplifies
// any off-origin authoring the full-body distance hides.
const portrait = this.framing === 'portrait';
const cx = portrait ? center.x : 0;
const cz = portrait ? center.z : 0;
- const target = new Vector3(cx, height * (portrait ? 0.72 : 0.55), cz);
- const dist = height * (portrait ? 1.2 : 1.6);
- this.camera.position.set(cx, height * (portrait ? 0.76 : 0.62), cz + dist);
+ const target = new Vector3(cx, height * (portrait ? 0.8 : 0.55), cz);
+ const dist = height * (portrait ? 0.92 : 1.6);
+ this.camera.position.set(cx, height * (portrait ? 0.83 : 0.62), cz + dist);
this.camera.near = Math.max(0.01, dist / 100);
this.camera.far = dist * 20;
this.camera.updateProjectionMatrix();
diff --git a/src/fingerspelling.js b/src/fingerspelling.js
index eaabfc2f0..e760ba304 100644
--- a/src/fingerspelling.js
+++ b/src/fingerspelling.js
@@ -91,8 +91,6 @@ export function normalizeWord(word) {
.trim();
}
-const SIDE = 'Right';
-
/** The letter's place in signing space, plus an optional metre offset. */
function letterPlace(letter, offset) {
const spec = { ...SPELLING_PLACE, ...(LETTER_ORIENT[letter]?.at ?? {}) };
diff --git a/src/garment-catalog.js b/src/garment-catalog.js
index 849cdcab7..ab8dbb64f 100644
--- a/src/garment-catalog.js
+++ b/src/garment-catalog.js
@@ -10,7 +10,7 @@
// browser and in vitest. Loading the GLB and binding it to an avatar is the
// caller's job (src/avatar-garment.js `attachGarment`).
-import { GARMENT_SLOTS, BODY_REGIONS } from './avatar-garment.js';
+import { GARMENT_SLOTS, BODY_REGIONS } from './garment-taxonomy.js';
export const GARMENT_SPEC_URI = 'https://three.ws/specs/garment-manifest-v1';
export const GARMENT_CATALOG_URL =
diff --git a/src/garment-taxonomy.js b/src/garment-taxonomy.js
new file mode 100644
index 000000000..ee3c3fdf9
--- /dev/null
+++ b/src/garment-taxonomy.js
@@ -0,0 +1,38 @@
+// Garment taxonomy — the shared vocabulary of the additive wardrobe.
+//
+// Pure constants, no three.js, no DOM: imported by the client runtime
+// (src/avatar-garment.js, src/garment-catalog.js), the server-side baker
+// (api/_lib/bake-garments.js), and mirrored by the zod schema in
+// api/_lib/validate.js. Change a slot or region HERE and in the spec
+// (specs/GARMENT_MANIFEST.md) — nowhere else.
+
+/** Slots a garment may occupy. One garment per slot; attaching to an occupied
+ * slot detaches the incumbent. */
+export const GARMENT_SLOTS = Object.freeze([
+ 'top', 'bottom', 'footwear', 'outerwear', 'hair', 'headwear', 'glasses', 'accessory',
+]);
+
+/** Body regions a garment can claim in its manifest's `occludes`. The body's
+ * skin is masked in every claimed region so it cannot poke through cloth. */
+export const BODY_REGIONS = Object.freeze([
+ 'torso', 'upperArms', 'lowerArms', 'hands',
+ 'hips', 'upperLegs', 'lowerLegs', 'feet', 'neck', 'scalp',
+]);
+
+/** Canonical bones that own each body region, for mask-free occlusion culling. */
+export const REGION_BONES = Object.freeze({
+ torso: ['Spine', 'Spine1', 'Spine2'],
+ upperArms: ['LeftArm', 'RightArm'],
+ lowerArms: ['LeftForeArm', 'RightForeArm'],
+ hands: ['LeftHand', 'RightHand'],
+ hips: ['Hips'],
+ upperLegs: ['LeftUpLeg', 'RightUpLeg'],
+ lowerLegs: ['LeftLeg', 'RightLeg'],
+ feet: ['LeftFoot', 'RightFoot', 'LeftToeBase', 'RightToeBase'],
+ neck: ['Neck'],
+ scalp: ['Head'],
+});
+
+/** Below this share of *weighted* garment bones resolving to avatar bones, the
+ * garment cannot deform sanely and is refused rather than shipped mangled. */
+export const MIN_BIND_COVERAGE = 0.6;
diff --git a/src/sign-clip.js b/src/sign-clip.js
index 3d597bc48..c15034fa4 100644
--- a/src/sign-clip.js
+++ b/src/sign-clip.js
@@ -25,7 +25,6 @@ import {
solveArm,
vAdd,
vNorm,
- vScale,
} from './sign-rig.js';
/**
diff --git a/tests/bake-garments.test.js b/tests/bake-garments.test.js
new file mode 100644
index 000000000..7f79d7791
--- /dev/null
+++ b/tests/bake-garments.test.js
@@ -0,0 +1,241 @@
+/**
+ * Server-side garment baker — api/_lib/bake-garments.js.
+ *
+ * Builds real GLB documents in memory with @gltf-transform (no fixtures, no
+ * network — catalog and bytes are injected through the test seams) and runs
+ * the actual merge+rebind used by bakeAppearance. The contract mirrors the
+ * runtime suite (tests/avatar-garment.test.js):
+ *
+ * - garment JOINTS_0 rewritten into avatar joint order via canonical names,
+ * - the rebound skin keeps the GARMENT's inverseBindMatrices where claimed,
+ * - a garment below MIN_BIND_COVERAGE is skipped, not baked in mangled,
+ * - occluded body regions have their triangles culled,
+ * - the baked document round-trips through the binary writer.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { Document, NodeIO } from '@gltf-transform/core';
+import { mergeDocuments, unpartition } from '@gltf-transform/functions';
+import {
+ applyGarments,
+ buildJointRemap,
+ cullBodyRegions,
+ findPrimarySkin,
+} from '../api/_lib/bake-garments.js';
+import { GARMENT_SPEC_URI } from '../src/garment-catalog.js';
+
+/* ── builders ────────────────────────────────────────────────────────────── */
+
+/**
+ * A minimal skinned humanoid document: Hips → Spine → Head (+LeftArm), one
+ * body mesh fully weighted to Spine and Head. `prefix` exercises foreign
+ * naming; `spineY` moves the rest pose for divergent-bind tests.
+ */
+function buildHumanoidDoc({ prefix = '', spineY = 2, vertsOnSpine = 2 } = {}) {
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+ const scene = doc.createScene('scene');
+ doc.getRoot().setDefaultScene(scene);
+
+ const hips = doc.createNode(`${prefix}Hips`).setTranslation([0, 1, 0]);
+ const spine = doc.createNode(`${prefix}Spine`).setTranslation([0, spineY - 1, 0]);
+ const head = doc.createNode(`${prefix}Head`).setTranslation([0, 1, 0]);
+ const leftArm = doc.createNode(`${prefix}LeftArm`).setTranslation([0.5, 0.5, 0]);
+ hips.addChild(spine);
+ spine.addChild(head);
+ spine.addChild(leftArm);
+ scene.addChild(hips);
+
+ const joints = [hips, spine, head, leftArm];
+ // IBMs: inverse of each joint's world translation (identity rotation).
+ const worldY = [1, spineY, spineY + 1, spineY + 0.5];
+ const worldX = [0, 0, 0, 0.5];
+ const ibm = new Float32Array(joints.length * 16);
+ joints.forEach((_, i) => {
+ ibm.set([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -worldX[i], -worldY[i], 0, 1], i * 16);
+ });
+ const ibmAccessor = doc.createAccessor('ibm').setType('MAT4').setArray(ibm).setBuffer(buffer);
+ const skin = doc.createSkin('skin').setInverseBindMatrices(ibmAccessor);
+ for (const j of joints) skin.addJoint(j);
+ skin.setSkeleton(hips);
+
+ // Body: vertsOnSpine vertices on Spine (joint 1), then 2 on Head (joint 2),
+ // indexed as triangles [0,1,2] (spine-ish) and [1,2,3] (mixed).
+ const vertCount = vertsOnSpine + 2;
+ const positions = new Float32Array(vertCount * 3);
+ const jointsArr = new Uint16Array(vertCount * 4);
+ const weightsArr = new Float32Array(vertCount * 4);
+ for (let v = 0; v < vertCount; v++) {
+ positions.set([v * 0.1, spineY + 0.5, 0], v * 3);
+ jointsArr[v * 4] = v < vertsOnSpine ? 1 : 2;
+ weightsArr[v * 4] = 1;
+ }
+ const prim = doc
+ .createPrimitive()
+ .setAttribute('POSITION', doc.createAccessor().setType('VEC3').setArray(positions).setBuffer(buffer))
+ .setAttribute('JOINTS_0', doc.createAccessor().setType('VEC4').setArray(jointsArr).setBuffer(buffer))
+ .setAttribute('WEIGHTS_0', doc.createAccessor().setType('VEC4').setArray(weightsArr).setBuffer(buffer))
+ .setIndices(doc.createAccessor().setType('SCALAR').setArray(new Uint16Array([0, 1, 2, 1, 2, 3])).setBuffer(buffer));
+ const mesh = doc.createMesh('body').addPrimitive(prim);
+ const meshNode = doc.createNode('bodyNode').setMesh(mesh).setSkin(skin);
+ scene.addChild(meshNode);
+
+ return { doc, skin, joints, mesh };
+}
+
+async function docToBytes(io, doc) {
+ return (await io.writeBinary(doc)).buffer.slice(0);
+}
+
+function manifestFor(id, slot, overrides = {}) {
+ return {
+ spec: GARMENT_SPEC_URI,
+ id,
+ name: id,
+ slot,
+ version: 1,
+ model: { uri: `https://t.test/${id}.glb`, format: 'gltf-binary', sha256: 'a'.repeat(64) },
+ rig: { skeleton: 'three.ws-canonical-v1' },
+ occludes: ['torso'],
+ license: 'CC0-1.0',
+ ...overrides,
+ };
+}
+
+/* ── unit pieces ─────────────────────────────────────────────────────────── */
+
+describe('findPrimarySkin', () => {
+ it('picks the skin deforming the most vertices', () => {
+ const { doc, skin } = buildHumanoidDoc({ vertsOnSpine: 10 });
+ expect(findPrimarySkin(doc).skin).toBe(skin);
+ });
+});
+
+describe('buildJointRemap (document level)', () => {
+ it('maps a foreign-named garment skeleton onto the avatar', () => {
+ const avatar = buildHumanoidDoc();
+ const garment = buildHumanoidDoc({ prefix: 'mixamorig:' });
+ // Parent map over the GARMENT document's nodes.
+ const parents = new Map();
+ for (const n of garment.doc.getRoot().listNodes()) {
+ for (const c of n.listChildren()) parents.set(c, n);
+ }
+ const remap = buildJointRemap(garment.skin, avatar.skin, parents);
+ expect([...remap]).toEqual([0, 1, 2, 3]);
+ });
+});
+
+describe('cullBodyRegions', () => {
+ it('drops triangles fully weighted to occluded regions', () => {
+ const { doc } = buildHumanoidDoc({ vertsOnSpine: 3 });
+ const primary = findPrimarySkin(doc);
+ // verts 0,1,2 are on Spine (torso); triangle [0,1,2] dies, [1,2,3] survives
+ // because vert 3 rides Head (scalp, not occluded).
+ const dropped = cullBodyRegions(primary.mesh, primary.skin, ['torso']);
+ expect(dropped).toBe(1);
+ const idx = primary.mesh.listPrimitives()[0].getIndices().getArray();
+ expect([...idx]).toEqual([1, 2, 3]);
+ });
+});
+
+/* ── full pipeline ───────────────────────────────────────────────────────── */
+
+describe('applyGarments', () => {
+ it('bakes a divergent-rest garment: joints remapped, garment IBMs kept, occlusion applied', async () => {
+ const io = new NodeIO();
+ // vertsOnSpine: 3 puts the body's first triangle fully on the torso so
+ // the occlusion pass has something to cull.
+ const avatar = buildHumanoidDoc({ spineY: 3, vertsOnSpine: 3 });
+ const garment = buildHumanoidDoc({ prefix: 'mixamorig:', spineY: 2 });
+ const garmentBytes = await docToBytes(io, garment.doc);
+
+ const manifest = manifestFor('oxford-shirt-white', 'top');
+ const { attached, skipped } = await applyGarments(
+ io,
+ avatar.doc,
+ [{ slot: 'top', id: 'oxford-shirt-white' }],
+ mergeDocuments,
+ { catalog: [manifest], fetchBytes: async () => garmentBytes },
+ );
+
+ expect(skipped).toEqual([]);
+ expect(attached).toEqual(['oxford-shirt-white']);
+
+ // The merged garment mesh is in the default scene with a rebound skin.
+ const garmentNode = avatar.doc
+ .getRoot()
+ .listNodes()
+ .find((n) => n.getMesh()?.getName() === 'body' && n.getSkin()?.getName()?.startsWith('garment:'));
+ expect(garmentNode).toBeTruthy();
+
+ const reboundSkin = garmentNode.getSkin();
+ // Joints are the AVATAR's four.
+ expect(reboundSkin.listJoints().map((j) => j.getName())).toEqual([
+ 'Hips', 'Spine', 'Head', 'LeftArm',
+ ]);
+ // IBM for Spine keeps the GARMENT's value (rest y=2 → translation -2),
+ // not the avatar's (-3): that is the divergent-rest reconciliation.
+ const ibm = reboundSkin.getInverseBindMatrices().getArray();
+ expect(ibm[1 * 16 + 13]).toBeCloseTo(-2, 5);
+
+ // Occlusion: avatar body had triangles [0,1,2] (torso) and [1,2,3];
+ // the manifest occludes torso, so only the mixed triangle survives.
+ const bodyIdx = findPrimarySkin(avatar.doc); // still the body (4 verts > garment 4? both 4 —
+ // primary is recomputed; guard by name instead:
+ const bodyNode = avatar.doc
+ .getRoot()
+ .listNodes()
+ .find((n) => n.getName() === 'bodyNode');
+ const idx = bodyNode.getMesh().listPrimitives()[0].getIndices().getArray();
+ expect([...idx]).toEqual([1, 2, 3]);
+ expect(bodyIdx).toBeTruthy();
+
+ // And the whole document still serializes to a valid GLB. mergeDocuments
+ // leaves one buffer per source document; unpartition() collapses them —
+ // exactly what bake.js's compression pass does before writing.
+ await avatar.doc.transform(unpartition());
+ const out = await io.writeBinary(avatar.doc);
+ expect(out.byteLength).toBeGreaterThan(500);
+ });
+
+ it('skips a garment that cannot reach the avatar skeleton', async () => {
+ const io = new NodeIO();
+ const avatar = buildHumanoidDoc();
+ const alien = buildHumanoidDoc({ prefix: 'tentacle_xx_' });
+ // Rename joints to names that canonicalize to nothing.
+ alien.joints.forEach((j, i) => j.setName(`blob_${i}`));
+ const bytes = await docToBytes(io, alien.doc);
+
+ const manifest = manifestFor('blob-suit', 'top');
+ const { attached, skipped } = await applyGarments(
+ io,
+ avatar.doc,
+ [{ slot: 'top', id: 'blob-suit' }],
+ mergeDocuments,
+ { catalog: [manifest], fetchBytes: async () => bytes },
+ );
+
+ expect(attached).toEqual([]);
+ expect(skipped).toHaveLength(1);
+ expect(skipped[0].reason).toMatch(/binds 0%/);
+
+ // Body untouched: no occlusion applied for a skipped garment.
+ const bodyNode = avatar.doc.getRoot().listNodes().find((n) => n.getName() === 'bodyNode');
+ expect([...bodyNode.getMesh().listPrimitives()[0].getIndices().getArray()])
+ .toEqual([0, 1, 2, 1, 2, 3]);
+ });
+
+ it('reports garments missing from the catalog', async () => {
+ const io = new NodeIO();
+ const avatar = buildHumanoidDoc();
+ const { attached, skipped } = await applyGarments(
+ io,
+ avatar.doc,
+ [{ slot: 'top', id: 'ghost' }],
+ mergeDocuments,
+ { catalog: [], fetchBytes: async () => { throw new Error('unreachable'); } },
+ );
+ expect(attached).toEqual([]);
+ expect(skipped).toEqual([{ id: 'ghost', reason: 'not in catalog' }]);
+ });
+});
diff --git a/tests/sniper-postmortem-fixes.test.js b/tests/sniper-postmortem-fixes.test.js
new file mode 100644
index 000000000..eb4c4f6f9
--- /dev/null
+++ b/tests/sniper-postmortem-fixes.test.js
@@ -0,0 +1,145 @@
+/**
+ * The three fixes the published fleet audit demanded
+ * (three.ws/blog/autonomous-trading-experiment) and their exact rationale:
+ *
+ * 1. llmVerdictGate — "0.9-plus verdicts went winless" (overconfidence
+ * ceiling) and "the failover chain answering most calls muddied the
+ * model-vs-model comparison" (named-model strictness).
+ * 2. liquidity-decay exit — "dead coins stop squatting on concurrency slots
+ * for half an hour".
+ * 3. classifyLoopHealth — "two closed loops looked alive for two days while
+ * doing nothing, behind green health checks. Count rows, not status codes."
+ */
+
+import { describe, expect, it } from 'vitest';
+import { llmVerdictGate } from '../workers/agent-sniper/llm-judge.js';
+import { decideLiquidityDecay, updateStaleClock } from '../workers/agent-sniper/exit-logic.js';
+import { LOOPS, classifyLoopHealth, describeStale } from '../api/_lib/sniper-loops-health.js';
+
+describe('llmVerdictGate', () => {
+ const strat = { llm_min_confidence: 0.65, llm_max_confidence: 0.9, llm_strict_model: false };
+ const verdict = (over) => ({ buy: true, confidence: 0.75, model: 'x-ai/grok-4.3', ...over });
+
+ it('passes the audit sweet spot (the 0.7 band was the best performer)', () => {
+ expect(llmVerdictGate(verdict({ confidence: 0.7 }), strat)).toEqual({ pass: true, reason: 'ok' });
+ expect(llmVerdictGate(verdict({ confidence: 0.89 }), strat).pass).toBe(true);
+ });
+
+ it('rejects the winless overconfidence band at and above the ceiling', () => {
+ expect(llmVerdictGate(verdict({ confidence: 0.9 }), strat)).toEqual({ pass: false, reason: 'overconfident' });
+ expect(llmVerdictGate(verdict({ confidence: 0.99 }), strat).reason).toBe('overconfident');
+ });
+
+ it('keeps the classic floor', () => {
+ expect(llmVerdictGate(verdict({ confidence: 0.6 }), strat).reason).toBe('below_floor');
+ expect(llmVerdictGate(verdict({ confidence: 0.4 }), { llm_min_confidence: null }).reason).toBe('below_floor'); // default 0.6
+ });
+
+ it('no ceiling configured = unchanged historical behavior', () => {
+ expect(llmVerdictGate(verdict({ confidence: 0.99 }), { llm_min_confidence: 0.65 }).pass).toBe(true);
+ });
+
+ it('a strict arm refuses to trade on a fallback model verdict', () => {
+ const strict = { ...strat, llm_strict_model: true };
+ expect(llmVerdictGate(verdict({ model: 'fallback:groq#instant' }), strict)).toEqual({ pass: false, reason: 'fallback_model' });
+ expect(llmVerdictGate(verdict({ model: 'fallback:ovh' }), strict).pass).toBe(false);
+ // The named model itself still trades.
+ expect(llmVerdictGate(verdict(), strict).pass).toBe(true);
+ });
+
+ it('a non-strict arm accepts a fallback verdict (the auto arm is any-model by design)', () => {
+ expect(llmVerdictGate(verdict({ model: 'fallback:ovh' }), strat).pass).toBe(true);
+ });
+
+ it('never buys on a skip or a malformed verdict', () => {
+ expect(llmVerdictGate(verdict({ buy: false }), strat).reason).toBe('no_buy');
+ expect(llmVerdictGate(null, strat).reason).toBe('no_buy');
+ expect(llmVerdictGate(verdict({ confidence: NaN }), strat).reason).toBe('below_floor');
+ });
+});
+
+describe('liquidity-decay clock', () => {
+ const ENTRY = 1_000_000;
+ const T = 1_700_000_000_000;
+
+ it('starts the clock when an underwater value stops moving', () => {
+ expect(updateStaleClock(800_000, 800_000, ENTRY, null, T)).toBe(T);
+ });
+
+ it('keeps the original start while the value stays frozen', () => {
+ expect(updateStaleClock(800_000, 800_000, ENTRY, T - 120_000, T)).toBe(T - 120_000);
+ });
+
+ it('resets on ANY movement — one trade is not dead liquidity', () => {
+ expect(updateStaleClock(800_000, 800_001, ENTRY, T - 120_000, T)).toBe(null);
+ });
+
+ it('never runs in profit — quiet winners belong to the exit ladder', () => {
+ expect(updateStaleClock(1_500_000, 1_500_000, ENTRY, null, T)).toBe(null);
+ expect(updateStaleClock(1_500_000, 1_500_000, ENTRY, T - 999_999, T)).toBe(null);
+ });
+
+ it('never starts on the first sweep (no previous value to compare)', () => {
+ expect(updateStaleClock(null, 800_000, ENTRY, null, T)).toBe(null);
+ });
+
+ it('fires the exit only after the threshold', () => {
+ expect(decideLiquidityDecay(T - 299_000, 300, T)).toBe(false);
+ expect(decideLiquidityDecay(T - 300_000, 300, T)).toBe(true);
+ expect(decideLiquidityDecay(T - 3_600_000, 300, T)).toBe(true);
+ });
+
+ it('is disabled by a zero threshold and a null clock', () => {
+ expect(decideLiquidityDecay(T - 999_999, 0, T)).toBe(false);
+ expect(decideLiquidityDecay(null, 300, T)).toBe(false);
+ });
+});
+
+describe('classifyLoopHealth (count rows, not status codes)', () => {
+ const NOW = 1_700_000_000_000;
+ const probe = (name, ageMs) => ({ name, lastAt: ageMs == null ? null : new Date(NOW - ageMs).toISOString() });
+
+ it('declares every audited loop', () => {
+ const names = LOOPS.map((l) => l.name);
+ // The two loops that silently died in the audit MUST be covered.
+ expect(names).toContain('optimizer');
+ expect(names).toContain('evolution');
+ expect(names).toContain('intel-weight-training');
+ expect(names).toContain('outcome-labeling');
+ expect(names).toContain('llm-judging');
+ expect(names).toContain('oracle-scoring');
+ });
+
+ it('passes loops with fresh rows', () => {
+ const { ok, stale } = classifyLoopHealth([probe('optimizer', 3600_000), probe('oracle-scoring', 60_000)], NOW);
+ expect(stale).toHaveLength(0);
+ expect(ok.map((o) => o.name).sort()).toEqual(['optimizer', 'oracle-scoring']);
+ });
+
+ it('flags a loop whose freshest row is too old', () => {
+ const { stale } = classifyLoopHealth([probe('optimizer', 27 * 3600_000)], NOW);
+ expect(stale).toHaveLength(1);
+ expect(stale[0].name).toBe('optimizer');
+ expect(stale[0].why).toMatch(/silently died/);
+ });
+
+ it('treats a loop with NO rows ever as the worst stale, not a pass', () => {
+ const { stale } = classifyLoopHealth([probe('evolution', null), probe('optimizer', 27 * 3600_000)], NOW);
+ expect(stale[0].name).toBe('evolution'); // Infinity sorts first
+ expect(stale[0].ageMs).toBe(Infinity);
+ expect(describeStale(stale[0])).toMatch(/NEVER produced a row/);
+ });
+
+ it('uses each loop’s own cadence-derived limit', () => {
+ // 40 minutes: fine for the 26h optimizer, stale for the 30m oracle scorer.
+ const { ok, stale } = classifyLoopHealth([probe('optimizer', 40 * 60_000), probe('oracle-scoring', 40 * 60_000)], NOW);
+ expect(ok.map((o) => o.name)).toEqual(['optimizer']);
+ expect(stale.map((s) => s.name)).toEqual(['oracle-scoring']);
+ });
+
+ it('ignores unknown probes rather than crashing the watchdog', () => {
+ const { ok, stale } = classifyLoopHealth([probe('not-a-loop', 0)], NOW);
+ expect(ok).toHaveLength(0);
+ expect(stale).toHaveLength(0);
+ });
+});
diff --git a/vercel.json b/vercel.json
index 7bbfae35a..1cd5d6c92 100644
--- a/vercel.json
+++ b/vercel.json
@@ -5254,6 +5254,10 @@
"path": "/api/cron/sniper-evolve",
"schedule": "30 */12 * * *"
},
+ {
+ "path": "/api/cron/sniper-loops-health",
+ "schedule": "20 * * * *"
+ },
{
"path": "/api/cron/oracle-realized-labels",
"schedule": "*/30 * * * *"
diff --git a/workers/agent-sniper/config.js b/workers/agent-sniper/config.js
index be552be4b..9d19dabe9 100644
--- a/workers/agent-sniper/config.js
+++ b/workers/agent-sniper/config.js
@@ -113,6 +113,12 @@ export function loadConfig() {
globalKill: bool('SNIPER_GLOBAL_KILL', false),
// Position re-quote / exit-evaluation cadence.
pollMs: Math.max(1_000, num('SNIPER_POLL_MS', 5_000)),
+ // Liquidity-decay exit: an underwater position whose quoted value has not
+ // moved AT ALL for this long (no one is trading the coin) exits early with
+ // reason 'liquidity_decay' instead of squatting on a concurrency slot until
+ // the 30-minute timeout. 0 disables. Default 5 minutes: on a minutes-old
+ // pump.fun launch, five minutes of literally zero trades is a dead market.
+ liquidityDecayS: Math.max(0, num('SNIPER_LIQUIDITY_DECAY_S', 300)),
// How often the strategy cache is refreshed from the DB.
strategyRefreshMs: Math.max(5_000, num('SNIPER_STRATEGY_REFRESH_MS', 15_000)),
// Platform-wide buy throttle — a backstop independent of per-agent caps.
diff --git a/workers/agent-sniper/exit-logic.js b/workers/agent-sniper/exit-logic.js
index 7fa0c4687..21d6d6a47 100644
--- a/workers/agent-sniper/exit-logic.js
+++ b/workers/agent-sniper/exit-logic.js
@@ -61,6 +61,47 @@ export function decideExit(pos, value, peak, now = Date.now(), sentiment = null)
return null;
}
+/**
+ * Liquidity-decay clock. A bonding-curve quote only moves when someone trades,
+ * so a position whose re-quoted value is EXACTLY unchanged sweep after sweep is
+ * a coin nobody is trading: dead liquidity. The July 2026 fleet audit found
+ * these squatting on concurrency slots for the full 30-minute timeout, the only
+ * exit that ever fired on them. This clock times them out in minutes instead.
+ *
+ * Semantics:
+ * - The clock runs only while the position is UNDERWATER. A quiet coin above
+ * entry is a winner consolidating, and the trailing stop / take-profit /
+ * moon-bag machinery owns that case.
+ * - Any value movement (any trade at all) resets the clock: one buyer is not
+ * dead liquidity.
+ * - Returns the new stale_since (epoch ms or null). Pure, no I/O.
+ *
+ * @param {number|null} prevValue last sweep's quoted value (lamports), null on first sweep
+ * @param {number} value this sweep's quoted value (lamports)
+ * @param {number} entry cost basis (lamports)
+ * @param {number|null} staleSince current clock start (epoch ms) or null
+ * @param {number} now epoch ms
+ * @returns {number|null}
+ */
+export function updateStaleClock(prevValue, value, entry, staleSince, now) {
+ const underwater = value < entry;
+ const unchanged = prevValue != null && Number(prevValue) === Number(value);
+ if (!underwater || !unchanged) return null;
+ return staleSince ?? now;
+}
+
+/**
+ * Should the position exit for dead liquidity? True once the stale clock has
+ * run for `decaySeconds`. The position is underwater by definition (the clock
+ * never runs in profit), so this is a full exit while the stake is still at
+ * risk; the caller keeps the moon-bag floor when the initials were already
+ * recovered (house money stays free even in a dead market).
+ */
+export function decideLiquidityDecay(staleSince, decaySeconds, now) {
+ if (staleSince == null || !(decaySeconds > 0)) return false;
+ return (now - staleSince) / 1000 >= decaySeconds;
+}
+
/** A confident bearish sentiment read. minConfidence defaults to 0.7. */
function isBearishFlip(sentiment) {
if (!sentiment || sentiment.signal !== 'bearish') return false;
diff --git a/workers/agent-sniper/index.js b/workers/agent-sniper/index.js
index e13c9d0ed..5ade0844d 100644
--- a/workers/agent-sniper/index.js
+++ b/workers/agent-sniper/index.js
@@ -17,7 +17,7 @@ import { refreshStrategies, cachedStrategies, logStrategyLoad } from './strategy
import { scoreMint, scoreIntel } from './scorer.js';
import { executeBuy } from './executor.js';
import { oracleGate } from './oracle-gate.js';
-import { judgeLaunch } from './llm-judge.js';
+import { judgeLaunch, llmVerdictGate } from './llm-judge.js';
import { runPositionSweep } from './positions.js';
import { runSwarmConsensus, runSwarmSettlement } from './swarm.js';
import { startFirstClaimWatch } from './first-claim-watch.js';
@@ -181,9 +181,9 @@ async function main() {
judgeLaunch(data, strat)
.then((verdict) => {
if (!verdict) return;
- const minConf = Number(strat.llm_min_confidence ?? 0.6);
- if (!verdict.buy || verdict.confidence < minConf) {
- log.info('llm judge pass', { agent: strat.agent_id, mint: data.mint, model: verdict.model, buy: verdict.buy, confidence: verdict.confidence });
+ const gate = llmVerdictGate(verdict, strat);
+ if (!gate.pass) {
+ log.info('llm judge pass', { agent: strat.agent_id, mint: data.mint, model: verdict.model, buy: verdict.buy, confidence: verdict.confidence, gate: gate.reason });
return;
}
log.info('llm judge buy', { agent: strat.agent_id, mint: data.mint, model: verdict.model, confidence: verdict.confidence, thesis: verdict.thesis });
diff --git a/workers/agent-sniper/positions.js b/workers/agent-sniper/positions.js
index 63d69dbc6..98401527b 100644
--- a/workers/agent-sniper/positions.js
+++ b/workers/agent-sniper/positions.js
@@ -11,7 +11,7 @@ import { getTradeCtx } from './trade-client.js';
import { getOpenPositions } from './strategy-store.js';
import { executeSell } from './executor.js';
import { quoteAmmSell } from './amm-exit.js';
-import { decideLadderedExit } from './exit-logic.js';
+import { decideLadderedExit, decideLiquidityDecay, moonbagAlways, moonbagFraction, updateStaleClock } from './exit-logic.js';
import { screenPush } from './screen-push.js';
async function tickPosition(cfg, pos) {
@@ -32,12 +32,39 @@ async function tickPosition(cfg, pos) {
const prevPeak = Number(pos.peak_value_lamports || pos.entry_quote_lamports || 0);
const peak = Math.max(prevPeak, value);
+
+ // Liquidity-decay clock: a value EXACTLY unchanged between sweeps means no
+ // one traded the coin at all. Underwater, that is dead liquidity, and the
+ // audit showed those positions squatting on their concurrency slot until the
+ // 30-minute timeout. The clock frees the slot in minutes instead.
+ const prevValue = pos.last_value_lamports != null ? Number(pos.last_value_lamports) : null;
+ const prevStale = pos.stale_since ? new Date(pos.stale_since).getTime() : null;
+ const staleSince = updateStaleClock(prevValue, Math.round(value), Number(pos.entry_quote_lamports || 0), prevStale, Date.now());
+
await sql`
UPDATE agent_sniper_positions
- SET last_value_lamports = ${Math.round(value)}, peak_value_lamports = ${Math.round(peak)}, last_quoted_at = now()
+ SET last_value_lamports = ${Math.round(value)}, peak_value_lamports = ${Math.round(peak)},
+ stale_since = ${staleSince != null ? new Date(staleSince).toISOString() : null},
+ last_quoted_at = now()
WHERE id = ${pos.id}
`;
+ if (decideLiquidityDecay(staleSince, cfg.liquidityDecayS, Date.now())) {
+ // Dead market: exit and free the slot. Consistency with the moon-bag rule:
+ // a position still carrying its cost basis exits fully (nothing free about
+ // it), but one whose initials were already recovered is house money and
+ // keeps its floor riding even here: a free bag of a dead coin costs
+ // nothing, and "dead for five minutes" is not "dead forever".
+ const houseMoney = pos.initials_recovered === true && moonbagAlways(pos);
+ log.info('liquidity decay exit', { agent: pos.agent_id, mint: pos.mint, staleForS: Math.round((Date.now() - staleSince) / 1000), houseMoney });
+ await executeSell({
+ cfg, position: pos, reason: 'liquidity_decay',
+ fraction: houseMoney ? 1 - moonbagFraction(pos.moonbag_min_pct) : 1,
+ keepsMoonbag: houseMoney,
+ });
+ return;
+ }
+
const entry = Number(pos.entry_quote_lamports || 0);
const pnlPct = entry > 0 ? ((value - entry) / entry) * 100 : 0;
const sym = (pos.symbol || pos.mint.slice(0, 6)).toUpperCase();
diff --git a/workers/avatar-reconstruction/eval/identity_eval.py b/workers/avatar-reconstruction/eval/identity_eval.py
index 748a52151..c905295bf 100644
--- a/workers/avatar-reconstruction/eval/identity_eval.py
+++ b/workers/avatar-reconstruction/eval/identity_eval.py
@@ -100,7 +100,9 @@ def selfie_landmarks(image_path: Path) -> np.ndarray:
landmarks = face_pipeline._get_landmarks_small_face(img)
if landmarks is None:
raise EvalError(f"no face detected in {image_path.name}")
- return face_geometry.landmarks_to_array(landmarks)
+ # Pixel dimensions matter: without them the landmark frame carries the photo's
+ # aspect ratio as if it were face shape. See landmarks_to_array.
+ return face_geometry.landmarks_to_array(landmarks, *img.size)
def head_landmark_points(glb_path: Path, face_map: face_geometry.FaceMap) -> np.ndarray:
diff --git a/workers/avatar-reconstruction/eval/make_refs.py b/workers/avatar-reconstruction/eval/make_refs.py
new file mode 100644
index 000000000..75be46e71
--- /dev/null
+++ b/workers/avatar-reconstruction/eval/make_refs.py
@@ -0,0 +1,187 @@
+"""
+Build the reconstruction benchmark's reference face set.
+
+A fidelity score is only meaningful against a fixed, known set of faces, and
+that set has to cover what the pipeline actually meets: every complexion, a wide
+age range, both presentations, and the accessories that break landmark
+detection. A benchmark drawn from whatever selfies were lying around measures
+the photos, not the pipeline.
+
+The faces are **synthesised, not collected**. That is a deliberate choice:
+
+- No real person's biometrics sit in a benchmark that gets copied between
+ machines, uploaded to buckets and quoted in reports.
+- No licensing question. Scraped or stock faces carry terms that a permanent
+ internal benchmark should not depend on.
+- Reproducible. The grid below is deterministic, so any agent can rebuild the
+ same set and get comparable numbers.
+
+The diversity axes are imported wholesale from the platform's existing seeder
+matrix (`api/_lib/avaturn-seed.js`) so the benchmark population matches the one
+the rest of the product already reasons about.
+
+Usage
+-----
+ python -m eval.make_refs --out eval/refs # full grid (40)
+ python -m eval.make_refs --out eval/refs --limit 8 # quick set
+ python -m eval.make_refs --out eval/refs --upload # mirror to GCS
+
+Requires application-default credentials with Vertex AI access, which this
+workspace already has (`gcloud auth print-access-token`).
+"""
+
+from __future__ import annotations
+
+import argparse
+import base64
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+import httpx
+
+PROJECT = "aerial-vehicle-466722-p5"
+LOCATION = "us-central1"
+# The live Gemini image model. The `imagen-3.0-*` :predict ids it replaced are
+# past shutdown — see the model-landscape note in api/_mcp3d/vertex-imagen.js.
+MODEL = "gemini-2.5-flash-image"
+GCS_PREFIX = "gs://three-ws-avatar-reconstructions/eval-refs"
+
+# Mirrors AGE_BANDS / ETHNICITIES / BUILDS in api/_lib/avaturn-seed.js. Kept as a
+# deterministic grid rather than the seeder's random draw: a benchmark must be
+# the same population every time it is rebuilt.
+AGES = [
+ ("young-adult", "in their early twenties"),
+ ("adult", "in their early thirties"),
+ ("middle-aged", "in their late forties, a few soft laugh lines"),
+ ("senior", "in their late sixties, natural wrinkles and gentle age lines"),
+]
+
+ETHNICITIES = [
+ ("east-asian", "East Asian"),
+ ("southeast-asian", "Southeast Asian"),
+ ("south-asian", "South Asian"),
+ ("black-african", "Black African"),
+ ("black-caribbean", "Afro-Caribbean"),
+ ("latino", "Latin American"),
+ ("middle-eastern", "Middle Eastern"),
+ ("white-european", "White European"),
+ ("nordic", "Nordic"),
+ ("pacific-islander", "Pacific Islander"),
+]
+
+# Conditions that are *hard* for landmark detection and texture transfer, cycled
+# across the grid so the benchmark contains the failures worth knowing about
+# rather than forty easy passport photos.
+CHALLENGES = [
+ ("clean", "no glasses, no hat, hair kept clear of the face"),
+ ("glasses", "wearing thin-rimmed prescription glasses"),
+ ("beard", "with a full beard and moustache"),
+ ("headscarf", "wearing a plain headscarf covering the hair"),
+ ("long-hair", "with long loose hair partly framing the cheeks"),
+]
+
+BASE_PROMPT = (
+ "photorealistic studio ID portrait of {who}, {challenge}, "
+ "neutral relaxed expression, mouth closed, looking at the camera, "
+ "plain light-grey seamless background, soft even frontal lighting, sharp focus, "
+ "natural detailed skin texture, head facing the camera straight on, symmetrical framing"
+)
+
+
+def grid(limit: int | None = None) -> list[dict]:
+ """The deterministic reference population: one entry per benchmark face."""
+ samples = []
+ for i, (eth_key, eth_desc) in enumerate(ETHNICITIES):
+ for j, (age_key, age_desc) in enumerate(AGES):
+ gender = "man" if (i + j) % 2 == 0 else "woman"
+ challenge_key, challenge_desc = CHALLENGES[(i + j) % len(CHALLENGES)]
+ # A beard on a woman is not the axis being tested — fall back to clean.
+ if challenge_key == "beard" and gender == "woman":
+ challenge_key, challenge_desc = CHALLENGES[0]
+ samples.append({
+ "slug": f"{eth_key}-{age_key}-{gender}-{challenge_key}",
+ "prompt": BASE_PROMPT.format(
+ who=f"a {eth_desc} {gender} {age_desc}", challenge=challenge_desc
+ ),
+ "ethnicity": eth_key,
+ "age": age_key,
+ "gender": gender,
+ "challenge": challenge_key,
+ })
+ return samples[:limit] if limit else samples
+
+
+def access_token() -> str:
+ return subprocess.run(
+ ["gcloud", "auth", "print-access-token"],
+ capture_output=True, text=True, check=True,
+ ).stdout.strip()
+
+
+def generate(client: httpx.Client, token: str, prompt: str) -> bytes:
+ """One face. Raises if the model returns no image (a safety block, usually)."""
+ url = (
+ f"https://{LOCATION}-aiplatform.googleapis.com/v1/projects/{PROJECT}"
+ f"/locations/{LOCATION}/publishers/google/models/{MODEL}:generateContent"
+ )
+ response = client.post(
+ url,
+ headers={"Authorization": f"Bearer {token}"},
+ json={
+ "contents": [{"role": "user", "parts": [{"text": prompt}]}],
+ "generationConfig": {
+ "responseModalities": ["IMAGE"],
+ "imageConfig": {"aspectRatio": "3:4"},
+ },
+ },
+ timeout=300.0,
+ )
+ response.raise_for_status()
+ payload = response.json()
+ for part in payload.get("candidates", [{}])[0].get("content", {}).get("parts", []):
+ if "inlineData" in part:
+ return base64.b64decode(part["inlineData"]["data"])
+ raise RuntimeError(f"no image returned: {json.dumps(payload)[:200]}")
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--out", type=Path, default=Path("eval/refs"))
+ ap.add_argument("--limit", type=int, help="generate only the first N of the grid")
+ ap.add_argument("--upload", action="store_true", help=f"mirror the set to {GCS_PREFIX}")
+ ap.add_argument("--force", action="store_true", help="regenerate faces that already exist")
+ args = ap.parse_args()
+
+ args.out.mkdir(parents=True, exist_ok=True)
+ samples = grid(args.limit)
+ token = access_token()
+ manifest = []
+
+ with httpx.Client() as client:
+ for i, sample in enumerate(samples, 1):
+ path = args.out / f"{sample['slug']}.png"
+ if path.exists() and not args.force:
+ print(f"[{i}/{len(samples)}] {sample['slug']} — exists, skipping")
+ manifest.append(sample)
+ continue
+ print(f"[{i}/{len(samples)}] {sample['slug']} … ", end="", flush=True)
+ try:
+ path.write_bytes(generate(client, token, sample["prompt"]))
+ manifest.append(sample)
+ print("ok")
+ except Exception as exc: # a blocked or failed generation must not stop the set
+ print(f"FAILED — {exc}")
+
+ (args.out / "manifest.json").write_text(json.dumps(manifest, indent=2))
+ print(f"\n{len(manifest)}/{len(samples)} faces in {args.out}")
+
+ if args.upload:
+ subprocess.run(["gsutil", "-m", "rsync", "-r", str(args.out), GCS_PREFIX], check=True)
+ print(f"mirrored → {GCS_PREFIX}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/workers/avatar-reconstruction/eval/tune_morph.py b/workers/avatar-reconstruction/eval/tune_morph.py
new file mode 100644
index 000000000..189b12fcb
--- /dev/null
+++ b/workers/avatar-reconstruction/eval/tune_morph.py
@@ -0,0 +1,157 @@
+"""
+Tune the identity morph's parameters against ISE, across the whole reference set.
+
+`morph_head_to_landmarks` has three knobs — `strength`, `max_displacement_frac`
+and `falloff` — whose shipped defaults were chosen before there was any way to
+score the result. This sweeps them over every reference face and reports the
+setting with the best mean ISE.
+
+It runs **offline**: landmarks are detected once per face, then each parameter
+combination is applied to the template head in-process. No worker, no GPU, no
+GLB round-trip, so a full grid over 40 faces is a couple of minutes rather than
+a day of job submissions.
+
+Two cautions the output enforces:
+
+- **Tuning on one face is overfitting.** The mean is reported alongside the
+ worst face, and a setting that improves the mean while wrecking an individual
+ face is not an improvement. `--detail` lists the per-face spread.
+- **ISE cannot see `falloff`.** The metric samples the head at the landmark
+ correspondence vertices, which are exactly the morph's control points, where
+ the off-face mask is 1 by construction. `falloff` governs how the displacement
+ decays *away* from the face — scalp, ears, neck — so it is invisible here and
+ must be guarded by the back-of-head assertion in `test_face_geometry.py`.
+ This tool deliberately does not sweep it.
+
+Usage
+-----
+ python -m eval.tune_morph --photos eval/refs
+ python -m eval.tune_morph --photos eval/refs --detail
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import statistics
+import sys
+from pathlib import Path
+
+import numpy as np
+
+sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+
+import face_geometry as fg # noqa: E402
+import glb_ops # noqa: E402
+from eval.identity_eval import EvalError, score, selfie_landmarks # noqa: E402
+
+PHOTO_SUFFIXES = {".jpg", ".jpeg", ".png", ".webp"}
+STRENGTHS = (0.5, 0.6, 0.7, 0.75, 0.85, 1.0)
+CLAMPS = (0.18, 0.25, 0.35, 0.45, 0.55, 0.65, 0.8, 1.0)
+
+
+def load_template(path: Path) -> np.ndarray:
+ glb = glb_ops.load_glb(path.read_bytes())
+ positions, _, _ = glb_ops.get_head_mesh_data(glb)
+ return positions.astype(np.float64)
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--photos", type=Path, default=Path("eval/refs"))
+ ap.add_argument("--template", type=Path, default=Path("templates/default.glb"))
+ ap.add_argument("--detail", action="store_true", help="per-face spread for the winner")
+ ap.add_argument("--out", type=Path, help="write the full grid as JSON")
+ args = ap.parse_args()
+
+ face_map = fg.FaceMap.load()
+ if face_map is None:
+ print("error: face_uv_map.json has no geometry fields", file=sys.stderr)
+ return 1
+
+ base = load_template(args.template)
+ photos = sorted(p for p in args.photos.iterdir() if p.suffix.lower() in PHOTO_SUFFIXES)
+ if not photos:
+ print(f"error: no photos in {args.photos}", file=sys.stderr)
+ return 1
+
+ print(f"detecting landmarks for {len(photos)} faces …")
+ detected: dict[str, np.ndarray] = {}
+ for photo in photos:
+ try:
+ detected[photo.name] = selfie_landmarks(photo)
+ except EvalError as exc:
+ print(f" skip {photo.name}: {exc}")
+ if not detected:
+ print("error: no face detected in any reference photo", file=sys.stderr)
+ return 1
+
+ floors = {
+ name: score(pts, base[face_map.landmark_vtx], face_map)["ise"]
+ for name, pts in detected.items()
+ }
+ floor_mean = statistics.fmean(floors.values())
+ print(f"{len(detected)} faces | template floor (texture-only) ISE {floor_mean:.4f}\n")
+
+ grid = []
+ header = " " + "".join(f"{c:>8}" for c in CLAMPS)
+ print("clamp →" + header[7:])
+ for strength in STRENGTHS:
+ row = []
+ for clamp in CLAMPS:
+ scores = [
+ score(
+ pts,
+ fg.morph_head_to_landmarks(
+ base, face_map, pts, strength=strength, max_displacement_frac=clamp
+ )[face_map.landmark_vtx],
+ face_map,
+ )["ise"]
+ for pts in detected.values()
+ ]
+ entry = {
+ "strength": strength,
+ "clamp": clamp,
+ "mean": statistics.fmean(scores),
+ "worst": max(scores),
+ "per_face": dict(zip(detected, scores)),
+ }
+ grid.append(entry)
+ row.append(entry["mean"])
+ print(f"s={strength:<5}" + "".join(f"{v:>8.4f}" for v in row))
+
+ best = min(grid, key=lambda e: e["mean"])
+ shipped = next(
+ (e for e in grid if e["strength"] == 0.75 and e["clamp"] == 0.18), None
+ )
+
+ print(f"\nbest: strength={best['strength']} clamp={best['clamp']}")
+ print(f" mean ISE {best['mean']:.4f} ({(1 - best['mean'] / floor_mean) * 100:.1f}% below the template floor)")
+ print(f" worst face {best['worst']:.4f}")
+ if shipped:
+ delta = (1 - best["mean"] / shipped["mean"]) * 100
+ print(f" shipped default (0.75 / 0.18) mean ISE {shipped['mean']:.4f} → {delta:+.1f}%")
+ regressed = [
+ name
+ for name, value in best["per_face"].items()
+ if value > shipped["per_face"][name] * 1.02
+ ]
+ print(f" faces made worse than the shipped default: {len(regressed)}")
+ if regressed and args.detail:
+ for name in regressed:
+ print(f" {name:45s} {shipped['per_face'][name]:.4f} → {best['per_face'][name]:.4f}")
+
+ if args.detail:
+ print("\nper-face at the winning setting (worst first):")
+ for name, value in sorted(best["per_face"].items(), key=lambda kv: -kv[1]):
+ print(f" {name:45s} {value:.4f} (floor {floors[name]:.4f})")
+
+ if args.out:
+ args.out.parent.mkdir(parents=True, exist_ok=True)
+ args.out.write_text(json.dumps({"floor_mean": floor_mean, "grid": grid}, indent=2))
+ print(f"\ngrid → {args.out}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/workers/avatar-reconstruction/face_geometry.py b/workers/avatar-reconstruction/face_geometry.py
index 67ffd539b..b0a1d5a24 100644
--- a/workers/avatar-reconstruction/face_geometry.py
+++ b/workers/avatar-reconstruction/face_geometry.py
@@ -15,10 +15,12 @@ Approach — sparse-to-dense identity transfer, fully commercial-clean:
stable identity subset IS the person's face-shape deviation from neutral.
3. Carry that per-landmark displacement onto the template head's corresponding
vertices (precomputed nearest-vertex map), scaled into head units.
- 4. Diffuse the sparse displacements across all head vertices with a normalised
- Gaussian RBF (partition of unity — local, bounded, never extrapolates), and
- fade to zero outside the face region so the neck, scalp and back of the head
- stay put.
+ 4. Interpolate the sparse displacements across all head vertices with a
+ thin-plate spline, which passes exactly through the control points so
+ localised identity (a wider jaw, a longer nose) survives instead of being
+ averaged away — the failure mode of normalised-Gaussian/Shepard weighting.
+ A Gaussian off-face mask fades the field to zero away from the face, since
+ TPS extrapolates freely, so the neck, scalp and back of the head stay put.
5. face_pipeline writes the morphed positions back with glb_ops.set_head_geometry,
which preserves skinning and all 52 ARKit blendshapes + visemes.
@@ -304,7 +306,24 @@ def _median_nn_spacing(pts: np.ndarray) -> float:
# ── MediaPipe adapter ────────────────────────────────────────────────────────
-def landmarks_to_array(landmarks) -> np.ndarray:
- """MediaPipe NormalizedLandmark list → (N,3) array. y is flipped to +up so the
- frame matches the canonical model (image space is y-down)."""
- return np.array([[lm.x, -lm.y, lm.z] for lm in landmarks], dtype=np.float64)
+def landmarks_to_array(landmarks, width: float | None = None, height: float | None = None) -> np.ndarray:
+ """
+ MediaPipe NormalizedLandmark list → (N,3) array. y is flipped to +up so the
+ frame matches the canonical model (image space is y-down).
+
+ **Pass the source image's pixel dimensions.** MediaPipe normalises x by image
+ width and y by image *height*, so on any non-square photo the returned frame
+ is anisotropic: the same face in a 3:4 portrait and a 1:1 crop yields two
+ differently-proportioned point clouds. Umeyama fits a single uniform scale
+ and cannot undo that, so the aspect distortion survives alignment and is read
+ as facial identity — baking the camera's aspect ratio into the avatar's skull.
+ Scaling by (W, H, W) — z shares x's width normalisation — restores an
+ isotropic pixel frame where uniform-scale alignment is valid.
+
+ Dimensions are optional only so existing callers keep working; every caller
+ that has the image should pass them.
+ """
+ pts = np.array([[lm.x, -lm.y, lm.z] for lm in landmarks], dtype=np.float64)
+ if width and height:
+ pts *= np.array([float(width), float(height), float(width)])
+ return pts
diff --git a/workers/avatar-reconstruction/face_pipeline.py b/workers/avatar-reconstruction/face_pipeline.py
index eb53a8cdc..a2a68abf8 100644
--- a/workers/avatar-reconstruction/face_pipeline.py
+++ b/workers/avatar-reconstruction/face_pipeline.py
@@ -551,7 +551,9 @@ def process(
fmap = _get_face_map()
if fmap is not None:
base_pos, _, faces = glb_ops.get_head_mesh_data(glb)
- detected = face_geometry.landmarks_to_array(landmarks)
+ detected = face_geometry.landmarks_to_array(
+ landmarks, *best_img.size
+ )
if detected.shape[0] >= fmap.canonical_norm.shape[0]:
morphed = face_geometry.morph_head_to_landmarks(base_pos, fmap, detected)
glb_ops.set_head_geometry(glb, morphed, faces=faces)
diff --git a/workers/avatar-reconstruction/test_face_geometry.py b/workers/avatar-reconstruction/test_face_geometry.py
index a7462d26b..1dbd29af5 100644
--- a/workers/avatar-reconstruction/test_face_geometry.py
+++ b/workers/avatar-reconstruction/test_face_geometry.py
@@ -169,6 +169,54 @@ def test_registration_preserves_rig_through_glb():
print("ok v2 registration survives GLB write with rig + 67 blendshapes intact")
+class _FakeLandmark:
+ """Stands in for a MediaPipe NormalizedLandmark (x, y, z in [0,1]-ish)."""
+
+ __slots__ = ("x", "y", "z")
+
+ def __init__(self, x, y, z):
+ self.x, self.y, self.z = float(x), float(y), float(z)
+
+
+def test_landmarks_are_independent_of_photo_aspect_ratio():
+ """
+ The same face shot at 3:4, 1:1 and 9:16 must produce the same morph.
+
+ MediaPipe normalises x by image width and y by image height, so its raw
+ output stretches with the photo's aspect ratio. Umeyama fits one uniform
+ scale and cannot undo an anisotropic one, so any leftover stretch survives
+ alignment and is read as facial identity — the camera's aspect ratio ends up
+ baked into the avatar's skull. Passing pixel dimensions restores an isotropic
+ frame. Without that, this test fails.
+ """
+ _, base, _, fmap = _load()
+ canon = fmap.canonical_norm
+
+ # One face in isotropic pixel space, then expressed in each photo's
+ # normalised coordinates — exactly what MediaPipe would return for a face
+ # occupying the same physical region of differently-shaped images.
+ face_px = (canon - canon.min(0)) / (canon.max(0) - canon.min(0)).max()
+ face_px[:, 1] *= -1 # canonical is y-up; image space is y-down
+
+ results = []
+ for width, height in ((864, 1152), (1024, 1024), (720, 1280)):
+ landmarks = [
+ _FakeLandmark(0.2 + p[0] * 0.6 * (720 / width),
+ 0.2 + p[1] * 0.6 * (720 / height),
+ p[2] * 0.6 * (720 / width))
+ for p in face_px
+ ]
+ detected = fg.landmarks_to_array(landmarks, width, height)
+ results.append(fg.morph_head_to_landmarks(base, fmap, detected, strength=0.75))
+
+ reference = results[0]
+ scale = np.linalg.norm(reference.max(0) - reference.min(0))
+ for i, other in enumerate(results[1:], 1):
+ drift = np.linalg.norm(other - reference, axis=1).max() / scale
+ assert drift < 1e-6, f"aspect ratio {i} changed the head shape by {drift:.2%}"
+ print("ok morph is invariant to source photo aspect ratio (3:4 / 1:1 / 9:16)")
+
+
if __name__ == "__main__":
tests = [v for k, v in sorted(globals().items()) if k.startswith("test_")]
try:
diff --git a/workers/garment-forge/Dockerfile b/workers/garment-forge/Dockerfile
new file mode 100644
index 000000000..323c394b9
--- /dev/null
+++ b/workers/garment-forge/Dockerfile
@@ -0,0 +1,30 @@
+# garment-forge: CPU orchestrator, no GPU. Mesh generation and rigging run on
+# the already-deployed GPU workers; this image only needs Python + geometry
+# libraries + the reference body GLB.
+FROM python:3.11-slim
+
+ENV PYTHONDONTWRITEBYTECODE=1 \
+ PYTHONUNBUFFERED=1 \
+ PIP_NO_CACHE_DIR=1
+
+COPY requirements.txt /app/requirements.txt
+RUN pip install --upgrade pip && pip install -r /app/requirements.txt
+
+WORKDIR /app
+COPY worker_security.py /app/worker_security.py
+COPY canonical_bones.py /app/canonical_bones.py
+COPY garment_glb.py /app/garment_glb.py
+COPY pipeline.py /app/pipeline.py
+COPY main.py /app/main.py
+COPY test_garment_glb.py /app/test_garment_glb.py
+
+# The canonical reference body (public/avatars/parametric-base.glb), staged
+# into assets/ by cloudbuild.yaml so the repo does not carry a second copy.
+COPY assets/ /app/assets/
+
+# Build-time guard: the pure glTF pipeline (compose → extract → stats →
+# validate) must pass its unit suite or the image does not ship.
+RUN python /app/test_garment_glb.py
+
+EXPOSE 8080
+CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--workers", "1"]
diff --git a/workers/garment-forge/README.md b/workers/garment-forge/README.md
new file mode 100644
index 000000000..b4bb97666
--- /dev/null
+++ b/workers/garment-forge/README.md
@@ -0,0 +1,153 @@
+# garment-forge: text prompt → rigged, wearable garment GLB + manifest
+
+Turns "a white oxford cotton dress shirt" into an asset the additive wardrobe
+can put on **any** humanoid avatar: a garment GLB skinned to the three.ws
+canonical skeleton, a manifest that passes every validation rule in
+[specs/GARMENT_MANIFEST.md](../../specs/GARMENT_MANIFEST.md), and a thumbnail,
+published to the immutable catalog layout in
+`gs://three-ws-model-weights/garments/`.
+
+The runtime consumer is `attachGarment()` in
+[src/avatar-garment.js](../../src/avatar-garment.js): it rebinds the garment's
+skin onto the target avatar's skeleton and refuses anything that binds under
+`MIN_BIND_COVERAGE` (60%) of its skin weight. This worker measures that same
+number before publishing and fails the job loudly rather than emitting a bad
+asset.
+
+## How it works
+
+This is a **CPU orchestrator**, not a model host. Every heavy stage runs on a
+GPU worker that is already deployed; garment-forge chains them and does the
+pure glTF work in between:
+
+1. **Reference image** (`pipeline.generate_reference_image`): the prompt
+ becomes a ghost-mannequin product photo via the platform's live Vertex AI
+ image lane (`gemini-2.5-flash-image`, the model that replaced the retiring
+ Imagen `:predict` family; see `api/_mcp3d/vertex-imagen.js` for the model
+ landscape). The photo is posed to match the reference body: worn shape,
+ A-pose, front view, plain background. Reference quality drives mesh
+ quality; the resolution is held at 2K.
+2. **Mesh** (`pipeline.generate_mesh`): the image goes through the deployed
+ image→3D failover chain, first healthy rung wins:
+ `model-hunyuan3d-21-rtx` (warm primary, full PBR: albedo +
+ metallicRoughness + normal) → `model-hunyuan3d-21` (L4 fallback, same
+ image) → `model-trellis` (different model, same API contract).
+3. **Compose** (`garment_glb.compose_scene`): the garment mesh is scaled and
+ placed into its slot's region box on the canonical reference body
+ (`assets/refbody.glb`, staged from `public/avatars/parametric-base.glb` at
+ build time: A-pose, 1.667 m, 52 mixamorig joints, front +Z). Slot boxes are
+ measured against that body in `garment_glb.SLOT_BOXES`.
+4. **Rig** (`pipeline.rig_composite`): the *composite* (body + garment) goes
+ to the deployed `model-rig` worker (Make-It-Animatable). Rigging the
+ composite rather than the garment alone is the load-bearing trick: the
+ rigger sees a normally proportioned clothed humanoid, so the skeleton
+ lands at body scale and the garment's vertices pick up weights from the
+ joints they actually sit on. Rigging a shirt alone would fit a full
+ skeleton inside the shirt and shred it on first animation.
+5. **Extract** (`garment_glb.extract_garment`): the reference body is
+ stripped back out. The binary buffer is rebuilt from scratch (only the
+ garment's geometry, skin matrices, and textures survive), and joint names
+ are canonicalized (`mixamorig:LeftArm` → `LeftArm`).
+6. **Validate + publish**: skin-weight statistics produce the bind coverage,
+ the `occludes` declaration (any REGION_BONES region carrying ≥ 1% of the
+ garment's skin weight; deliberately over-declared per the spec), and the
+ manifest's `rig.bones`. All 6 manifest validation rules run in-process;
+ any failure fails the job. On success `garment.glb`, `manifest.json`, and
+ `thumb.webp` (from the reference image) land in
+ `garments/<slot>/<id>/v<version>/` and the manifest is appended to
+ `garments/catalog.json` under an optimistic generation-match loop.
+
+## API
+
+Same wire shape as `workers/avatar-reconstruction` (bearer `API_KEY`):
+
+```
+POST /generate { prompt, slot, tier?, yaw_deg?, job_id? }
+ → 202 { job_id, status: "queued" }
+GET /jobs/:id → { job_id, status, stage, glb_url?, manifest_url?, thumb_url?,
+ coverage?, occludes?, bones?, error?, updated_at }
+GET /health → { ok, refbody_loaded, mesh_backends, rig_url, active_jobs }
+```
+
+`slot` is one of `top, bottom, footwear, outerwear, hair, headwear, glasses,
+accessory`. `stage` walks `image → mesh → compose → rig → extract → validate
+→ publish` so pollers can show real progress. Job state is durable in GCS
+(`garments/jobs/<id>.json`), so polls survive instance restarts and the
+service scales to zero.
+
+Example:
+
+```bash
+KEY=$(gcloud secrets versions access latest --secret avatar-reconstruction-key)
+URL=$(gcloud run services describe garment-forge --region us-central1 --format='value(status.url)')
+
+JOB=$(curl -s -X POST "$URL/generate" \
+ -H "authorization: Bearer $KEY" -H 'content-type: application/json' \
+ -d '{"prompt":"a white oxford cotton dress shirt, long sleeves, buttoned","slot":"top"}' \
+ | python3 -c 'import json,sys;print(json.load(sys.stdin)["job_id"])')
+
+watch -n 10 "curl -s $URL/jobs/$JOB -H 'authorization: Bearer $KEY' | python3 -m json.tool"
+```
+
+A finished job reports the published `manifest_url`, `glb_url`, and the
+measured `coverage`.
+
+## Deploy
+
+```bash
+gcloud builds submit --config workers/garment-forge/cloudbuild.yaml \
+ --region us-central1 --project aerial-vehicle-466722-p5 \
+ --substitutions=SHORT_SHA=manual$(date +%s) .
+```
+
+The build stages the reference body out of `public/avatars/` (the repo keeps
+one copy), runs `test_garment_glb.py` as a build gate, and deploys the
+`garment-forge` Cloud Run service (CPU only, scale-to-zero, runtime SA
+`avatar-reconstruction-sa@`, `API_KEY` from the `avatar-reconstruction-key`
+secret). The cloudbuild config pins the `three-ws-build@` service account,
+as every build in this project must.
+
+One-time infra the service depends on (already applied):
+
+- `avatar-reconstruction-sa@` has `roles/storage.objectAdmin` on
+ `three-ws-model-weights` (writes garments/**, jobs, catalog) and
+ `roles/aiplatform.user` on the project (Vertex image lane).
+- `three-ws-model-weights` carries a CORS policy allowing `GET` from any
+ origin, so published garment GLBs are readable by the viewer, per the
+ manifest spec's CORS requirement.
+
+## Local tests (no GPU, no network)
+
+```bash
+python3 workers/garment-forge/test_garment_glb.py
+```
+
+33 checks over the pure glTF pipeline: canonicalization, placement math,
+composition, body-strip + buffer repack, coverage/occludes derivation, and
+each of the 6 manifest validation rules failing for its own reason. The same
+suite runs inside `docker build`, so a regression cannot ship.
+
+## Environment
+
+| Var | Default | Meaning |
+|---|---|---|
+| `API_KEY` | (secret) | shared bearer secret (`avatar-reconstruction-key`); also sent to the mesh/rig workers |
+| `GCS_BUCKET` | (required) | bucket holding `garments/**` (`three-ws-model-weights`) |
+| `MESH_WORKER_URLS` | (required) | comma-separated `/infer`-contract mesh workers, priority order |
+| `RIG_URL` | (required) | `model-rig` base URL |
+| `REFBODY_PATH` | `/app/assets/refbody.glb` | reference body baked into the image |
+| `GOOGLE_CLOUD_PROJECT` | (required) | Vertex project |
+| `VERTEX_IMAGEN_MODEL` | `gemini-2.5-flash-image` | Vertex image model |
+| `VERTEX_IMAGEN_LOCATION` | `global` | Vertex location for the image model |
+| `VERTEX_IMAGE_SIZE` | `2K` | reference image resolution |
+| `GARMENT_YAW_DEG` | `0` | yaw applied to generator output before placement |
+| `MESH_TIMEOUT_S` / `RIG_TIMEOUT_S` | `1200` / `600` | per-stage poll ceilings |
+| `MAX_CONCURRENT` | `2` | parallel jobs per instance |
+
+## Provenance and licensing
+
+Generated manifests carry `source.kind: "generated"` with the prompt, the
+mesh backend that produced the geometry, and `pipeline: "garment-forge@1"`,
+so every catalog entry is reproducible and auditable. The reference body is
+CC0 (MakeHuman/MPFB2-derived), Make-It-Animatable is MIT, and published
+manifests declare `CC0-1.0`.
diff --git a/workers/garment-forge/cloudbuild.yaml b/workers/garment-forge/cloudbuild.yaml
new file mode 100644
index 000000000..5728ca4d4
--- /dev/null
+++ b/workers/garment-forge/cloudbuild.yaml
@@ -0,0 +1,80 @@
+substitutions:
+ _REGION: us-central1
+ _RUN_SA: avatar-reconstruction-sa@aerial-vehicle-466722-p5.iam.gserviceaccount.com
+ _SERVICE: garment-forge
+ _REPO: garment-forge
+ # Garment assets, catalog, and job records live in the weights bucket, per
+ # the storage layout pinned in specs/GARMENT_MANIFEST.md.
+ _GCS_BUCKET: three-ws-model-weights
+ # Mesh generation failover chain, priority order: warm RTX 2.1 primary,
+ # L4 2.1 fallback, TRELLIS last (different model, always-compatible API).
+ _MESH_WORKER_URLS: https://model-hunyuan3d-21-rtx-lp642k3kpa-uc.a.run.app,https://model-hunyuan3d-21-lp642k3kpa-uc.a.run.app,https://model-trellis-lp642k3kpa-uc.a.run.app
+ _RIG_URL: https://model-rig-lp642k3kpa-uc.a.run.app
+
+steps:
+ # Stage the canonical reference body into the Docker context. The repo keeps
+ # a single copy (public/avatars/parametric-base.glb); the image bakes it so
+ # cold starts never fetch it.
+ - id: stage-refbody
+ name: gcr.io/cloud-builders/docker
+ entrypoint: bash
+ args:
+ - -c
+ - mkdir -p workers/garment-forge/assets &&
+ cp public/avatars/parametric-base.glb workers/garment-forge/assets/refbody.glb
+
+ - id: build
+ name: gcr.io/cloud-builders/docker
+ dir: workers/garment-forge
+ args:
+ - build
+ - --tag
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA
+ - --tag
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest
+ - --cache-from
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest
+ - .
+
+ - id: push
+ name: gcr.io/cloud-builders/docker
+ args:
+ - push
+ - --all-tags
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server
+
+ - id: deploy
+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim
+ entrypoint: gcloud
+ args:
+ - run
+ - deploy
+ - ${_SERVICE}
+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA
+ - --region=${_REGION}
+ - --service-account=${_RUN_SA}
+ - --platform=managed
+ - --port=8080
+ - --cpu=4
+ - --memory=8Gi
+ - --min-instances=0
+ - --max-instances=2
+ - --timeout=600
+ - --allow-unauthenticated
+ - --set-env-vars=^;^GCS_BUCKET=${_GCS_BUCKET};MESH_WORKER_URLS=${_MESH_WORKER_URLS};RIG_URL=${_RIG_URL};GOOGLE_CLOUD_PROJECT=$PROJECT_ID;VERTEX_IMAGEN_MODEL=gemini-2.5-flash-image;VERTEX_IMAGEN_LOCATION=global;VERTEX_IMAGE_SIZE=2K;MAX_CONCURRENT=2
+ - --set-secrets=API_KEY=avatar-reconstruction-key:latest
+
+images:
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest
+
+options:
+ machineType: E2_HIGHCPU_8
+ logging: CLOUD_LOGGING_ONLY
+
+# The project's default compute service account was deleted (see
+# docs/ops/gcp-production.md): every Cloud Build must pin the build SA
+# explicitly or the submit fails with "Unknown service account".
+serviceAccount: projects/aerial-vehicle-466722-p5/serviceAccounts/[email protected]
+
+timeout: 1200s
diff --git a/workers/garment-forge/garment_glb.py b/workers/garment-forge/garment_glb.py
new file mode 100644
index 000000000..544a3aec8
--- /dev/null
+++ b/workers/garment-forge/garment_glb.py
@@ -0,0 +1,579 @@
+"""
+Pure glTF/geometry operations for the garment forge: no network, no GCP, no
+GPU, so every function here is unit-testable (see test_garment_glb.py).
+
+The pipeline (main.py) composes these into:
+
+ 1. compose_scene() garment mesh + reference body → one GLB for model-rig.
+ The garment is scaled/placed into the region box its
+ wardrobe slot occupies on the reference body, so the
+ rigger predicts its weights with full-body context.
+ 2. extract_garment() rigged composite → garment-only skinned GLB. Strips
+ the reference body, canonicalizes bone names, and
+ repacks the binary buffer so none of the body's
+ geometry or textures ship inside the published asset.
+ 3. skin_stats() weight mass per canonical bone + bind coverage: the
+ number attachGarment() (src/avatar-garment.js) will
+ gate on at runtime.
+ 4. derive_occludes() REGION_BONES weight mass → `occludes` declaration.
+ 5. validate_manifest() the 6 validation rules from specs/GARMENT_MANIFEST.md.
+
+Geometry constants (slot boxes) are measured against the reference body baked
+into this worker's image: public/avatars/parametric-base.glb, an A-pose,
+1.667 m tall canonical humanoid whose front faces +Z.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import io
+import re
+
+import numpy as np
+import pygltflib
+import trimesh
+
+from canonical_bones import (
+ BODY_REGIONS,
+ CANONICAL_BONES,
+ GARMENT_SLOTS,
+ MIN_BIND_COVERAGE,
+ canonicalize_bone_name,
+ region_of_bone,
+)
+
+SPEC_URI = "https://three.ws/specs/garment-manifest-v1"
+
+# SPDX identifiers the catalog accepts (validation rule 6: recognised SPDX,
+# commercial use permitted). Extend deliberately, never guess.
+COMMERCIAL_SPDX = frozenset({
+ "CC0-1.0", "MIT", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause",
+ "CC-BY-4.0", "Unlicense", "Zlib",
+})
+
+# A region must carry at least this share of the garment's total skin weight
+# to be declared in `occludes`. Deliberately LOW: the spec says over-declare
+# (hidden skin is invisible, exposed skin is the worst artefact), so any
+# region the garment meaningfully touches gets declared.
+OCCLUDES_MIN_SHARE = 0.01
+
+# A canonical bone enters the manifest's rig.bones list above this weight
+# share: enough to filter numeric noise without dropping real influences.
+RIG_BONES_MIN_SHARE = 0.001
+
+# ── Slot placement boxes on the reference body ──────────────────────────────
+# center (x, y, z) and size (w, h, d) in reference-body meters; `fit` is the
+# axis (0=x, 1=y) whose extent the garment is scaled to match. Height-fit for
+# body-length garments, width-fit for items whose height varies wildly with
+# style (shoes, hair, glasses).
+SLOT_BOXES = {
+ "top": {"center": (0.0, 1.14, 0.03), "size": (0.90, 0.56, 0.45), "fit": 1},
+ "outerwear": {"center": (0.0, 1.05, 0.03), "size": (1.00, 0.80, 0.50), "fit": 1},
+ "bottom": {"center": (0.0, 0.50, 0.02), "size": (0.50, 0.90, 0.35), "fit": 1},
+ "footwear": {"center": (0.0, 0.09, 0.06), "size": (0.60, 0.18, 0.32), "fit": 0},
+ "hair": {"center": (0.0, 1.58, 0.03), "size": (0.30, 0.25, 0.30), "fit": 0},
+ "headwear": {"center": (0.0, 1.60, 0.03), "size": (0.30, 0.22, 0.30), "fit": 0},
+ "glasses": {"center": (0.0, 1.547, 0.11), "size": (0.18, 0.08, 0.12), "fit": 0},
+ "accessory": {"center": (0.0, 1.20, 0.05), "size": (0.35, 0.35, 0.25), "fit": 0},
+}
+
+GARMENT_PREFIX = "garment"
+REFBODY_PREFIX = "refbody"
+
+# glTF componentType → numpy dtype / byte size.
+_COMPONENT_DTYPES = {
+ 5120: np.int8, 5121: np.uint8, 5122: np.int16,
+ 5123: np.uint16, 5125: np.uint32, 5126: np.float32,
+}
+_TYPE_COUNTS = {"SCALAR": 1, "VEC2": 2, "VEC3": 3, "VEC4": 4, "MAT2": 4, "MAT3": 9, "MAT4": 16}
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# Scene composition
+# ────────────────────────────────────────────────────────────────────────────
+
+def _scene_meshes(data: bytes) -> list[trimesh.Trimesh]:
+ """Load a GLB into world-space trimesh geometries (transforms baked)."""
+ loaded = trimesh.load(io.BytesIO(data), file_type="glb", process=False)
+ if isinstance(loaded, trimesh.Trimesh):
+ return [loaded]
+ meshes = []
+ for node_name in loaded.graph.nodes_geometry:
+ transform, geom_name = loaded.graph[node_name]
+ geom = loaded.geometry[geom_name]
+ if not isinstance(geom, trimesh.Trimesh):
+ continue
+ mesh = geom.copy()
+ mesh.apply_transform(transform)
+ meshes.append(mesh)
+ if not meshes:
+ raise ValueError("GLB contains no triangle meshes")
+ return meshes
+
+
+def _bounds(meshes: list[trimesh.Trimesh]) -> tuple[np.ndarray, np.ndarray]:
+ lo = np.min([m.bounds[0] for m in meshes], axis=0)
+ hi = np.max([m.bounds[1] for m in meshes], axis=0)
+ return lo, hi
+
+
+def garment_placement(meshes: list[trimesh.Trimesh], slot: str, yaw_deg: float = 0.0) -> np.ndarray:
+ """4x4 transform that carries a normalized generator-output garment into
+ its slot's region box on the reference body: yaw to face +Z, uniform
+ scale to the slot's fit-axis extent, translate to the box center."""
+ box = SLOT_BOXES[slot]
+ rot = trimesh.transformations.rotation_matrix(np.radians(yaw_deg), [0, 1, 0])
+
+ rotated = [m.copy() for m in meshes]
+ for m in rotated:
+ m.apply_transform(rot)
+ lo, hi = _bounds(rotated)
+ extent = hi - lo
+ fit = box["fit"]
+ if extent[fit] <= 1e-9:
+ raise ValueError(f"degenerate garment mesh (zero extent on fit axis {fit})")
+ scale = box["size"][fit] / extent[fit]
+
+ center = (lo + hi) / 2.0
+ target = np.array(box["center"], dtype=np.float64)
+ move = trimesh.transformations.translation_matrix(target - center * scale)
+ scale_m = np.eye(4)
+ scale_m[:3, :3] *= scale
+ return move @ scale_m @ rot
+
+
+def compose_scene(garment_bytes: bytes, refbody_bytes: bytes, slot: str,
+ yaw_deg: float = 0.0) -> bytes:
+ """One GLB holding the reference body plus the garment placed into its
+ slot box. Mesh names carry the garment/refbody split through the rigger,
+ which preserves names, so extract_garment() can tell them apart."""
+ if slot not in SLOT_BOXES:
+ raise ValueError(f"unknown slot: {slot}")
+ garment = _scene_meshes(garment_bytes)
+ body = _scene_meshes(refbody_bytes)
+
+ placement = garment_placement(garment, slot, yaw_deg)
+ scene = trimesh.Scene()
+ for i, m in enumerate(body):
+ scene.add_geometry(m, node_name=f"{REFBODY_PREFIX}_{i}", geom_name=f"{REFBODY_PREFIX}_{i}")
+ for i, m in enumerate(garment):
+ placed = m.copy()
+ placed.apply_transform(placement)
+ scene.add_geometry(placed, node_name=f"{GARMENT_PREFIX}_{i}", geom_name=f"{GARMENT_PREFIX}_{i}")
+ return scene.export(file_type="glb")
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# glTF accessor plumbing
+# ────────────────────────────────────────────────────────────────────────────
+
+def _accessor_array(glb: pygltflib.GLTF2, blob: bytes, idx: int) -> np.ndarray:
+ """Decode accessor `idx` to a (count, components) float/int array. Handles
+ tightly packed and interleaved (byteStride) layouts."""
+ acc = glb.accessors[idx]
+ dtype = _COMPONENT_DTYPES[acc.componentType]
+ ncomp = _TYPE_COUNTS[acc.type]
+ elem = np.dtype(dtype).itemsize * ncomp
+ bv = glb.bufferViews[acc.bufferView]
+ base = (bv.byteOffset or 0) + (acc.byteOffset or 0)
+ stride = bv.byteStride or elem
+ if stride == elem:
+ raw = np.frombuffer(blob, dtype=dtype, count=acc.count * ncomp, offset=base)
+ return raw.reshape(acc.count, ncomp)
+ rows = np.frombuffer(blob, dtype=np.uint8, count=stride * acc.count, offset=base)
+ rows = rows.reshape(acc.count, stride)[:, :elem].copy()
+ return rows.view(dtype).reshape(acc.count, ncomp)
+
+
+def _accessor_bytes(glb: pygltflib.GLTF2, blob: bytes, idx: int) -> bytes:
+ """Raw, tightly packed bytes of accessor `idx` (de-interleaved if needed)."""
+ return np.ascontiguousarray(_accessor_array(glb, blob, idx)).tobytes()
+
+
+def _prim_attribute_indices(prim) -> dict[str, int]:
+ """Attribute name → accessor index for every set attribute of a primitive."""
+ out = {}
+ for name, value in vars(prim.attributes).items():
+ if isinstance(value, int):
+ out[name] = value
+ return out
+
+
+def _material_texture_slots(material) -> list:
+ """The texture-info objects a standard PBR material can reference."""
+ slots = []
+ if material.pbrMetallicRoughness:
+ slots += [material.pbrMetallicRoughness.baseColorTexture,
+ material.pbrMetallicRoughness.metallicRoughnessTexture]
+ slots += [material.normalTexture, material.occlusionTexture, material.emissiveTexture]
+ return [s for s in slots if s is not None]
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# Garment extraction (strip reference body + repack)
+# ────────────────────────────────────────────────────────────────────────────
+
+def extract_garment(rigged_bytes: bytes, keep_prefix: str = GARMENT_PREFIX) -> bytes:
+ """From a rigged composite GLB, keep only the garment meshes, the skeleton
+ and its skin, and the resources they reference. Joint node names are
+ canonicalized (mixamorig:LeftArm → LeftArm). The binary buffer is rebuilt
+ from scratch so none of the reference body's geometry or textures survive
+ into the published asset."""
+ glb = pygltflib.GLTF2.load_from_bytes(rigged_bytes)
+ blob = glb.binary_blob() or b""
+
+ keep_meshes = {i for i, m in enumerate(glb.meshes)
+ if (m.name or "").startswith(keep_prefix)}
+ if not keep_meshes:
+ raise ValueError(f"no mesh named '{keep_prefix}*' in rigged GLB")
+
+ # Skins still referenced once the body meshes are gone.
+ keep_skins = set()
+ for node in glb.nodes:
+ if node.mesh in keep_meshes and node.skin is not None:
+ keep_skins.add(node.skin)
+ if not keep_skins:
+ raise ValueError("garment mesh carries no skin: rigging did not bind it")
+
+ # ── collect used resources ──
+ used_accessors: set[int] = set()
+ used_materials: set[int] = set()
+ for mi in keep_meshes:
+ for prim in glb.meshes[mi].primitives:
+ used_accessors.update(_prim_attribute_indices(prim).values())
+ if prim.indices is not None:
+ used_accessors.add(prim.indices)
+ if prim.material is not None:
+ used_materials.add(prim.material)
+ for target in (prim.targets or []):
+ for value in vars(target).values():
+ if isinstance(value, int):
+ used_accessors.add(value)
+ for si in keep_skins:
+ if glb.skins[si].inverseBindMatrices is not None:
+ used_accessors.add(glb.skins[si].inverseBindMatrices)
+
+ used_textures: set[int] = set()
+ for mati in used_materials:
+ for slot in _material_texture_slots(glb.materials[mati]):
+ used_textures.add(slot.index)
+ used_images: set[int] = set()
+ used_samplers: set[int] = set()
+ for ti in used_textures:
+ tex = glb.textures[ti]
+ if tex.source is not None:
+ used_images.add(tex.source)
+ if tex.sampler is not None:
+ used_samplers.add(tex.sampler)
+
+ # ── rebuild the binary buffer: one tight bufferView per used accessor,
+ # plus one per used embedded image ──
+ new_blob = bytearray()
+ new_views: list[pygltflib.BufferView] = []
+ new_accessors: list[pygltflib.Accessor] = []
+ accessor_remap: dict[int, int] = {}
+
+ def _append_view(data: bytes, target: int | None = None) -> int:
+ while len(new_blob) % 4:
+ new_blob.append(0)
+ view = pygltflib.BufferView(buffer=0, byteOffset=len(new_blob), byteLength=len(data))
+ if target is not None:
+ view.target = target
+ new_blob.extend(data)
+ new_views.append(view)
+ return len(new_views) - 1
+
+ for old_idx in sorted(used_accessors):
+ acc = glb.accessors[old_idx]
+ clone = pygltflib.Accessor(
+ componentType=acc.componentType, count=acc.count, type=acc.type,
+ normalized=acc.normalized, min=acc.min, max=acc.max, name=acc.name,
+ )
+ if acc.bufferView is not None:
+ old_target = glb.bufferViews[acc.bufferView].target
+ clone.bufferView = _append_view(_accessor_bytes(glb, blob, old_idx), old_target)
+ clone.byteOffset = 0
+ accessor_remap[old_idx] = len(new_accessors)
+ new_accessors.append(clone)
+
+ image_remap: dict[int, int] = {}
+ new_images = []
+ for old_idx in sorted(used_images):
+ img = glb.images[old_idx]
+ clone = pygltflib.Image(mimeType=img.mimeType, name=img.name)
+ if img.bufferView is not None:
+ bv = glb.bufferViews[img.bufferView]
+ start = bv.byteOffset or 0
+ clone.bufferView = _append_view(bytes(blob[start:start + bv.byteLength]))
+ elif img.uri:
+ clone.uri = img.uri
+ image_remap[old_idx] = len(new_images)
+ new_images.append(clone)
+
+ sampler_remap = {old: new for new, old in enumerate(sorted(used_samplers))}
+ new_samplers = [glb.samplers[i] for i in sorted(used_samplers)]
+
+ texture_remap: dict[int, int] = {}
+ new_textures = []
+ for old_idx in sorted(used_textures):
+ tex = glb.textures[old_idx]
+ clone = pygltflib.Texture(
+ source=image_remap.get(tex.source) if tex.source is not None else None,
+ sampler=sampler_remap.get(tex.sampler) if tex.sampler is not None else None,
+ name=tex.name,
+ )
+ texture_remap[old_idx] = len(new_textures)
+ new_textures.append(clone)
+
+ material_remap: dict[int, int] = {}
+ new_materials = []
+ for old_idx in sorted(used_materials):
+ mat = glb.materials[old_idx]
+ for slot in _material_texture_slots(mat):
+ slot.index = texture_remap[slot.index]
+ material_remap[old_idx] = len(new_materials)
+ new_materials.append(mat)
+
+ mesh_remap: dict[int, int] = {}
+ new_meshes = []
+ for old_idx in sorted(keep_meshes):
+ mesh = glb.meshes[old_idx]
+ for prim in mesh.primitives:
+ for name, value in _prim_attribute_indices(prim).items():
+ setattr(prim.attributes, name, accessor_remap[value])
+ if prim.indices is not None:
+ prim.indices = accessor_remap[prim.indices]
+ if prim.material is not None:
+ prim.material = material_remap[prim.material]
+ for target in (prim.targets or []):
+ for name, value in list(vars(target).items()):
+ if isinstance(value, int):
+ setattr(target, name, accessor_remap[value])
+ mesh_remap[old_idx] = len(new_meshes)
+ new_meshes.append(mesh)
+
+ skin_remap: dict[int, int] = {}
+ new_skins = []
+ for old_idx in sorted(keep_skins):
+ skin = glb.skins[old_idx]
+ if skin.inverseBindMatrices is not None:
+ skin.inverseBindMatrices = accessor_remap[skin.inverseBindMatrices]
+ skin_remap[old_idx] = len(new_skins)
+ new_skins.append(skin)
+
+ # ── nodes: drop mesh/skin refs to removed resources, remap the kept ones,
+ # canonicalize joint names. Node indices are untouched (joint hierarchy,
+ # scene lists and skin.joints stay valid). ──
+ joint_nodes = set()
+ for skin in new_skins:
+ joint_nodes.update(skin.joints or [])
+ for ni, node in enumerate(glb.nodes):
+ if node.mesh is not None:
+ node.mesh = mesh_remap.get(node.mesh)
+ if node.mesh is None:
+ node.skin = None
+ if node.skin is not None:
+ node.skin = skin_remap.get(node.skin)
+ if ni in joint_nodes:
+ canonical = canonicalize_bone_name(node.name)
+ if canonical:
+ node.name = canonical
+
+ glb.meshes = new_meshes
+ glb.skins = new_skins
+ glb.materials = new_materials
+ glb.textures = new_textures
+ glb.images = new_images
+ glb.samplers = new_samplers
+ glb.accessors = new_accessors
+ glb.bufferViews = new_views
+ glb.animations = []
+
+ glb.set_binary_blob(bytes(new_blob))
+ if not glb.buffers:
+ glb.buffers.append(pygltflib.Buffer())
+ glb.buffers = [glb.buffers[0]]
+ glb.buffers[0].byteLength = len(new_blob)
+ glb.buffers[0].uri = None
+ out = glb.save_to_bytes()
+ return b"".join(out) if isinstance(out, (list, tuple)) else out
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# Skin statistics, coverage, occlusion
+# ────────────────────────────────────────────────────────────────────────────
+
+def skin_stats(glb_bytes: bytes) -> dict:
+ """Weight mass per canonical bone across every skinned primitive, plus the
+ bind coverage the runtime will measure: the share of total skin weight
+ carried by joints that canonicalize into CANONICAL_BONES."""
+ glb = pygltflib.GLTF2.load_from_bytes(glb_bytes)
+ blob = glb.binary_blob() or b""
+
+ bone_mass: dict[str, float] = {}
+ unresolved_mass = 0.0
+ total_mass = 0.0
+ triangles = 0
+
+ for mesh in glb.meshes:
+ for prim in mesh.primitives:
+ attrs = _prim_attribute_indices(prim)
+ if "POSITION" in attrs:
+ if prim.indices is not None:
+ triangles += glb.accessors[prim.indices].count // 3
+ else:
+ triangles += glb.accessors[attrs["POSITION"]].count // 3
+ if "JOINTS_0" not in attrs or "WEIGHTS_0" not in attrs:
+ continue
+
+ node_skin = None
+ for node in glb.nodes:
+ if node.mesh is not None and glb.meshes[node.mesh] is mesh and node.skin is not None:
+ node_skin = glb.skins[node.skin]
+ break
+ if node_skin is None:
+ continue
+ joint_names = [glb.nodes[j].name or "" for j in node_skin.joints]
+ canonical = [canonicalize_bone_name(n) for n in joint_names]
+
+ joints = _accessor_array(glb, blob, attrs["JOINTS_0"]).astype(np.int64)
+ weights = _accessor_array(glb, blob, attrs["WEIGHTS_0"]).astype(np.float64)
+ acc = glb.accessors[attrs["WEIGHTS_0"]]
+ if acc.componentType == 5121:
+ weights /= 255.0
+ elif acc.componentType == 5123:
+ weights /= 65535.0
+
+ flat_j = joints.reshape(-1)
+ flat_w = weights.reshape(-1)
+ positive = flat_w > 0
+ per_joint = np.bincount(flat_j[positive], weights=flat_w[positive],
+ minlength=len(joint_names))
+ for ji, mass in enumerate(per_joint):
+ if mass <= 0:
+ continue
+ total_mass += float(mass)
+ name = canonical[ji] if ji < len(canonical) else None
+ if name:
+ bone_mass[name] = bone_mass.get(name, 0.0) + float(mass)
+ else:
+ unresolved_mass += float(mass)
+
+ coverage = (total_mass - unresolved_mass) / total_mass if total_mass > 0 else 0.0
+ return {
+ "coverage": coverage,
+ "total_mass": total_mass,
+ "bone_mass": bone_mass,
+ "unresolved_mass": unresolved_mass,
+ "triangle_count": triangles,
+ }
+
+
+def derive_occludes(bone_mass: dict[str, float], total_mass: float,
+ min_share: float = OCCLUDES_MIN_SHARE) -> list[str]:
+ """Body regions whose bones carry ≥ min_share of the garment's skin
+ weight, in BODY_REGIONS order. Over-declares by design (low threshold):
+ hiding a covered square centimetre of skin is invisible, exposing one is
+ the most obvious artefact an additive wardrobe can produce."""
+ if total_mass <= 0:
+ return []
+ region_mass: dict[str, float] = {}
+ for bone, mass in bone_mass.items():
+ region = region_of_bone(bone)
+ if region:
+ region_mass[region] = region_mass.get(region, 0.0) + mass
+ return [r for r in BODY_REGIONS if region_mass.get(r, 0.0) / total_mass >= min_share]
+
+
+def weighted_bones(bone_mass: dict[str, float], total_mass: float,
+ min_share: float = RIG_BONES_MIN_SHARE) -> list[str]:
+ """Canonical bones carrying a real share of skin weight, in canonical order
+ : the manifest's rig.bones list."""
+ if total_mass <= 0:
+ return []
+ return [b for b in CANONICAL_BONES if bone_mass.get(b, 0.0) / total_mass >= min_share]
+
+
+# ────────────────────────────────────────────────────────────────────────────
+# Manifest
+# ────────────────────────────────────────────────────────────────────────────
+
+def slugify(text: str, max_words: int = 5) -> str:
+ words = re.findall(r"[a-z0-9]+", (text or "").lower())
+ return "-".join(words[:max_words]) or "garment"
+
+
+def sha256_hex(data: bytes) -> str:
+ return hashlib.sha256(data).hexdigest()
+
+
+def validate_manifest(manifest: dict, glb_bytes: bytes) -> dict:
+ """Enforce all 6 validation rules from specs/GARMENT_MANIFEST.md.
+ Returns {ok, failures, coverage}; a garment failing any rule must not be
+ published."""
+ failures: list[str] = []
+
+ if manifest.get("spec") != SPEC_URI:
+ failures.append(f"rule 1: spec is not {SPEC_URI}")
+ if manifest.get("slot") not in GARMENT_SLOTS:
+ failures.append(f"rule 2: slot {manifest.get('slot')!r} not in {GARMENT_SLOTS}")
+ bad_regions = [r for r in manifest.get("occludes", []) if r not in BODY_REGIONS]
+ if bad_regions:
+ failures.append(f"rule 3: unknown occludes regions {bad_regions}")
+ declared = (manifest.get("model") or {}).get("sha256")
+ if declared != sha256_hex(glb_bytes):
+ failures.append("rule 4: model.sha256 does not match the GLB bytes")
+
+ coverage = 0.0
+ try:
+ stats = skin_stats(glb_bytes)
+ coverage = stats["coverage"]
+ if stats["total_mass"] <= 0:
+ failures.append("rule 5: GLB has no skinned mesh")
+ elif coverage < MIN_BIND_COVERAGE:
+ failures.append(
+ f"rule 5: bind coverage {coverage:.3f} below MIN_BIND_COVERAGE {MIN_BIND_COVERAGE}")
+ except Exception as exc: # noqa: BLE001: a GLB that fails to parse fails rule 5
+ failures.append(f"rule 5: GLB does not load ({exc})")
+
+ if manifest.get("license") not in COMMERCIAL_SPDX:
+ failures.append(
+ f"rule 6: license {manifest.get('license')!r} is not a recognised "
+ "commercial-use SPDX identifier")
+
+ return {"ok": not failures, "failures": failures, "coverage": coverage}
+
+
+def build_manifest(*, garment_id: str, name: str, slot: str, version: int,
+ model_uri: str, glb_bytes: bytes, triangle_count: int,
+ bones: list[str], occludes: list[str], prompt: str,
+ mesh_model: str, thumb_uri: str) -> dict:
+ return {
+ "spec": SPEC_URI,
+ "id": garment_id,
+ "name": name,
+ "slot": slot,
+ "version": version,
+ "model": {
+ "uri": model_uri,
+ "format": "gltf-binary",
+ "sha256": sha256_hex(glb_bytes),
+ "sizeBytes": len(glb_bytes),
+ "triangleCount": triangle_count,
+ },
+ "rig": {
+ "skeleton": "three.ws-canonical-v1",
+ "bindPose": "a-pose",
+ "bones": bones,
+ },
+ "occludes": occludes,
+ "materials": {"tintable": False, "palette": "garment"},
+ "license": "CC0-1.0",
+ "source": {
+ "kind": "generated",
+ "prompt": prompt,
+ "model": mesh_model,
+ "pipeline": "garment-forge@1",
+ },
+ "preview": {"thumbnail": thumb_uri},
+ }
diff --git a/workers/garment-forge/main.py b/workers/garment-forge/main.py
new file mode 100644
index 000000000..b321f711b
--- /dev/null
+++ b/workers/garment-forge/main.py
@@ -0,0 +1,276 @@
+"""
+garment-forge: text prompt → rigged, wearable garment GLB + manifest.
+
+Orchestrates the platform's already-deployed GPU workers instead of hosting a
+model itself, so this service runs on plain CPU:
+
+ prompt ─→ Vertex AI image lane (ghost-mannequin reference photo)
+ ─→ model-hunyuan3d-21-rtx → model-hunyuan3d-21 → model-trellis
+ (image → PBR-textured mesh, first healthy rung wins)
+ ─→ compose with the canonical reference body (parametric-base)
+ ─→ model-rig (Make-It-Animatable: skeleton + skin weights with
+ full-body context)
+ ─→ strip the reference body, canonicalize bones, validate the 6
+ manifest rules, publish to GCS + garments/catalog.json
+
+API contract (same wire shape as workers/avatar-reconstruction/main.py):
+
+ POST /generate { prompt, slot, tier?, yaw_deg? }
+ → 202 { job_id, status: "queued" }
+ GET /jobs/:id → { job_id, status, stage, glb_url?, manifest_url?,
+ thumb_url?, coverage?, occludes?, error?, updated_at }
+ GET /health → { ok, refbody_loaded, mesh_backends, rig_url }
+
+Job state is persisted to a durable GCS blob on every transition (the same
+pattern as the hunyuan 2.1 worker): a POST and a later poll that land on
+different instances still see one record, and the service can scale to zero.
+
+Environment variables:
+ API_KEY shared bearer secret (avatar-reconstruction-key), used both
+ to authenticate callers and to call the other workers
+ GCS_BUCKET bucket holding garments/** (three-ws-model-weights)
+ MESH_WORKER_URLS comma-separated /infer-contract mesh workers, priority order
+ RIG_URL model-rig base URL
+ REFBODY_PATH reference body GLB baked into the image
+ GOOGLE_CLOUD_PROJECT, VERTEX_IMAGEN_MODEL, VERTEX_IMAGEN_LOCATION,
+ VERTEX_IMAGE_SIZE Vertex image lane (see pipeline.py)
+ GARMENT_YAW_DEG yaw applied to generator output before placement (default 0)
+ MAX_CONCURRENT parallel jobs per instance (default 2; CPU-bound stages only)
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import logging
+import os
+import time
+import uuid
+from contextlib import asynccontextmanager
+from datetime import datetime, timezone
+from typing import Optional
+
+from fastapi import BackgroundTasks, FastAPI, Header, HTTPException
+from google.api_core.exceptions import NotFound
+from google.cloud import storage
+from pydantic import BaseModel, Field
+
+import garment_glb
+import pipeline
+from canonical_bones import GARMENT_SLOTS
+from worker_security import require_api_key, safe_error
+
+logging.basicConfig(
+ level=logging.INFO,
+ format="%(asctime)s %(levelname)s %(name)s %(message)s",
+)
+log = logging.getLogger("garment-forge")
+
+API_KEY = os.environ["API_KEY"]
+GCS_BUCKET = os.environ["GCS_BUCKET"]
+MESH_WORKER_URLS = [u.strip().rstrip("/") for u in
+ os.environ["MESH_WORKER_URLS"].split(",") if u.strip()]
+RIG_URL = os.environ["RIG_URL"].rstrip("/")
+REFBODY_PATH = os.environ.get("REFBODY_PATH", "/app/assets/refbody.glb")
+GARMENT_YAW_DEG = float(os.environ.get("GARMENT_YAW_DEG", "0"))
+MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "2"))
+
+_bucket: Optional[storage.Bucket] = None
+_sem: Optional[asyncio.Semaphore] = None
+_refbody: Optional[bytes] = None
+_jobs: dict[str, dict] = {}
+
+
+def _job_blob(job_id: str):
+ return _bucket.blob(f"garments/jobs/{job_id}.json")
+
+
+async def _update_job(job_id: str, **fields) -> dict:
+ job = _jobs.setdefault(job_id, {"job_id": job_id})
+ job.update(fields, updated_at=datetime.now(timezone.utc).isoformat())
+ loop = asyncio.get_event_loop()
+ await loop.run_in_executor(
+ None,
+ lambda: _job_blob(job_id).upload_from_string(
+ json.dumps(job), content_type="application/json"),
+ )
+ return job
+
+
+@asynccontextmanager
+async def lifespan(app: FastAPI):
+ global _bucket, _sem, _refbody
+ _bucket = storage.Client().bucket(GCS_BUCKET)
+ _sem = asyncio.Semaphore(MAX_CONCURRENT)
+ with open(REFBODY_PATH, "rb") as fh:
+ _refbody = fh.read()
+ log.info("garment-forge ready: refbody=%d bytes, mesh backends=%s, rig=%s",
+ len(_refbody), MESH_WORKER_URLS, RIG_URL)
+ yield
+
+
+app = FastAPI(title="garment-forge", lifespan=lifespan)
+
+
+def _require_api_key(authorization: str) -> None:
+ try:
+ require_api_key(authorization, API_KEY)
+ except PermissionError as exc:
+ raise HTTPException(status_code=401, detail=str(exc)) from exc
+
+
+def _run_stages(job_id: str, prompt: str, slot: str, tier: str,
+ yaw_deg: float, progress) -> dict:
+ """The blocking pipeline; runs in a worker thread. `progress(stage)`
+ persists the stage transition so pollers watch the job move."""
+ progress("image")
+ image_bytes, image_model = pipeline.generate_reference_image(prompt, slot)
+
+ progress("mesh")
+ mesh_bytes, mesh_backend = pipeline.generate_mesh(
+ image_bytes, MESH_WORKER_URLS, API_KEY, tier=tier)
+
+ progress("compose")
+ composite = garment_glb.compose_scene(mesh_bytes, _refbody, slot, yaw_deg)
+
+ progress("rig")
+ rigged = pipeline.rig_composite(composite, RIG_URL, API_KEY, _bucket, job_id)
+
+ progress("extract")
+ garment_bytes = garment_glb.extract_garment(rigged)
+
+ progress("validate")
+ stats = garment_glb.skin_stats(garment_bytes)
+ occludes = garment_glb.derive_occludes(stats["bone_mass"], stats["total_mass"])
+ bones = garment_glb.weighted_bones(stats["bone_mass"], stats["total_mass"])
+
+ garment_id = f"{garment_glb.slugify(prompt)}-{job_id[:6]}"
+ version = pipeline.next_version(_bucket, slot, garment_id)
+ base = (f"https://storage.googleapis.com/{_bucket.name}/garments/"
+ f"{slot}/{garment_id}/v{version}")
+ manifest = garment_glb.build_manifest(
+ garment_id=garment_id,
+ name=prompt.strip().capitalize(),
+ slot=slot,
+ version=version,
+ model_uri=f"{base}/garment.glb",
+ glb_bytes=garment_bytes,
+ triangle_count=stats["triangle_count"],
+ bones=bones,
+ occludes=occludes,
+ prompt=prompt,
+ mesh_model=mesh_backend,
+ thumb_uri=f"{base}/thumb.webp",
+ )
+ verdict = garment_glb.validate_manifest(manifest, garment_bytes)
+ if not verdict["ok"]:
+ raise RuntimeError("manifest validation failed: "
+ + "; ".join(verdict["failures"]))
+
+ progress("publish")
+ thumb = pipeline.make_thumbnail(image_bytes)
+ urls = pipeline.publish(_bucket, slot, garment_id, version,
+ garment_bytes, manifest, thumb)
+ return {
+ **urls,
+ "garment_id": garment_id,
+ "version": version,
+ "coverage": round(verdict["coverage"], 4),
+ "occludes": occludes,
+ "bones": bones,
+ "triangle_count": stats["triangle_count"],
+ "mesh_backend": mesh_backend,
+ "image_model": image_model,
+ }
+
+
+async def _process_job(job_id: str, prompt: str, slot: str, tier: str,
+ yaw_deg: float) -> None:
+ async with _sem:
+ loop = asyncio.get_event_loop()
+ t0 = time.time()
+
+ def progress(stage: str) -> None:
+ # Persist synchronously from the worker thread: a poll may land
+ # on another instance the moment the stage flips.
+ job = _jobs.setdefault(job_id, {"job_id": job_id})
+ job.update(status="running", stage=stage,
+ updated_at=datetime.now(timezone.utc).isoformat())
+ _job_blob(job_id).upload_from_string(
+ json.dumps(job), content_type="application/json")
+ log.info("[%s] stage: %s", job_id, stage)
+
+ try:
+ result = await loop.run_in_executor(
+ None, _run_stages, job_id, prompt, slot, tier, yaw_deg, progress)
+ await _update_job(job_id, status="done", stage="done",
+ elapsed_ms=int((time.time() - t0) * 1000), **result)
+ log.info("[%s] done in %.1fs → %s (coverage %.3f)",
+ job_id, time.time() - t0, result["glb_url"], result["coverage"])
+ except Exception as exc: # noqa: BLE001: surfaced via job status
+ await _update_job(
+ job_id, status="failed",
+ error=safe_error(exc, context=f"[{job_id}] garment pipeline"),
+ elapsed_ms=int((time.time() - t0) * 1000),
+ )
+ log.error("[%s] failed: %s", job_id, exc)
+
+
+class GenerateRequest(BaseModel):
+ prompt: str = Field(..., min_length=3, max_length=500)
+ slot: str
+ tier: str = "high"
+ yaw_deg: float | None = None
+ job_id: str | None = None
+
+
[email protected]("/generate", status_code=202)
+async def generate(
+ body: GenerateRequest,
+ background_tasks: BackgroundTasks,
+ authorization: str = Header(...),
+) -> dict:
+ _require_api_key(authorization)
+ if body.slot not in GARMENT_SLOTS:
+ raise HTTPException(status_code=422,
+ detail=f"slot must be one of {list(GARMENT_SLOTS)}")
+ job_id = body.job_id or str(uuid.uuid4())
+ await _update_job(job_id, status="queued", stage="queued",
+ prompt=body.prompt, slot=body.slot)
+ background_tasks.add_task(
+ _process_job, job_id, body.prompt, body.slot, body.tier,
+ body.yaw_deg if body.yaw_deg is not None else GARMENT_YAW_DEG,
+ )
+ return {"job_id": job_id, "status": "queued"}
+
+
[email protected]("/jobs/{job_id}")
+async def get_job(job_id: str, authorization: str = Header(...)) -> dict:
+ _require_api_key(authorization)
+ job = _jobs.get(job_id)
+ if job is not None:
+ return job
+ loop = asyncio.get_event_loop()
+ try:
+ data = await loop.run_in_executor(None, _job_blob(job_id).download_as_bytes)
+ except NotFound:
+ raise HTTPException(status_code=404, detail="job not found")
+ except Exception as exc:
+ raise HTTPException(status_code=502,
+ detail=safe_error(exc, context="job lookup")) from exc
+ job = json.loads(data)
+ _jobs[job_id] = job
+ return job
+
+
+async def health() -> dict:
+ return {
+ "ok": True,
+ "pipeline": "garment-forge@1",
+ "refbody_loaded": _refbody is not None,
+ "mesh_backends": MESH_WORKER_URLS,
+ "rig_url": RIG_URL,
+ "active_jobs": sum(1 for j in _jobs.values()
+ if j.get("status") in ("queued", "running")),
+ }
diff --git a/workers/garment-forge/pipeline.py b/workers/garment-forge/pipeline.py
new file mode 100644
index 000000000..53bc703ee
--- /dev/null
+++ b/workers/garment-forge/pipeline.py
@@ -0,0 +1,297 @@
+"""
+Effectful stages of the garment forge: every function here talks to a real
+service: Vertex AI image generation, the deployed mesh-generation workers
+(model-hunyuan3d-21-rtx → model-hunyuan3d-21 → model-trellis), the deployed
+auto-rigger (model-rig), and Cloud Storage. The pure geometry/manifest logic
+lives in garment_glb.py so it stays unit-testable without any of this.
+
+Auth model: one shared bearer secret (the platform's avatar-reconstruction
+key) authenticates this worker's own API and its calls to the other workers.
+Vertex AI and GCS use the service account Cloud Run runs as (ADC).
+"""
+
+from __future__ import annotations
+
+import base64
+import io
+import json
+import logging
+import os
+import time
+from urllib.parse import urlparse
+
+import google.auth
+import google.auth.transport.requests
+import httpx
+from google.api_core.exceptions import NotFound, PreconditionFailed
+from google.cloud import storage
+from PIL import Image
+
+log = logging.getLogger("garment-forge.pipeline")
+
+VERTEX_MODEL = os.environ.get("VERTEX_IMAGEN_MODEL", "gemini-2.5-flash-image")
+VERTEX_LOCATION = os.environ.get("VERTEX_IMAGEN_LOCATION", "global")
+VERTEX_IMAGE_SIZE = os.environ.get("VERTEX_IMAGE_SIZE", "2K").upper()
+
+MESH_POLL_S = float(os.environ.get("MESH_POLL_S", "5"))
+MESH_TIMEOUT_S = float(os.environ.get("MESH_TIMEOUT_S", "1200"))
+RIG_TIMEOUT_S = float(os.environ.get("RIG_TIMEOUT_S", "600"))
+
+_credentials = None
+
+
+def _access_token() -> str:
+ global _credentials
+ if _credentials is None:
+ _credentials, _ = google.auth.default(
+ scopes=["https://www.googleapis.com/auth/cloud-platform"])
+ if not _credentials.valid:
+ _credentials.refresh(google.auth.transport.requests.Request())
+ return _credentials.token
+
+
+def _vertex_host(location: str) -> str:
+ return ("https://aiplatform.googleapis.com" if location == "global"
+ else f"https://{location}-aiplatform.googleapis.com")
+
+
+# How each slot should be photographed so the generated mesh matches the
+# reference body's A-pose and the slot box's fit axis. The ghost-mannequin
+# framing gives the mesh generator a worn, volume-filled shape instead of a
+# flat-lay it cannot infer depth from.
+_SLOT_POSE_HINTS = {
+ "top": "shown worn in three-dimensional filled-out shape as if on an invisible "
+ "person standing upright in an A-pose, arms angled 45 degrees downward",
+ "outerwear": "shown worn in three-dimensional filled-out shape as if on an "
+ "invisible person standing upright in an A-pose, arms angled 45 "
+ "degrees downward",
+ "bottom": "shown worn in three-dimensional filled-out shape as if on invisible "
+ "legs standing upright, legs straight and slightly apart",
+ "footwear": "the pair side by side, both facing forward, soles on the ground",
+ "hair": "shown in three-dimensional shape as if on an invisible head, facing forward",
+ "headwear": "shown in three-dimensional shape as if worn on an invisible head, "
+ "facing forward",
+ "glasses": "shown front-on in three-dimensional shape as if worn on an invisible face",
+ "accessory": "shown in three-dimensional worn shape, facing forward",
+}
+
+
+def generate_reference_image(prompt: str, slot: str) -> tuple[bytes, str]:
+ """Text prompt → ghost-mannequin product photo via the platform's live
+ Vertex AI image lane. Returns (png/jpeg bytes, model label)."""
+ pose = _SLOT_POSE_HINTS.get(slot, _SLOT_POSE_HINTS["accessory"])
+ full_prompt = (
+ f"Professional ghost mannequin product photograph of {prompt}, {pose}. "
+ "Front view, centered, the entire item visible with a small margin, "
+ "plain uniform light gray studio background, soft even lighting, "
+ "no person, no mannequin, no props, no text, no watermark."
+ )
+ project = os.environ["GOOGLE_CLOUD_PROJECT"]
+ endpoint = (
+ f"{_vertex_host(VERTEX_LOCATION)}/v1/projects/{project}/locations/"
+ f"{VERTEX_LOCATION}/publishers/google/models/{VERTEX_MODEL}:generateContent"
+ )
+ body = {
+ "contents": [{"role": "user", "parts": [{"text": full_prompt}]}],
+ "generationConfig": {
+ "responseModalities": ["IMAGE"],
+ "imageConfig": {"aspectRatio": "1:1", "imageSize": VERTEX_IMAGE_SIZE},
+ },
+ }
+ headers = {"authorization": f"Bearer {_access_token()}",
+ "content-type": "application/json"}
+ with httpx.Client(timeout=120) as client:
+ res = client.post(endpoint, json=body, headers=headers)
+ if res.status_code == 400:
+ # Older image models reject the imageSize knob; retry without it.
+ del body["generationConfig"]["imageConfig"]["imageSize"]
+ res = client.post(endpoint, json=body, headers=headers)
+ res.raise_for_status()
+ data = res.json()
+
+ parts = (data.get("candidates") or [{}])[0].get("content", {}).get("parts", [])
+ img_part = next((p for p in parts if p.get("inlineData", {}).get("data")), None)
+ if not img_part:
+ reason = (data.get("candidates") or [{}])[0].get("finishReason")
+ raise RuntimeError(f"Vertex returned no image data"
+ f"{f' (finishReason: {reason})' if reason else ''}")
+ return base64.b64decode(img_part["inlineData"]["data"]), f"vertex-ai/{VERTEX_MODEL}"
+
+
+def _mesh_backend_label(url: str) -> str:
+ host = urlparse(url).hostname or url
+ if "trellis" in host:
+ return "trellis"
+ if "hunyuan3d" in host:
+ return "hunyuan3d-2.1"
+ return host
+
+
+def _poll_task(client: httpx.Client, base_url: str, task_id: str, api_key: str,
+ timeout_s: float, result_field: str) -> str:
+ deadline = time.time() + timeout_s
+ headers = {"authorization": f"Bearer {api_key}"}
+ while time.time() < deadline:
+ res = client.get(f"{base_url}/tasks/{task_id}", headers=headers)
+ res.raise_for_status()
+ task = res.json()
+ status = task.get("status")
+ if status == "done":
+ url = task.get(result_field)
+ if not url:
+ raise RuntimeError(f"task {task_id} done but no {result_field}")
+ return url
+ if status == "failed":
+ raise RuntimeError(f"task {task_id} failed: {task.get('error')}")
+ time.sleep(MESH_POLL_S)
+ raise TimeoutError(f"task {task_id} on {base_url} exceeded {timeout_s:.0f}s")
+
+
+def download_gcs_url(url: str) -> bytes:
+ """Download an https://storage.googleapis.com/<bucket>/<name> object via
+ the storage client, so worker-to-worker transfers never depend on public
+ object ACLs."""
+ parsed = urlparse(url)
+ if parsed.hostname != "storage.googleapis.com":
+ raise ValueError(f"not a GCS URL: {url}")
+ bucket_name, _, blob_name = parsed.path.lstrip("/").partition("/")
+ return storage.Client().bucket(bucket_name).blob(blob_name).download_as_bytes()
+
+
+def generate_mesh(image_bytes: bytes, mesh_urls: list[str], api_key: str,
+ tier: str = "high") -> tuple[bytes, str]:
+ """Image → textured GLB through the deployed mesh-generation failover
+ chain. Every backend speaks the same /infer + /tasks contract."""
+ data_uri = "data:image/png;base64," + base64.b64encode(image_bytes).decode()
+ errors: list[str] = []
+ with httpx.Client(timeout=60) as client:
+ for url in mesh_urls:
+ label = _mesh_backend_label(url)
+ try:
+ res = client.post(
+ f"{url}/infer",
+ json={"images": [data_uri], "tier": tier},
+ headers={"authorization": f"Bearer {api_key}"},
+ )
+ res.raise_for_status()
+ task_id = res.json()["task_id"]
+ log.info("mesh task %s queued on %s", task_id, label)
+ result_url = _poll_task(client, url, task_id, api_key,
+ MESH_TIMEOUT_S, "result_gcs_url")
+ return download_gcs_url(result_url), label
+ except Exception as exc: # noqa: BLE001: try the next rung
+ log.warning("mesh backend %s failed: %s", label, exc)
+ errors.append(f"{label}: {exc}")
+ raise RuntimeError("every mesh backend failed: " + " | ".join(errors))
+
+
+def rig_composite(composite_bytes: bytes, rig_url: str, api_key: str,
+ bucket: storage.Bucket, job_id: str) -> bytes:
+ """Composite GLB → rigged GLB via the deployed model-rig worker. The
+ composite is staged to GCS because /rig takes a URL, not bytes."""
+ blob = bucket.blob(f"garments/tmp/{job_id}-composite.glb")
+ blob.upload_from_string(composite_bytes, content_type="model/gltf-binary")
+ composite_url = f"https://storage.googleapis.com/{bucket.name}/{blob.name}"
+
+ with httpx.Client(timeout=60) as client:
+ res = client.post(
+ f"{rig_url}/rig",
+ json={"mesh_gcs_url": composite_url, "blendshapes": False},
+ headers={"authorization": f"Bearer {api_key}"},
+ )
+ res.raise_for_status()
+ task_id = res.json()["task_id"]
+ log.info("rig task %s queued", task_id)
+ result_url = _poll_task(client, rig_url, task_id, api_key,
+ RIG_TIMEOUT_S, "rigged_gcs_url")
+ rigged = download_gcs_url(result_url)
+ blob.delete()
+ return rigged
+
+
+def make_thumbnail(image_bytes: bytes, size: int = 512) -> bytes:
+ """Reference image → square WEBP thumbnail for the catalog card."""
+ img = Image.open(io.BytesIO(image_bytes)).convert("RGB")
+ img.thumbnail((size, size), Image.LANCZOS)
+ out = io.BytesIO()
+ img.save(out, format="WEBP", quality=88)
+ return out.getvalue()
+
+
+def _try_make_public(blob: storage.Blob) -> None:
+ """Garment assets must be CORS/anonymously readable by the viewer. On a
+ fine-grained-ACL bucket this sets the object ACL; if the bucket enforces
+ uniform access this is a no-op handled at the bucket IAM level instead."""
+ try:
+ blob.make_public()
+ except Exception as exc: # noqa: BLE001: bucket-level policy takes over
+ log.warning("make_public failed for %s (bucket-level policy governs): %s",
+ blob.name, exc)
+
+
+def publish(bucket: storage.Bucket, slot: str, garment_id: str, version: int,
+ glb_bytes: bytes, manifest: dict, thumb_bytes: bytes) -> dict:
+ """Write the immutable v<n> directory and append to the catalog."""
+ prefix = f"garments/{slot}/{garment_id}/v{version}"
+ uploads = [
+ (f"{prefix}/garment.glb", glb_bytes, "model/gltf-binary"),
+ (f"{prefix}/manifest.json", json.dumps(manifest, indent=2).encode(),
+ "application/json"),
+ (f"{prefix}/thumb.webp", thumb_bytes, "image/webp"),
+ ]
+ for name, data, ctype in uploads:
+ blob = bucket.blob(name)
+ blob.cache_control = "public, max-age=31536000, immutable"
+ blob.upload_from_string(data, content_type=ctype)
+ _try_make_public(blob)
+
+ append_to_catalog(bucket, manifest)
+ base = f"https://storage.googleapis.com/{bucket.name}/{prefix}"
+ return {
+ "glb_url": f"{base}/garment.glb",
+ "manifest_url": f"{base}/manifest.json",
+ "thumb_url": f"{base}/thumb.webp",
+ }
+
+
+def append_to_catalog(bucket: storage.Bucket, manifest: dict,
+ attempts: int = 6) -> None:
+ """Append one manifest to garments/catalog.json with an optimistic
+ generation-match loop, so concurrent publishes never lose entries."""
+ blob_name = "garments/catalog.json"
+ for attempt in range(attempts):
+ blob = bucket.blob(blob_name)
+ try:
+ blob.reload()
+ generation = blob.generation
+ catalog = json.loads(blob.download_as_bytes())
+ if not isinstance(catalog, list):
+ raise RuntimeError("garments/catalog.json is not a JSON array")
+ except NotFound:
+ generation = 0
+ catalog = []
+ catalog.append(manifest)
+ blob.cache_control = "public, max-age=60"
+ try:
+ blob.upload_from_string(
+ json.dumps(catalog, indent=2), content_type="application/json",
+ if_generation_match=generation,
+ )
+ _try_make_public(blob)
+ return
+ except PreconditionFailed:
+ log.info("catalog append raced (attempt %d), retrying", attempt + 1)
+ time.sleep(0.5 * (attempt + 1))
+ raise RuntimeError(f"catalog append lost {attempts} generation races")
+
+
+def next_version(bucket: storage.Bucket, slot: str, garment_id: str) -> int:
+ """1 + highest published version of slot/id in the catalog (spec: publish
+ a change as v<n+1>, never overwrite v<n>)."""
+ try:
+ catalog = json.loads(bucket.blob("garments/catalog.json").download_as_bytes())
+ except NotFound:
+ return 1
+ versions = [int(m.get("version", 0)) for m in catalog
+ if m.get("slot") == slot and m.get("id") == garment_id]
+ return max(versions, default=0) + 1
diff --git a/workers/garment-forge/requirements.txt b/workers/garment-forge/requirements.txt
new file mode 100644
index 000000000..858cb6e2c
--- /dev/null
+++ b/workers/garment-forge/requirements.txt
@@ -0,0 +1,26 @@
+# garment-forge is a CPU orchestrator: no torch, no CUDA. It calls the
+# deployed GPU workers (mesh generation, rigging) over HTTP and does pure
+# glTF/geometry work locally. Everything pinned or bounded, matching the
+# convention set after the 2026-07-16 unpinned-transformers outage.
+
+# ── Geometry / glTF ──────────────────────────────────────────────────────────
+numpy==1.26.4
+trimesh==4.5.3
+pygltflib==1.16.2
+# trimesh scene-graph operations (Scene.add_geometry / export) use networkx.
+networkx==3.3
+# GLB export path in trimesh imports scipy for spatial ops on some meshes.
+scipy==1.13.1
+
+# ── Imaging (reference-image decode, WEBP thumbnails) ────────────────────────
+Pillow>=10.3.0
+
+# ── Server ────────────────────────────────────────────────────────────────────
+fastapi==0.115.0
+uvicorn[standard]==0.32.0
+pydantic>=2.0.0
+httpx>=0.27.0
+
+# ── GCP (storage for assets/jobs, ADC token for the Vertex image lane) ───────
+google-cloud-storage==2.18.0
+google-auth>=2.30.0
diff --git a/workers/garment-forge/test_garment_glb.py b/workers/garment-forge/test_garment_glb.py
new file mode 100644
index 000000000..489fe2cb6
--- /dev/null
+++ b/workers/garment-forge/test_garment_glb.py
@@ -0,0 +1,298 @@
+"""
+Unit tests for the pure glTF pipeline in garment_glb.py: no GPU, no network,
+no GCP. Runs as a Docker build gate (see Dockerfile) and locally:
+
+ python3 workers/garment-forge/test_garment_glb.py
+
+Covers, in pipeline order:
+ - bone-name canonicalization (the Mixamo-scope port),
+ - slot placement math (scale + translation into the slot box),
+ - scene composition (garment + reference body, names preserved, textures
+ survive the trimesh round-trip),
+ - garment extraction from a rigged composite (body stripped, buffer
+ repacked, joints canonicalized, garment texture kept),
+ - skin statistics / coverage / occludes derivation,
+ - all 6 manifest validation rules, each failing for its own reason.
+"""
+
+from __future__ import annotations
+
+import io
+import struct
+import sys
+
+import numpy as np
+import pygltflib
+import trimesh
+from PIL import Image
+
+from canonical_bones import canonicalize_bone_name
+from garment_glb import (
+ GARMENT_PREFIX,
+ MIN_BIND_COVERAGE,
+ REFBODY_PREFIX,
+ SLOT_BOXES,
+ SPEC_URI,
+ build_manifest,
+ compose_scene,
+ derive_occludes,
+ extract_garment,
+ garment_placement,
+ sha256_hex,
+ skin_stats,
+ slugify,
+ validate_manifest,
+ weighted_bones,
+)
+
+PASS = 0
+
+
+def check(name: str, condition: bool, detail: str = "") -> None:
+ global PASS
+ if not condition:
+ print(f"FAIL {name} {detail}")
+ sys.exit(1)
+ PASS += 1
+ print(f"ok {name}")
+
+
+# ── fixtures ────────────────────────────────────────────────────────────────
+
+def textured_box_glb() -> bytes:
+ """A box with a real baseColorTexture, exported through trimesh."""
+ mesh = trimesh.creation.box(extents=(1.0, 2.0, 0.5))
+ img = Image.new("RGB", (8, 8), (200, 40, 40))
+ uv = np.zeros((len(mesh.vertices), 2), dtype=np.float64)
+ mesh.visual = trimesh.visual.TextureVisuals(
+ uv=uv, material=trimesh.visual.material.PBRMaterial(baseColorTexture=img))
+ scene = trimesh.Scene()
+ scene.add_geometry(mesh, node_name="src", geom_name="src")
+ return scene.export(file_type="glb")
+
+
+def plain_body_glb() -> bytes:
+ scene = trimesh.Scene()
+ scene.add_geometry(trimesh.creation.capsule(radius=0.2, height=1.2),
+ node_name="body", geom_name="body")
+ return scene.export(file_type="glb")
+
+
+def _pack_floats(values) -> bytes:
+ return struct.pack(f"<{len(values)}f", *values)
+
+
+def build_rigged_composite(garment_joint_weights, body_texture: bool = True) -> bytes:
+ """A minimal rigged composite the way model-rig would emit it: a mixamorig
+ joint chain, one skin, a `garment_0` mesh and a `refbody_0` mesh, both
+ skinned, the garment with a real embedded texture.
+
+ garment_joint_weights: list of (joint_index, weight) rows, one per garment
+ vertex (3 vertices required), letting tests steer coverage/occludes.
+ """
+ glb = pygltflib.GLTF2()
+ blob = bytearray()
+
+ def append_view(data: bytes, target=None) -> int:
+ while len(blob) % 4:
+ blob.append(0)
+ view = pygltflib.BufferView(buffer=0, byteOffset=len(blob), byteLength=len(data))
+ if target is not None:
+ view.target = target
+ blob.extend(data)
+ glb.bufferViews.append(view)
+ return len(glb.bufferViews) - 1
+
+ def add_accessor(view, comp, count, typ, mn=None, mx=None) -> int:
+ acc = pygltflib.Accessor(bufferView=view, componentType=comp, count=count, type=typ)
+ if mn is not None:
+ acc.min, acc.max = mn, mx
+ glb.accessors.append(acc)
+ return len(glb.accessors) - 1
+
+ # Joints: Hips(0) → Spine(1) → LeftArm(2), plus a helper the canonical set
+ # lacks (3) to exercise unresolved-mass accounting.
+ joint_names = ["mixamorig:Hips", "mixamorig:Spine", "mixamorig:LeftArm",
+ "mixamorig:WeirdHelper"]
+ for i, name in enumerate(joint_names):
+ glb.nodes.append(pygltflib.Node(name=name, translation=[0, 0.3 * i, 0]))
+ glb.nodes[0].children = [1]
+ glb.nodes[1].children = [2, 3]
+
+ ibm = np.tile(np.eye(4, dtype=np.float32).T.reshape(-1), (len(joint_names), 1))
+ ibm_acc = add_accessor(append_view(ibm.tobytes()), 5126, len(joint_names), "MAT4")
+ glb.skins.append(pygltflib.Skin(joints=[0, 1, 2, 3], inverseBindMatrices=ibm_acc,
+ skeleton=0))
+
+ def add_skinned_mesh(name: str, rows, material=None) -> int:
+ pos = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0]], dtype=np.float32)
+ pos_acc = add_accessor(append_view(pos.tobytes(), 34962), 5126, 3, "VEC3",
+ mn=pos.min(axis=0).tolist(), mx=pos.max(axis=0).tolist())
+ joints = np.zeros((3, 4), dtype=np.uint8)
+ weights = np.zeros((3, 4), dtype=np.float32)
+ for vi, (ji, w) in enumerate(rows):
+ joints[vi, 0] = ji
+ weights[vi, 0] = w
+ rest = 1.0 - w
+ if rest > 0:
+ joints[vi, 1] = 0
+ weights[vi, 1] = rest
+ j_acc = add_accessor(append_view(joints.tobytes(), 34962), 5121, 3, "VEC4")
+ w_acc = add_accessor(append_view(weights.tobytes(), 34962), 5126, 3, "VEC4")
+ idx = np.array([0, 1, 2], dtype=np.uint16)
+ i_acc = add_accessor(append_view(idx.tobytes(), 34963), 5123, 3, "SCALAR")
+ prim = pygltflib.Primitive(
+ attributes=pygltflib.Attributes(POSITION=pos_acc, JOINTS_0=j_acc,
+ WEIGHTS_0=w_acc),
+ indices=i_acc, material=material)
+ glb.meshes.append(pygltflib.Mesh(name=name, primitives=[prim]))
+ node = pygltflib.Node(name=name, mesh=len(glb.meshes) - 1, skin=0)
+ glb.nodes.append(node)
+ return len(glb.nodes) - 1
+
+ # Garment texture: a real PNG embedded in the buffer.
+ png = io.BytesIO()
+ Image.new("RGB", (4, 4), (10, 200, 10)).save(png, format="PNG")
+ img_view = append_view(png.getvalue())
+ glb.images.append(pygltflib.Image(bufferView=img_view, mimeType="image/png"))
+ glb.samplers.append(pygltflib.Sampler())
+ glb.textures.append(pygltflib.Texture(source=0, sampler=0))
+ glb.materials.append(pygltflib.Material(
+ name="garment-mat",
+ pbrMetallicRoughness=pygltflib.PbrMetallicRoughness(
+ baseColorTexture=pygltflib.TextureInfo(index=0))))
+
+ # Body texture: a second PNG that extraction must drop.
+ body_mat = None
+ if body_texture:
+ png2 = io.BytesIO()
+ Image.new("RGB", (4, 4), (10, 10, 200)).save(png2, format="PNG")
+ img_view2 = append_view(png2.getvalue())
+ glb.images.append(pygltflib.Image(bufferView=img_view2, mimeType="image/png"))
+ glb.textures.append(pygltflib.Texture(source=1, sampler=0))
+ glb.materials.append(pygltflib.Material(
+ name="body-mat",
+ pbrMetallicRoughness=pygltflib.PbrMetallicRoughness(
+ baseColorTexture=pygltflib.TextureInfo(index=1))))
+ body_mat = 1
+
+ garment_node = add_skinned_mesh(f"{GARMENT_PREFIX}_0", garment_joint_weights, 0)
+ body_node = add_skinned_mesh(f"{REFBODY_PREFIX}_0",
+ [(0, 1.0), (0, 1.0), (1, 1.0)], body_mat)
+
+ glb.scenes.append(pygltflib.Scene(nodes=[0, garment_node, body_node]))
+ glb.scene = 0
+ glb.buffers.append(pygltflib.Buffer(byteLength=len(blob)))
+ glb.set_binary_blob(bytes(blob))
+ out = glb.save_to_bytes()
+ return b"".join(out) if isinstance(out, (list, tuple)) else out
+
+
+# ── canonicalization ────────────────────────────────────────────────────────
+
+check("mixamorig namespace strips", canonicalize_bone_name("mixamorig:LeftArm") == "LeftArm")
+check("numbered namespace strips", canonicalize_bone_name("mixamorig1:Spine2") == "Spine2")
+check("glued mixamo prefix strips", canonicalize_bone_name("mixamorigRightFoot") == "RightFoot")
+check("canonical passes through", canonicalize_bone_name("LeftHandIndex2") == "LeftHandIndex2")
+check("separators normalize", canonicalize_bone_name("left_fore_arm") == "LeftForeArm")
+check("non-humanoid rejects", canonicalize_bone_name("tentacle_tip") is None)
+
+# ── placement ───────────────────────────────────────────────────────────────
+
+box_glb = textured_box_glb()
+loaded = trimesh.load(io.BytesIO(box_glb), file_type="glb", process=False)
+meshes = [g.copy() for g in loaded.geometry.values()]
+placement = garment_placement(meshes, "top")
+placed = meshes[0].copy()
+placed.apply_transform(placement)
+top = SLOT_BOXES["top"]
+height = placed.bounds[1][1] - placed.bounds[0][1]
+center_y = (placed.bounds[1][1] + placed.bounds[0][1]) / 2
+check("placement fits slot height", abs(height - top["size"][1]) < 1e-6, f"height={height}")
+check("placement centers on slot", abs(center_y - top["center"][1]) < 1e-6, f"cy={center_y}")
+
+# ── composition ─────────────────────────────────────────────────────────────
+
+composite = compose_scene(box_glb, plain_body_glb(), "top")
+comp_glb = pygltflib.GLTF2.load_from_bytes(composite)
+names = sorted(m.name or "" for m in comp_glb.meshes)
+check("composite keeps both parts",
+ any(n.startswith(GARMENT_PREFIX) for n in names)
+ and any(n.startswith(REFBODY_PREFIX) for n in names), str(names))
+check("composite garment textured", len(comp_glb.images) >= 1)
+
+# ── extraction ──────────────────────────────────────────────────────────────
+
+# Garment weighted: Spine 100%, Spine 80%/Hips 20%, LeftArm 100%.
+rigged = build_rigged_composite([(1, 1.0), (1, 0.8), (2, 1.0)])
+garment_only = extract_garment(rigged)
+out = pygltflib.GLTF2.load_from_bytes(garment_only)
+
+check("extraction drops body mesh",
+ [m.name for m in out.meshes] == [f"{GARMENT_PREFIX}_0"],
+ str([m.name for m in out.meshes]))
+check("extraction keeps the skin", len(out.skins) == 1)
+check("extraction drops body texture", len(out.images) == 1 and len(out.materials) == 1,
+ f"images={len(out.images)} materials={len(out.materials)}")
+check("extraction shrinks the buffer", len(garment_only) < len(rigged))
+joint_names = [out.nodes[j].name for j in out.skins[0].joints]
+check("joints canonicalized", joint_names[:3] == ["Hips", "Spine", "LeftArm"],
+ str(joint_names))
+check("unmappable joint keeps its name", joint_names[3] == "mixamorig:WeirdHelper")
+kept_png = None
+for img in out.images:
+ view = out.bufferViews[img.bufferView]
+ blob = out.binary_blob()
+ kept_png = bytes(blob[view.byteOffset:view.byteOffset + view.byteLength])
+check("kept texture is the garment's",
+ kept_png is not None and Image.open(io.BytesIO(kept_png)).getpixel((0, 0))[1] > 150)
+
+# ── stats / coverage / occludes ─────────────────────────────────────────────
+
+stats = skin_stats(garment_only)
+check("full coverage when all joints resolve", abs(stats["coverage"] - 1.0) < 1e-9,
+ f"coverage={stats['coverage']}")
+occ = derive_occludes(stats["bone_mass"], stats["total_mass"])
+check("occludes torso from Spine mass", "torso" in occ, str(occ))
+check("occludes upperArms from LeftArm mass", "upperArms" in occ, str(occ))
+check("occludes hips from the 20% share", "hips" in occ, str(occ))
+check("no phantom regions", all(r in ("torso", "upperArms", "hips") for r in occ), str(occ))
+bones = weighted_bones(stats["bone_mass"], stats["total_mass"])
+check("rig.bones in canonical order", bones == ["Hips", "Spine", "LeftArm"], str(bones))
+
+# Low coverage: 70% of weight on the helper joint that cannot canonicalize.
+low = extract_garment(build_rigged_composite([(3, 0.7), (3, 0.7), (3, 0.7)]))
+low_stats = skin_stats(low)
+check("unresolved joints lower coverage", low_stats["coverage"] < MIN_BIND_COVERAGE,
+ f"coverage={low_stats['coverage']}")
+
+# ── manifest validation ─────────────────────────────────────────────────────
+
+manifest = build_manifest(
+ garment_id="test-shirt-abc123", name="Test shirt", slot="top", version=1,
+ model_uri="https://storage.googleapis.com/bucket/garments/top/test/v1/garment.glb",
+ glb_bytes=garment_only, triangle_count=stats["triangle_count"],
+ bones=bones, occludes=occ, prompt="test shirt", mesh_model="hunyuan3d-2.1",
+ thumb_uri="https://storage.googleapis.com/bucket/garments/top/test/v1/thumb.webp")
+verdict = validate_manifest(manifest, garment_only)
+check("valid manifest passes all 6 rules", verdict["ok"], str(verdict["failures"]))
+check("manifest pins the spec URI", manifest["spec"] == SPEC_URI)
+
+bad = dict(manifest, spec="https://example.com/other-spec")
+check("rule 1 rejects unknown spec", not validate_manifest(bad, garment_only)["ok"])
+bad = dict(manifest, slot="cape")
+check("rule 2 rejects unknown slot", not validate_manifest(bad, garment_only)["ok"])
+bad = dict(manifest, occludes=["torso", "tail"])
+check("rule 3 rejects unknown region", not validate_manifest(bad, garment_only)["ok"])
+bad = dict(manifest, model=dict(manifest["model"], sha256="0" * 64))
+check("rule 4 rejects a hash mismatch", not validate_manifest(bad, garment_only)["ok"])
+low_manifest = dict(manifest, model=dict(manifest["model"], sha256=sha256_hex(low)))
+check("rule 5 rejects low coverage", not validate_manifest(low_manifest, low)["ok"])
+bad = dict(manifest, license="CC-BY-NC-4.0")
+check("rule 6 rejects non-commercial license", not validate_manifest(bad, garment_only)["ok"])
+
+# ── slug ────────────────────────────────────────────────────────────────────
+
+check("slugify", slugify("A White Oxford Shirt, long sleeves!") == "a-white-oxford-shirt-long")
+
+print(f"\nall {PASS} checks passed")
diff --git a/workers/garment-forge/worker_security.py b/workers/garment-forge/worker_security.py
new file mode 100644
index 000000000..1e569c4e2
--- /dev/null
+++ b/workers/garment-forge/worker_security.py
@@ -0,0 +1,222 @@
+"""
+Shared security helpers for the three.ws GPU/CPU workers.
+
+This module is intentionally dependency-light (stdlib only) so it can be
+COPYed verbatim into every worker's Docker build context. The same canonical
+file lives in each worker directory; keep them byte-identical when editing.
+
+It provides three primitives that every worker needs:
+
+ 1. ``require_api_key`` — constant-time bearer-token check (timing-safe).
+ 2. ``fetch_remote_bytes`` — SSRF-hardened HTTP(S) fetch of caller-supplied
+ URLs: https-only, DNS resolution with private/loopback/link-local/metadata
+ IP rejection, per-hop redirect re-validation, and a bounded response size.
+ 3. ``safe_error`` — turns an exception into an opaque, correlation-id-tagged
+ message safe to persist/return to callers, after logging the full
+ traceback server-side only.
+"""
+
+from __future__ import annotations
+
+import hmac
+import ipaddress
+import logging
+import socket
+import uuid
+from typing import Iterable, Optional
+from urllib.parse import urlsplit
+
+import httpx
+
+log = logging.getLogger("worker_security")
+
+# ── auth ────────────────────────────────────────────────────────────────────────
+
+
+def require_api_key(authorization: Optional[str], api_key: str) -> None:
+ """Validate a ``Bearer <token>`` header in constant time.
+
+ Raises ``PermissionError`` on any failure so callers can translate it into
+ the framework's 401 (FastAPI workers map this to HTTPException(401)).
+ """
+ if not authorization or not authorization.startswith("Bearer "):
+ raise PermissionError("missing bearer token")
+ token = authorization[len("Bearer "):].strip()
+ # hmac.compare_digest is timing-safe and accepts str (ASCII) operands.
+ if not hmac.compare_digest(token, api_key):
+ raise PermissionError("invalid api key")
+
+
+# ── SSRF-hardened fetch ─────────────────────────────────────────────────────────
+
+# Default cap on a fetched response. Avatar selfies / driving audio / raw meshes
+# are comfortably under this; anything larger is almost certainly abuse.
+DEFAULT_MAX_BYTES = 64 * 1024 * 1024 # 64 MiB
+_MAX_REDIRECTS = 4
+
+
+class UnsafeUrlError(ValueError):
+ """Raised when a URL targets a disallowed scheme or a private/internal IP."""
+
+
+def _is_blocked_ip(ip: ipaddress._BaseAddress) -> bool:
+ """Reject any address that could reach internal infrastructure.
+
+ Covers loopback, RFC1918 private ranges, link-local (incl. the cloud
+ metadata server at 169.254.169.254), unique-local IPv6 (fc00::/7),
+ multicast, reserved, and unspecified addresses. IPv4-mapped IPv6 addresses
+ are unwrapped first so a mapped private v4 can't slip through.
+ """
+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:
+ ip = ip.ipv4_mapped
+ return (
+ ip.is_private
+ or ip.is_loopback
+ or ip.is_link_local
+ or ip.is_multicast
+ or ip.is_reserved
+ or ip.is_unspecified
+ )
+
+
+def _resolve_safe_host(host: str) -> None:
+ """DNS-resolve ``host`` and raise UnsafeUrlError if ANY address is internal.
+
+ Resolving and checking every returned address closes the gap where a name
+ resolves to both a public and a private address.
+ """
+ if not host:
+ raise UnsafeUrlError("missing host")
+ try:
+ infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)
+ except socket.gaierror as exc:
+ raise UnsafeUrlError(f"could not resolve host: {host}") from exc
+
+ addrs = {info[4][0] for info in infos}
+ if not addrs:
+ raise UnsafeUrlError(f"no addresses for host: {host}")
+ for addr in addrs:
+ ip = ipaddress.ip_address(addr)
+ if _is_blocked_ip(ip):
+ raise UnsafeUrlError(f"host resolves to a disallowed address: {host}")
+
+
+def assert_safe_url(url: str, *, allow_http: bool = False) -> str:
+ """Validate scheme + resolved IPs for a single URL. Returns it unchanged.
+
+ https is required by default; ``allow_http`` exists only for callers that
+ legitimately need cleartext (not used by the workers).
+ """
+ parts = urlsplit(url)
+ scheme = parts.scheme.lower()
+ allowed = ("https", "http") if allow_http else ("https",)
+ if scheme not in allowed:
+ raise UnsafeUrlError(f"scheme not allowed: {scheme or '(none)'}")
+ if not parts.hostname:
+ raise UnsafeUrlError("missing host")
+ _resolve_safe_host(parts.hostname)
+ return url
+
+
+def fetch_remote_bytes(
+ url: str,
+ *,
+ timeout: float = 30.0,
+ max_bytes: int = DEFAULT_MAX_BYTES,
+ allow_http: bool = False,
+ headers: Optional[dict] = None,
+) -> bytes:
+ """Fetch ``url`` safely and return its body bytes.
+
+ Hardening applied:
+ * https-only (unless ``allow_http``).
+ * every URL — including each redirect target — is DNS-resolved and
+ rejected if it maps to a private/loopback/link-local/metadata address.
+ * redirects are followed manually (max ``_MAX_REDIRECTS``) so each hop is
+ re-validated; httpx's own redirect following is disabled.
+ * the response body is streamed and aborted once it exceeds ``max_bytes``.
+
+ Raises ``UnsafeUrlError`` for disallowed targets and ``httpx.HTTPError`` /
+ ``ValueError`` for transport or size failures.
+ """
+ current = assert_safe_url(url, allow_http=allow_http)
+ with httpx.Client(follow_redirects=False, timeout=timeout) as client:
+ for _ in range(_MAX_REDIRECTS + 1):
+ with client.stream("GET", current, headers=headers) as resp:
+ if resp.is_redirect:
+ location = resp.headers.get("location")
+ if not location:
+ raise UnsafeUrlError("redirect without Location header")
+ current = assert_safe_url(
+ str(resp.url.join(location)), allow_http=allow_http
+ )
+ continue
+ resp.raise_for_status()
+ declared = resp.headers.get("content-length")
+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:
+ raise ValueError(f"response too large: {declared} bytes")
+ chunks: list[bytes] = []
+ total = 0
+ for chunk in resp.iter_bytes(65536):
+ total += len(chunk)
+ if total > max_bytes:
+ raise ValueError(f"response exceeded {max_bytes} bytes")
+ chunks.append(chunk)
+ return b"".join(chunks)
+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")
+
+
+async def fetch_remote_bytes_async(
+ client: "httpx.AsyncClient",
+ url: str,
+ *,
+ max_bytes: int = DEFAULT_MAX_BYTES,
+ allow_http: bool = False,
+ headers: Optional[dict] = None,
+) -> bytes:
+ """Async variant of ``fetch_remote_bytes`` using a caller-provided client.
+
+ The provided ``client`` MUST be constructed with ``follow_redirects=False``
+ so this function can re-validate each redirect hop itself.
+ """
+ current = assert_safe_url(url, allow_http=allow_http)
+ for _ in range(_MAX_REDIRECTS + 1):
+ async with client.stream("GET", current, headers=headers) as resp:
+ if resp.is_redirect:
+ location = resp.headers.get("location")
+ if not location:
+ raise UnsafeUrlError("redirect without Location header")
+ current = assert_safe_url(
+ str(resp.url.join(location)), allow_http=allow_http
+ )
+ continue
+ resp.raise_for_status()
+ declared = resp.headers.get("content-length")
+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:
+ raise ValueError(f"response too large: {declared} bytes")
+ chunks: list[bytes] = []
+ total = 0
+ async for chunk in resp.aiter_bytes(65536):
+ total += len(chunk)
+ if total > max_bytes:
+ raise ValueError(f"response exceeded {max_bytes} bytes")
+ chunks.append(chunk)
+ return b"".join(chunks)
+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")
+
+
+# ── opaque error handling ───────────────────────────────────────────────────────
+
+
+def safe_error(exc: BaseException, *, context: str = "") -> str:
+ """Log the full traceback server-side and return an opaque client message.
+
+ Never leak ``traceback.format_exc()`` (absolute paths, library versions,
+ internal hostnames, fragments of upstream responses) to callers. A short
+ correlation id is embedded in both the log line and the returned string so
+ operators can join a client-reported failure to the server log.
+ """
+ correlation_id = uuid.uuid4().hex[:12]
+ label = f"{context} " if context else ""
+ log.exception("%serror [correlation_id=%s]", label, correlation_id)
+ return f"internal error (ref {correlation_id})"