Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
docs(ops): write the Materialize fulfillment runbook and map photo mode in STRUCTURE
nirholas0f37c78efa40
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 25f0797e2..88c3fa02d 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -107,6 +107,7 @@ bottom.| `/play` in-game economy (cash, bank/ATM, vendors, $THREE boutique) | Client: [src/game/coincommunities.js](src/game/coincommunities.js) `→ /play`, general-store/bank NPCs [src/game/npc/economy-npcs.js](src/game/npc/economy-npcs.js), store/bank UI [src/game/economy-ui.js](src/game/economy-ui.js), on-chain purchase flow [src/game/boutique-purchase.js](src/game/boutique-purchase.js), wardrobe [src/game/play-systems.js](src/game/play-systems.js). Server: [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) (store/bank/boutique handlers), price tables [multiplayer/src/shop.js](multiplayer/src/shop.js), purse/bank model [multiplayer/src/economy.js](multiplayer/src/economy.js), on-chain settlement [multiplayer/src/game-token.js](multiplayer/src/game-token.js) | In-repo | The GTA-style open world's real economy (W04 of the World Online program, program brief retired to git history). Walk up to a General Store clerk (E) to buy tools/consumables or sell gathered goods for cash, server-priced and validated every time; walk up to the Bank Teller to deposit cash into a protected balance (survives a death drop) or withdraw it. Premium wardrobe cosmetics unlock with a real on-chain `$THREE` payment from the player's connected Solana wallet; the server only grants the item after re-verifying the confirmed transaction on RPC. Distinct from the separate USDC/x402 avatar-shop rail ([api/x402/cosmetic-purchase.js](api/x402/cosmetic-purchase.js)), which sells a different catalog for the standalone character creator. Published publicly at [pages/play/economy.html](pages/play/economy.html) `→ /play/economy` ([src/play-economy.js](src/play-economy.js)), fed by [api/play/economy.js](api/play/economy.js) `→ /api/play/economy`, which serializes the SAME shop/economy/spin-wheel modules the server prices trades with rather than restating them, so the public reference cannot drift from the game. Docs: [docs/in-game-economy.md](docs/in-game-economy.md), tutorial [docs/tutorials/earn-and-spend-in-play.md](docs/tutorials/earn-and-spend-in-play.md). Tests: [tests/api/play-economy.test.js](tests/api/play-economy.test.js) || `/play` character & avatar customization (avatar creator, selfie→3D, wardrobe boutique) | Lobby creator flow [src/game/coincommunities-ui.js](src/game/coincommunities-ui.js) `_openCreate()`, selfie SDK wrapper [src/avatar-creator.js](src/avatar-creator.js), shop [src/game/cosmetics-shop.js](src/game/cosmetics-shop.js), wardrobe [src/game/cosmetics-wardrobe.js](src/game/cosmetics-wardrobe.js), boutique NPCs [src/game/npc/npc-catalog.js](src/game/npc/npc-catalog.js) (`npc-tailor`, `npc-fitting-room`), boutique spawn points [src/game/world-zones.js](src/game/world-zones.js) (`type: 'boutique'`), in-world avatar switcher [src/game/avatar-switcher.js](src/game/avatar-switcher.js) (HUD Avatar button / `V`, swap applied in [src/game/coincommunities.js](src/game/coincommunities.js) `_applyAvatarSwap()`) | In-repo | W03 of the World Online program (program brief retired to git history). Before dropping into `/play`, design an avatar from scratch or a selfie (real Avaturn SDK), upload a `.glb`, or sculpt in the full Avatar Studio; no sign-in required. Once in the world, press `V` (or the HUD Avatar button) to change avatars without leaving: saved three.ws avatars, quick picks, gallery, paste-a-URL, upload, and the creator, rebuilt live on your rig and broadcast to peers over the room's `avatar` message. The cosmetics shop/wardrobe (real x402-settled catalog, server-persisted equip) also has a physical home: walk up to Roux · Tailor to browse/buy, or Nell's Fitting Room to equip anything you own. Doc: [docs/character-studio.md](docs/character-studio.md#character-customization-in-play-world-online). Tests: [tests/play-avatar-switcher.test.js](tests/play-avatar-switcher.test.js), [tests/walkroom-avatar-swap.test.js](tests/walkroom-avatar-swap.test.js). || `/play` forge-in-world (prompt or photo to a live prop) | Lane client [src/game/forge-prop.js](src/game/forge-prop.js), palette form + `/forge` chat command [src/game/coincommunities-ui.js](src/game/coincommunities-ui.js) (`_buildForgeRow()`, `_submitForge()`), placement handler [src/game/coincommunities.js](src/game/coincommunities.js) (`_forgeProp()`), styles [src/game/coincommunities.css](src/game/coincommunities.css), rendering [src/game/world-objects.js](src/game/world-objects.js) (`registerUploadedProp`), server gate [multiplayer/src/build-limits.js](multiplayer/src/build-limits.js) (`normalizePropAssetUrl`) | In-repo | Describe an item in the build palette's Forge form (or type `/forge a glowing campfire` in world chat, or attach a reference photo) and the free draft forge lane generates a real textured GLB in about half a minute. The finished model is registered as a placeable prop and armed, so the next click drops it into the shared world through the SAME `obj:spawn` channel player uploads use: the URL travels on the object, every connected player renders it, and the room persists it like any other build. No new server surface was needed because the durable forge URL (`S3_PUBLIC_DOMAIN`, an `*.r2.dev` host) already satisfies the world asset allow-list; an off-list host is refused with `obj:reject`/`asset_url`. Generation is one-at-a-time per player, and every failure (rate limit, refused prompt, dead upload, timeout) reports a recovery line in the palette's status strip. Docs: [docs/play-forge-in-world.md](docs/play-forge-in-world.md). Tests: [tests/forge-prop.test.js](tests/forge-prop.test.js) |+| `/play` photo mode (the screenshot people post) | Card compositor + preview sheet [src/game/photo-mode.js](src/game/photo-mode.js) + [src/game/photo-mode.css](src/game/photo-mode.css), shared offscreen capture [src/game/scene-capture.js](src/game/scene-capture.js), HUD camera button [src/game/coincommunities-ui.js](src/game/coincommunities-ui.js) (`photoBtn`, `setPhotoActive()`), `P` keybinding + lazy host [src/game/coincommunities.js](src/game/coincommunities.js) (`_openPhotoMode()`), event agenda action [src/game/meetup-event.js](src/game/meetup-event.js) (`_capturePhoto()`) | In-repo | Press `P` or the HUD camera button and the world lands on a monochrome share card: the shot, the three.ws mark, the coin's name and symbol, the date, and during a live event that event's own name, read from the same `public/event.json` the countdown and agenda run on, so an event photo stamps itself with nothing to keep in sync. Download and Copy-image sit under a preview that the world keeps running behind; Escape or the X closes it, and `P` retakes over it. **The shot is an offscreen render, not a canvas grab.** `captureSceneCanvas()` renders one extra frame into a `WebGLRenderTarget` and reads that back, which is why the HUD, chat, name tags and the preview card itself are never in the frame, why the classic black-screenshot bug (reading a drawing buffer the compositor already took) cannot happen, and why nobody pays the permanent per-frame cost of `preserveDrawingBuffer`. Cost when no one is taking a photo is zero twice over: no extra render, and the whole module plus its CSS is imported on the FIRST press. Deliberately alive in zen mode, building and driving, since a clean world is exactly when the shot is wanted. Clipboard support is feature-detected: where `ClipboardItem` is missing the Copy button stays visible and says so rather than breaking. Same capture path backs the build-share thumbnail (`_captureBuildShot()`). Tests: [tests/photo-mode.test.js](tests/photo-mode.test.js) (compositor geometry, preview sheet, clipboard fallback, event stamp), [tests/e2e/play-photo-mode.spec.js](tests/e2e/play-photo-mode.spec.js) (real Chromium + WebKit, pixels of the saved PNG), walkthrough [scripts/play-photo-mode-check.mjs](scripts/play-photo-mode-check.mjs) || `/play` combat & weapons (server-authoritative, danger zones, wanted, tombstones) | Client: [src/game/combat-system.js](src/game/combat-system.js) `→ /play` (vitals HUD wiring, danger-zone ground, tombstone loot, hit feedback, the `window.twsCombat` bridge into W08's `MobSystem`), HUD [src/game/hud/world-hud.js](src/game/hud/world-hud.js). Server: [multiplayer/src/combat-handlers.js](multiplayer/src/combat-handlers.js) (mob AI, attack/loot intents, death + respawn), pure math [multiplayer/src/combat.js](multiplayer/src/combat.js), weapon/mob/loot tables [multiplayer/src/items.js](multiplayer/src/items.js), zone geometry [multiplayer/src/world-features.js](multiplayer/src/world-features.js), handlers wired in [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) | In-repo | W07 of the World Online program (program brief retired to git history). Equip a sword/bat/pistol/bow from the hotbar and press `X` (or tap the touch Attack button) to fight; but only inside one of three named danger zones (Southern Wilds, Northern Wilds, Eastern Marches); town stays lawful by construction. PvE mobs chase and swing back through the same server-side damage path a player's attack uses; a kill (mob or PvP) spills a lootable tombstone, PvP raises the attacker's wanted/heat stars (visible on `WorldHud` and a downed peer's nameplate), and death drops carried cash/pack before an automatic respawn in town. || `/play` NPCs & world life (traffic, vendors, quest-givers, mobs) | Manager [src/game/npc/world-life.js](src/game/npc/world-life.js), nav graph [src/game/npc/nav-graph.js](src/game/npc/nav-graph.js), ambient crowd/traffic [src/game/npc/ambient-life.js](src/game/npc/ambient-life.js), quest-giver NPCs [src/game/npc/quest-npcs.js](src/game/npc/quest-npcs.js), quest-zone waypoints [src/game/npc/quest-markers.js](src/game/npc/quest-markers.js), Jobs Board UI [src/game/quests-ui.js](src/game/quests-ui.js), W07-gated mobs [src/game/npc/mobs.js](src/game/npc/mobs.js). Server: quest engine [multiplayer/src/quests.js](multiplayer/src/quests.js), quest zones [multiplayer/src/quest-zones.js](multiplayer/src/quest-zones.js), handlers in [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) | In-repo | W08 of the World Online program (program brief retired to git history). A deterministic nav graph drives client-side ambient pedestrians + ring-road traffic that read identically for every player without a single packet; real gameplay stays server-authoritative. Five quest-giver NPCs (Dockmaster Reyes, Warden Okoro, Cook Mara, Foreman Dell, The Fixer) front the jobs board the quest engine (W05) already ran server-side but no client ever reached; pressing E opens the real board, accepting a job drops a waypoint at its objective (goto zones auto-complete by walking there, interact zones get their own "press E"), and finishing pays real cash server-side. Hostile mobs are live: W07's `CombatSystem` ([src/game/combat-system.js](src/game/combat-system.js)) installs the `window.twsCombat` contract this module's mobs were built against, so `MobSystem` renders real server-authoritative PvE hostiles with zero changes here. Two jobs; `cross-town-delivery` (North↔South) and `east-west-express` (East↔West); are real driving missions: each `goto` leg is flagged `vehicle: true` and only completes off the authoritative vehicle-driver map ([multiplayer/src/vehicles.js](multiplayer/src/vehicles.js)), so walking through a depot never counts, only driving through it does. Depots sit on the avenue vehicle spawns, so a car is always parked at the start. Tests: [tests/quests-vehicle-delivery.test.js](tests/quests-vehicle-delivery.test.js). || `/play` vehicles (the drivable fleet & the Trench Car) | Handling spec + fleet registry [multiplayer/src/vehicles.js](multiplayer/src/vehicles.js), client manager [src/game/vehicles.js](src/game/vehicles.js), meshes [src/game/vehicle-mesh.js](src/game/vehicle-mesh.js), shared GLB loader [src/game/vehicle-model.js](src/game/vehicle-model.js), staged model [public/vehicles/](public/vehicles) (built by [scripts/build-trench-car.mjs](scripts/build-trench-car.mjs), `npm run build:trench-car`), Rapier chassis [src/physics/physics-world.js](src/physics/physics-world.js), server gate + anti-cheat [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) | In-repo | W02 of the World Online program. Real cars you drive with WASD (touch gets pedals and a wheel), simulated locally on the SAME Rapier world the character controller uses, so a car collides with the town exactly as a walking avatar does, and relayed through a server that validates per-type speed and bounds and owns who may drive what. The **Trench Car**, a community model from the avatar gallery (`trench-car`), is the only car in the world: ambient traffic drives it in every town ([src/game/npc/ambient-life.js](src/game/npc/ambient-life.js)) and it is parked in every vehicle bay, so the car you watch go past is the car you can get into (the four procedural box types it used to share the road with were retired 2026-08-17). A car builds a procedural stand-in instantly and swaps the GLB body and wheels into the same group and pivots when the download lands, so a car that upgrades mid-drive keeps its physics, camera and driver, and a failed download still leaves a drivable car. One shared template per model; only the brake-light material is per car. Drivers sit in a seated pose that peers see too (server-authored `drive` motion). Docs: [docs/play-vehicles.md](docs/play-vehicles.md). Tests: [tests/vehicles-trench-car.test.js](tests/vehicles-trench-car.test.js), [tests/e2e/play-vehicles.spec.js](tests/e2e/play-vehicles.spec.js), [tests/quests-vehicle-delivery.test.js](tests/quests-vehicle-delivery.test.js); real-Rapier repro `node scripts/verify-w02-physics-core.mjs trench` |@@ -155,7 +156,7 @@ bottom.| Forge thumbnail coverage | [api/_lib/forge-thumbs.js](api/_lib/forge-thumbs.js) + cron [api/cron/forge-thumbnail-backfill.js](api/cron/forge-thumbnail-backfill.js) (`*/5`) | Live | Gives every finished forge model a real picture. The dominant free NVIDIA/TRELLIS lane is geometry-first and paints no reference image, so ~83% of finished `forge_creations` land with `preview_image_url = NULL` and render as gradient placeholders on every browse surface (showcase, gallery, `/community`, `/search`, creator portfolios). This cron claims the newest previewless models, renders each GLB to a 768² PNG via the shared headless-chromium renderer ([api/_lib/render-glb.js](api/_lib/render-glb.js)), uploads it, and fills the preview slot — object confirmed in R2 **before** the key is committed (same ORB-safety invariant as avatars), and **fill-only** so a maker's captured poster always wins. Self-provisioning claim ledger (`forge_thumbnail_backfill`, created at runtime), bounded attempts, lease-based reclaim, browser-death batch abort with attempt refund. `?dry_run=1` reports coverage. Tests: [tests/forge-thumbs.test.js](tests/forge-thumbs.test.js). || Catalog quality gate (what earns a slot in the public catalog) | [api/_lib/seed-quality.js](api/_lib/seed-quality.js), consumed by [api/cron/forge-seed-cron.js](api/cron/forge-seed-cron.js) | Live · mesh stage always on, vision stage behind `SEED_CRON_VISION` | The bar every platform-seeded model clears before it reaches [/characters](public/characters.html) or [/objects](pages/objects.html). Nobody asked for seeded content, so it has to earn its slot: a user who generates a coarse mesh chose to, a visitor browsing the catalog did not. Two stages, cheapest first. **Mesh sanity** is free and deterministic (reuses [api/_lib/glb-quality.js](api/_lib/glb-quality.js), the interactive forge's own scorer, plus catalog bounds: vertex floor/ceiling, byte floor/ceiling, must-carry-a-texture, non-collapsed bbox, and a mesh-count rule that applies to `avatar` only because a prop may legitimately be a pile of parts): a degenerate blob is rejected here for the price of a GLB fetch and never costs a model call. **Vision judge** renders one view and asks two questions: realism via `judgeOnce` imported (never forked) from [api/_lib/quality-bench.js](api/_lib/quality-bench.js) so the gate and the regression bench can never disagree about what a score means, plus a catalog-specific rig-readiness check (one complete humanoid with separated limbs, or a bust / blob / crowd?). **Fails closed on mesh, fails soft on vision:** an unreachable judge publishes on the mesh verdict marked `vision_unavailable`, because recording a Vertex outage as a quality reject would corrupt the accept-rate maths. Rejects are copied (never moved) to `forge/rejected/` with a full-verdict JSON sidecar, which is the tuning dataset. `SEED_GATE_VERSION` stamps every verdict since an accept rate is only comparable within one version. Two transports (in-process for Cloud Run, remote via `/api/render/avatar-clip` + `/api/vision` for a credential-less workstation) share one decision path. Docs: [docs/seed-quality.md](docs/seed-quality.md). Tests: [tests/seed-quality.test.js](tests/seed-quality.test.js) || Forge-Off (community voting + weekly board) | Store [api/_lib/forge-store.js](api/_lib/forge-store.js) (`castVote`/`removeVote`/`listShowcase` sort+voter/`forgeOffWeekStart`), endpoint [api/forge-vote.js](api/forge-vote.js), board read [api/forge-gallery.js](api/forge-gallery.js) (`scope=community&sort=top&window=week`), weekly crown cron [api/cron/forge-off-crown.js](api/cron/forge-off-crown.js) (`7 0 * * 1`), UI [src/forge-showcase.js](src/forge-showcase.js) + `/forge-studio` twin [src/forge-studio/forge-showcase.js](src/forge-studio/forge-showcase.js), schema [migration 20260625120000_forge_board.sql](api/_lib/migrations/20260625120000_forge_board.sql) | Live | Turns the "Fresh from the Forge" strip on [/forge](pages/forge.html) into a live board: auth-free upvotes (one per browser, keyed to the same `forge:cid` id as "Your creations"), a Fresh/Top-this-week sort toggle, optimistic vote pills that reconcile against the authoritative `vote_count` (recomputed from `forge_votes`, never a drifting counter), and a Monday-00:07-UTC cron that permanently crowns each week's top-voted creation into `forge_board_winners`. The crown is the writer the [Sketchfab showcase](docs/sketchfab.md) cron's strongest tier had been waiting on. Docs: [docs/forge-off.md](docs/forge-off.md). Tests: [tests/api/forge-gallery-community.test.js](tests/api/forge-gallery-community.test.js) |-| Materialize (generation to a physical object) | Page [pages/materialize.html](pages/materialize.html) `→ /materialize` + [src/materialize-lib.js](src/materialize-lib.js), order tracking [src/materialize-order.js](src/materialize-order.js) `→ /materialize/orders/:id`, operator console [pages/materialize-ops.html](pages/materialize-ops.html) + [src/materialize-ops.js](src/materialize-ops.js) `→ /materialize/ops`, certificate page [pages/certificate.html](pages/certificate.html) `→ /cert/:id` + [src/certificate-page.js](src/certificate-page.js), insert card [pages/print-insert.html](pages/print-insert.html) `→ /materialize/insert/:id`. Engine [api/_lib/print/](api/_lib/print) (mesh-io, topology, bvh, voxel-sdf, analyze, repair, export-stl, export-3mf, quote, gate, rules, certificate, editions, adapters, fulfillment, ops-notify). State machine [api/_lib/print-store.js](api/_lib/print-store.js). HTTP [api/print/](api/print) (catalog, quote, prepare, upload, orders, orders/[id], orders/[id]/confirm, certs/[id], editions, ops/[action], webhook/[provider]) plus the agent lane [api/x402/print-order.js](api/x402/print-order.js). Catalog [data/print-catalog.json](data/print-catalog.json). Sweep [api/cron/print-orders-sync.js](api/cron/print-orders-sync.js) | Live | The physical lane of the forge: any generation becomes a real print, shipped. One `POST /api/print/quote` both analyzes the mesh (manifold check, shells, open edges, thinnest wall, exact volume via the Manifold WASM kernel, a 0-100 score with buyer-readable deductions) and prices it from one tunable catalog file, returning an HMAC-signed 24h quote token that carries every priced parameter so checkout cannot be replayed or edited. Prepare reconstructs the solid, fills holes, scales, optionally hollows with drain holes, and writes STL / 3MF (with per-vertex colour sampled from the source texture, which is what makes a full-colour print possible) / repaired GLB. Checkout is USDC on Solana for humans and x402 for agents, on the same pipeline: `POST /api/x402/print-order` validates the token and address BEFORE issuing the 402, so a malformed order is refused for free. Fulfillment is an adapter layer (manual operator lane plus a partner API) behind a whitelisted state machine; provider webhooks are HMAC-verified against the raw bytes and idempotent by delivery id. Every shipped print gets a Solana-attested certificate hashing the exact manufactured file. **The fabrication gate runs twice and is not advisory:** deterministically at quote time (before money moves, returning 451 with the category and the policy link) and again on the paid order through the LLM chain, with `submitOrder()` refusing anything without a recorded `allow` verdict. Docs: [docs/materialize.md](docs/materialize.md). Spec: [specs/PRINT_PIPELINE.md](specs/PRINT_PIPELINE.md). Tests: [tests/api/print-fabrication-gate.test.js](tests/api/print-fabrication-gate.test.js), [tests/api/print-gate-wiring.test.js](tests/api/print-gate-wiring.test.js), [tests/api/print-exporters.test.js](tests/api/print-exporters.test.js), [tests/print-store.test.js](tests/print-store.test.js), [tests/print-adapter-contract.test.js](tests/print-adapter-contract.test.js), [tests/print-certificate.test.js](tests/print-certificate.test.js), [tests/print-ops-authorization.test.js](tests/print-ops-authorization.test.js) |+| Materialize (generation to a physical object) | Page [pages/materialize.html](pages/materialize.html) `→ /materialize` + [src/materialize-lib.js](src/materialize-lib.js), order tracking [src/materialize-order.js](src/materialize-order.js) `→ /materialize/orders/:id`, operator console [pages/materialize-ops.html](pages/materialize-ops.html) + [src/materialize-ops.js](src/materialize-ops.js) `→ /materialize/ops`, certificate page [pages/certificate.html](pages/certificate.html) `→ /cert/:id` + [src/certificate-page.js](src/certificate-page.js), insert card [pages/print-insert.html](pages/print-insert.html) `→ /materialize/insert/:id`. Engine [api/_lib/print/](api/_lib/print) (mesh-io, topology, bvh, voxel-sdf, analyze, repair, export-stl, export-3mf, quote, gate, rules, certificate, editions, adapters, fulfillment, ops-notify). State machine [api/_lib/print-store.js](api/_lib/print-store.js). HTTP [api/print/](api/print) (catalog, quote, prepare, upload, orders, orders/[id], orders/[id]/confirm, certs/[id], editions, ops/[action], webhook/[provider]) plus the agent lane [api/x402/print-order.js](api/x402/print-order.js). Catalog [data/print-catalog.json](data/print-catalog.json). Sweep [api/cron/print-orders-sync.js](api/cron/print-orders-sync.js) | Live | The physical lane of the forge: any generation becomes a real print, shipped. One `POST /api/print/quote` both analyzes the mesh (manifold check, shells, open edges, thinnest wall, exact volume via the Manifold WASM kernel, a 0-100 score with buyer-readable deductions) and prices it from one tunable catalog file, returning an HMAC-signed 24h quote token that carries every priced parameter so checkout cannot be replayed or edited. Prepare reconstructs the solid, fills holes, scales, optionally hollows with drain holes, and writes STL / 3MF (with per-vertex colour sampled from the source texture, which is what makes a full-colour print possible) / repaired GLB. Checkout is USDC on Solana for humans and x402 for agents, on the same pipeline: `POST /api/x402/print-order` validates the token and address BEFORE issuing the 402, so a malformed order is refused for free. Fulfillment is an adapter layer (manual operator lane plus a partner API) behind a whitelisted state machine; provider webhooks are HMAC-verified against the raw bytes and idempotent by delivery id. Every shipped print gets a Solana-attested certificate hashing the exact manufactured file. **The fabrication gate runs twice and is not advisory:** deterministically at quote time (before money moves, returning 451 with the category and the policy link) and again on the paid order through the LLM chain, with `submitOrder()` refusing anything without a recorded `allow` verdict. Docs: [docs/materialize.md](docs/materialize.md), operator runbook [docs/ops/materialize-fulfillment.md](docs/ops/materialize-fulfillment.md). Spec: [specs/PRINT_PIPELINE.md](specs/PRINT_PIPELINE.md). Tests: [tests/api/print-fabrication-gate.test.js](tests/api/print-fabrication-gate.test.js), [tests/api/print-gate-wiring.test.js](tests/api/print-gate-wiring.test.js), [tests/api/print-exporters.test.js](tests/api/print-exporters.test.js), [tests/print-store.test.js](tests/print-store.test.js), [tests/print-adapter-contract.test.js](tests/print-adapter-contract.test.js), [tests/print-certificate.test.js](tests/print-certificate.test.js), [tests/print-ops-authorization.test.js](tests/print-ops-authorization.test.js), [tests/print-webhook-idempotency.test.js](tests/print-webhook-idempotency.test.js), [tests/print-orders-sync.test.js](tests/print-orders-sync.test.js), [tests/print-fulfillment-routing.test.js](tests/print-fulfillment-routing.test.js) || Realism quality bench | Benchmark [data/quality-bench/prompts.json](data/quality-bench/prompts.json) (23 fixed prompts + 3 CC0 reference photos), runner [scripts/quality-bench.mjs](scripts/quality-bench.mjs), shared generate/render/judge core [api/_lib/quality-bench.js](api/_lib/quality-bench.js), dashboard [api/quality-bench.js](api/quality-bench.js) + [pages/quality-bench.html](pages/quality-bench.html) `→ /quality-bench` (internal, not in `data/pages.json`), weekly smoke cron [api/cron/quality-bench.js](api/cron/quality-bench.js) (`23 3 * * 1`) | Live | The measurement loop the realism campaign hangs on: fires the fixed prompt set through the real `/api/forge` path, renders 3 canonical views per result with the same headless three.js renderer as the avatar clip/OG-card renders ([api/_lib/render-clip.js](api/_lib/render-clip.js)), and scores every view with Vertex Gemini vision (`gemini-2.5-pro`, temperature 0, scored twice and averaged, judge never sees forge's internal prompt-enhancement text). Runs are committed append-only JSON under `data/quality-bench/runs/`; the dashboard renders score trends by lane/tier/subject-class, a worst-5 critique gallery, and the full results table. `node scripts/quality-bench.mjs --compare=latest,previous` exits nonzero on a >1.0 mean drop — run it before/after any forge change that could affect quality. Docs: [data/quality-bench/README.md](data/quality-bench/README.md). || Likeness bench (Phase 1 verification metric) | Scoring core [api/_lib/likeness-score.js](api/_lib/likeness-score.js), face-embedding runtime [api/_lib/face-embed.js](api/_lib/face-embed.js), store + distribution queries [api/_lib/likeness-store.js](api/_lib/likeness-store.js) ([schema](api/_lib/migrations/20260814000000_avatar_likeness_scores.sql)), weekly sweep [api/cron/likeness-eval.js](api/cron/likeness-eval.js) (`47 3 * * 1`), by-hand runner [scripts/likeness-eval.mjs](scripts/likeness-eval.mjs), internal board [api/likeness-bench.js](api/likeness-bench.js) + [pages/likeness-bench.html](pages/likeness-bench.html) `→ /likeness-bench` (admin or `x-ops-secret`, not in `data/pages.json`) | Live · applied 2026-08-14 (this file alone, via `apply-migrations.mjs --apply --file`, because `db:migrate` would have applied seven other agents' pending migrations with it). The header comment still reads "Draft, NOT applied" and must stay that way: an applied migration is an immutable record and editing its bytes trips the drift guard | The number the roadmap gates Phase 1 on, measured instead of asserted. The realism bench scores whether a generation looks real and never asks whose face it is; the reconstruction worker's ISE eval scores face *shape* offline against a synthetic set and stores nothing. This closes the gap: it renders a finished reconstruction head-framed at three yaws (head-on 0°, three-quarter 35°, profile 65°) with the platform's own `headshot` preset, embeds every render and every input capture with OSS face recognition (YuNet detection, MIT + SFace 128-d identity, Apache-2.0, both hash-pinned from OpenCV Zoo and run on `onnxruntime-web`'s WASM backend so there is no native install step), and files a 1-5 score against the generation record in `forge_creations`. The 1-5 mapping is anchored on SFace's own published decision boundary (cosine 0.363 = 3.0, so the roadmap's 4/5 gate is cosine 0.68, roughly twice the same-identity threshold) rather than on taste. **Refuses rather than fabricates:** `captures_unusable`, `render_unusable` and a genuinely low score are three separate statuses, and a budget-truncated sweep is withheld from the distribution. Reports `turn_falloff` (identity lost between head-on and the worst view), which is the only place a frontally-flattering texture transfer is visible. **Stores no biometrics:** no capture URLs, no crops, no embeddings, only the measurement. Docs: [docs/likeness-eval.md](docs/likeness-eval.md). Tests: [tests/likeness-score.test.js](tests/likeness-score.test.js) || Payment-outcome board (x402 failure visibility) | Endpoint [api/ops/payment-outcomes.js](api/ops/payment-outcomes.js), page [pages/payment-outcomes.html](pages/payment-outcomes.html) `-> /payment-outcomes` (admin session or `x-ops-secret`, `noindex`, not in `data/pages.json`), sensors [api/_lib/ops/x402-settle-health.js](api/_lib/ops/x402-settle-health.js) + [api/_lib/x402/wallet-balance-monitor.js](api/_lib/x402/wallet-balance-monitor.js) + [api/_lib/x402/sponsor-runway.js](api/_lib/x402/sponsor-runway.js) + [api/_lib/custodial-key-health.js](api/_lib/custodial-key-health.js) | Live | Every way an x402 payment can fail, in one read, before it halts the economy. The 2026-07-11 audit found the griefing classes (verify-reject floods, settle failures, sponsor-fee starvation) were only visible after the economy stopped: `recordPaymentMetric` was already emitting the events and nothing surfaced them. Four panels: inbound rates over 1h/3h/24h from the durable `x402_audit_log` (settle success, verify reject, replay reject with its own `inbound_attempts` denominator, top failure reasons by stage, replay stage split), the outbound ring settle sensor with its triage hint, every configured ring wallet against **its own** floor plus the measured sponsor runway, and stranded custody. The wallet panel is per-wallet on purpose: settle-floor starvation and dry wallets look identical from outside and have opposite fixes, and a board showing only the sponsor renders a starved payer as healthy. Panels are read independently and a failed one names itself in `degraded` (207 Multi-Status) rather than blanking the board; on the page a rate with no attempts renders `n/a` and an unmeasured custody total renders `not measured`, because a green zero on a reading that never happened is worse than no board. Docs: [docs/ops/payment-outcomes.md](docs/ops/payment-outcomes.md). |diff --git a/docs/ops/README.md b/docs/ops/README.mdindex 67ec4b68e..1a5209438 100644--- a/docs/ops/README.md+++ b/docs/ops/README.md@@ -15,6 +15,7 @@ Start with [gcp-production.md](gcp-production.md); it is the complete operationa| [production-log-triage.md](production-log-triage.md) | Known error/warning signature map: what each recurring log signature means and the fix. || [forge-error-triage.md](forge-error-triage.md) | `npm run forge:errors`: which 3D generation failures actually recur, ranked by class and lane over a real window. || [cron-auth.md](cron-auth.md) | The two locks on `/api/cron/*`: the handler gate, the edge gate, and the header trap that makes attaching Cloud Scheduler OIDC take the whole fleet down if done naively. |+| [materialize-fulfillment.md](materialize-fulfillment.md) | Running physical print fulfillment: the operator console, its authorization doors, the adapter contract for wiring a partner, webhook idempotency, and the stall sweep. || [payment-outcomes.md](payment-outcomes.md) | The payment-outcome board (`GET /api/ops/payment-outcomes`): verify-reject, settle-fail, replay, and sponsor-runway signals and how to read them in an incident. || [agent-index.md](agent-index.md) | The agent index crawls end to end: the cursor stall both chain legs share, the error-class table, the recovery script, and how the freshness sensor scores each leg. || [solana-rpc-lanes.md](solana-rpc-lanes.md) | The Solana RPC tier end to end: one-sweep diagnosis, per-lane method capability, what must rotate vs fail, config traps, recovery. |diff --git a/docs/ops/materialize-fulfillment.md b/docs/ops/materialize-fulfillment.mdnew file mode 100644index 000000000..f5c41d39b--- /dev/null+++ b/docs/ops/materialize-fulfillment.md@@ -0,0 +1,251 @@+# Materialize fulfillment: the operator console and the adapter layer++Every paid Materialize order has to become an object in a box. This runbook is+for the person who makes that happen, and for whoever wires the next+fulfillment partner.++Two things are worth stating before the mechanics, because they explain every+design decision below:++1. **The launch lane is a human.** A print marketplace's first fulfillment lane+ is always an operator driving a real print bureau by hand. That is not a+ placeholder for a partner API; it is a first-class adapter with a+ first-class console, and the product ships on it.+2. **The state machine, not the provider, decides what may follow what.** A+ partner reporting "shipped" for a job we already refunded is refused and+ recorded, never applied. That refusal is what keeps a partner's release+ notes from being able to corrupt an order.++Buyer-facing documentation lives in [../materialize.md](../materialize.md).+This file is the other half.++## The console++`/materialize/ops` ([pages/materialize-ops.html](../../pages/materialize-ops.html),+runtime [src/materialize-ops.js](../../src/materialize-ops.js)). Queues on the+left, orders in the middle, one order's whole story in a drawer on the right.++The working loop:++1. Open **Needs action**. Anything late shows `+Nd` next to its status, so the+ question "which of these is in trouble" is answered before you click.+2. Open an order. The drawer carries the prepared STL / 3MF / GLB as download+ links (this is what you hand the bureau), the shipping address, the timeline,+ and every webhook delivery we have received for it.+3. **Submit to lane.** Pick a lane or leave it on *Route automatically*, which+ takes the first configured adapter whose declared capabilities cover the+ order. The order moves to `submitted` and the operator channel is paged.+4. Run the job. Move the order as reality moves: `printing`, then+ `quality check`. Notes go on the timeline; write them for the next operator,+ not for yourself.+5. **Enter the tracking number.** That is the action that marks the order+ `shipped`, which is also what issues its certificate. Correcting a typo+ afterwards updates the number without a second shipment event.++Every button is generated from the order's own legal moves, so the console can+never offer a transition the server would refuse. A closed order shows no+actions and says so.++### Authorization++Three doors, strongest first+([api/_lib/print/ops-auth.js](../../api/_lib/print/ops-auth.js)):++| Door | Who | Attribution on the timeline |+|---|---|---|+| Platform admin session | wallet in `ADMIN_ADDRESSES`, the built-in owner address, or `is_admin` | the operator's user id |+| Operator allowlist | a signed-in user whose id or wallet is in `PRINT_OPERATORS` | the operator's user id |+| `x-ops-secret` header | scripts, matching `OPS_SECRET` | `ops-secret`, no user id |++`PRINT_OPERATORS` exists so fulfillment can be staffed without handing out+platform admin, which is a far larger privilege than "may mark a job shipped".+It is a comma-separated list of user ids or wallet addresses.++**This gate fails closed in development too.** The read-only ops boards+(`api/_lib/ops-auth.js`) deliberately open when no `OPS_SECRET` is configured;+these endpoints must not, because they return shipping addresses. A deployment+with no credentials configured serves nobody.++Shipping addresses are the first real PII this platform stores. They appear in+exactly two places: the order detail in this console, and the payload handed to+a fulfillment adapter. They are never logged, never in an analytics event, and+never in an operator notification, which carries only the destination country.++## The adapters++An adapter is the machine-readable face of whoever actually prints the thing.+The contract is one interface+([api/_lib/print/adapters/contract.js](../../api/_lib/print/adapters/contract.js)):++```+key stable string, stored in print_orders.provider+label human name for the console+capabilities { materials, maxBboxMm, shipsFrom, leadTimeDays }+configured() false hides the adapter from the registry entirely+submit(order, assets) → { providerOrderId, status, leadTimeDays, note, state }+status(providerOrderId) → { status | null, trackingNumber, carrier, note, state }+cancel(order, reason) → { ok, note, state }+verifyWebhook(raw, headers) → { ok, deliveryId, reason }+parseWebhook(payload) → { providerOrderId, status, trackingNumber, carrier, note, state }+```++Rules that make the layer worth having:++- **An adapter never writes the database.** It returns vocabulary the store+ understands and the caller drives the transition. Every result is normalized+ first, so a malformed return fails at its own boundary with a named error.+- **Capabilities are declared, not inferred.** Routing an order to a lane is a+ comparison against published facts, so a lane that cannot run a part declines+ it before the job is taken rather than after.+- **An adapter may only drive `submitted`, `printing`, `quality_check`,+ `shipped`, `delivered`, `canceled`, `rejected`.** Everything before+ submission is ours, and `refunded` is a money decision that stays with an+ operator.+- **An unknown provider status maps to `null`, meaning "no news".** Guessing a+ transition from a string a partner added in a release we have not read is+ exactly how a state machine gets corrupted.+- **Registration is conditional on `configured()`.** A lane whose credentials+ are absent is invisible: nothing can route into it and the console never+ offers it.++### `manual`, the launch lane++[api/_lib/print/adapters/manual.js](../../api/_lib/print/adapters/manual.js).+Always configured, because it needs a person rather than a credential.++- `submit()` puts the job on the operator queue and pages the operator channel.+- The provider order id **is** our order id. There is no second system, so an+ opaque handle would be a fiction the operator has to translate back by hand.+- `status()` reads our own order row: the console's transitions are this lane's+ source of truth, so a poll always agrees with the order it is polling and+ reports "no change" by construction.+- There is no webhook. `verifyWebhook()` refuses every delivery rather than+ leaving an unauthenticated door open on a lane that cannot call it.++### `partner-cn`, wired and waiting on a contract++[api/_lib/print/adapters/partner-cn.js](../../api/_lib/print/adapters/partner-cn.js).++The Chinese high-precision print operator who approached us on 2026-08-13 is+**unverified and uncontracted.** The adapter is fully structured and registers+itself only when both env vars are present:++```+PRINT_PARTNER_CN_URL https base of the partner API, no trailing slash+PRINT_PARTNER_CN_KEY bearer credential, also the webhook HMAC secret+```++The request and callback shapes the module assumes are documented in its own+header, in the store's vocabulary. They are the contract to reconcile against+the partner's real API documentation the day it arrives; reconciling should be+a rename of wire fields, never a redesign. The status mapping is one table+(`PARTNER_STATE_MAP`), which is the piece most likely to need a line added.++Signing a partner is an owner action. Nothing in this lane is reachable until+the credentials exist.++### Adding a lane++1. Write the module beside the other two, satisfying the interface above.+2. Register it in [adapters/index.js](../../api/_lib/print/adapters/index.js).+ Order matters: the first configured adapter that supports an order is the+ default route, and `manual` is deliberately last. A contracted partner+ should take a job it can run; a human should take everything else.+3. Add it to the conformance suite's adapter list in+ [tests/print-adapter-contract.test.js](../../tests/print-adapter-contract.test.js).+ Every adapter runs through the same checks; that is the point.++## Webhooks++`POST /api/print/webhook/:provider`+([api/print/webhook/[provider].js](../../api/print/webhook/%5Bprovider%5D.js)).+Three properties, enforced in this order:++1. **Authenticity.** The adapter verifies the delivery against the exact bytes+ received, constant-time. An unverified delivery is refused before the body+ is parsed, so a forged payload never reaches a `JSON.parse`.+2. **Idempotency.** Every serious provider retries. The claim on+ `print_webhook_deliveries` is a unique-key insert and happens *before* the+ payload is interpreted, so even a delivery we end up not applying is+ recorded and cannot be replayed. A duplicate answers `200 {duplicate:true}`;+ a 4xx would make the provider retry forever.+3. **Ordering.** A report the state machine refuses is written to the timeline+ as a provider event carrying the refusal, and answered `200+ {applied:false}`.++A provider that sends no delivery id gets a stable one derived from the payload+hash, so "the same event twice" is still one row.++## The reconciliation sweep++[api/cron/print-orders-sync.js](../../api/cron/print-orders-sync.js), hourly at+`:17` (registered in `vercel.json`; Cloud Scheduler is synced by+`scripts/create-gcp-scheduler.mjs` at deploy time).++Webhooks are the fast path and are not sufficient: a delivery gets lost, a+callback queue backs up, and the manual lane has no webhook at all. Without the+sweep, the worst failure a physical product has goes unnoticed, which is a+finished order sitting in `printing` until the buyer asks.++Two passes, deliberately separate:++- **Reconcile.** Poll every order a configured adapter still owns and apply the+ answer through the state machine. A provider with no news moves nothing, so+ this is safe to run often. **One unreachable partner is counted, not thrown**,+ because the stall pass is exactly what catches the orders that partner is+ sitting on.+- **Stall.** Page the operator once for any order more than `lead_time_days + 2`+ old, then stamp `stall_alerted_at` so the next sweep stays quiet for 24 hours.++Read the response: `{ open, polled, applied, stalled, alerted, failures }`. A+non-empty `failures` array names the orders whose lane could not be reached and+why.++## The operator channel++[api/_lib/print/ops-notify.js](../../api/_lib/print/ops-notify.js). Three sinks,+layered so no single missing credential silences the queue:++1. **Telegram**, to a private ops chat: `TELEGRAM_PRINT_OPS_CHAT_ID`, falling+ back to the existing `TELEGRAM_ALERTS_CHAT_ID`. Same bot token and the same+ retrying sender the ops alerts use. Never the public changelog channel:+ these messages carry order ids.+2. **The in-app bell**, for every platform admin. This is what makes the channel+ work on a deployment with no dedicated ops chat id.+3. **`ops_alerts`**, for stalls only, which is the durable record when the other+ two are unconfigured.++## Refunds++Marking an order `refunded` in the console records the decision, attributes it+to the operator, and returns the exact payout instruction: amount, recipient,+chain, asset. **It moves no money.** Sending USDC is an owner-executed action+under the CLAUDE.md spend gate, and the console renders what the owner needs+rather than performing it. The instruction stays on screen after the order+reloads, so it can be acted on rather than glimpsed.++## Environment variables++| Var | Required for | Notes |+|---|---|---|+| `DATABASE_URL` | everything | Without it the console and the sweep answer 503. |+| `PRINT_OPERATORS` | staffing without platform admin | Comma-separated user ids or wallet addresses. Optional: admins always get in. |+| `OPS_SECRET` | script access to the ops API | The dedicated ops credential. Never `CRON_SECRET`. |+| `CRON_SECRET` | the sweep | Standard cron gate. |+| `TELEGRAM_BOT_TOKEN` + `TELEGRAM_PRINT_OPS_CHAT_ID` | Telegram paging | Falls back to `TELEGRAM_ALERTS_CHAT_ID`. Without either, paging degrades to the bell and `ops_alerts`. |+| `PRINT_PARTNER_CN_URL` + `PRINT_PARTNER_CN_KEY` | the partner lane | Absent today. Until both exist the adapter is not registered at all. |++## Diagnosing a stuck order++1. Open it in the console and read the timeline bottom to top. Every status+ change is there with its actor; nothing mutates history.+2. Check **Webhook deliveries** in the drawer. Empty on a partner order means+ their callbacks are not reaching us, which is a different problem from a+ slow print. Empty on a manual order is expected.+3. Run the sweep by hand and read `failures`:+ ```bash+ curl -s -H "authorization: Bearer $CRON_SECRET" https://three.ws/api/cron/print-orders-sync | jq+ ```+4. A refused provider report appears on the timeline as+ `Refused provider report '<status>': <reason>`. That means their system and+ ours disagree about where the job is; the timeline is right.