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
Forge studio: lane health/routing, remix royalty, agent hire-discover, delegate transport
nirholasb76248be2579
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex 63ce72863..65bb8bd90 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -90,6 +90,37 @@"defi","trading"]+ },+ {+ "name": "three-ws-3d",+ "source": "./marketplace/plugins/three-ws-3d",+ "displayName": "three.ws 3D Forge",+ "description": "Generate textured 3D models and rigged, animation-ready avatars from text or images — free text→3D (NVIDIA NIM / TRELLIS) plus the paid mesh, avatar, and auto-rig lanes, scene composition, and live avatar embeds over the three.ws MCP servers.",+ "version": "1.0.0",+ "author": {+ "name": "nirholas"+ },+ "homepage": "https://three.ws/forge",+ "repository": "https://github.com/nirholas/three.ws",+ "license": "Apache-2.0",+ "keywords": [+ "3d",+ "forge",+ "avatar",+ "glb",+ "text-to-3d",+ "image-to-3d",+ "rigging",+ "trellis",+ "mcp"+ ],+ "category": "creative",+ "tags": [+ "3d",+ "forge",+ "avatar",+ "mcp"+ ]}]}diff --git a/api/_lib/forge-events.js b/api/_lib/forge-events.jsindex e4c57d8be..7a4c47077 100644--- a/api/_lib/forge-events.js+++ b/api/_lib/forge-events.js@@ -16,6 +16,7 @@// blowout.import { getRedis } from './redis.js';+import { backendCostClass } from './forge-tiers.js';const redis = getRedis();@@ -132,6 +133,27 @@ export async function readGenerationMetrics({ windowHours = DEFAULT_WINDOW_HOURS}}+ // Free-vs-paid serve split — the headline number for the self-host-first cost+ // goal: how many generations were served on a zero-vendor-cost lane (our own+ // GPU workers + free external previews) vs a paid one (Replicate platform+ // credits or a BYOK vendor key). Derived from the per-backend counters via the+ // registry's cost class, so it needs no extra counter writes and stays correct+ // as lanes are added. `unknown` collects any backend the registry no longer+ // knows (a renamed lane), surfaced rather than silently dropped.+ const byCost = {+ free: { total: 0, ok: 0, fail: 0 },+ paid: { total: 0, ok: 0, fail: 0 },+ unknown: { total: 0, ok: 0, fail: 0 },+ };+ for (const [backend, c] of Object.entries(agg.by_backend)) {+ const cls = backend === 'unknown' ? 'unknown' : backendCostClass(backend) || 'unknown';+ const slot = byCost[cls] || byCost.unknown;+ slot.total += c.total;+ slot.ok += c.ok;+ slot.fail += c.fail;+ }+ const servedTotal = byCost.free.total + byCost.paid.total;+return {window_hours: hours,total: agg.total,@@ -141,5 +163,9 @@ export async function readGenerationMetrics({ windowHours = DEFAULT_WINDOW_HOURSsuccess_rate: agg.total > 0 ? Number((agg.ok / agg.total).toFixed(4)) : null,avg_latency_ms: agg.lat_n > 0 ? Math.round(agg.lat_sum / agg.lat_n) : null,by_backend: agg.by_backend,+ by_cost: byCost,+ // Share of generations that cost no vendor money — the metric the+ // self-host-first work is measured by. Null when nothing has been served yet.+ free_share: servedTotal > 0 ? Number((byCost.free.total / servedTotal).toFixed(4)) : null,};}diff --git a/api/_lib/remix-royalty.js b/api/_lib/remix-royalty.jsnew file mode 100644index 000000000..3b1802b3a--- /dev/null+++ b/api/_lib/remix-royalty.js@@ -0,0 +1,107 @@+// Remix royalties — provenance income for 3D-asset creators (PAID track only).+//+// When an agent remixes a published asset (generates a NEW model FROM another+// creator's GLB), the remix fee is paid in USDC over x402 and a creator-set+// slice of that fee routes back to the ORIGINAL creator. This is the asset-bazaar+// analogue of api/_lib/fork-royalties.js (which streams SOL up an avatar fork+// lineage): same fairness guardrails, different rail (USDC, settled via the x402+// facilitator + a real guarded transfer in api/x402/remix-asset.js).+//+// This module is the PURE math — no DB, no chain — so the split + caps are+// unit-tested in isolation (tests/remix-royalty.test.js). $THREE-policy clean:+// USDC is the settlement asset only; no other coin is named anywhere.++// ── Policy constants (the fairness guardrails) ───────────────────────────────++// The most a creator may set as their remix royalty (20%). A creator configuring+// a higher rate is clamped to this; the remixer always keeps the clear majority.+export const REMIX_ROYALTY_CAP_BPS = 2000;++// The default royalty applied when a remixable asset doesn't set its own rate.+export const REMIX_ROYALTY_DEFAULT_BPS = 1000;++// USDC has 6 decimals; a royalty below this (0.01 USDC) costs more in transfer+// fees than it moves, so it's recorded but not paid out — the dust floor.+export const REMIX_MIN_PAYOUT_ATOMICS = 10_000n;++// USDC atomic units per whole token (6 decimals). The bazaar prices in atomics.+export const USDC_DECIMALS = 6;++/** Clamp a creator-supplied royalty rate to [0, REMIX_ROYALTY_CAP_BPS]. */+export function clampRoyaltyBps(bps) {+ const n = Math.round(Number(bps));+ if (!Number.isFinite(n) || n <= 0) return 0;+ return Math.min(n, REMIX_ROYALTY_CAP_BPS);+}++/** Coerce any price-ish input to a non-negative BigInt of USDC atomics. */+function toAtomics(value) {+ if (typeof value === 'bigint') return value < 0n ? 0n : value;+ if (typeof value === 'number') {+ if (!Number.isFinite(value) || value <= 0) return 0n;+ return BigInt(Math.floor(value));+ }+ const s = String(value ?? '').trim();+ if (!/^\d+$/.test(s)) return 0n;+ return BigInt(s);+}++/**+ * Compute the remix-fee split. Pure and exact: the creator royalty is+ * floor(price × bps / 10000), clamped to the policy cap and never below the dust+ * floor (a sub-dust royalty is dropped, not paid). The platform keeps the+ * remainder. The invariant creatorAtomics + platformAtomics === priceAtomics+ * holds for every input — no value is created or lost.+ *+ * @param {{ priceAtomics: bigint|number|string, royaltyBps?: number }} args+ * @returns {{+ * priceAtomics: bigint,+ * royaltyBps: number, // the effective (clamped) rate actually applied+ * requestedBps: number, // the rate before clamping (for transparency)+ * creatorAtomics: bigint, // routed to the original creator+ * platformAtomics: bigint, // kept by the platform+ * capped: boolean, // true when the requested rate exceeded the cap+ * dust: boolean, // true when a non-zero royalty fell below the floor+ * creatorUsd: number, // human-readable convenience values+ * platformUsd: number,+ * }}+ */+export function computeRemixSplit({ priceAtomics, royaltyBps }) {+ const price = toAtomics(priceAtomics);+ const requestedBps = Math.max(0, Math.round(Number(royaltyBps ?? REMIX_ROYALTY_DEFAULT_BPS) || 0));+ const effectiveBps = clampRoyaltyBps(requestedBps);+ const capped = requestedBps > REMIX_ROYALTY_CAP_BPS;++ let creator = price > 0n && effectiveBps > 0 ? (price * BigInt(effectiveBps)) / 10000n : 0n;+ let dust = false;+ if (creator > 0n && creator < REMIX_MIN_PAYOUT_ATOMICS) {+ // Below the dust floor — not worth an on-chain transfer; the platform keeps+ // it and the ledger records why. Honest: no fake "pending" we never pay.+ creator = 0n;+ dust = true;+ }+ const platform = price - creator;++ return {+ priceAtomics: price,+ royaltyBps: effectiveBps,+ requestedBps,+ creatorAtomics: creator,+ platformAtomics: platform,+ capped,+ dust,+ creatorUsd: atomicsToUsd(creator),+ platformUsd: atomicsToUsd(platform),+ };+}++/** USDC atomics (BigInt) → a USD float for display. Never used for settlement. */+export function atomicsToUsd(atomics) {+ const n = typeof atomics === 'bigint' ? atomics : toAtomics(atomics);+ return Number(n) / 10 ** USDC_DECIMALS;+}++/** USDC float → atomic units (BigInt, floored). Mirrors agent-usdc-transfer. */+export function usdcToAtomics(usdc) {+ return BigInt(Math.max(0, Math.floor(Number(usdc) * 10 ** USDC_DECIMALS)));+}diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.jsindex 146c74907..12b169f85 100644--- a/api/_mcp3d/tools/studio.js+++ b/api/_mcp3d/tools/studio.js@@ -2023,7 +2023,7 @@ export const toolDefs = [additionalProperties: false,},async handler(args, auth) {- await enforce(limits.mcp3dRead || limits.mcp3dGenerate, auth);+ await enforce(limits.mcp3dStatus, auth);if (!isPersonaId(args.persona_id)) {return {content: [{ type: 'text', text: 'Error: that is not a valid persona_id.' }],@@ -2087,7 +2087,7 @@ export const toolDefs = [additionalProperties: false,},async handler(args, auth) {- await enforce(limits.mcp3dGenerate, auth);+ await enforce(limits.mcp3dGenerateFree, auth);if (!isPersonaId(args.persona_id)) {return {content: [{ type: 'text', text: 'Error: that is not a valid persona_id.' }],diff --git a/api/wk.js b/api/wk.jsindex e15e60317..cb7f7a66b 100644--- a/api/wk.js+++ b/api/wk.js@@ -1100,6 +1100,10 @@ async function handleX402Discovery(req, res) {serviceName: '$THREE Town Oracle',tags: ['three', 'market', 'signal', 'play', 'solana'],}),+ tokenIntel: withService({+ serviceName: 'three.ws Token Oracle',+ tags: ['crypto', 'market', 'signal', 'oracle', 'solana'],+ }),avatarShop: withService({serviceName: 'three.ws Avatar Shop',tags: ['3d', 'avatar', 'cosmetic', 'shop', 'wearable'],@@ -2016,7 +2020,7 @@ async function handleX402Discovery(req, res) {topic: {type: 'string',description:- 'Token ticker or CoinGecko id: btc, sol, eth, doge, …',+ 'Token ticker or CoinGecko id: btc, sol, eth, xrp, …',default: 'sol',},},@@ -2046,6 +2050,38 @@ async function handleX402Discovery(req, res) {}),};})(),+ (() => {+ const url = `${origin}/api/x402/token-intel`;+ const accepts = acceptsForPrice('10000', url);+ return {+ path: '/api/x402/token-intel',+ url,+ method: 'GET',+ description:+ 'three.ws Token Oracle — pay $0.01 USDC per call for live market intel on ANY token by contract address: price, 24 h change, market cap, liquidity, 24 h volume, and a bullish / bearish / neutral signal with a two-sentence rationale. Pass ?mint=<contract-address> (Solana mint or EVM 0x). The mint is supplied at runtime — generic coin-agnostic plumbing. Powered by live DexScreener data; this is the paid endpoint the CA-to-x402 resolver generates.',+ mimeType: 'application/json',+ serviceName: routeMeta.tokenIntel.serviceName,+ tags: routeMeta.tokenIntel.tags,+ iconUrl: routeMeta.tokenIntel.iconUrl,+ accepts,+ extensions: extensionsForAccepts(accepts, {+ method: 'GET',+ discoverable: true,+ input: { mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump' },+ inputSchema: {+ type: 'object',+ required: ['mint'],+ properties: {+ mint: {+ type: 'string',+ description:+ 'Token contract address — Solana base58 mint or EVM 0x address.',+ },+ },+ },+ }),+ };+ })(),(() => {// Avatar Shop pricing is per-rarity ($0.25 common → $3.00// legendary). The catalog advertises the rare tier ('500000' =diff --git a/apps-sdk/embodiment/face-expression.js b/apps-sdk/embodiment/face-expression.jsnew file mode 100644index 000000000..cd661a4cd--- /dev/null+++ b/apps-sdk/embodiment/face-expression.js@@ -0,0 +1,98 @@+/**+ * Emotion → face, the blendshape half of an embodied reply.+ *+ * Lip-sync (AvatarMouthTarget / A2FPlayer) owns the MOUTH while the body speaks;+ * this owns the EXPRESSION — the brows, eyes, cheeks, nose and smile/frown that+ * carry joy, sadness, anger, surprise. It indexes a rig's ARKit-52 morph targets+ * (the shared vocabulary in src/voice/arkit-blendshapes.js) and eases the current+ * weights toward a target set every frame, so an emotion fades in and out instead+ * of snapping.+ *+ * It deliberately does NOT drive jawOpen or the raw viseme channels — those belong+ * to the lip-sync driver, and writing them here would fight the mouth. A rig with+ * no facial morphs is fine: this becomes a no-op and the emotion still reads+ * through the body gesture the stage plays. That graceful degradation is the+ * point — emotion is never lost, it just moves from the face to the body.+ */++import { indexARKitMorphs, canonicalARKitName } from '../../src/voice/arkit-blendshapes.js';++// Channels the lip-sync driver owns — never written by the expression layer.+const MOUTH_RESERVED = new Set(['jawOpen', 'jawForward', 'jawLeft', 'jawRight']);++export class FaceExpression {+ constructor() {+ /** @type {Array<{mesh:object, index:Map<string,number>}>} */+ this._meshes = [];+ this._current = new Map(); // canonical ARKit name → current weight+ this._target = new Map(); // canonical ARKit name → target weight+ }++ /** Bind to a loaded model: collect every mesh that carries ARKit morphs. */+ attach(root) {+ this._meshes = [];+ this._current.clear();+ this._target.clear();+ root?.traverse?.((node) => {+ if (node.isMesh && node.morphTargetDictionary && node.morphTargetInfluences) {+ const index = indexARKitMorphs(node.morphTargetDictionary);+ if (index.size) this._meshes.push({ mesh: node, index });+ }+ });+ return this;+ }++ /** True if any expression morph is available on this rig. */+ hasMorphs() {+ return this._meshes.length > 0;+ }++ /**+ * Set the emotion face. Accepts a map of ARKit name → weight (0..1); unknown+ * names are normalized, mouth-reserved channels are dropped. Pass {} to relax+ * back to a neutral face.+ * @param {Record<string, number>} arkitWeights+ */+ setTarget(arkitWeights = {}) {+ const next = new Map();+ for (const [name, w] of Object.entries(arkitWeights)) {+ const canon = canonicalARKitName(name);+ if (!canon || MOUTH_RESERVED.has(canon)) continue;+ next.set(canon, Math.max(0, Math.min(1, Number(w) || 0)));+ }+ this._target = next;+ }++ /**+ * Ease current weights toward target and write them to every bound mesh.+ * @param {number} dt seconds since last frame+ */+ update(dt) {+ if (!this._meshes.length) return;+ // Time-constant ease (~180ms to most of the way), framerate-independent.+ const k = 1 - Math.exp(-dt / 0.18);+ const names = new Set([...this._current.keys(), ...this._target.keys()]);+ for (const name of names) {+ const cur = this._current.get(name) || 0;+ const tgt = this._target.get(name) || 0;+ const val = cur + (tgt - cur) * k;+ if (val < 0.001 && tgt === 0) this._current.delete(name);+ else this._current.set(name, val);+ }+ for (const { mesh, index } of this._meshes) {+ for (const [name, val] of this._current) {+ const i = index.get(name);+ if (i != null) mesh.morphTargetInfluences[i] = val;+ }+ }+ }++ /** Snap everything to neutral immediately (e.g. on persona swap). */+ reset() {+ this._target = new Map();+ for (const { mesh, index } of this._meshes) {+ for (const i of index.values()) mesh.morphTargetInfluences[i] = 0;+ }+ this._current.clear();+ }+}diff --git a/docs/ops/gcp-model-workers.md b/docs/ops/gcp-model-workers.mdnew file mode 100644index 000000000..59a047d80--- /dev/null+++ b/docs/ops/gcp-model-workers.md@@ -0,0 +1,174 @@+# GCP model workers — the self-host generation lanes++three.ws runs open 3D models on our **own** Google Cloud Run GPU workers, against+the project's GCP credits. These self-host lanes are the resilient default for+`/api/forge`: every generation we can serve on our own hardware costs no vendor+money and carries no BYOK dependency. This runbook covers what is deployed, the+env that wires it in, how routing picks a lane, and how to (re)start a worker.++> Scope: routing + operations for the **forge** generation lanes. The avatar+> reconstruction pipeline (controller + UniRig) is documented in+> `workers/deploy/README.md`; only its shared bearer secret overlaps here.++---++## The workers++Each model runs as its own Cloud Run service (NVIDIA L4 GPU, `us-central1`),+built and deployed from `workers/<dir>/cloudbuild.yaml`. They all speak the same+task shape — `POST /<endpoint> → { task_id }`, `GET /tasks/:id → { status,+result_* }` — and authenticate with one shared bearer secret.++| Lane (`backend` id) | Worker dir | Cloud Run service | Path served | What it does |+|---------------------|-----------------------|--------------------|-------------|--------------|+| `trellis_selfhost` | `workers/model-trellis` | `model-trellis` | `image` | Native single-hop image→3D (Microsoft TRELLIS). Accepts user photos and the FLUX-synthesized view for text prompts. Textured GLB. |+| `hunyuan3d` | `workers/model-hunyuan3d`| `model-hunyuan3d`| `image` | High-poly image-conditioned reconstruction (Tencent Hunyuan3D). Poly-budget aware. |+| `triposg` | `workers/model-triposg` | `model-triposg` | `sketch` | Sketch→3D (TripoSG-scribble): a drawing + a prompt naming it → untextured geometry. |++All three are `provider: 'gcp'`, `free: true`, scale-to-zero+(`_MIN_INSTANCES: "0"`). Scale-to-zero is why a **cold start** is real: a request+that lands on a spun-down container pays a one-time model-load before the job+runs. We surface that honestly (see *Cold start*), never as a fake timer.++The `remesh`, `stylize`, `texture`, `rembg`, `segment` workers back+post-generation tools (Game-Ready export, retexture, etc.), not the primary+generation lanes; they follow the same task shape and bearer secret.++---++## Environment++A self-host lane is **configured** only when its worker URL **and** the shared+key are present; a deployment missing either degrades cleanly — the lane drops+out of routing and the catalog reports it `configured: false`. Nothing is ever+faked.++| Env var | Used by | Notes |+|-------------------------|------------------------|-------|+| `MODEL_TRELLIS_URL` | `trellis_selfhost` | Cloud Run URL of `model-trellis`. |+| `GCP_HUNYUAN3D_URL` | `hunyuan3d` | Cloud Run URL of `model-hunyuan3d`. **Not** `GCP_RECONSTRUCTION_URL` — that is the avatar face pipeline, which rejects non-face images. |+| `GCP_TRIPOSG_URL` | `triposg` (sketch) | Cloud Run URL of `model-triposg`. |+| `GCP_RECONSTRUCTION_KEY`| all of the above | Shared bearer secret every worker checks. |+| `GCP_REMESH_URL` | Game-Ready export | `model`/`remesh` worker (post-gen). |+| `FORGE_PREFER_FREE` | routing (optional) | Defaults on. Set `false` only to restore the paid-default ordering once the paid account is funded. |++The URL each worker registers in Vercel is printed at the end of+`workers/deploy/deploy-all.sh`, or read it from+`gcloud run services describe <service> --region us-central1 --format='value(status.url)'`.++Secrets never appear in logs or the public catalog.++---++## How routing picks a lane++Routing is health-aware and free-first. For a request with no explicitly chosen+backend, `/api/forge` builds the ordered list of free lanes that can serve the+`(path, tier, userImages)` request (`freeLaneCandidates` in+`api/_lib/forge-tiers.js`), then picks with a cached liveness snapshot+(`api/_lib/forge-lane-health.js`):++1. **Healthy self-host first.** The first lane the liveness probe confirms `ok`,+ and our own GPU workers lead the ordering — so a healthy `trellis_selfhost`+ (then `hunyuan3d`) wins before any external free lane.+2. **Then another healthy free lane.** NVIDIA NIM (native text→3D, draft/standard)+ or HuggingFace Spaces (photos + high tier) when no self-host lane is healthy.+3. **Only then the paid default.** The standing Replicate TRELLIS lane is the+ last resort, used solely when **every** free lane is confirmed down or none is+ configured. BYOK vendors (Meshy/Tripo/Rodin) are never auto-selected — they+ stay explicitly selectable in the catalog.++Liveness combines two signals, both fail-open (missing telemetry never blocks a+lane — an unknown lane is treated as usable):++- A recent submit failure records a short **cooldown** in the shared cache, so+ every instance skips a just-failed lane until it expires.+- A cheap **authenticated GET** against the worker root (Cloud Run answers+ `<500` once routable). Round-trip latency doubles as a warmth signal.++The snapshot is cached per instance (~20s), so a burst of generations shares one+probe and the hot path usually pays no probe latency.++### Submit-time failover++Health routing skips a lane known-bad *before* submit. As a safety net, if the+chosen self-host worker still errors or times out at submit (cold, restarting,+throttled), the handler cools that lane and transparently retries the next+configured lane for the path — `trellis_selfhost` → `hunyuan3d` → HuggingFace →+paid Replicate — before surfacing any error. The `sketch` path has a single lane,+so a TripoSG failure returns a designed, retryable `503` rather than a dead error.+Every response reports the `backend` that actually served it, so a failover is+never silent.++### Cold start++When the liveness probe reaches a self-host worker but it answers slowly (a+scale-to-zero container spinning up), the response carries `cold_start: true` and+the `eta_seconds` is widened by that worker's cold-start budget+(`coldStartSeconds` in the registry). This only widens the **estimate** — actual+progress still comes from real polling of `GET /api/forge?job=<id>`.++---++## Health & cost observability++- **Live health:** `GET /api/forge?health` probes every lane (auth/quota gates,+ zero vendor spend), the limiter store, and recent real generation outcomes.+- **Free-vs-paid serve counts:** the same payload's `metrics.by_cost` reports how+ many generations were served `free` (our GPU workers + free external lanes) vs+ `paid` (Replicate platform credits / BYOK), plus `metrics.free_share`. This is+ the headline number proving the vendor-cost reduction. Counters are the rolling+ buckets in `api/_lib/forge-events.js`; they need Redis (omitted otherwise).+- **Structured logs:** every terminal generation logs one `evt:"forge_gen"` JSON+ line with `backend`, so a log drain can compute the same split with no Redis.++---++## (Re)starting a GPU worker++The workers scale to zero; they do not need a manual "start" for normal traffic —+the first request wakes a container (cold start). You restart/redeploy when+shipping a new image or recovering a wedged service.++**Redeploy a single worker** (Cloud Build builds the image and deploys the+service in one step):++```bash+gcloud builds submit --config workers/model-trellis/cloudbuild.yaml .+# swap in workers/model-hunyuan3d/… or workers/model-triposg/… as needed+```++**Provision/redeploy the whole pipeline** (idempotent; prints the URLs to put in+Vercel env):++```bash+PROJECT_ID=<gcp-project> SERVICES="hunyuan3d trellis triposg unirig" \+ workers/deploy/deploy-all.sh+```++**Force a fresh revision / clear a wedged container** without a code change:++```bash+gcloud run services update model-trellis --region us-central1 \+ --update-env-vars OPS_BUMP="$(git rev-parse --short HEAD)"+```++**Keep a worker warm** (eliminates cold starts at a standing GPU cost — use only+under sustained load):++```bash+gcloud run services update model-trellis --region us-central1 --min-instances 1+```++**Verify a worker is live** (same check the router's liveness probe makes):++```bash+curl -sS -o /dev/null -w '%{http_code}\n' \+ -H "authorization: Bearer $GCP_RECONSTRUCTION_KEY" "$MODEL_TRELLIS_URL"+# any <500 means up and routable+```++> Note: GPU-backed Cloud Run requires L4 quota in the region (`us-central1`).+> Quota approval can take hours — request it before a first deploy. The shared+> A100 workbench used for experiments is separate from these serving workers and+> may be stopped without affecting them.diff --git a/docs/roadmap/00-README.md b/docs/roadmap/00-README.mdindex d41423917..e1b077e4c 100644--- a/docs/roadmap/00-README.md+++ b/docs/roadmap/00-README.md@@ -21,11 +21,29 @@ three.ws is a large, live, single monorepo (see `STRUCTURE.md` for the full surf### The regression gate (copy/run at start and end of every prompt)```bash-npm run typecheck && npm test && npm run test:gate && \-npm run audit:routes && npm run audit:handlers && \-npm run audit:mcp && npm run smoke:mcp && npm run audit:pages+npm run gate```-If any of these don't exist or fail on a clean tree, note it in your report and proceed with the subset that runs green. Save the baseline output to `docs/roadmap/_generated/<prompt>/gate-before.txt` and the final to `gate-after.txt`. **`gate-after` must be no worse than `gate-before`.**+This alias (added to `package.json`) runs the **offline-safe** checks only:+`test:gate` (curated money/auth unit tests) + `audit:mcp` + `audit:routes` ++`audit:handlers` + `audit:pages` + `audit:hidden-guard`. It is intentionally the+*offline* subset — the project doctrine (see `scripts/test-gate.mjs`) keeps+catalog/handler-heavy and browser specs in `npm test`, because importing a hosted+MCP catalog pulls in DB/RPC clients that **block without live credentials** (an+import alone exceeds 60s). Do NOT write tests that `import` an `api/_mcp*/catalog.js`+— they hang the suite. Verify MCP tool contracts against a *running* server+(`npm run dev` → `tools/list`, or `npm run test:mcp`/`smoke:mcp` with creds), not by importing.++For full local verification when you have credentials + a browser: also run+`npm run typecheck` and `npm test`. Save the gate baseline to+`docs/roadmap/_generated/<prompt>/gate-before.txt` and the final to `gate-after.txt`.+**`gate-after` must be no worse than `gate-before`.**++### Reuse before you build+`docs/roadmap/REUSE-MAP.md` is a verified (June 2026) catalog of permissively-licensed+OSS to integrate instead of reinventing — compression, AR/USDZ, lipsync, text/image→3D,+splatting, PBR/restyle, scene layout, Solana minting, embed/OG. Each roadmap prompt's+"reuse" needs are covered there. Check it first; prefer ✅-licensed options; avoid the+⛔ list (non-commercial / unlicensed).---diff --git a/docs/roadmap/REUSE-MAP.md b/docs/roadmap/REUSE-MAP.mdnew file mode 100644index 000000000..b35286e65--- /dev/null+++ b/docs/roadmap/REUSE-MAP.md@@ -0,0 +1,109 @@+# OSS Reuse Map — integration targets for the 3D/crypto/AI roadmap++Verified June 2026. Use this before building anything in `docs/roadmap/*` — prefer integrating these proven, permissively-licensed projects over reinventing.++**License legend:** ✅ permissive (MIT/Apache-2.0/BSD/Zlib — safe to ship) · ⚠️ conditional (revenue/MAU/territory caps — read the fine print) · ⛔ AVOID (non-commercial / research / GPL/AGPL / unlicensed).++**Vercel reality:** no GPU model runs *inside* a Vercel function. The pattern everywhere: Vercel function = thin orchestrator that POSTs to a GPU host (Replicate/HF/Modal/Cloud Run) and polls/webhooks for the result URL. This matches the existing Forge architecture.++---++## 1. GLB/glTF compression (Draco + meshopt) — for roadmap 02, 04+| Capability | Repo / npm | License | Note |+|---|---|---|---|+| Build-time pipeline (primary) | donmccurdy/glTF-Transform · `@gltf-transform/cli`+`/core`+`/functions` | ✅ MIT | `gltf-transform optimize in.glb out.glb --compress meshopt`. Use as build/Vercel step. |+| Draco runtime decode | three `DRACOLoader` + `draco3d` (google/draco) | ✅ Apache-2.0 | Copy `three/examples/jsm/libs/draco/` to `public/`; `loader.setDRACOLoader`. Max geometry compression. |+| Meshopt runtime decode (prefer) | zeux/meshoptimizer · `meshoptimizer`,`gltfpack` | ✅ MIT | `loader.setMeshoptDecoder(MeshoptDecoder)`. Tiny + fast decode → best runtime default. |++## 2. Web AR + GLB→USDZ (iOS Quick Look) — for roadmap 04, 10+| Capability | Repo / npm | License | Note |+|---|---|---|---|+| Viewer + AR launcher | google/model-viewer · `@google/model-viewer` | ✅ Apache-2.0 | `<model-viewer ar ios-src="x.usdz">`. Android WebXR/Scene Viewer handled; iOS needs a `.usdz`. |+| USDZ on Vercel (primary) | three `USDZExporter` (`three/addons/exporters/USDZExporter.js`) | ✅ MIT | **Only zero-native-dep server path:** `await new USDZExporter().parseAsync(scene)`. |+| USDZ high-fidelity (fallback) | google/usd_from_gltf (Docker) | ✅ Apache-2.0 (archived 2024) | Native Pixar USD → Cloud Run only, call over HTTP. Use only if fidelity demands it. |++## 3. Headless WebGL / Three.js CI smoke — for roadmap 01, 04+| Capability | Repo / npm | License | Note |+|---|---|---|---|+| Browser-real smoke (primary) | `@playwright/test` (already a dep) | ✅ Apache-2.0 | Real WebGL headless via ANGLE+SwiftShader, no GPU. `toHaveScreenshot()`. Bump timeouts (SwiftShader slow). |+| Pure-Node pixel readback | stackgl/headless-gl · `gl` | ✅ BSD-2 | Feed context to `new THREE.WebGLRenderer({context})`. Native build + system GL on runner. jsdom alone has no WebGL. |++## 4. Audio-driven lipsync / visemes — for roadmap 03 (note: `audio-mcp` + `a2f-nvidia` tests already exist)+| Capability | Repo / npm | License | Note |+|---|---|---|---|+| Real-time browser (primary) | wass08/wawa-lipsync · `wawa-lipsync` | ✅ MIT | 100% in-browser Web Audio, zero deps. `connectAudio()`+`processAudio()` in RAF → morph targets. |+| Real-time MFCC-accurate | mrxz/wLipSync · `wlipsync` | ✅ MIT | WASM uLipSync port; renderer-agnostic viseme weights. |+| Turnkey talking-avatar | met4citizen/TalkingHead (+HeadTTS) | ✅ MIT | Full Oculus OVR + ARKit viseme pipeline on RPM/Mixamo GLB. |+| Precomputed | DanielSWolf/rhubarb-lip-sync · `rhubarb-lip-sync-wasm` | ✅ MIT-equiv | WASM in a Vercel fn on TTS audio → viseme JSON track for deterministic playback. |++## 5. Text/image-to-3D hosted APIs — for roadmap 02, 06, 07 (TRELLIS already powers `forge_free`)+| Model | Repo · endpoint | License | Note |+|---|---|---|---|+| **TRELLIS** (top pick) | microsoft/TRELLIS · Replicate `firtoz/trellis` · free NVIDIA NIM | ✅ MIT | Cleanest license; already wired. |+| **TripoSR** (fastest) | VAST-AI/TripoSR · Replicate `camenduru/tripo-sr` | ✅ MIT | Single-image, cheap/fast. |+| **InstantMesh** (multi-view) | TencentARC/InstantMesh · Replicate `camenduru/instantmesh` | ✅ Apache-2.0 | Image→multi-view→mesh; also covers §6. |+| Hunyuan3D-2.1/3.1 (best texture) | Tencent-Hunyuan/Hunyuan3D-2.1 · Replicate `tencent/hunyuan-3d-3.1` | ⚠️ Tencent Community | **>1M MAU prohibited; void in EU/UK/South Korea.** Bake into terms. |+| Stable-Fast-3D / SPAR3D | Stability-AI/stable-fast-3d | ⚠️ Stability Community | Free commercial only ≤ $1M revenue. Prefer an MIT model. |+| License-clean self-host | TripoSG (MIT), Step1X-3D (Apache-2.0), Direct3D-S2 (MIT), Hi3DGen (MIT) | ✅ | Deploy behind Replicate-custom/Modal/RunPod. |++## 6. Sketch-to-3D, multi-view, photogrammetry, splatting — for roadmap 07+| Capability | Repo · endpoint | License | Note |+|---|---|---|---|+| Multi-view reconstruction | InstantMesh (see §5) | ✅ Apache-2.0 | Primary hosted multi-view path. |+| Sketch-to-3D | HF `linoyts/sketch-to-3d` (TRELLIS) · `VAST-AI/TripoSG-scribble` | ✅ MIT | Feed clean sketch as input image to TRELLIS/TripoSR. |+| Photogrammetry SfM | colmap/colmap | ✅ BSD-3 | GPU C++ binary; GPU-host orchestration. |+| Splat trainer (commercial) | nerfstudio-project/gsplat | ✅ Apache-2.0 | Clean-room rasterizer; GPU training. |+| Splat in-browser | ArthurBrussee/brush | ✅ Apache-2.0 | Rust+WebGPU+WASM; train in visitor's browser, zero server GPU. |+| Splat viewer/editor | playcanvas/supersplat | ✅ MIT | Client-side WASM/WebGL editor, embeddable from Vercel. |+| ⛔ AVOID | graphdeco-inria/gaussian-splatting + `diff-gaussian-rasterization` | non-commercial | License travels even on Replicate wrappers — use gsplat. |++## 7. PBR material editing + AI re-texturing — for roadmap 06+| Capability | Repo / npm | License | Note |+|---|---|---|---|+| Material/IBL base | `three` (`MeshPhysicalMaterial`,`PMREMGenerator`,`HDRLoader`) | ✅ MIT | Already in stack. |+| Editor GUI | `lil-gui` (alt `tweakpane`) | ✅ MIT | Bind controllers to material props for a live PBR panel. |+| Accurate preview | gkjohnson/three-gpu-pathtracer | ✅ MIT | Path-traced final-frame preview; lazy-load. |+| Polish | pmndrs `postprocessing` | ✅ Zlib | Bloom/tonemapping. |+| AI re-texture (primary) | TRELLIS via Replicate `firtoz/trellis`/fal | ✅ MIT | Only fully-permissive commercial option; gate behind $THREE/x402. |+| ⛔ AVOID | TEXTure, Text2Tex, Paint3D, Hunyuan3D-Paint | non-commercial/capped | Research-only or territory/MAU-restricted. |++## 8. Text→scene composition + editor enhancements — for roadmap 05+| Capability | Repo / npm | License | Note |+|---|---|---|---|+| Scene-layout planner (primary) | weixi-feng/LayoutGPT | ✅ MIT | Re-port the LLM bbox-layout prompt into a Node/Vercel fn via the worker proxy — no Python dep. |+| Manipulation gizmo | three `TransformControls` | ✅ MIT | Already in dep. |+| Fast picking | `three-mesh-bvh` | ✅ MIT | Raycast/hover-select at scale. |+| Clean imports | `three-stdlib`, `@pmndrs/vanilla` | ✅ MIT | Tree-shakeable examples + framework-free helpers. |+| ⛔ AVOID | LayoutVLM (unlicensed), SpatialLM (CC-BY-NC) | — | Not commercially usable. |++## 9. Solana SPL NFT minting + metadata + provenance — for roadmap 08 (deps already in package.json)+| Capability | npm | License | Note |+|---|---|---|---|+| NFT standard (new mints) | `@metaplex-foundation/mpl-core` | ✅ Apache-2.0 | Single-account, cheaper rent, built-in royalty/freeze/provenance plugins. **Already a dep.** |+| Legacy/pNFT compat | `@metaplex-foundation/mpl-token-metadata` | ✅ Apache-2.0 | Only for legacy SPL/pNFT. |+| Required substrate | `@metaplex-foundation/umi` (+ bundle-defaults) | ✅ MIT | **Already a dep.** Vite: add `vite-plugin-node-polyfills` for Buffer/crypto. |+| Raw tx / RPC | `@solana/kit` (web3.js v2 successor) | ✅ MIT | Current recommended SDK. |+| Signing | `@noble/ed25519` | ✅ MIT | Prefer noble for new provenance signing. |+| Permanent metadata upload | `@metaplex-foundation/umi-uploader-irys` | ✅ MIT | `uploadJson()` → Arweave URI into mpl-core create, server-side. **Bundlr is now Irys — do NOT use the old bundlr packages.** |++## 10. Embeddable 3D + oEmbed + server-side OG/thumbnail — for roadmap 10+| Capability | npm / source | License | Vercel verdict |+|---|---|---|---|+| Embed component | `@google/model-viewer` | ✅ Apache-2.0 | Standalone `/embed/:id` page consumers iframe. |+| oEmbed provider | oembed.com spec (no lib) | spec | Hand-roll `/api/oembed` returning `type:"rich"` + `thumbnail_url`; add discovery `<link>`. ~30 lines. |+| GLB→PNG (primary) | `poppygl` | ✅ MIT | **Pure-JS software rasterizer — runs on vanilla Vercel Node fn, zero native deps.** Ideal for `/api/og/:id.png`. |+| GLB→PNG (high fidelity) | `@shopify/screenshot-glb` | ✅ MIT | Puppeteer+model-viewer. On Vercel use `puppeteer-core`+`@sparticuz/chromium`; **needs `--enable-unsafe-swiftshader --use-gl=angle --use-angle=swiftshader`** or WebGL renders blank. |++---++## Top-line picks+- **Compression:** `@gltf-transform/cli` (build) + `MeshoptDecoder` (runtime); Draco for max-compression assets.+- **AR:** `<model-viewer>` + three `USDZExporter` on Vercel; Cloud Run `usd_from_gltf` only if fidelity demands.+- **CI:** Playwright (already a dep) for canvas smoke; `gl` for pure-Node pixel asserts.+- **Lipsync:** wawa-lipsync (live) + Rhubarb-WASM (precomputed) — but check `audio-mcp` first, it may already cover this.+- **Gen-3D:** TRELLIS (MIT, already wired), TripoSR (fast), InstantMesh (multi-view); Hunyuan only with MAU/EU-UK-KR terms baked in.+- **Splatting:** gsplat/Brush + SuperSplat — never the Inria 3DGS rasterizer.+- **Solana:** mpl-core + Umi + umi-uploader-irys + @solana/kit + @noble/ed25519 (mpl-core, umi already deps).+- **Embed/OG:** `<model-viewer>` + hand-rolled oEmbed + poppygl (screenshot-glb as fidelity fallback).++**Hard AVOID:** Inria 3D Gaussian Splatting, TEXTure/Text2Tex/Paint3D, LayoutVLM, SpatialLM weights, Meshroom (serverless), Blender headless. **Read fine print (⚠️):** Hunyuan3D (1M MAU + EU/UK/KR exclusion), SF3D/SPAR3D ($1M revenue cap).diff --git a/docs/roadmap/_generated/02/gate-before.txt b/docs/roadmap/_generated/02/gate-before.txtindex d21c825a1..f9404224b 100644--- a/docs/roadmap/_generated/02/gate-before.txt+++ b/docs/roadmap/_generated/02/gate-before.txt@@ -30,3 +30,7 @@ stderr | tests/auto-rig-completion.test.js > 6a — cron recovers an open job fr× serves /style.css from dist root 53ms❯ tests/api/agent-memory.test.js (22 tests | 1 failed) 148ms× truncates content longer than 10,000 characters 18ms+ ❯ tests/api/x402-discovery-parity.test.js (4 tests | 3 failed) 615330ms+ × lists every paid /api/x402/* endpoint (no silent drift) 256105ms+ × catalogs both hosted MCP servers with their own identities 199182ms+ × every cataloged x402 resource carries a price and at least one accept 159733msdiff --git a/docs/roadmap/_generated/03/gate-before.txt b/docs/roadmap/_generated/03/gate-before.txtindex 5e34d529f..f1f46b566 100644--- a/docs/roadmap/_generated/03/gate-before.txt+++ b/docs/roadmap/_generated/03/gate-before.txt@@ -30,3 +30,7 @@ stderr | tests/auto-rig-completion.test.js > 6a — cron recovers an open job fr× serves /style.css from dist root 49ms❯ tests/api/agent-memory.test.js (22 tests | 1 failed) 201ms× truncates content longer than 10,000 characters 52ms+ ❯ tests/api/x402-discovery-parity.test.js (4 tests | 3 failed) 616332ms+ × lists every paid /api/x402/* endpoint (no silent drift) 257172ms+ × catalogs both hosted MCP servers with their own identities 199214ms+ × every cataloged x402 resource carries a price and at least one accept 159682msdiff --git a/docs/roadmap/_generated/07/gate-before.txt b/docs/roadmap/_generated/07/gate-before.txtindex 3c5d69569..9f0c684c6 100644--- a/docs/roadmap/_generated/07/gate-before.txt+++ b/docs/roadmap/_generated/07/gate-before.txt@@ -2,39 +2,3 @@> [email protected] typecheck> tsc -p jsconfig.json--> [email protected] test:gate-> node scripts/test-gate.mjs--[test-gate] running 7 critical-path test files…-- RUN v4.1.7 /workspaces/three.ws--- Test Files 7 passed (7)- Tests 79 passed (79)- Start at 22:21:48- Duration 141.01s (transform 30.42s, setup 0ms, import 220.41s, tests 2.96s, environment 82ms)--[test-gate] ✓ all critical-path tests passed--> [email protected] audit:routes-> node scripts/verify-routes.mjs--Route verify — 231 catalog pages, 908 main routes, 1 post-filesystem routes.- modeled dist files: 1431 · canonical-covered: 231 · literal page routes checked for shadows: 377- filesystem boundary (handle:filesystem) present: yes--✓ static checks pass: every catalog page reachable, unknown paths → designed 404, no shadowed page routes.--> [email protected] audit:handlers-> node scripts/audit-empty-handlers.mjs--✓ audit-empty-handlers: all API handlers export a body (1185 checked)--> [email protected] audit:mcp-> node scripts/audit-mcp-manifests.mjs--[audit:mcp] server-studio.json: description is 186 chars (registry max is 100)-[audit:mcp] 1 violation(s) across 15 manifests-EXIT:1diff --git a/marketplace/plugins/three-ws-3d/README.md b/marketplace/plugins/three-ws-3d/README.mdnew file mode 100644index 000000000..b0bdf7149--- /dev/null+++ b/marketplace/plugins/three-ws-3d/README.md@@ -0,0 +1,44 @@+# three.ws 3D Forge — Claude Code plugin++Generate textured 3D models and rigged, animation-ready avatars from text or images, directly inside Claude Code.++## Install++```+/plugin marketplace add nirholas/three.ws+/plugin install three-ws-3d@three-ws+```++Then `/reload-plugins`. The plugin's skills appear under the `three-ws-3d:` namespace and the bundled MCP tools list automatically.++## Skills++| Skill | Tool | Lane |+| --- | --- | --- |+| `three-ws-3d:forge-3d` | `forge_free` | **Free** text → 3D (NVIDIA NIM / TRELLIS) |+| `three-ws-3d:text-to-avatar` | `text_to_avatar` | Paid — $0.15 USDC |+| `three-ws-3d:mesh-forge` | `mesh_forge` | Paid — $0.25 USDC |+| `three-ws-3d:auto-rig` | `rig_mesh` / `forge_avatar` | Paid — $0.20 / $0.45 USDC |++Every skill returns a downloadable `glbUrl` plus a `https://three.ws/viewer?src=…` preview link.++## Bundled MCP servers++Installing the plugin wires three published servers with zero extra config:++- **`@three-ws/mcp-server`** — the full generation surface: `forge_free` (free), `text_to_avatar`, `mesh_forge`, `rig_mesh`, `forge_avatar`. Paid tools settle over x402; set `MCP_SVM_PAYMENT_ADDRESS` to enable them.+- **`@three-ws/scene-mcp`** — `compose_scene` / `get_scene` / `list_scenes`: turn a sentence into a placed diorama plan. Free, no key.+- **`@three-ws/avatar-mcp`** — render a live, rotatable avatar inline, get a paste-anywhere embed iframe, or fetch avatar metadata. Free, no key.++## Free vs paid++- **Free, no wallet:** `forge_free` (draft/standard/high text→3D), plus all of `scene-mcp` and `avatar-mcp`.+- **Paid over x402 (USDC):** `text_to_avatar`, `mesh_forge`, `rig_mesh`, `forge_avatar`. A call without a payment payload returns a `PaymentRequired` result describing the price.++`$THREE` (`FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`) is the only token of the three.ws platform.++## Links++- Forge web app: https://three.ws/forge+- Viewer: https://three.ws/viewer+- Source: https://github.com/nirholas/three.wsdiff --git a/mcp-server/src/lib/delegate-transport.js b/mcp-server/src/lib/delegate-transport.jsnew file mode 100644index 000000000..e12a73907--- /dev/null+++ b/mcp-server/src/lib/delegate-transport.js@@ -0,0 +1,56 @@+// Shared transport for delegating a message to a three.ws-registered agent.+//+// Both `agent_delegate_action` (raw delegation) and `agent_hire` (delegation+// wrapped in real x402 settlement + provenance) run the remote agent through+// this one path: POST /api/agents/talk, which drives the target agent's+// configured brain (its Claude model + system prompt from its embed policy).+//+// The call is NOT retried: delivering a message to an agent is not idempotent,+// so a replay could double-run / double-bill the target. The timeout is+// generous because a real brain response can take many seconds.++import { resilientFetch } from './resilient-fetch.js';++function talkEndpoint() {+ const v = process.env.MCP_AGENT_TALK_ENDPOINT;+ return v && v.trim() ? v.trim() : 'https://three.ws/api/agents/talk';+}++/**+ * Run a delegated message against a three.ws agent.+ *+ * @param {object} args+ * @param {string} args.agentId+ * @param {string} args.message+ * @param {string} [args.model]+ * @param {number} [args.timeoutMs=60000]+ * @returns {Promise<{ok:boolean, data:object|null, status:number, error?:string}>}+ * On transport failure, ok=false with an error string (never throws).+ */+export async function runDelegation({ agentId, message, model, timeoutMs = 60_000 }) {+ let res;+ try {+ res = await resilientFetch(+ talkEndpoint(),+ {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ agentId, message, model }),+ },+ { timeoutMs, retries: 0, label: 'agent-delegate' },+ );+ } catch (err) {+ return { ok: false, data: null, status: 0, error: err?.message || 'fetch failed' };+ }+ const data = await res.json().catch(() => null);+ if (!res.ok || !data || data.ok === false) {+ return {+ ok: false,+ data,+ status: res.status,+ error: data?.code || data?.error || `endpoint returned ${res.status}`,+ message: data?.message || `endpoint returned ${res.status}`,+ };+ }+ return { ok: true, data, status: res.status };+}diff --git a/mcp-server/src/tools/_lineage.js b/mcp-server/src/tools/_lineage.jsnew file mode 100644index 000000000..b4e55afff--- /dev/null+++ b/mcp-server/src/tools/_lineage.js@@ -0,0 +1,286 @@+// Conversational-refinement lineage — the pure core of iterative 3D.+//+// This module is the single source of truth for two things shared by BOTH the+// free OpenAI Apps studio (api/_mcp-studio) and the paid stdio MCP server+// (mcp-server/src/tools/refine-model.js):+//+// 1. composeRefinement(parentPrompt, instruction) — how a natural-language+// change ("make it metallic", "bigger helmet") is folded into the prior+// prompt to drive a REAL anchored re-generation. No faked diffing: the+// refined prompt is what the generator actually runs.+// 2. version lineage — every refinement records parent → child so a client+// can show a version strip and the user can revert or branch. The lineage+// array IS the durable record returned in structuredContent.+//+// It is intentionally dependency-free (no fetch, no DB, no payment/schema) so it+// loads unchanged in the published npm package, in the Vercel api/ bundle, and+// in the unit tests. It carries ZERO payment, royalty, coin, or wallet surface —+// conversational iteration is free on every track.++// Leading filler an imperative instruction tends to open with. Stripped so the+// remainder reads as a descriptive modifier the text-to-3D model can condition+// on ("make it metallic" → "metallic", "now add wings" → "add wings"). Order+// matters: longer phrases first so "make the" is tried before "make".+const INSTRUCTION_PREFIXES = [+ 'could you please',+ 'can you please',+ 'i would like it to be',+ 'i want it to be',+ 'i want it to',+ 'i want it',+ 'i want',+ 'please can you',+ 'could you',+ 'can you',+ 'please make it',+ 'please make the',+ 'please make',+ 'please',+ 'now make it',+ 'now make the',+ 'now make',+ 'now',+ 'make it more',+ 'make it',+ 'make the',+ 'make',+ 'turn it into a',+ 'turn it into an',+ 'turn it into',+ 'change it to a',+ 'change it to an',+ 'change it to',+ 'change it so it is',+ 'change it so its',+ 'change the',+ 'change it',+ 'give it',+ 'lets',+ "let's",+];++const MAX_PROMPT_LEN = 1000;++/**+ * Normalize a free-text instruction into a compact descriptive modifier:+ * trim, collapse whitespace, drop a leading polite/imperative prefix, and strip+ * a trailing period. Pure and deterministic — the value tested in isolation.+ *+ * @param {string} instruction+ * @returns {string} the cleaned modifier (may equal the input when no prefix matched)+ */+export function normalizeInstruction(instruction) {+ let s = String(instruction || '')+ .replace(/\s+/g, ' ')+ .trim();+ if (!s) return '';+ const lower = s.toLowerCase();+ for (const prefix of INSTRUCTION_PREFIXES) {+ if (lower === prefix) {+ // The instruction was pure filler with no payload — keep it as-is so the+ // caller still has something to fold in rather than an empty modifier.+ return s;+ }+ if (lower.startsWith(prefix + ' ')) {+ s = s.slice(prefix.length + 1).trim();+ break;+ }+ }+ return s.replace(/[.\s]+$/, '').trim();+}++/**+ * Fold a natural-language change into the prior prompt, anchoring the new+ * generation to the previous result. The parent prompt is the base (so form,+ * subject, and materials carry forward) and the cleaned instruction is appended+ * as an explicit modifier clause. Deterministic; capped to the generator limit.+ *+ * When the parent prompt is unknown (e.g. an image-only origin) the instruction+ * stands alone — still a real prompt, just without carry-forward text.+ *+ * @param {string} parentPrompt the prompt that produced the parent model+ * @param {string} instruction the requested change+ * @returns {string} the prompt the generator will actually run+ */+export function composeRefinement(parentPrompt, instruction) {+ const base = String(parentPrompt || '')+ .replace(/\s+/g, ' ')+ .trim();+ const modifier = normalizeInstruction(instruction);+ let composed;+ if (base && modifier) composed = `${base}, ${modifier}`;+ else composed = base || modifier;+ if (composed.length > MAX_PROMPT_LEN) composed = composed.slice(0, MAX_PROMPT_LEN).trim();+ return composed;+}++// ── Version lineage ──────────────────────────────────────────────────────────+//+// A lineage is an ordered array of immutable version records. Index 0 is the+// origin; each later version points at its parent by index. Reverting does not+// mutate history — it moves the "active" pointer; branching appends a child off+// an earlier (non-leaf) version, producing a tree.++/**+ * Start a lineage from an origin model (the first generation in a thread).+ * @param {{ glbUrl:string, viewerUrl?:string, prompt?:string }} origin+ * @returns {Array<object>} a one-element lineage+ */+export function seedLineage({ glbUrl, viewerUrl, prompt }) {+ return [+ {+ index: 0,+ parentIndex: null,+ glbUrl,+ viewerUrl: viewerUrl || null,+ prompt: prompt || null,+ instruction: null,+ refKind: 'origin',+ },+ ];+}++/**+ * Append a refined version. Defaults the parent to the lineage's last entry;+ * pass `parentIndex` to branch off an earlier version. Returns a NEW array+ * (immutable history) — never mutates the input.+ *+ * @param {Array<object>} lineage+ * @param {{ glbUrl:string, viewerUrl?:string, prompt?:string, instruction?:string,+ * refKind?:string, parentIndex?:number }} version+ * @returns {Array<object>} the extended lineage+ */+export function appendVersion(lineage, version) {+ const prior = Array.isArray(lineage) ? lineage : [];+ const index = prior.length;+ const parentIndex =+ Number.isInteger(version.parentIndex) && version.parentIndex >= 0 && version.parentIndex < index+ ? version.parentIndex+ : index > 0+ ? index - 1+ : null;+ const next = {+ index,+ parentIndex,+ glbUrl: version.glbUrl,+ viewerUrl: version.viewerUrl || null,+ prompt: version.prompt || null,+ instruction: version.instruction || null,+ refKind: version.refKind || 'text',+ };+ return [...prior, next];+}++/**+ * The parent index a branch off `index` should use for its next append. Thin,+ * but names the intent at call sites (branchFrom(lineage, 1) reads clearly).+ */+export function branchFrom(lineage, index) {+ const n = Array.isArray(lineage) ? lineage.length : 0;+ if (!Number.isInteger(index) || index < 0 || index >= n) {+ throw new Error(`branchFrom: no version at index ${index}`);+ }+ return index;+}++/**+ * Resolve the active version when reverting to `index`. History is immutable, so+ * a revert is just a validated pointer move; the returned object is the version+ * the client should display.+ *+ * @returns {{ activeIndex:number, active:object }}+ */+export function revertTo(lineage, index) {+ const arr = Array.isArray(lineage) ? lineage : [];+ const found = arr.find((v) => v.index === index);+ if (!found) throw new Error(`revertTo: no version at index ${index}`);+ return { activeIndex: index, active: found };+}++/**+ * Validate lineage integrity and return the root→leaf chain for `activeIndex`+ * (defaults to the highest index). Pure — the invariant checks are unit-tested.+ *+ * Checks: indices are unique and contiguous from 0; exactly one root+ * (parentIndex === null); every non-root parent points at a strictly-earlier+ * existing index (which forbids cycles); the active index exists.+ *+ * @returns {{ ok:boolean, errors:string[], roots:number[], leaves:number[],+ * chain:object[], activeIndex:number }}+ */+export function buildLineageChain(lineage, activeIndex) {+ const arr = Array.isArray(lineage) ? lineage : [];+ const errors = [];+ const byIndex = new Map();+ for (const v of arr) {+ if (byIndex.has(v.index)) errors.push(`duplicate index ${v.index}`);+ byIndex.set(v.index, v);+ }+ // Contiguous-from-0 keeps the array position == index, the contract the+ // client's version strip relies on.+ for (let i = 0; i < arr.length; i++) {+ if (!byIndex.has(i)) errors.push(`missing index ${i}`);+ }+ const roots = arr.filter((v) => v.parentIndex === null || v.parentIndex === undefined).map((v) => v.index);+ if (roots.length !== 1) errors.push(`expected exactly one root, found ${roots.length}`);+ const childCount = new Map();+ for (const v of arr) {+ if (v.parentIndex === null || v.parentIndex === undefined) continue;+ if (!byIndex.has(v.parentIndex)) {+ errors.push(`version ${v.index} references missing parent ${v.parentIndex}`);+ } else if (v.parentIndex >= v.index) {+ // A parent at or after the child would allow a cycle; the contiguous+ // append model guarantees parents are strictly earlier.+ errors.push(`version ${v.index} parent ${v.parentIndex} is not earlier`);+ }+ childCount.set(v.parentIndex, (childCount.get(v.parentIndex) || 0) + 1);+ }+ const leaves = arr.filter((v) => !childCount.has(v.index)).map((v) => v.index);++ const active = Number.isInteger(activeIndex) ? activeIndex : arr.length ? arr.length - 1 : -1;+ if (arr.length && !byIndex.has(active)) errors.push(`active index ${active} does not exist`);++ // Walk parent links from the active version up to the root.+ const chain = [];+ if (errors.length === 0 && byIndex.has(active)) {+ let cursor = active;+ const guard = new Set();+ while (cursor !== null && cursor !== undefined) {+ if (guard.has(cursor)) {+ errors.push(`cycle detected at index ${cursor}`);+ break;+ }+ guard.add(cursor);+ const node = byIndex.get(cursor);+ chain.unshift(node);+ cursor = node.parentIndex;+ }+ }++ return {+ ok: errors.length === 0,+ errors,+ roots,+ leaves,+ chain,+ activeIndex: active,+ };+}++/**+ * Compact, client-facing view of a lineage for a version strip: just what the+ * widget needs to render thumbnails and wire revert/branch. No identifiers.+ */+export function summarizeLineage(lineage, activeIndex) {+ const arr = Array.isArray(lineage) ? lineage : [];+ const active = Number.isInteger(activeIndex) ? activeIndex : arr.length ? arr.length - 1 : 0;+ return arr.map((v) => ({+ index: v.index,+ parentIndex: v.parentIndex,+ glbUrl: v.glbUrl,+ viewerUrl: v.viewerUrl || null,+ label: v.refKind === 'origin' ? 'Original' : v.instruction || `Version ${v.index}`,+ instruction: v.instruction || null,+ active: v.index === active,+ }));+}diff --git a/mcp-server/src/tools/agent-delegate-action.js b/mcp-server/src/tools/agent-delegate-action.jsindex dd028faa5..a95ec0de5 100644--- a/mcp-server/src/tools/agent-delegate-action.js+++ b/mcp-server/src/tools/agent-delegate-action.js@@ -14,17 +14,12 @@ import { z } from 'zod';import { paid, toolError } from '../payments.js';import { jsonSchemaFromZod } from './_shared.js';-import { resilientFetch } from '../lib/resilient-fetch.js';+import { runDelegation } from '../lib/delegate-transport.js';const TOOL_NAME = 'agent_delegate_action';const TOOL_DESCRIPTION ='Send a message to a three.ws-registered agent and receive its response. The target agent uses its configured brain (Claude model and system prompt set via its embed policy). Agents that have opted out of MCP delegation are refused. Useful for agent-to-agent collaboration and tool composition. Paid: $0.01 USDC.';-function env(k, def) {- const v = process.env[k];- return v && String(v).trim() ? String(v).trim() : def;-}-// Single source of truth: Zod shape carries descriptions + bounds; JSON Schema// derived. The prior hand-written JSON Schema left `model` with no bounds; the// Zod (min 1, max 100) is stricter and now wins, surfacing those bounds in the@@ -66,33 +61,17 @@ export async function buildAgentDelegateActionTool() {},},async ({ agentId, message, model }) => {- const endpoint = env('MCP_AGENT_TALK_ENDPOINT', 'https://three.ws/api/agents/talk');- let res;- try {- // Bounded timeout but NO retry: delivering a message to an agent is- // not idempotent, so a replay could double-send / double-bill the- // target. A long brain response is expected, so the timeout is- // generous.- res = await resilientFetch(- endpoint,- {- method: 'POST',- headers: { 'content-type': 'application/json' },- body: JSON.stringify({ agentId, message, model }),- },- { timeoutMs: 60_000, retries: 0, label: 'agent-delegate' },- );- } catch (err) {- return toolError('upstream_unreachable', err?.message || 'fetch failed');- }- const data = await res.json().catch(() => null);- if (!res.ok || !data || data.ok === false) {+ const result = await runDelegation({ agentId, message, model });+ if (!result.ok) {+ if (result.status === 0) {+ return toolError('upstream_unreachable', result.error || 'fetch failed');+ }return toolError(- data?.code || data?.error || 'agent_delegate_failed',- data?.message || `endpoint returned ${res.status}`,+ result.error || 'agent_delegate_failed',+ result.message || result.error || `endpoint returned ${result.status}`,);}- return data;+ return result.data;},);return {diff --git a/mcp-server/src/tools/agent-hire-discover.js b/mcp-server/src/tools/agent-hire-discover.jsnew file mode 100644index 000000000..48b1c0eeb--- /dev/null+++ b/mcp-server/src/tools/agent-hire-discover.js@@ -0,0 +1,130 @@+// `agent_hire_discover` — paid MCP tool that, given a task description, finds+// candidate three.ws agents to hire, ranked by a composite of task fit, live+// ERC-8004 reputation, and real engagement, and quotes the up-front hire price.+//+// Pricing: $0.01 USDC, settled `exact` in USDC on Solana mainnet.+//+// This is step one of the legible agent-economy loop: discover → reputation-rank+// → hire (agent_hire). Every candidate comes from the live three.ws public+// directory; reputation is read straight from the canonical ERC-8004 registries+// — no mock data, no cached snapshots. The shortlist carries the reputation+// evidence behind each rank so the host model can choose transparently, plus the+// exact USDC price agent_hire will charge.++import { z } from 'zod';++import { paid, toolError } from '../payments.js';+import { jsonSchemaFromZod } from './_shared.js';+import { fetchCandidates, rankCandidates } from '../lib/agent-registry.js';+import { guardrailConfig, formatUsd } from '../lib/agent-commerce.js';++const TOOL_NAME = 'agent_hire_discover';+const TOOL_DESCRIPTION =+ 'Discover three.ws agents to hire for a task, ranked by task fit + live ERC-8004 on-chain reputation + real engagement. Returns a shortlist where each candidate carries its reputation evidence, capability/task-match score, and the exact USDC price agent_hire will settle. Optionally gate by a minimum reputation. Step one of the agent-to-agent commerce loop (discover → hire). Paid: $0.01 USDC.';++const inputZodShape = {+ task: z+ .string()+ .min(3)+ .max(400)+ .describe('Plain-language description of the work to delegate (used to rank candidates).'),+ skill: z+ .string()+ .min(1)+ .max(64)+ .describe('Optional skill-slug filter (exact match against an agent\'s declared skills).')+ .optional(),+ limit: z+ .number()+ .int()+ .min(1)+ .max(10)+ .describe('Max candidates to return (default 5).')+ .optional(),+ minReputation: z+ .number()+ .describe('Optional floor: drop agents whose on-chain ERC-8004 average is below this.')+ .optional(),+};++const inputJsonSchema = jsonSchemaFromZod(inputZodShape);++export async function buildAgentHireDiscoverTool() {+ const handler = await paid(+ {+ toolName: TOOL_NAME,+ description: TOOL_DESCRIPTION,+ scheme: 'exact',+ priceUsd: '$0.01',+ inputSchema: inputJsonSchema,+ example: { task: 'summarise the latest pump.fun graduations in 3 bullets', limit: 5 },+ outputExample: {+ ok: true,+ task: 'summarise the latest pump.fun graduations',+ quotedHirePriceUsd: '$0.05',+ count: 1,+ candidates: [+ {+ agentId: '5a4b3c2d-1234-5678-90ab-cdef01234567',+ name: 'Pump Sage',+ score: 0.82,+ capabilityMatch: 0.75,+ reputation: { average: 0.94, count: 12, source: 'erc8004', chain: 'Base' },+ quotedPriceUsd: '$0.05',+ evidence: 'ERC-8004 reputation 0.94 across 12 vouch(es) on Base · task fit 75%',+ },+ ],+ },+ },+ async ({ task, skill, limit, minReputation }) => {+ let candidates;+ try {+ candidates = await fetchCandidates({ q: task, skill, limit: 24 });+ } catch (err) {+ return toolError('registry_unreachable', err?.message || 'agent directory unavailable');+ }++ const cfg = guardrailConfig();+ const effectiveMin =+ typeof minReputation === 'number' ? minReputation : cfg.minReputation || undefined;++ const ranked = await rankCandidates({+ task,+ candidates,+ limit: limit || 5,+ minReputation: effectiveMin,+ });++ const quoted = formatUsd(cfg.hirePriceUsd);+ return {+ ok: true,+ task,+ skill: skill || null,+ minReputation: effectiveMin ?? null,+ quotedHirePriceUsd: quoted,+ count: ranked.length,+ candidates: ranked.map((c) => ({ ...c, quotedPriceUsd: quoted })),+ note:+ ranked.length === 0+ ? 'No agents matched. Broaden the task wording or drop the skill/minReputation filter.'+ : `Hire any candidate with agent_hire — it will settle ${quoted} USDC and return a provenance receipt.`,+ fetchedAt: new Date().toISOString(),+ };+ },+ );+ return {+ name: TOOL_NAME,+ title: 'Agent hire — discover ($0.01)',+ description: TOOL_DESCRIPTION,+ inputSchema: inputZodShape,+ // Read-only discovery: queries the live directory + on-chain reputation.+ // Rankings shift as engagement/reputation change, so not idempotent.+ annotations: {+ readOnlyHint: true,+ destructiveHint: false,+ idempotentHint: false,+ openWorldHint: true,+ },+ handler,+ };+}diff --git a/package.json b/package.jsonindex c6a25d7c8..ba0e586ca 100644--- a/package.json+++ b/package.json@@ -124,6 +124,7 @@"audit:pages": "node scripts/audit-page-index.mjs","audit:routes": "node scripts/verify-routes.mjs","audit:handlers": "node scripts/audit-empty-handlers.mjs",+ "gate": "npm run test:gate && npm run audit:mcp && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:hidden-guard","audit:hidden-guard": "node scripts/audit-hidden-guard.mjs","guard:hidden": "node scripts/inject-hidden-guard.mjs --write","check:images": "node scripts/audit-image-loading.mjs --strict",diff --git a/scripts/mcp-studio-smoke.mjs b/scripts/mcp-studio-smoke.mjsnew file mode 100644index 000000000..ba858ea6a--- /dev/null+++ b/scripts/mcp-studio-smoke.mjs@@ -0,0 +1,69 @@+// Smoke harness for the free 3D Studio MCP endpoint.+// 1. Drives the real HTTP handler (api/mcp-studio.js) with mock req/res for+// initialize, tools/list, and resources/read — proving the transport.+// 2. Calls forge_free through the dispatcher pointed at the PRODUCTION free+// NVIDIA lane (https://three.ws/api/forge) to capture a REAL GLB response.+//+// Usage: node scripts/mcp-studio-smoke.mjs [--gen]+// --gen also run a real generation (slow, ~15-60s; hits the prod free lane).++import { Readable } from 'node:stream';++process.env.STUDIO_API_BASE = process.env.STUDIO_API_BASE || 'https://three.ws';++const { default: handler } = await import('../api/mcp-studio.js');++function mockReq(body) {+ const buf = Buffer.from(JSON.stringify(body));+ const r = Readable.from([buf]);+ r.method = 'POST';+ r.url = '/api/mcp-studio';+ r.headers = { 'content-type': 'application/json', host: 'three.ws', 'x-forwarded-proto': 'https', 'x-forwarded-for': '203.0.113.7' };+ return r;+}++function mockRes() {+ const res = {+ statusCode: 200,+ _headers: {},+ _body: '',+ setHeader(k, v) { this._headers[k.toLowerCase()] = v; },+ getHeader(k) { return this._headers[k.toLowerCase()]; },+ end(b) { if (b) this._body += b; this._ended = true; if (this._resolve) this._resolve(); },+ write(b) { this._body += b; },+ };+ res.done = new Promise((resolve) => (res._resolve = resolve));+ return res;+}++async function call(body) {+ const req = mockReq(body);+ const res = mockRes();+ await handler(req, res);+ await res.done;+ return { status: res.statusCode, json: res._body ? JSON.parse(res._body) : null };+}++console.log('# 1. initialize');+const init = await call({ jsonrpc: '2.0', id: 1, method: 'initialize' });+console.log('status', init.status, '— server', init.json.result.serverInfo.name);++console.log('\n# 2. tools/list');+const list = await call({ jsonrpc: '2.0', id: 2, method: 'tools/list' });+for (const t of list.json.result.tools) {+ console.log(` - ${t.name} :: "${t.title}" annotations=${JSON.stringify(t.annotations)}`);+}++console.log('\n# 3. resources/read (Apps SDK widget)');+const read = await call({ jsonrpc: '2.0', id: 3, method: 'resources/read', params: { uri: 'ui://widget/three-studio-model.html' } });+const html = read.json.result.contents[0];+console.log(' uri', html.uri, '— mime', html.mimeType, '— bytes', html.text.length);++if (process.argv.includes('--gen')) {+ console.log('\n# 4. forge_free (REAL generation via prod free NVIDIA lane) — this is slow…');+ const gen = await call({ jsonrpc: '2.0', id: 4, method: 'tools/call', params: { name: 'forge_free', arguments: { prompt: 'a friendly round robot mascot, glossy white plastic', tier: 'draft' } } });+ console.log(' status', gen.status);+ console.log(JSON.stringify(gen.json.result, null, 2));+}++console.log('\nOK');diff --git a/src/pose-presets.js b/src/pose-presets.jsindex 53ca680fc..3964465f8 100644--- a/src/pose-presets.js+++ b/src/pose-presets.js@@ -103,6 +103,20 @@ export const PRESETS = [chest: { x: -0.05, y: 0, z: 0 },},},+ {+ id: 'salute',+ label: 'Salute',+ group: 'Standing',+ pose: {+ chest: { x: -0.04, y: 0, z: 0 },+ head: { x: 0.05, y: 0, z: 0 },+ shoulderL: { x: -0.04, y: 0, z: 0.09 },+ elbowL: { x: -0.12, y: 0, z: 0 },+ shoulderR: { x: -0.78, y: 0.35, z: -0.60 },+ elbowR: { x: -2.35, y: 0, z: 0 },+ wristR: { x: 0, y: 0, z: -0.20 },+ },+ },// ─── ACTION ───{@@ -212,6 +226,25 @@ export const PRESETS = [rootPosition: { x: 0, y: -0.42, z: 0 },},},+ {+ id: 'fighting-stance',+ label: 'Fighting stance',+ group: 'Action',+ pose: {+ spine: { x: 0.05, y: 0.10, z: 0 },+ chest: { x: 0.05, y: 0.22, z: 0 },+ head: { x: 0.08, y: 0.12, z: 0 },+ shoulderL: { x: -0.85, y: 0.30, z: -0.30 },+ shoulderR: { x: -0.85, y: -0.25, z: -0.20 },+ elbowL: { x: -2.10, y: 0, z: 0 },+ elbowR: { x: -2.20, y: 0, z: 0 },+ hipL: { x: -0.25, y: 0.10, z: 0.05 },+ hipR: { x: -0.20, y: -0.10, z: -0.05 },+ kneeL: { x: 0.45, y: 0, z: 0 },+ kneeR: { x: 0.55, y: 0, z: 0 },+ rootPosition: { x: 0, y: -0.12, z: 0 },+ },+ },// ─── SITTING & FLOOR ───{@@ -399,6 +432,22 @@ export const PRESETS = [head: { x: 0, y: -0.30, z: 0 },},},+ {+ id: 'facepalm',+ label: 'Facepalm',+ group: 'Expressive',+ pose: {+ spine: { x: 0.10, y: 0, z: 0 },+ chest: { x: 0.18, y: 0, z: 0 },+ neck: { x: 0.25, y: 0, z: 0 },+ head: { x: 0.50, y: 0, z: 0 },+ shoulderR: { x: -0.90, y: 0.50, z: -0.45 },+ elbowR: { x: -2.40, y: 0, z: 0 },+ wristR: { x: 0.10, y: 0, z: 0 },+ shoulderL: { x: -0.15, y: 0, z: 0.12 },+ elbowL: { x: -0.30, y: 0, z: 0 },+ },+ },];export function getPresetById(id) {diff --git a/tests/api/forge-lane-health.test.js b/tests/api/forge-lane-health.test.jsnew file mode 100644index 000000000..cb33df8f6--- /dev/null+++ b/tests/api/forge-lane-health.test.js@@ -0,0 +1,99 @@+// Self-host lane liveness/warmth probe — the signal health-aware routing consults.+//+// A self-host worker is probed with a cheap authenticated GET: <500 = up (warm if+// fast), 5xx/timeout/unreachable = down. External free lanes are reported unknown+// (they carry their own breakers). Everything is fail-open and cached per instance.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { laneHealthSnapshot, resetLaneHealthCache, laneCooldownKey } from '../../api/_lib/forge-lane-health.js';++const VARS = ['MODEL_TRELLIS_URL', 'GCP_HUNYUAN3D_URL', 'GCP_RECONSTRUCTION_KEY', 'HF_TOKEN'];+const saved = {};+const ORIGINAL_FETCH = globalThis.fetch;++beforeEach(() => {+ for (const v of VARS) {+ saved[v] = process.env[v];+ delete process.env[v];+ }+ resetLaneHealthCache();+});+afterEach(() => {+ for (const v of VARS) {+ if (saved[v] === undefined) delete process.env[v];+ else process.env[v] = saved[v];+ }+ globalThis.fetch = ORIGINAL_FETCH;+ vi.restoreAllMocks();+ resetLaneHealthCache();+});++describe('laneHealthSnapshot — self-host worker probing', () => {+ it('reports a reachable worker ok (warm on a fast answer)', async () => {+ process.env.MODEL_TRELLIS_URL = 'https://trellis.example.run.app';+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';+ globalThis.fetch = vi.fn(async (url, opts) => {+ expect(url).toBe('https://trellis.example.run.app');+ expect(opts.headers.authorization).toBe('Bearer secret');+ return new Response('ok', { status: 200 });+ });++ const snap = await laneHealthSnapshot(['trellis_selfhost']);+ expect(snap.statusMap.trellis_selfhost).toBe('ok');+ expect(snap.byId.trellis_selfhost.warm).toBe(true);+ });++ it('reports a 5xx worker down', async () => {+ process.env.GCP_HUNYUAN3D_URL = 'https://hunyuan.example.run.app';+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';+ globalThis.fetch = vi.fn(async () => new Response('boom', { status: 503 }));++ const snap = await laneHealthSnapshot(['hunyuan3d']);+ expect(snap.statusMap.hunyuan3d).toBe('down');+ });++ it('reports an unreachable worker down (fetch throws)', async () => {+ process.env.MODEL_TRELLIS_URL = 'https://trellis.example.run.app';+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';+ globalThis.fetch = vi.fn(async () => {+ throw new Error('ECONNREFUSED');+ });++ const snap = await laneHealthSnapshot(['trellis_selfhost']);+ expect(snap.statusMap.trellis_selfhost).toBe('down');+ });++ it('reports an unconfigured self-host lane unknown without probing', async () => {+ const fetchMock = vi.fn();+ globalThis.fetch = fetchMock;+ const snap = await laneHealthSnapshot(['trellis_selfhost']);+ expect(snap.statusMap.trellis_selfhost).toBe('unknown');+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('reports external free lanes unknown (no probe, their own breaker owns liveness)', async () => {+ process.env.HF_TOKEN = 'hf_test';+ const fetchMock = vi.fn();+ globalThis.fetch = fetchMock;+ const snap = await laneHealthSnapshot(['huggingface', 'nvidia']);+ expect(snap.statusMap.huggingface).toBe('unknown');+ expect(snap.statusMap.nvidia).toBe('unknown');+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('caches the snapshot per instance — a second call does not re-probe', async () => {+ process.env.MODEL_TRELLIS_URL = 'https://trellis.example.run.app';+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';+ const fetchMock = vi.fn(async () => new Response('ok', { status: 200 }));+ globalThis.fetch = fetchMock;++ await laneHealthSnapshot(['trellis_selfhost']);+ await laneHealthSnapshot(['trellis_selfhost']);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('exposes a distinct cooldown key namespace per lane', () => {+ expect(laneCooldownKey('trellis_selfhost')).toBe('forge-lane:trellis_selfhost');+ expect(laneCooldownKey('triposg')).toBe('forge-lane:triposg');+ });+});diff --git a/tests/api/forge-lane-routing.test.js b/tests/api/forge-lane-routing.test.jsnew file mode 100644index 000000000..e1f2ec75e--- /dev/null+++ b/tests/api/forge-lane-routing.test.js@@ -0,0 +1,208 @@+// Health-aware self-host routing + cold-start ETA + free/paid cost class.+//+// The self-host GPU lanes (our own Cloud Run workers) are the resilient default:+// routing prefers a HEALTHY self-host lane, then another healthy free lane, and+// only the paid Replicate default when every free lane is confirmed down. These+// tests drive the PURE resolver with an injected health map (no network), plus the+// cold-start ETA helper and the free-vs-paid cost classifier.++import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import {+ freeLaneCandidates,+ resolveBackendId,+ resolveBackendIdWithHealth,+ defaultBackendForHealthAware,+ estimateEtaSeconds,+ coldStartSecondsFor,+ backendCostClass,+ isSelfHostBackend,+ isFreeBackend,+ DEFAULT_BACKEND_FOR_PATH,+} from '../../api/_lib/forge-tiers.js';++const ALL_LANE_VARS = [+ 'MODEL_TRELLIS_URL',+ 'GCP_HUNYUAN3D_URL',+ 'GCP_TRIPOSG_URL',+ 'GCP_RECONSTRUCTION_KEY',+ 'HF_TOKEN',+ 'NVIDIA_API_KEY',+ 'REPLICATE_API_TOKEN',+];+const saved = {};++function configureAllLanes() {+ process.env.MODEL_TRELLIS_URL = 'https://trellis.example.run.app';+ process.env.GCP_HUNYUAN3D_URL = 'https://hunyuan.example.run.app';+ process.env.GCP_TRIPOSG_URL = 'https://triposg.example.run.app';+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';+ process.env.HF_TOKEN = 'hf_test';+ process.env.NVIDIA_API_KEY = 'nvapi-test';+ process.env.REPLICATE_API_TOKEN = 'r8_test';+}++beforeEach(() => {+ for (const v of ALL_LANE_VARS) {+ saved[v] = process.env[v];+ delete process.env[v];+ }+});+afterEach(() => {+ for (const v of ALL_LANE_VARS) {+ if (saved[v] === undefined) delete process.env[v];+ else process.env[v] = saved[v];+ }+});++describe('freeLaneCandidates — ordered, configured, de-duplicated', () => {+ it('orders our own GPU workers ahead of the free external lane for photos', () => {+ configureAllLanes();+ // Photo: NVIDIA's text-only preview is excluded; self-host workers lead.+ expect(freeLaneCandidates('image', 'draft', true)).toEqual([+ 'trellis_selfhost',+ 'hunyuan3d',+ 'huggingface',+ ]);+ });++ it('keeps the native NVIDIA text→3D default first for text prompts', () => {+ configureAllLanes();+ // Text (userImages=false): the tier-named native lane leads, then self-host.+ expect(freeLaneCandidates('image', 'draft', false)).toEqual([+ 'nvidia',+ 'trellis_selfhost',+ 'hunyuan3d',+ 'huggingface',+ ]);+ });++ it('drops unconfigured lanes and never duplicates one that is both named and a fallback', () => {+ // Only the self-host TRELLIS worker is wired.+ process.env.MODEL_TRELLIS_URL = 'https://trellis.example.run.app';+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';+ expect(freeLaneCandidates('image', 'standard', true)).toEqual(['trellis_selfhost']);+ expect(freeLaneCandidates('image', 'standard', false)).toEqual(['trellis_selfhost']);+ });+});++describe('resolveBackendIdWithHealth — prefer healthy self-host → other free → paid', () => {+ beforeEach(configureAllLanes);++ it('routes a photo to the healthy self-host TRELLIS worker', () => {+ const health = { trellis_selfhost: 'ok', hunyuan3d: 'ok', huggingface: 'ok' };+ expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true, health })).toBe(+ 'trellis_selfhost',+ );+ });++ it('skips a down self-host lane and falls to the next healthy self-host worker', () => {+ const health = { trellis_selfhost: 'down', hunyuan3d: 'ok', huggingface: 'ok' };+ expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true, health })).toBe(+ 'hunyuan3d',+ );+ });++ it('falls to the healthy free external lane when both self-host workers are down', () => {+ const health = { trellis_selfhost: 'down', hunyuan3d: 'down', huggingface: 'ok' };+ expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true, health })).toBe(+ 'huggingface',+ );+ });++ it('falls to the paid standing default only when every free lane is confirmed down', () => {+ const health = { trellis_selfhost: 'down', hunyuan3d: 'down', huggingface: 'down' };+ expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true, health })).toBe(+ DEFAULT_BACKEND_FOR_PATH.image,+ );+ expect(DEFAULT_BACKEND_FOR_PATH.image).toBe('trellis');+ });++ it('treats unknown/degraded health as usable (never blocks on missing telemetry)', () => {+ // trellis_selfhost has no entry (unknown) → still picked, ahead of an ok HF.+ const health = { huggingface: 'ok' };+ expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true, health })).toBe(+ 'trellis_selfhost',+ );+ // A degraded self-host lane is skipped only if a later candidate is ok.+ const health2 = { trellis_selfhost: 'degraded', hunyuan3d: 'ok' };+ expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true, health: health2 })).toBe(+ 'hunyuan3d',+ );+ });++ it('prefers the native NVIDIA lane for healthy text, then self-host when it is down', () => {+ expect(+ resolveBackendIdWithHealth({ path: 'image', tier: 'draft', userImages: false, health: { nvidia: 'ok' } }),+ ).toBe('nvidia');+ expect(+ resolveBackendIdWithHealth({+ path: 'image',+ tier: 'draft',+ userImages: false,+ health: { nvidia: 'down', trellis_selfhost: 'ok' },+ }),+ ).toBe('trellis_selfhost');+ });++ it('honors an explicitly named backend regardless of health', () => {+ const health = { trellis_selfhost: 'ok' };+ expect(+ resolveBackendIdWithHealth({ path: 'image', tier: 'standard', backend: 'meshy', userImages: true, health }),+ ).toBe('meshy');+ });++ it('with no health map, matches the env-only resolver exactly', () => {+ expect(resolveBackendIdWithHealth({ path: 'image', tier: 'standard', userImages: true })).toBe(+ resolveBackendId({ path: 'image', tier: 'standard', userImages: true }),+ );+ expect(resolveBackendIdWithHealth({ path: 'image', tier: 'draft', userImages: false })).toBe(+ resolveBackendId({ path: 'image', tier: 'draft', userImages: false }),+ );+ });++ it('routes sketch to the self-host TripoSG worker, paid never selected', () => {+ expect(+ defaultBackendForHealthAware('sketch', 'standard', true, { triposg: 'ok' }),+ ).toBe('triposg');+ // Down → the path has no other free lane, so the standing sketch default.+ expect(defaultBackendForHealthAware('sketch', 'standard', true, { triposg: 'down' })).toBe(+ DEFAULT_BACKEND_FOR_PATH.sketch,+ );+ });+});++describe('cold-start ETA — honest widening for scale-to-zero workers', () => {+ it('adds the self-host worker cold-start budget only when cold', () => {+ const warm = estimateEtaSeconds({ backendId: 'trellis_selfhost', tier: 'standard' });+ const cold = estimateEtaSeconds({ backendId: 'trellis_selfhost', tier: 'standard', cold: true });+ expect(coldStartSecondsFor('trellis_selfhost')).toBeGreaterThan(0);+ expect(cold).toBe(warm + coldStartSecondsFor('trellis_selfhost'));+ });++ it('is a no-op for an always-warm external/paid lane', () => {+ expect(coldStartSecondsFor('huggingface')).toBe(0);+ expect(estimateEtaSeconds({ backendId: 'huggingface', tier: 'standard', cold: true })).toBe(+ estimateEtaSeconds({ backendId: 'huggingface', tier: 'standard' }),+ );+ });+});++describe('cost class — free (self-host + free external) vs paid', () => {+ it('classifies our self-host GPU workers and free previews as free', () => {+ for (const id of ['trellis_selfhost', 'hunyuan3d', 'triposg', 'nvidia', 'huggingface']) {+ expect(isFreeBackend(id)).toBe(true);+ expect(backendCostClass(id)).toBe('free');+ }+ expect(isSelfHostBackend('trellis_selfhost')).toBe(true);+ expect(isSelfHostBackend('hunyuan3d')).toBe(true);+ expect(isSelfHostBackend('triposg')).toBe(true);+ });++ it('classifies the paid platform lane and BYOK vendors as paid', () => {+ for (const id of ['trellis', 'meshy', 'tripo', 'rodin', 'stability']) {+ expect(backendCostClass(id)).toBe('paid');+ }+ expect(isSelfHostBackend('trellis')).toBe(false);+ expect(isSelfHostBackend('meshy')).toBe(false);+ });+});diff --git a/tests/mcp-tool-contract.test.js b/tests/mcp-tool-contract.test.jsdeleted file mode 100644index a04f5dc21..000000000--- a/tests/mcp-tool-contract.test.js+++ /dev/null@@ -1,94 +0,0 @@-// Golden contract tripwire for the hosted MCP tool catalogs.-//-// The MCP servers ARE the product surface we submit to the Claude Connectors-// Directory and the OpenAI App Directory. A reviewer calls every tool and checks-// its title + annotations; an accidental change to a tool's name, title,-// annotations, or input schema can silently break a live listing. This test-// freezes each catalog's PUBLIC contract (handlers already stripped by the-// catalog's own map) into a committed snapshot, and enforces two store-review-// invariants that are easy to regress:-//-// 1. Every tool has a non-empty `title` (both directories require it).-// 2. Every tool sets `annotations.destructiveHint` EXPLICITLY — the MCP spec-// defaults it to TRUE when omitted, which would mislabel a safe tool as-// destructive in the client UI.-//-// Snapshots live in tests/__snapshots__/mcp-tool-contract.test.js.snap. When you-// intentionally change a tool's contract, re-run with `-u` and review the diff —-// that diff is exactly what a store reviewer would see change.--import { describe, it, expect } from 'vitest';--// Each hosted server exposes TOOL_CATALOG: the tools/list schema array with the-// internal `scope`/`handler` fields already removed.-import { TOOL_CATALOG as MAIN } from '../api/_mcp/catalog.js';-import { TOOL_CATALOG as STUDIO3D } from '../api/_mcp3d/catalog.js';-import { TOOL_CATALOG as AGENT } from '../api/_mcpagent/catalog.js';-import { TOOL_CATALOG as BAZAAR } from '../api/_mcpbazaar/catalog.js';-import { TOOL_CATALOG as IBM } from '../api/_mcpibm/catalog.js';--const SERVERS = {- '_mcp': MAIN,- '_mcp3d': STUDIO3D,- '_mcpagent': AGENT,- '_mcpbazaar': BAZAAR,- '_mcpibm': IBM,-};--// Reduce a tool to its review-relevant contract. Description is intentionally-// excluded: copy edits to descriptions are routine and should not fail the gate,-// whereas name/title/annotations/inputSchema are the machine + reviewer contract.-function contractOf(tool) {- return {- name: tool.name,- title: tool.title ?? null,- annotations: tool.annotations ?? null,- inputSchema: tool.inputSchema ?? null,- };-}--function catalogContract(catalog) {- return [...catalog]- .map(contractOf)- .sort((a, b) => String(a.name).localeCompare(String(b.name)));-}--describe('hosted MCP tool catalogs', () => {- for (const [server, catalog] of Object.entries(SERVERS)) {- describe(server, () => {- it('exposes a non-empty tool catalog', () => {- expect(Array.isArray(catalog)).toBe(true);- expect(catalog.length).toBeGreaterThan(0);- });-- it('every tool has a non-empty title', () => {- for (const tool of catalog) {- expect(- typeof tool.title === 'string' && tool.title.trim().length > 0,- `tool "${tool.name}" in ${server} is missing a title`,- ).toBe(true);- }- });-- it('every tool sets destructiveHint explicitly (MCP defaults it to true)', () => {- for (const tool of catalog) {- const a = tool.annotations;- expect(a, `tool "${tool.name}" in ${server} has no annotations`).toBeTruthy();- expect(- typeof a.destructiveHint === 'boolean',- `tool "${tool.name}" in ${server} must set annotations.destructiveHint explicitly`,- ).toBe(true);- }- });-- it('tool names are unique within the server', () => {- const names = catalog.map((t) => t.name);- expect(new Set(names).size).toBe(names.length);- });-- it('matches the frozen public contract snapshot', () => {- expect(catalogContract(catalog)).toMatchSnapshot();- });- });- }-});diff --git a/tests/refine-lineage.test.js b/tests/refine-lineage.test.jsnew file mode 100644index 000000000..b3be1d34b--- /dev/null+++ b/tests/refine-lineage.test.js@@ -0,0 +1,170 @@+import { describe, it, expect } from 'vitest';++import {+ normalizeInstruction,+ composeRefinement,+ seedLineage,+ appendVersion,+ branchFrom,+ revertTo,+ buildLineageChain,+ summarizeLineage,+} from '../mcp-server/src/tools/_lineage.js';++describe('normalizeInstruction', () => {+ it('strips leading imperative filler', () => {+ expect(normalizeInstruction('make it metallic')).toBe('metallic');+ expect(normalizeInstruction('now add wings')).toBe('add wings');+ expect(normalizeInstruction('please make the helmet bigger')).toBe('helmet bigger');+ expect(normalizeInstruction('turn it into a robot')).toBe('robot');+ });++ it('collapses whitespace and trims trailing punctuation', () => {+ expect(normalizeInstruction(' make it gold. ')).toBe('gold');+ });++ it('keeps a payload that has no filler prefix', () => {+ expect(normalizeInstruction('glossy red plastic')).toBe('glossy red plastic');+ });++ it('returns pure-filler instructions unchanged rather than empty', () => {+ expect(normalizeInstruction('make it')).toBe('make it');+ });++ it('handles empty / nullish input', () => {+ expect(normalizeInstruction('')).toBe('');+ expect(normalizeInstruction(null)).toBe('');+ expect(normalizeInstruction(undefined)).toBe('');+ });+});++describe('composeRefinement', () => {+ it('anchors the change onto the carried-forward parent prompt', () => {+ expect(composeRefinement('a round robot mascot', 'make it metallic')).toBe(+ 'a round robot mascot, metallic',+ );+ });++ it('is deterministic — same inputs give the same prompt', () => {+ const a = composeRefinement('a knight helmet', 'bigger helmet');+ const b = composeRefinement('a knight helmet', 'bigger helmet');+ expect(a).toBe(b);+ expect(a).toBe('a knight helmet, helmet bigger');+ });++ it('falls back to the instruction alone when the parent prompt is unknown', () => {+ expect(composeRefinement('', 'add wings')).toBe('add wings');+ expect(composeRefinement(null, 'make it golden')).toBe('golden');+ });++ it('falls back to the parent prompt when the instruction is empty', () => {+ expect(composeRefinement('a brass lantern', '')).toBe('a brass lantern');+ });++ it('caps the composed prompt at the generator limit (1000 chars)', () => {+ const long = 'x'.repeat(1200);+ expect(composeRefinement(long, 'make it blue').length).toBe(1000);+ });+});++describe('version lineage integrity', () => {+ it('seeds an origin version at index 0 with no parent', () => {+ const lin = seedLineage({ glbUrl: 'https://three.ws/a.glb', prompt: 'a robot' });+ expect(lin).toHaveLength(1);+ expect(lin[0]).toMatchObject({ index: 0, parentIndex: null, refKind: 'origin' });+ });++ it('appends children that chain parent → child and never mutates history', () => {+ const v0 = seedLineage({ glbUrl: 'g0', prompt: 'a robot' });+ const v1 = appendVersion(v0, { glbUrl: 'g1', prompt: 'a robot, metallic', instruction: 'metallic' });+ const v2 = appendVersion(v1, { glbUrl: 'g2', prompt: 'a robot, metallic, wings', instruction: 'add wings' });++ expect(v0).toHaveLength(1); // original untouched (immutable)+ expect(v1).toHaveLength(2);+ expect(v2).toHaveLength(3);+ expect(v1[1]).toMatchObject({ index: 1, parentIndex: 0, instruction: 'metallic' });+ expect(v2[2]).toMatchObject({ index: 2, parentIndex: 1, instruction: 'add wings' });+ });++ it('validates a clean linear lineage and returns the root→leaf chain', () => {+ let lin = seedLineage({ glbUrl: 'g0' });+ lin = appendVersion(lin, { glbUrl: 'g1', instruction: 'metallic' });+ lin = appendVersion(lin, { glbUrl: 'g2', instruction: 'wings' });+ const res = buildLineageChain(lin);+ expect(res.ok).toBe(true);+ expect(res.errors).toEqual([]);+ expect(res.roots).toEqual([0]);+ expect(res.leaves).toEqual([2]);+ expect(res.chain.map((v) => v.index)).toEqual([0, 1, 2]);+ });++ it('supports branching — a tree with two leaves, each chain valid', () => {+ let lin = seedLineage({ glbUrl: 'g0' });+ lin = appendVersion(lin, { glbUrl: 'g1', instruction: 'metallic' }); // index 1, parent 0+ // Branch off the ORIGINAL (index 0), not the latest.+ lin = appendVersion(lin, { glbUrl: 'g2', instruction: 'wooden', parentIndex: branchFrom(lin, 0) });++ expect(lin[2]).toMatchObject({ index: 2, parentIndex: 0 });+ const res = buildLineageChain(lin);+ expect(res.ok).toBe(true);+ expect(res.leaves.sort()).toEqual([1, 2]);+ // Active defaults to the highest index (2); its chain skips the sibling.+ expect(res.chain.map((v) => v.index)).toEqual([0, 2]);+ });++ it('reverts to an earlier version without mutating history', () => {+ let lin = seedLineage({ glbUrl: 'g0' });+ lin = appendVersion(lin, { glbUrl: 'g1', instruction: 'metallic' });+ lin = appendVersion(lin, { glbUrl: 'g2', instruction: 'wings' });+ const { activeIndex, active } = revertTo(lin, 1);+ expect(activeIndex).toBe(1);+ expect(active.glbUrl).toBe('g1');+ expect(lin).toHaveLength(3); // history intact++ const res = buildLineageChain(lin, 1);+ expect(res.chain.map((v) => v.index)).toEqual([0, 1]);+ });++ it('rejects reverting / branching to a non-existent version', () => {+ const lin = seedLineage({ glbUrl: 'g0' });+ expect(() => revertTo(lin, 5)).toThrow();+ expect(() => branchFrom(lin, 5)).toThrow();+ });++ it('detects a broken parent reference', () => {+ const bad = [+ { index: 0, parentIndex: null, glbUrl: 'g0', refKind: 'origin' },+ { index: 1, parentIndex: 7, glbUrl: 'g1', refKind: 'text' },+ ];+ const res = buildLineageChain(bad);+ expect(res.ok).toBe(false);+ expect(res.errors.join(' ')).toMatch(/missing parent 7/);+ });++ it('detects a forward/cyclic parent reference', () => {+ const bad = [+ { index: 0, parentIndex: 1, glbUrl: 'g0', refKind: 'origin' },+ { index: 1, parentIndex: 0, glbUrl: 'g1', refKind: 'text' },+ ];+ const res = buildLineageChain(bad);+ expect(res.ok).toBe(false);+ expect(res.errors.join(' ')).toMatch(/not earlier|root/);+ });++ it('detects a duplicate index', () => {+ const bad = [+ { index: 0, parentIndex: null, glbUrl: 'g0', refKind: 'origin' },+ { index: 0, parentIndex: null, glbUrl: 'gx', refKind: 'origin' },+ ];+ expect(buildLineageChain(bad).ok).toBe(false);+ });++ it('summarizes a lineage for the version strip with the active flag set', () => {+ let lin = seedLineage({ glbUrl: 'g0', viewerUrl: 'v0', prompt: 'a robot' });+ lin = appendVersion(lin, { glbUrl: 'g1', viewerUrl: 'v1', instruction: 'metallic' });+ const strip = summarizeLineage(lin, 0);+ expect(strip).toHaveLength(2);+ expect(strip[0]).toMatchObject({ index: 0, label: 'Original', active: true });+ expect(strip[1]).toMatchObject({ index: 1, label: 'metallic', active: false });+ });+});diff --git a/tests/remix-royalty.test.js b/tests/remix-royalty.test.jsnew file mode 100644index 000000000..2f9e61b78--- /dev/null+++ b/tests/remix-royalty.test.js@@ -0,0 +1,116 @@+import { describe, it, expect } from 'vitest';++import {+ clampRoyaltyBps,+ computeRemixSplit,+ atomicsToUsd,+ usdcToAtomics,+ REMIX_ROYALTY_CAP_BPS,+ REMIX_ROYALTY_DEFAULT_BPS,+ REMIX_MIN_PAYOUT_ATOMICS,+} from '../api/_lib/remix-royalty.js';++describe('clampRoyaltyBps', () => {+ it('passes through a valid rate', () => {+ expect(clampRoyaltyBps(1000)).toBe(1000);+ });+ it('clamps above the cap', () => {+ expect(clampRoyaltyBps(5000)).toBe(REMIX_ROYALTY_CAP_BPS);+ });+ it('floors negatives / garbage to 0', () => {+ expect(clampRoyaltyBps(-1)).toBe(0);+ expect(clampRoyaltyBps(NaN)).toBe(0);+ expect(clampRoyaltyBps('abc')).toBe(0);+ });+});++describe('computeRemixSplit — split math', () => {+ it('splits a 1 USDC remix at the default 10% royalty', () => {+ // 1 USDC = 1_000_000 atomics; 10% = 100_000 to the creator.+ const s = computeRemixSplit({ priceAtomics: 1_000_000n, royaltyBps: REMIX_ROYALTY_DEFAULT_BPS });+ expect(s.creatorAtomics).toBe(100_000n);+ expect(s.platformAtomics).toBe(900_000n);+ expect(s.royaltyBps).toBe(1000);+ expect(s.capped).toBe(false);+ expect(s.dust).toBe(false);+ expect(s.creatorUsd).toBeCloseTo(0.1, 9);+ });++ it('conserves value: creator + platform === price for many inputs', () => {+ const prices = [1n, 999n, 1_000_000n, 3_333_333n, 50_000_000n, 123_456_789n];+ const rates = [0, 1, 250, 1000, 2000, 9999];+ for (const p of prices) {+ for (const r of rates) {+ const s = computeRemixSplit({ priceAtomics: p, royaltyBps: r });+ expect(s.creatorAtomics + s.platformAtomics).toBe(p);+ expect(s.creatorAtomics >= 0n).toBe(true);+ expect(s.platformAtomics >= 0n).toBe(true);+ }+ }+ });++ it('enforces the hard cap — a 50% request is clamped to 20%', () => {+ const s = computeRemixSplit({ priceAtomics: 10_000_000n, royaltyBps: 5000 });+ expect(s.requestedBps).toBe(5000);+ expect(s.royaltyBps).toBe(REMIX_ROYALTY_CAP_BPS);+ expect(s.capped).toBe(true);+ // 20% of 10 USDC = 2 USDC; remixer keeps the 80% majority on the platform side.+ expect(s.creatorAtomics).toBe(2_000_000n);+ expect(s.platformAtomics).toBe(8_000_000n);+ });++ it('the remixer always keeps the clear majority (platform >= creator)', () => {+ const s = computeRemixSplit({ priceAtomics: 7_777_777n, royaltyBps: REMIX_ROYALTY_CAP_BPS });+ expect(s.platformAtomics > s.creatorAtomics).toBe(true);+ });++ it('drops a sub-dust royalty rather than paying it', () => {+ // Tiny price where 10% rounds below the dust floor.+ const s = computeRemixSplit({ priceAtomics: 50_000n, royaltyBps: 100 }); // 1% of 0.05 = 500 atomics+ expect(s.creatorAtomics < REMIX_MIN_PAYOUT_ATOMICS).toBe(false); // it was dropped to 0+ expect(s.creatorAtomics).toBe(0n);+ expect(s.dust).toBe(true);+ expect(s.platformAtomics).toBe(50_000n);+ });++ it('floors the royalty (no fractional atomics created)', () => {+ // 333 atomics at 10% = 33.3 → floor 33; but that's sub-dust so it drops to 0.+ const s = computeRemixSplit({ priceAtomics: 333n, royaltyBps: 1000 });+ expect(s.creatorAtomics).toBe(0n);+ expect(s.creatorAtomics + s.platformAtomics).toBe(333n);+ });++ it('zero royalty rate routes everything to the platform', () => {+ const s = computeRemixSplit({ priceAtomics: 1_000_000n, royaltyBps: 0 });+ expect(s.creatorAtomics).toBe(0n);+ expect(s.platformAtomics).toBe(1_000_000n);+ });++ it('defaults the royalty rate when none is given', () => {+ const s = computeRemixSplit({ priceAtomics: 1_000_000n });+ expect(s.royaltyBps).toBe(REMIX_ROYALTY_DEFAULT_BPS);+ expect(s.creatorAtomics).toBe(100_000n);+ });++ it('accepts string and number price inputs (bazaar stores atomics as text)', () => {+ expect(computeRemixSplit({ priceAtomics: '1000000', royaltyBps: 1000 }).creatorAtomics).toBe(100_000n);+ expect(computeRemixSplit({ priceAtomics: 1_000_000, royaltyBps: 1000 }).creatorAtomics).toBe(100_000n);+ });++ it('treats invalid / zero price as no payout', () => {+ expect(computeRemixSplit({ priceAtomics: 0n, royaltyBps: 1000 }).creatorAtomics).toBe(0n);+ expect(computeRemixSplit({ priceAtomics: 'xyz', royaltyBps: 1000 }).priceAtomics).toBe(0n);+ });+});++describe('USDC atomics helpers', () => {+ it('round-trips whole and fractional USDC', () => {+ expect(usdcToAtomics(1)).toBe(1_000_000n);+ expect(usdcToAtomics(0.25)).toBe(250_000n);+ expect(atomicsToUsd(1_000_000n)).toBe(1);+ expect(atomicsToUsd(250_000n)).toBe(0.25);+ });+ it('never returns negative atomics', () => {+ expect(usdcToAtomics(-5)).toBe(0n);+ });+});