Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(forge): quality gate, reference-image lane, and tier/worker upgrades
nirholasfb3cc68b08c3
diff --git a/api/_lib/forge-quality-gate.js b/api/_lib/forge-quality-gate.jsnew file mode 100644index 000000000..0894faf25--- /dev/null+++ b/api/_lib/forge-quality-gate.js@@ -0,0 +1,526 @@+// Forge realism / quality gate — the vision-model half of "raise the floor".+//+// glb-quality.js (scoreGlbQuality) answers the CHEAP, deterministic question+// from the glTF JSON chunk alone: is this a valid, dense, textured mesh, or a+// degenerate blob? It cannot see what the mesh actually LOOKS like. This module+// answers the harder, product-facing question: does a render of this model read+// as a real photograph of a real subject, or as a plastic toy / melted blob /+// incomplete / duplicated mess a user should never be shown?+//+// It renders the GLB (or takes a render you already have), sends the image to+// Vertex Gemini vision (GCP-credit-funded, no third-party key) with a subject-+// aware photoreal rubric, and returns a structured verdict:+// { pass, score, realism, completeness, defects, reason, suggested_retry_hint }.+//+// ── Fail-open, always ─────────────────────────────────────────────────────────+// Quality gating is a BOOST, never a hard gate. If Vertex is down, the render+// fails, the token can't be minted, or the model returns garbage, runQualityGate+// returns pass:true with qa_available:false and a "qa_unavailable" reason. A QA+// outage must never take down a working generation. The router treats a non-pass+// verdict as "try one adjusted regeneration"; it must treat qa_available:false as+// "ship what we have".+//+// ── Provider order ────────────────────────────────────────────────────────────+// 1. Vertex Gemini (gemini-2.5-flash) — the intended lane, bills GCP credits.+// 2. Platform vision chain (describeImageJson: free NVIDIA NIM VLMs) — used+// when Vertex is unconfigured or errors, so the gate still functions off the+// free lanes rather than silently disabling itself.+// 3. Neither available → fail-open pass with qa_available:false.+//+// ── The router seam ───────────────────────────────────────────────────────────+// The generation router (api/forge.js, owned by another agent) wires this in by:+// const verdict = await runQualityGate({ glbUrl, prompt });+// if (!verdict.pass && verdict.qa_available) {+// const next = buildRetryDirective(verdict, { prompt, tier, path, attempt });+// if (next) { /* regenerate once with next.prompt / next.tier / next.path */ }+// }+// See the SEAM comment block at the end of this file for the copy-paste contract.++import { getGcpAccessToken } from './gcp-auth.js';+import { describeImageJson, visionConfigured, parseJsonLoose } from './vision.js';+import { renderAvatarScene, SCENE_PRESETS } from './avatar-render.js';+import { validatePublicUrl, isPrivateAddress, SsrfError } from './ssrf.js';+import { isIP } from 'node:net';++function readEnv(name) {+ if (typeof process !== 'undefined' && process.env?.[name]) return process.env[name];+ return null;+}++function intEnv(name, fallback) {+ const v = readEnv(name);+ const n = v == null || v === '' ? NaN : Number(v);+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : fallback;+}++// Env-tunable knobs. Defaults chosen for the Forge lanes; a deployment can retune+// without a code change.+export const QUALITY_GATE_DEFAULTS = Object.freeze({+ // A verdict at or above this composite score passes the gate.+ passScore: intEnv('FORGE_QUALITY_PASS_SCORE', 60),+ // Hard cap on auto-retries per generation, so a persistently-bad prompt can+ // never burn unbounded GCP credit. attempt is 0-indexed, so 2 means the+ // original plus up to two adjusted regenerations.+ maxRetries: intEnv('FORGE_QUALITY_MAX_RETRIES', 2),+ // Vertex model + region. gemini-2.5-flash is vision-capable and serves on+ // us-central1 and global (both probed live).+ model: readEnv('VERTEX_QUALITY_MODEL') || 'gemini-2.5-flash',+ location: readEnv('GOOGLE_CLOUD_LOCATION_QUALITY') || readEnv('GOOGLE_CLOUD_LOCATION') || 'us-central1',+ // Render size for scoring. Small keeps image-token cost low while staying+ // legible enough for a realism call.+ renderSize: intEnv('FORGE_QUALITY_RENDER_SIZE', 640),+ // Per-call vision timeout.+ timeoutMs: intEnv('FORGE_QUALITY_TIMEOUT_MS', 25_000),+});++// ── Subject awareness ─────────────────────────────────────────────────────────+// The photoreal bar differs by subject: a person needs correct anatomy and skin;+// food needs appetizing surface and no plastic sheen; a vehicle needs panel gaps+// and real paint. Detecting the subject lets the rubric ask for the right cues+// and lets the retry hint steer regeneration toward them.+const SUBJECT_RULES = Object.freeze({+ person: {+ match: /\b(person|man|woman|boy|girl|human|character|warrior|knight|astronaut|soldier|king|queen|figure|portrait|avatar|face|guy|lady|ninja|wizard|hero)\b/i,+ cues: 'correct human anatomy and proportions, five fingers per hand, two eyes, symmetric face, realistic skin with pores (not plastic or waxy), one single complete body (no extra or fused limbs, no duplicated heads)',+ },+ animal: {+ match: /\b(cat|dog|horse|bird|dragon|lion|tiger|bear|wolf|fox|animal|creature|fish|snake|deer|rabbit|elephant|monster|beast)\b/i,+ cues: 'correct animal anatomy (right leg count, single head/tail), real fur/scale/feather texture, no melted or fused limbs',+ },+ food: {+ match: /\b(food|burger|pizza|cake|fruit|apple|bread|sushi|donut|coffee|drink|meal|dish|sandwich|ice cream|cookie|steak)\b/i,+ cues: 'appetizing photoreal surface, real food texture and translucency, no plastic sheen, no toy-like uniform color',+ },+ vehicle: {+ match: /\b(car|truck|vehicle|motorcycle|plane|aircraft|ship|boat|tank|bike|bus|train|rocket|helicopter)\b/i,+ cues: 'real paint with panel gaps and reflections, correct wheel/window/light placement, symmetric body, no warped or collapsed panels',+ },+ plant: {+ match: /\b(tree|plant|flower|bush|leaf|grass|cactus|fern|rose|palm|forest)\b/i,+ cues: 'natural organic branching and leaf texture, real botanical silhouette, no fused or repeating geometry',+ },+ building: {+ match: /\b(house|building|castle|tower|church|temple|bridge|structure|architecture|room|shop|store|hut|cabin)\b/i,+ cues: 'straight structural lines, real material texture (brick/wood/stone/glass), coherent architecture, no floating or collapsed sections',+ },+ object: {+ match: /.*/,+ cues: 'real PBR-looking materials (metal/wood/fabric/leather read as their true material, not flat plastic), complete single object, correct proportions, no melted or blobby geometry',+ },+});++// Resolve a subject category from an explicit hint or the prompt text. Falls back+// to the generic "object" bar, which every asset must at least clear.+export function subjectFromPrompt(prompt, hint = null) {+ if (hint && SUBJECT_RULES[hint]) return hint;+ const text = String(prompt || '');+ for (const key of ['person', 'animal', 'food', 'vehicle', 'plant', 'building']) {+ if (SUBJECT_RULES[key].match.test(text)) return key;+ }+ return 'object';+}++// Build the rubric prompt sent to the vision model. Subject-aware, and it demands+// a strict JSON reply so the parse is reliable (VLMs honor "reply ONLY JSON").+function rubricPrompt(subject, prompt) {+ const rule = SUBJECT_RULES[subject] || SUBJECT_RULES.object;+ const promptLine = prompt+ ? `The model was generated from this request: "${String(prompt).slice(0, 400)}".`+ : 'No source prompt was provided.';+ return [+ 'You are a strict quality inspector for an AI 3D-model generator. You are shown a render of ONE generated 3D model.',+ promptLine,+ `This model is a ${subject}. For this subject, a good result shows: ${rule.cues}.`,+ '',+ 'OUR BAR is photoreal: the render should look like a real photograph of a real physical object or being, not a video-game asset, not a plastic toy, not a clay sculpt.',+ '',+ 'Reject (low score) any of these failure modes if present: blobby/melted/undefined geometry; a plastic or toy-like look when the subject should be real; incomplete or partial mesh (missing parts, holes, cut-off body); duplicated or fused parts (two heads, extra limbs, merged copies); floating disconnected fragments; garbled or smeared textures; flat untextured gray/white surfaces; wildly wrong proportions.',+ '',+ 'Reply with ONLY this JSON object and nothing else:',+ '{',+ ' "score": <int 0-100, overall how photoreal and correct this is>,',+ ' "realism": <int 0-100, how photographic vs toy/plastic/CG the materials and shading look>,',+ ' "completeness": <int 0-100, how complete and single-subject the geometry is (100 = one whole subject, low = missing/partial/duplicated/fragmented)>,',+ ' "is_photoreal": <true|false>,',+ ' "subject_detected": "<what you actually see>",',+ ' "defects": [<zero or more short tags from: blob, melted, plastic, toy, incomplete, partial, holes, duplicated, fused, extra_limbs, floating_fragments, garbled_texture, untextured, wrong_proportions, low_detail>],',+ ' "reason": "<one concrete sentence on the main quality issue, or why it is good>",',+ ' "retry_hint": "<one short instruction to improve a regeneration, or empty string if it is already good>"',+ '}',+ ].join('\n');+}++// Clamp a value into a 0-100 integer, or null when it is not a finite number.+function score100(v) {+ const n = Number(v);+ if (!Number.isFinite(n)) return null;+ return Math.max(0, Math.min(100, Math.round(n)));+}++// SSRF guard for a caller-supplied render URL we fetch server-side. Mirrors the+// guard in vision.js: require https (http only in dev) and reject private IP+// literals + localhost. DNS-name hosts pass (we can't pin resolution here).+function assertSafeUrl(rawUrl) {+ let url;+ try {+ url = validatePublicUrl(rawUrl);+ } catch (e) {+ if (e instanceof SsrfError) throw Object.assign(new Error('render URL is not a public https address'), { code: 'invalid_url' });+ throw e;+ }+ const host = url.hostname.replace(/^\[|\]$/g, '');+ const fam = isIP(host);+ const blocked = fam ? isPrivateAddress(host, fam) : host === 'localhost' || /\.(local|internal|localdomain)$/i.test(host);+ if (blocked) throw Object.assign(new Error('render URL resolves to a non-public host'), { code: 'invalid_url' });+ return url;+}++// Fetch an image URL and return { base64, mimeType }. Guarded + size-capped.+async function fetchImageBase64(rawUrl, timeoutMs) {+ assertSafeUrl(rawUrl);+ const res = await fetch(rawUrl, { signal: AbortSignal.timeout(timeoutMs) });+ if (!res.ok) throw new Error(`render fetch ${res.status}`);+ const ct = (res.headers.get('content-type') || 'image/png').split(';')[0].trim();+ const buf = Buffer.from(await res.arrayBuffer());+ if (buf.byteLength > 16 * 1024 * 1024) throw new Error('render image exceeds 16 MB');+ return { base64: buf.toString('base64'), mimeType: ct.startsWith('image/') ? ct : 'image/png' };+}++// Render a GLB to a PNG and return { base64, mimeType }. Uses the shared headless+// pipeline (avatar-render.js) with a full-body framing on a neutral dark+// background so the whole subject is judged, not a cropped portrait.+async function renderGlbBase64(glbUrl, size) {+ assertSafeUrl(glbUrl);+ const { png } = await renderAvatarScene({+ glbUrl,+ width: size,+ height: size,+ background: '#101014',+ scenePreset: SCENE_PRESETS['full-body'],+ });+ return { base64: Buffer.from(png).toString('base64'), mimeType: 'image/png' };+}++// Resolve a GCP OAuth bearer token. Primary path is the shared service-account /+// metadata-server minter (production Cloud Run). As an additive fallback for+// environments where an ambient gcloud token is exported (local verification,+// CI shells), accept GOOGLE_ACCESS_TOKEN / GCLOUD_ACCESS_TOKEN. Never logged.+async function resolveGcpToken() {+ try {+ return await getGcpAccessToken();+ } catch (e) {+ const ambient = readEnv('GOOGLE_ACCESS_TOKEN') || readEnv('GCLOUD_ACCESS_TOKEN');+ if (ambient) return ambient.trim();+ throw e;+ }+}++// True when the Vertex Gemini lane can be attempted (GCP project configured).+export function vertexQualityConfigured() {+ return Boolean(readEnv('GOOGLE_CLOUD_PROJECT'));+}++// True when the gate can score at all — Vertex OR the free platform vision chain.+// Use to decide whether to bother rendering (a cheap pre-check the router can run).+export function qualityGateConfigured() {+ return vertexQualityConfigured() || visionConfigured();+}++// Score one render via Vertex Gemini. Returns { json, provider, model } or throws.+async function scoreViaVertex({ imageBase64, mimeType, prompt, subject, timeoutMs }) {+ const project = readEnv('GOOGLE_CLOUD_PROJECT');+ if (!project) throw Object.assign(new Error('GOOGLE_CLOUD_PROJECT unset'), { code: 'unconfigured' });+ const location = QUALITY_GATE_DEFAULTS.location;+ const model = QUALITY_GATE_DEFAULTS.model;+ const token = await resolveGcpToken();+ const host = location === 'global' ? 'https://aiplatform.googleapis.com' : `https://${location}-aiplatform.googleapis.com`;+ const endpoint = `${host}/v1/projects/${project}/locations/${location}/publishers/google/models/${model}:generateContent`;++ const body = {+ contents: [+ {+ role: 'user',+ parts: [+ { text: rubricPrompt(subject, prompt) },+ { inlineData: { mimeType, data: imageBase64 } },+ ],+ },+ ],+ generationConfig: { temperature: 0, responseMimeType: 'application/json', maxOutputTokens: 700 },+ };++ const res = await fetch(endpoint, {+ method: 'POST',+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },+ body: JSON.stringify(body),+ signal: AbortSignal.timeout(timeoutMs),+ });+ if (!res.ok) {+ const text = await res.text().catch(() => '');+ throw Object.assign(new Error(`vertex ${res.status}: ${text.slice(0, 200)}`), { status: res.status });+ }+ const data = await res.json();+ const parts = data?.candidates?.[0]?.content?.parts || [];+ const text = parts.map((p) => p?.text || '').join('').trim();+ if (!text) {+ const reason = data?.candidates?.[0]?.finishReason;+ throw new Error(`vertex returned no text${reason ? ` (finishReason: ${reason})` : ''}`);+ }+ return { json: parseJsonLoose(text), provider: 'vertex', model: `vertex-ai/${model}` };+}++// Score one render via the free platform vision chain (NVIDIA NIM VLMs). Reuses+// describeImageJson so the free-first doctrine and spend ledger are inherited.+async function scoreViaPlatformVision({ imageBase64, mimeType, prompt, subject, timeoutMs, track }) {+ const out = await describeImageJson({+ prompt: rubricPrompt(subject, prompt),+ imageBase64,+ mimeType,+ maxTokens: 700,+ timeoutMs,+ deadlineMs: timeoutMs + 4000,+ track: { ...(track || {}), tool: 'api/_lib/forge-quality-gate' },+ });+ return { json: out.json, provider: out.provider, model: out.model };+}++// Normalize a raw model reply into the public verdict shape, applying our pass+// threshold. A model that flags a critical structural defect fails even if it+// reported a generous score, because those defects are exactly what users must+// never see.+const CRITICAL_DEFECTS = new Set(['blob', 'melted', 'incomplete', 'partial', 'holes', 'duplicated', 'fused', 'extra_limbs', 'floating_fragments']);++function normalizeVerdict(raw, { subject, provider, model, passScore, renderSource }) {+ const score = score100(raw?.score);+ const realism = score100(raw?.realism);+ const completeness = score100(raw?.completeness);+ const defects = Array.isArray(raw?.defects)+ ? raw.defects.map((d) => String(d).toLowerCase().trim().replace(/\s+/g, '_')).filter(Boolean).slice(0, 12)+ : [];+ const hasCritical = defects.some((d) => CRITICAL_DEFECTS.has(d));+ const hint = typeof raw?.retry_hint === 'string' ? raw.retry_hint.trim() : '';+ // Pass requires clearing the score threshold AND not carrying a critical+ // structural defect. A null score (unparseable field) fails closed to a retry+ // only if the provider still answered; a total outage is handled upstream by+ // fail-open.+ const pass = score != null && score >= passScore && !hasCritical;+ return {+ pass,+ score,+ realism,+ completeness,+ subject,+ subject_detected: typeof raw?.subject_detected === 'string' ? raw.subject_detected.slice(0, 120) : null,+ is_photoreal: raw?.is_photoreal === true,+ defects,+ reason: typeof raw?.reason === 'string' ? raw.reason.slice(0, 400) : (pass ? 'meets the realism bar' : 'below the realism bar'),+ suggested_retry_hint: hint || (pass ? null : 'increase realism and detail; render as a real photograph of the subject'),+ provider,+ model,+ qa_available: true,+ render_source: renderSource,+ };+}++// A fail-open pass verdict, returned whenever scoring cannot run. The router MUST+// ship this (qa_available:false) rather than retry — a QA outage is not a quality+// failure of the model.+function failOpen(reason, { subject = 'object', renderSource = 'none' } = {}) {+ return {+ pass: true,+ score: null,+ realism: null,+ completeness: null,+ subject,+ subject_detected: null,+ is_photoreal: null,+ defects: [],+ reason: `qa_unavailable: ${reason}`,+ suggested_retry_hint: null,+ provider: null,+ model: null,+ qa_available: false,+ render_source: renderSource,+ };+}++/**+ * Run the realism / quality gate on a generated model.+ *+ * Provide the GLB to render, or a render you already have. Exactly one image is+ * scored: a provided renderBase64, else a fetched renderUrl, else a fresh render+ * of glbUrl.+ *+ * @param {object} opts+ * @param {string} [opts.glbUrl] public GLB URL to render + score+ * @param {string} [opts.renderUrl] public image URL of an existing render+ * @param {string} [opts.renderBase64] base64 (or data: URI) of an existing render+ * @param {string} [opts.mimeType] mime for renderBase64 (default image/png)+ * @param {string} [opts.prompt] the source generation prompt (steers rubric + retry)+ * @param {string} [opts.subject] explicit subject category override+ * @param {number} [opts.passScore] override the pass threshold+ * @param {object} [opts.track] spend-ledger attribution passed to platform vision+ * @returns {Promise<object>} verdict (never throws — fail-open on any error)+ */+export async function runQualityGate({+ glbUrl = null,+ renderUrl = null,+ renderBase64 = null,+ mimeType = 'image/png',+ prompt = null,+ subject = null,+ passScore = QUALITY_GATE_DEFAULTS.passScore,+ track = null,+} = {}) {+ const subj = subjectFromPrompt(prompt, subject);++ if (!qualityGateConfigured()) {+ return failOpen('no vision provider configured (set GOOGLE_CLOUD_PROJECT for Vertex, or NVIDIA_API_KEY for the free lane)', { subject: subj });+ }++ // 1. Obtain exactly one image to score.+ let image;+ let renderSource;+ try {+ if (renderBase64) {+ const m = String(renderBase64).match(/^data:(image\/[a-z+]+);base64,(.*)$/i);+ image = { base64: m ? m[2] : String(renderBase64).replace(/^data:[^,]*,/, ''), mimeType: m ? m[1].toLowerCase() : mimeType };+ renderSource = 'provided_base64';+ } else if (renderUrl) {+ image = await fetchImageBase64(renderUrl, QUALITY_GATE_DEFAULTS.timeoutMs);+ renderSource = 'provided_url';+ } else if (glbUrl) {+ image = await renderGlbBase64(glbUrl, QUALITY_GATE_DEFAULTS.renderSize);+ renderSource = 'rendered_glb';+ } else {+ return failOpen('no glbUrl, renderUrl, or renderBase64 supplied', { subject: subj });+ }+ } catch (e) {+ // A render / fetch failure is a QA outage, not a model failure — fail open.+ return failOpen(`could not obtain a render: ${e?.message || e}`, { subject: subj });+ }++ // 2. Score it. Vertex first, free platform vision as automatic backup.+ let scored = null;+ let lastErr = null;+ if (vertexQualityConfigured()) {+ try {+ scored = await scoreViaVertex({ ...image, prompt, subject: subj, timeoutMs: QUALITY_GATE_DEFAULTS.timeoutMs });+ } catch (e) {+ lastErr = e;+ }+ }+ if (!scored && visionConfigured()) {+ try {+ scored = await scoreViaPlatformVision({ ...image, prompt, subject: subj, timeoutMs: QUALITY_GATE_DEFAULTS.timeoutMs, track });+ } catch (e) {+ lastErr = lastErr || e;+ }+ }+ if (!scored) {+ return failOpen(`scoring failed: ${lastErr?.message || 'no provider answered'}`, { subject: subj, renderSource });+ }++ // 3. Normalize + apply the threshold.+ return normalizeVerdict(scored.json, {+ subject: subj,+ provider: scored.provider,+ model: scored.model,+ passScore,+ renderSource,+ });+}++// ── Auto-retry directive ──────────────────────────────────────────────────────++const TIER_LADDER = ['draft', 'standard', 'high'];++function nextTier(tier) {+ const i = TIER_LADDER.indexOf(tier);+ if (i < 0) return 'standard';+ return TIER_LADDER[Math.min(i + 1, TIER_LADDER.length - 1)];+}++// Turn defect tags into a short negative-guidance clause the regeneration prompt+// can carry, plus a decision on whether to switch the generation path.+function guidanceFromDefects(defects) {+ const set = new Set(defects || []);+ const avoid = [];+ if (set.has('plastic') || set.has('toy')) avoid.push('plastic or toy-like materials');+ if (set.has('blob') || set.has('melted')) avoid.push('blobby or melted geometry');+ if (set.has('incomplete') || set.has('partial') || set.has('holes')) avoid.push('missing or incomplete parts');+ if (set.has('duplicated') || set.has('fused') || set.has('extra_limbs')) avoid.push('duplicated or fused parts');+ if (set.has('floating_fragments')) avoid.push('floating disconnected fragments');+ if (set.has('garbled_texture') || set.has('untextured')) avoid.push('smeared or missing textures');+ if (set.has('wrong_proportions')) avoid.push('wrong proportions');+ // A structural defect (blob/incomplete/duplicated) is best fought with more+ // geometric budget and the image path, which grounds the mesh in a reference.+ const structural = ['blob', 'melted', 'incomplete', 'partial', 'holes', 'duplicated', 'fused', 'extra_limbs', 'floating_fragments'];+ const wantsMoreGeometry = structural.some((d) => set.has(d));+ return { avoid, wantsMoreGeometry };+}++/**+ * Given a failed verdict and the directive that produced it, build a concrete+ * adjusted directive for ONE regeneration. Returns null when a retry should not+ * happen: the verdict passed, QA was unavailable (never retry on an outage), or+ * the retry cap is reached.+ *+ * @param {object} verdict a runQualityGate() result+ * @param {object} base { prompt, tier, path, attempt, maxRetries }+ * attempt is 0-indexed (0 = the original generation). The returned directive+ * carries attempt+1. Stop when attempt+1 > maxRetries.+ * @returns {object|null} { prompt, tier, path, attempt, reason } or null+ */+export function buildRetryDirective(verdict, base = {}) {+ if (!verdict || verdict.pass || verdict.qa_available === false) return null;+ const maxRetries = Number.isFinite(base.maxRetries) ? base.maxRetries : QUALITY_GATE_DEFAULTS.maxRetries;+ const attempt = Number.isFinite(base.attempt) ? base.attempt : 0;+ const nextAttempt = attempt + 1;+ if (nextAttempt > maxRetries) return null;++ const { avoid, wantsMoreGeometry } = guidanceFromDefects(verdict.defects);+ const basePrompt = String(base.prompt || '').trim();+ const hint = verdict.suggested_retry_hint ? ` ${verdict.suggested_retry_hint.trim()}` : '';+ const avoidClause = avoid.length ? ` Avoid: ${avoid.join(', ')}.` : '';+ // Append photoreal steering to the original prompt without discarding it, so+ // the subject stays intact while the realism bar is pushed.+ const prompt = `${basePrompt}, photorealistic, real photograph, high detail, accurate proportions, realistic PBR materials.${avoidClause}${hint}`.trim();++ const tier = wantsMoreGeometry ? nextTier(base.tier || 'standard') : (base.tier || 'standard');+ // Switch to the image path on a structural failure: a reference image grounds+ // the reconstruction and cuts blob/duplication failure modes. Leave a non-+ // structural (material-only) failure on its current path — a tighter prompt+ // alone usually fixes plastic/toy looks.+ const path = wantsMoreGeometry ? 'image' : (base.path || 'image');++ return {+ prompt,+ tier,+ path,+ attempt: nextAttempt,+ reason: `retry ${nextAttempt}/${maxRetries}: ${verdict.reason || 'below realism bar'}`,+ };+}++// ── ROUTER SEAM (copy-paste contract for api/forge.js, owned by another agent) ──+//+// After a generation produces { glb_url } and BEFORE returning it to the user,+// the router can gate + auto-retry like this (fail-open by construction):+//+// import { runQualityGate, buildRetryDirective, QUALITY_GATE_DEFAULTS } from './_lib/forge-quality-gate.js';+//+// let directive = { prompt, tier, path, attempt: 0, maxRetries: QUALITY_GATE_DEFAULTS.maxRetries };+// let result = await generateOnce(directive); // existing generation call+// let verdict = await runQualityGate({ glbUrl: result.glb_url, prompt: directive.prompt });+//+// while (!verdict.pass && verdict.qa_available) {+// const next = buildRetryDirective(verdict, directive); // null when cap reached+// if (!next) break;+// directive = next;+// result = await generateOnce(directive); // regenerate with adjusted directive+// verdict = await runQualityGate({ glbUrl: result.glb_url, prompt: directive.prompt });+// }+// // Ship `result` regardless. Attach `verdict` to creation metadata for observability.+// // verdict.qa_available === false → QA outage, ship as-is, do NOT retry.+// // verdict.pass === false && cap hit → best effort shipped; the verdict explains why.diff --git a/api/_lib/forge-reference-image.js b/api/_lib/forge-reference-image.jsnew file mode 100644index 000000000..7c2020cdd--- /dev/null+++ b/api/_lib/forge-reference-image.js@@ -0,0 +1,247 @@+// Reference-image builder for the text→3D forge (NEW, additive lane).+//+// ── Why this module exists ───────────────────────────────────────────────────+// The text→3D pipeline is: user prompt → prompt director rewrite → a reference+// IMAGE is generated → TRELLIS/Hunyuan3D reconstructs a textured GLB from that+// image. The realism of the final mesh is set almost entirely by the realism of+// that one reference image: a photoreal, single-subject, plain-seamless-+// background, evenly-lit image reconstructs into a real-looking mesh; a+// cartoonish or cluttered one does not.+//+// This module generates that reference image on the Vertex Gemini 2.5 Flash+// Image lane (GCP-credit funded, owner-approved spend), tuned specifically to+// produce the IDEAL reconstruction input:+// - a single centered subject on a plain seamless studio background,+// - soft even shadowless lighting,+// - real-world materials and surface micro-detail (the photoreal look),+// - the directed prompt's positive cues PLUS the director's negative prompt+// folded in as explicit natural-language avoidance (Gemini honors "Do not+// include: …" reliably; generateContent has no negative_prompt parameter),+// - the highest resolution the model tier serves (imageConfig.imageSize "2K").+//+// It is ADDITIVE and never a gate: if the Vertex lane is unconfigured or fails+// for any reason, it falls through to the existing reference-image provider+// (api/_mcp3d/text-to-image.js — NIM FLUX free lane, Vertex Imagen, Replicate+// backstop), so nothing regresses relative to today's behavior.+//+// ── Router seam ──────────────────────────────────────────────────────────────+// api/forge.js currently synthesizes the text→3D reference view at ~line 1557:+//+// const synthesized = await textToImage(directedPrompt, {+// aspectRatio: aspect,+// skipNim: nimGatewayDegraded,+// seed: opts.seed ?? undefined,+// });+//+// The router agent (which owns forge.js) can drop this module in as a direct+// replacement — the return shape { imageUrl, model } is identical, so nothing+// else in that function changes:+//+// import { generateReferenceImage } from './_lib/forge-reference-image.js';+// const synthesized = await generateReferenceImage(directedPrompt, {+// aspectRatio: aspect,+// skipNim: nimGatewayDegraded,+// seed: opts.seed ?? undefined,+// negativePrompt: directorNegativePrompt, // optional; auto-derived if omitted+// });+//+// `negativePrompt` is optional: when omitted, a subject-aware default is derived+// from the prompt via subjectNegativePrompt() (the same assembly the+// /api/forge-enhance response uses), so the router gets subject-aware negatives+// for free without having to run the enhance endpoint first.+//+// Output: { imageUrl, model, lane } where imageUrl is a durable public https URL+// (persisted to R2, same as textToImage), model is a provider/model label, and+// lane is 'vertex-reference' or the fallthrough provider's own label.++import { getGcpAccessToken } from './gcp-auth.js';+import { putObject, publicUrl } from './r2.js';+import { subjectNegativePrompt } from '../forge-enhance.js';+import { textToImage } from '../_mcp3d/text-to-image.js';++// Gemini image model on Vertex ("Nano Banana"): live, credit-billed, uses the+// :generateContent shape. Overridable without a code change.+const DEFAULT_MODEL = process.env.VERTEX_IMAGEN_MODEL || 'gemini-2.5-flash-image';+// The Gemini image lane is served on the un-prefixed global host by default; a+// regional value ('us-central1') uses the region-prefixed host. Both verified+// live 2026-07-16. Separate from the text lanes so the image lane can be pinned+// independently.+const DEFAULT_LOCATION =+ process.env.GOOGLE_CLOUD_LOCATION_IMAGE || process.env.GOOGLE_CLOUD_LOCATION || 'global';+// Request the highest resolution the model tier serves. "2K" is accepted today+// and currently renders at 1024px on this project's tier (harmless, and it+// upgrades automatically when the tier serves true 2K). Force 1K with+// VERTEX_IMAGE_SIZE=1K if a deployment wants the smaller/faster output.+const DEFAULT_IMAGE_SIZE = process.env.VERTEX_IMAGE_SIZE || '2K';++// Aspect ratios Gemini image generation accepts via generationConfig.imageConfig.+const GEMINI_ASPECTS = new Set([+ '1:1', '3:2', '2:3', '3:4', '4:3', '4:5', '5:4', '9:16', '16:9', '21:9',+]);++// Match the private gate in text-to-image.js / ai-image-lanes.js: the Vertex+// image lane is active when GOOGLE_CLOUD_PROJECT is set unless VERTEX_IMAGEN_ENABLED+// explicitly disables it.+function vertexImageEnabled() {+ if (!process.env.GOOGLE_CLOUD_PROJECT) return false;+ const raw = process.env.VERTEX_IMAGEN_ENABLED;+ if (raw == null) return true;+ return !/^(0|false|no|off)$/i.test(String(raw).trim());+}++function aiplatformHost(location) {+ return location === 'global'+ ? 'https://aiplatform.googleapis.com'+ : `https://${location}-aiplatform.googleapis.com`;+}++// Wrap the directed prompt into a reference-image instruction that pins the+// exact composition a reconstructor needs: one centered subject, plain seamless+// studio sweep, soft even shadowless light, photoreal real-world materials, and+// the negative prompt as explicit avoidance. This is the difference between+// "draw the thing" and "shoot the thing the way a photogrammetry rig needs it".+export function buildReferenceInstruction(prompt, negativePrompt) {+ const subject = String(prompt || '').trim();+ // The instruction never names the downstream use ("for 3D reconstruction"):+ // telling an image model its output feeds a reconstructor measurably nudges it+ // toward a CGI/render aesthetic. It only ever describes the desired LOOK — a+ // real studio photograph — and the composition a reconstructor happens to need.+ const lines = [+ 'A single photorealistic studio photograph of the following subject, shot on a professional camera.',+ `Subject: ${subject}.`,+ 'Composition: exactly one subject, centered and fully in frame, filling most of the frame, ' ++ 'shot straight-on at eye level like a product or portrait catalog photo.',+ 'Background: a plain, seamless, uncluttered light-grey studio sweep with nothing else in the scene.',+ 'Lighting: soft, even, neutral studio lighting with no harsh shadows and no colored gels, so the ' ++ 'subject is evenly lit from all sides.',+ 'Look: this must read as a genuine photograph taken with a real camera, with true-to-life ' ++ 'materials, natural surface micro-detail (grain, weave, pores, wear, brush marks), real depth ' ++ 'of field and sharp focus. Absolutely not a 3D render, not CGI, not an illustration, not a cartoon.',+ ];+ if (negativePrompt && String(negativePrompt).trim()) {+ lines.push(`Do NOT include: ${String(negativePrompt).trim()}.`);+ }+ return lines.join(' ');+}++// Persist a base64 image to R2 and return a durable public https URL. The 3D+// backends take URLs (Replicate caps inline data URIs at ~256 KB), so neither+// the Vertex inline data nor a NIM artifact can be forwarded as-is. Format is+// sniffed from the magic bytes so the key extension and Content-Type match the+// real payload (Gemini image returns PNG; sniff keeps it correct if that changes).+async function persistImageBase64(b64) {+ const body = Buffer.from(b64, 'base64');+ const isJpeg = body.length > 2 && body[0] === 0xff && body[1] === 0xd8 && body[2] === 0xff;+ const ext = isJpeg ? 'jpg' : 'png';+ const key = `forge/refs/${globalThis.crypto.randomUUID()}.${ext}`;+ await putObject({ key, body, contentType: isJpeg ? 'image/jpeg' : 'image/png' });+ return publicUrl(key);+}++// One Vertex Gemini image generation. Returns { b64, mime } on success; throws a+// designed error on any failure so the caller can fall through. Retries once+// without imageConfig.imageSize if the tier rejects that field (defensive: the+// field is accepted today, but a tier change must degrade to a valid request+// rather than a hard failure that skips the whole Vertex lane).+async function generateViaVertex({ instruction, aspectRatio }) {+ const project = process.env.GOOGLE_CLOUD_PROJECT;+ const location = DEFAULT_LOCATION;+ const model = DEFAULT_MODEL;+ const aspect = GEMINI_ASPECTS.has(aspectRatio) ? aspectRatio : '1:1';+ const endpoint =+ `${aiplatformHost(location)}/v1/projects/${project}` ++ `/locations/${location}/publishers/google/models/${model}:generateContent`;+ const token = await getGcpAccessToken();++ const request = async (withSize) => {+ const imageConfig = withSize+ ? { aspectRatio: aspect, imageSize: DEFAULT_IMAGE_SIZE }+ : { aspectRatio: aspect };+ const res = await fetch(endpoint, {+ method: 'POST',+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },+ body: JSON.stringify({+ contents: [{ role: 'user', parts: [{ text: instruction }] }],+ generationConfig: { responseModalities: ['IMAGE'], imageConfig },+ }),+ signal: AbortSignal.timeout(60_000),+ });+ return res;+ };++ let res = await request(true);+ if (res.status === 400) {+ // Peek at the error: only retry-without-size when it is specifically about+ // imageConfig/imageSize, so a genuine bad request still fails fast.+ const detail = await res.text().catch(() => '');+ if (/imageSize|imageConfig/i.test(detail)) {+ res = await request(false);+ } else {+ throw Object.assign(new Error(`Vertex reference image 400: ${detail.slice(0, 200)}`), {+ providerStatus: 400,+ });+ }+ }+ if (!res.ok) {+ const detail = await res.text().catch(() => '');+ const err = Object.assign(+ new Error(`Vertex reference image returned ${res.status}: ${detail.slice(0, 200)}`),+ { providerStatus: res.status },+ );+ if (res.status === 429) err.code = 'rate_limited';+ throw err;+ }+ const data = await res.json();+ const parts = data?.candidates?.[0]?.content?.parts || [];+ const imgPart = parts.find((p) => p?.inlineData?.data);+ const b64 = imgPart?.inlineData?.data;+ if (!b64) {+ const reason = data?.candidates?.[0]?.finishReason;+ throw new Error(`Vertex reference image produced no image${reason ? ` (finishReason: ${reason})` : ''}`);+ }+ return { b64, mime: imgPart.inlineData.mimeType || 'image/png', model: `vertex-ai/${model}` };+}++// Generate the reconstruction reference image for a directed text→3D prompt.+//+// generateReferenceImage(directedPrompt, {+// aspectRatio = '1:1', // Gemini aspect; unknown values → '1:1'+// negativePrompt = null, // director negatives; auto-derived from the prompt if omitted+// seed, // honored only on the fallthrough lanes (Gemini image has no seed)+// skipNim = false, // forwarded to the fallthrough textToImage lane+// })+//+// Vertex-first (high-res, reference-tuned), then automatic fallthrough to the+// existing provider chain. Returns { imageUrl, model, lane }. Never throws for a+// recoverable Vertex issue — only the fallthrough's terminal error surfaces when+// every lane is exhausted, exactly as textToImage does today.+export async function generateReferenceImage(+ prompt,+ { aspectRatio = '1:1', negativePrompt = null, seed, skipNim = false } = {},+) {+ const negatives =+ negativePrompt && String(negativePrompt).trim()+ ? String(negativePrompt).trim()+ : subjectNegativePrompt(prompt, { realistic: true });++ if (vertexImageEnabled()) {+ try {+ const instruction = buildReferenceInstruction(prompt, negatives);+ const { b64, model } = await generateViaVertex({ instruction, aspectRatio });+ const imageUrl = await persistImageBase64(b64);+ console.log(`[forge-reference-image] served by ${model} (vertex-reference lane)`);+ return { imageUrl, model, lane: 'vertex-reference' };+ } catch (err) {+ // Any Vertex failure (unconfigured token, safety block, throttle, tier+ // change) degrades to the existing chain — the reference image still gets+ // made, just on the prior path. Warn, don't error.+ console.warn(`[forge-reference-image] vertex lane failed, falling through: ${err?.message}`);+ }+ }++ // Fallthrough: the current reference-image provider (NIM FLUX free → Vertex+ // Imagen → Replicate). Same call the router makes today, so this can only ever+ // add the Vertex-reference lane in front, never remove a path.+ const served = await textToImage(prompt, { aspectRatio, skipNim, seed });+ return { ...served, lane: served.lane || (served.predictionId ? 'replicate' : 'fallthrough') };+}diff --git a/api/_lib/forge-tiers.js b/api/_lib/forge-tiers.jsindex ad8088e88..21448fd4e 100644--- a/api/_lib/forge-tiers.js+++ b/api/_lib/forge-tiers.js@@ -398,12 +398,41 @@ export const FREE_DEFAULT_FOR_TIERS = Object.freeze({// of a paid engine. First configured + capable lane wins, and our OWN GPU workers// come first so the platform leans on the credits we control before any external// free lane: self-hosted TRELLIS (native single-hop image→3D), then self-hosted-// Hunyuan3D, then the free HuggingFace Spaces lane. Every entry is env-gated, so-// the list degrades cleanly on deployments that configure only some of them.+// Hunyuan3D, then the free HuggingFace Spaces lane. The free NVIDIA NIM TRELLIS+// lane trails as the final health-gated fallthrough so a text prompt still+// returns a model when every GPU worker (and HuggingFace) is cold or down — this+// is the realism-tier safety net that guarantees the High/MAX path never dead-ends+// on a cold self-host worker. NIM is text-only (userImages:false), so a photo+// submission filters it out and stops at HuggingFace, exactly as before. Every+// entry is env-gated, so the list degrades cleanly on partial deployments.export const FREE_FALLBACK_FOR_PATH = Object.freeze({- image: Object.freeze(['trellis_selfhost', 'hunyuan3d', 'huggingface']),+ image: Object.freeze(['trellis_selfhost', 'hunyuan3d', 'huggingface', 'nvidia']),});+// Realism subject classes. The two self-host PBR lanes have different strengths:+// Hunyuan3D-2.1 (shape DiT + multiview PBR paint) leads on people / organic /+// highly-detailed subjects, while self-host TRELLIS's single-hop reconstruction+// is crisp on hard-surface / mechanical / geometric subjects. The High tier keeps+// Hunyuan3D first by default (the safest realism bet) and only swaps TRELLIS ahead+// of it when the prompt clearly reads hard-surface — a stable, reversible reorder+// that never touches the draft/standard free-default ordering. Returns 'organic',+// 'hardsurface', or null (unknown → keep the default order).+const HARDSURFACE_SUBJECT_RE = /\b(robot|mech|mecha|drone|vehicle|car|truck|tank|spaceship|spacecraft|starship|rocket|weapon|gun|rifle|sword|blade|knife|armor|armour|helmet|shield|machine|engine|turbine|gear|building|architecture|house|tower|bridge|furniture|chair|table|desk|lamp|tool|wrench|hammer|gadget|device|console|controller|phone|laptop|camera|watch|ring|coin|logo|emblem|badge|crystal|gem|geometric|hard-surface|hardsurface|metallic|chrome|sci-?fi\s+prop)\b/i;+const ORGANIC_SUBJECT_RE = /\b(person|people|man|woman|boy|girl|child|human|face|portrait|character|avatar|figure|hero|warrior|knight|wizard|elf|orc|goblin|monster|creature|beast|dragon|animal|cat|dog|horse|bird|fish|lion|tiger|bear|wolf|fox|dinosaur|plant|tree|flower|body|anatomy|muscle|skin|hair|fur|organic)\b/i;++export function classifyForgeSubject(prompt) {+ if (typeof prompt !== 'string' || !prompt.trim()) return null;+ const p = prompt.toLowerCase();+ const organic = ORGANIC_SUBJECT_RE.test(p);+ const hard = HARDSURFACE_SUBJECT_RE.test(p);+ // A prompt that trips both signals (e.g. "knight in mecha armor") is treated+ // as organic — Hunyuan3D's people/creature strength is the higher-value bet and+ // stays first. Only an unambiguously hard-surface subject reorders the lanes.+ if (organic) return 'organic';+ if (hard) return 'hardsurface';+ return null;+}+// Our own GPU workers, by provider. A "self-host" lane runs on infrastructure we// operate (Cloud Run + GPU) against substantial GCP credits, so it is the lane we// most want to serve every request: zero per-call vendor cost and no BYOK@@ -448,11 +477,24 @@ function freeLaneUsable(id, p, userImages) {// free external Spaces). De-duplicated; only configured + capable lanes survive.// This is the single ordering both the env-only default and the health-aware// resolver walk, so they can never drift apart.-export function freeLaneCandidates(p, tierId, userImages) {+export function freeLaneCandidates(p, tierId, userImages, subjectClass = null) {const ordered = [];const named = FREE_DEFAULT_FOR_TIERS[tierId]?.[p];if (named) ordered.push(named);for (const id of FREE_FALLBACK_FOR_PATH[p] || []) ordered.push(id);+ // Subject-aware realism reorder (High tier only): an unambiguously hard-surface+ // subject puts self-host TRELLIS ahead of Hunyuan3D. Stable — it swaps only+ // those two ids relative to each other and leaves every other lane's position+ // (and the whole draft/standard ordering) untouched. A null/organic subject is+ // a no-op, so the default Hunyuan3D-first realism order stands.+ if (tierId === 'high' && subjectClass === 'hardsurface') {+ const hi = ordered.indexOf('hunyuan3d');+ const ti = ordered.indexOf('trellis_selfhost');+ if (hi !== -1 && ti !== -1 && ti > hi) {+ ordered.splice(ti, 1);+ ordered.splice(hi, 0, 'trellis_selfhost');+ }+ }// FORGE_SELFHOST_PRIMARY: when our own Cloud Run GPU fleet is live, hoist the// self-host lanes ahead of every hosted free lane (NVIDIA NIM / HuggingFace) so// the platform spends the GCP credits it controls before any external free@@ -478,8 +520,8 @@ export function freeLaneCandidates(p, tierId, userImages) {// Resolve the default backend for a (path, tier) when the caller didn't name one.// Free-for-us policy: the first configured free lane in the candidate ordering,// and only the paid standing default when NO free lane is live on this deployment.-function defaultBackendFor(p, tierId, userImages) {- const candidates = freeLaneCandidates(p, tierId, userImages);+function defaultBackendFor(p, tierId, userImages, subjectClass = null) {+ const candidates = freeLaneCandidates(p, tierId, userImages, subjectClass);return candidates[0] || DEFAULT_BACKEND_FOR_PATH[p];}@@ -497,8 +539,8 @@ function defaultBackendFor(p, tierId, userImages) {// 3. Only when every free lane is confirmed down, the paid standing default.// With an empty/undefined health map this returns exactly what defaultBackendFor// would, so callers with no telemetry are unaffected.-export function defaultBackendForHealthAware(p, tierId, userImages, health) {- const candidates = freeLaneCandidates(p, tierId, userImages);+export function defaultBackendForHealthAware(p, tierId, userImages, health, subjectClass = null) {+ const candidates = freeLaneCandidates(p, tierId, userImages, subjectClass);if (!candidates.length) return DEFAULT_BACKEND_FOR_PATH[p];const statusOf = (id) => health?.[id];const preferred = candidates.find((id) => {@@ -517,13 +559,13 @@ export function defaultBackendForHealthAware(p, tierId, userImages, health) {// the resolved default must be a backend that accepts them. An explicitly named// backend is always honored here — the forge handler rejects an unsupported// (backend, input) combination with a designed error at the boundary instead.-export function resolveBackendId({ path, tier, backend, userImages = false }) {+export function resolveBackendId({ path, tier, backend, userImages = false, subjectClass = null }) {const p = PATHS.includes(path) ? path : DEFAULT_PATH;if (backend && BACKENDS[backend] && BACKENDS[backend].paths.includes(p)) {return backend;}const tierId = tier?.id || tier || DEFAULT_TIER;- return defaultBackendFor(p, tierId, userImages);+ return defaultBackendFor(p, tierId, userImages, subjectClass);}// Health-aware twin of resolveBackendId: an explicitly named backend is always@@ -533,13 +575,13 @@ export function resolveBackendId({ path, tier, backend, userImages = false }) {// laneId → status map (see defaultBackendForHealthAware). Pure — the caller// gathers the (cached) snapshot and passes it in, so this stays trivially// testable and adds no I/O of its own.-export function resolveBackendIdWithHealth({ path, tier, backend, userImages = false, health }) {+export function resolveBackendIdWithHealth({ path, tier, backend, userImages = false, health, subjectClass = null }) {const p = PATHS.includes(path) ? path : DEFAULT_PATH;if (backend && BACKENDS[backend] && BACKENDS[backend].paths.includes(p)) {return backend;}const tierId = tier?.id || tier || DEFAULT_TIER;- return defaultBackendForHealthAware(p, tierId, userImages, health);+ return defaultBackendForHealthAware(p, tierId, userImages, health, subjectClass);}function readEnv(name) {diff --git a/api/forge-enhance.js b/api/forge-enhance.jsindex e8ed8bb55..14c77f100 100644--- a/api/forge-enhance.js+++ b/api/forge-enhance.js@@ -23,6 +23,7 @@import { cors, method, wrap, error, readJson, json, rateLimited } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { llmComplete, LlmUnavailableError } from './_lib/llm.js';+import { getGcpAccessToken } from './_lib/gcp-auth.js';const MAX_IN = 1000;const MAX_OUT = 240;@@ -47,6 +48,130 @@ export const FORGE_PHOTOREAL_NEGATIVE_PROMPT ='cartoon shading, cel shading, airbrushed skin, uncanny valley, wax figure, cgi render look, ' +'video game character, low detail skin, plastic sheen';+// Subject-aware negatives. Each subject class reconstructs badly in a DIFFERENT+// way, so a single flat negative list under-serves all of them: a person's+// failure mode is hands and faces, a vehicle's is wheel count and panel+// symmetry, food's is a fake plastic-replica sheen. These are appended on top of+// FORGE_NEGATIVE_PROMPT for the detected subject so the reference-image and+// reconstruction steps are steered away from the failures that actually happen+// for THAT kind of thing. Included for every style (a low-poly car still must+// not sprout a third wheel); the photoreal block above is layered on separately+// only for the realistic default.+export const SUBJECT_NEGATIVES = Object.freeze({+ person:+ 'extra fingers, six fingers, fused fingers, deformed hands, malformed hands, extra arms, ' ++ 'extra limbs, missing limbs, asymmetric eyes, crossed eyes, lifeless glassy eyes, distorted face, ' ++ 'warped facial features, mannequin joints, elongated neck, unnatural body proportions',+ animal:+ 'extra legs, missing legs, fused limbs, malformed paws, distorted muzzle, two heads, extra tails, ' ++ 'matted clumped fur, unnatural eye placement, warped anatomy, hybrid creature',+ food:+ 'plastic food replica, wax food model, artificial glossy coating, inedible sheen, moldy, rotten, ' ++ 'grey unappetizing tones, cartoon food, candy colors on savory food, styrofoam prop',+ vehicle:+ 'wrong number of wheels, asymmetric wheels, warped body panels, misaligned doors, melted chrome, ' ++ 'floating parts, impossible geometry, bent chassis, duplicated headlights, deformed frame',+ object:+ 'warped edges, asymmetric silhouette, melted contours, duplicated features, distorted proportions, ' ++ 'uneven symmetry',+});++// Detect the subject class of a rough prompt so the director and the negatives+// can adapt. Ordered person → animal → vehicle → food → object: a "knight on a+// horse" is a person subject, "food truck" is a vehicle, so the more specific+// human/animal/vehicle cues win before the broad food/object nets. Whole-word+// matching so "manatee" can't read as "man" or "carrot" as "car".+const PERSON_WORDS = [+ 'person', 'human', 'man', 'woman', 'guy', 'girl', 'boy', 'lady', 'gentleman', 'people',+ 'face', 'portrait', 'selfie', 'warrior', 'knight', 'soldier', 'wizard', 'ninja', 'astronaut',+ 'pirate', 'king', 'queen', 'hero', 'villain', 'avatar', 'child', 'baby', 'elf', 'dwarf',+ // Occupations and archetypes read as a person even without the word "man/woman".+ 'firefighter', 'fireman', 'policeman', 'policewoman', 'police officer', 'officer', 'cop',+ 'nurse', 'doctor', 'surgeon', 'chef', 'cook', 'farmer', 'cowboy', 'cowgirl', 'ranger',+ 'teacher', 'pilot', 'sailor', 'captain', 'monk', 'priest', 'nun', 'samurai', 'viking',+ 'gladiator', 'barbarian', 'mage', 'sorcerer', 'sorceress', 'witch', 'princess', 'prince',+ 'superhero', 'athlete', 'dancer', 'ballerina', 'chef', 'builder', 'miner', 'diver',+];+const ANIMAL_WORDS = [+ 'animal', 'creature', 'pet', 'dog', 'puppy', 'doggo', 'cat', 'kitten', 'horse', 'pony', 'bird',+ 'eagle', 'owl', 'fish', 'shark', 'lion', 'tiger', 'bear', 'wolf', 'fox', 'rabbit', 'bunny', 'deer',+ 'cow', 'pig', 'sheep', 'goat', 'elephant', 'giraffe', 'monkey', 'dragon', 'dinosaur', 'dino',+ 'snake', 'frog', 'turtle', 'lizard', 'crab', 'octopus', 'whale', 'dolphin', 'penguin', 'panda',+ 'koala', 'mouse', 'rat', 'hamster', 'duck', 'chicken', 'rooster', 'insect', 'butterfly', 'bee',+ 'spider', 'kangaroo', 'zebra', 'rhino', 'hippo', 'crocodile', 'alligator', 'gorilla', 'squirrel',+ // Common dog breeds (whole-word) so "a golden retriever" reads as an animal.+ 'retriever', 'labrador', 'poodle', 'bulldog', 'terrier', 'husky', 'chihuahua', 'corgi',+ 'dalmatian', 'pug', 'beagle', 'shepherd', 'rottweiler', 'doberman', 'dachshund',+];+const VEHICLE_WORDS = [+ 'car', 'truck', 'van', 'bus', 'motorcycle', 'motorbike', 'bike', 'bicycle', 'scooter', 'plane',+ 'airplane', 'aeroplane', 'jet', 'aircraft', 'helicopter', 'boat', 'ship', 'yacht', 'submarine',+ 'train', 'tram', 'tank', 'spaceship', 'spacecraft', 'rocket', 'vehicle', 'sedan', 'suv', 'coupe',+ 'convertible', 'tractor', 'forklift', 'ambulance', 'firetruck',+];+const FOOD_WORDS = [+ 'food', 'fruit', 'vegetable', 'burger', 'hamburger', 'cheeseburger', 'pizza', 'cake', 'cupcake',+ 'bread', 'baguette', 'sushi', 'apple', 'banana', 'orange', 'strawberry', 'sandwich', 'donut',+ 'doughnut', 'cookie', 'biscuit', 'meal', 'dish', 'drink', 'coffee', 'latte', 'tea', 'juice',+ 'smoothie', 'ice cream', 'icecream', 'steak', 'taco', 'burrito', 'noodles', 'ramen', 'pasta',+ 'salad', 'soup', 'pie', 'pancake', 'waffle', 'croissant', 'pretzel', 'chocolate', 'candy',+ 'lollipop', 'egg', 'cheese', 'meat', 'chicken leg', 'drumstick',+];+function wordRe(words) {+ return new RegExp(`\\b(?:${words.join('|')})\\b`, 'i');+}+const PERSON_RE = wordRe(PERSON_WORDS);+const ANIMAL_RE = wordRe(ANIMAL_WORDS);+const VEHICLE_RE = wordRe(VEHICLE_WORDS);+const FOOD_RE = wordRe(FOOD_WORDS);++export function classifySubject(text) {+ const t = String(text || '');+ if (PERSON_RE.test(t)) return 'person';+ if (ANIMAL_RE.test(t)) return 'animal';+ if (VEHICLE_RE.test(t)) return 'vehicle';+ if (FOOD_RE.test(t)) return 'food';+ return 'object';+}++// The complete negative-prompt string for a prompt: the universal reconstruction+// failures, the photoreal failures (only when the result should look real), and+// the failures specific to the detected subject. This is the one place negatives+// are assembled, so the /api/forge-enhance response and the reference-image+// module (which imports this) never drift apart.+export function subjectNegativePrompt(text, { realistic = true } = {}) {+ const subject = classifySubject(text);+ const parts = [FORGE_NEGATIVE_PROMPT];+ if (realistic) parts.push(FORGE_PHOTOREAL_NEGATIVE_PROMPT);+ parts.push(SUBJECT_NEGATIVES[subject]);+ return parts.join(', ');+}++// Per-subject realism cue injected into the director's system prompt, so the+// rewrite reaches for the material and surface language that makes THAT subject+// read as a real photographed thing rather than a render.+const SUBJECT_REALISM_HINT = {+ person:+ 'This subject is a person or character: describe real skin with visible pores and subtle ' ++ 'asymmetry, individual hair strands with natural flyaways, a natural catchlight in the eyes, ' ++ 'and real worn fabric. Ordinary human proportions, never doll-like symmetry or oversized eyes.',+ animal:+ 'This subject is an animal or creature: describe real fur, feathers, or scales with directional ' ++ 'flow and natural variation, a moist natural nose or beak, lifelike eyes with a catchlight, and ' ++ 'correct anatomy for the species.',+ vehicle:+ 'This subject is a vehicle: describe real painted or brushed-metal body panels with accurate ' ++ 'panel gaps, rubber tires with tread, glass and chrome trim, and the correct wheel count and ' ++ 'symmetry. It sits still, fully in frame, three-quarter or side product view.',+ food:+ 'This subject is food or a drink: describe real edible surface texture, natural moisture and ' ++ 'freshness, appetizing true-to-life color, and real crumb, grain, or glaze. It looks freshly ' ++ 'made and edible, never a plastic or wax replica.',+ object:+ 'This subject is an object: describe its real material, finish, and surface micro-detail (grain, ' ++ 'brush marks, wear, weave) so the reconstruction bakes a convincing true-to-life texture.',+};+// Style presets: a caller can pass `style` to keep generated-set consistency// (“I want all my assets to look like low-poly game items”).const STYLE_PRESETS = {@@ -76,40 +201,50 @@ const DEFAULT_REALISM_BLOCK ='worn. Faces are anatomically ordinary — no oversized eyes, no doll-like symmetry, no exaggerated ' +'proportions — like an actual person stood in front of the camera.';-function buildSystem(style) {+export function buildSystem(style, subject = 'object') {const isRealistic = !style || style === 'photorealistic';const styleBlock =style && STYLE_PRESETS[style]? `\n- Apply this target aesthetic to every prompt you write: ${STYLE_PRESETS[style]}.`: '';const realismBlock = isRealistic ? DEFAULT_REALISM_BLOCK : '';+ // Subject-specific realism guidance only when the result should look real —+ // for an opted-in non-real style the subject hint would fight the user's ask.+ const subjectBlock =+ isRealistic && SUBJECT_REALISM_HINT[subject] ? `\n- ${SUBJECT_REALISM_HINT[subject]}` : '';return `You rewrite a user's rough idea into ONE optimal prompt for a text-to-3D pipeline \(a diffusion model paints a reference image, then a photogrammetry-style model reconstructs \-a textured 3D mesh from it).+a textured 3D mesh from it). The realism of the final 3D model is set almost entirely by this \+one reference image, so your prompt must describe a scene that photographs like a REAL object or \+a REAL person, not an illustration or a render.A great prompt for this pipeline describes a SINGLE, SOLID physical subject (an object, or a \-person/creature) with clear geometry, centered on a plain background as if shot for a product \-or portrait catalog. Rewrite the user's idea following every rule:-- Exactly one subject. If the user named several things, pick the most central one — for a person \-or character, that means the person themselves, not props scattered around them.-- Add concrete material, surface and color cues that photograph well AND reconstruct well, \-e.g. “brushed aluminium with visible machining marks”, “worn oak with tight grain”, \+person/creature) with clear geometry, CENTERED on a plain seamless background as if shot for a \+product or portrait catalog. Rewrite the user's idea following every rule:+- Exactly one subject, centered and fully in frame. If the user named several things, pick the \+most central one — for a person or character, that means the person themselves, not props \+scattered around them.+- Add concrete REAL-WORLD material, surface and color cues that photograph well AND reconstruct \+well, e.g. “brushed aluminium with visible machining marks”, “worn oak with tight grain”, \“matte ceramic with slight subsurface glow”, “cast iron with rust-speckled patina”, or for a \person: “weathered tan skin with faint freckles”, “close-cropped grey stubble”, “fine wool knit \-with visible stitching”. Surface micro-detail helps the reconstruction model generate dense, \-clean geometry and a convincing texture bake.+with visible stitching”. Name the surface micro-detail (grain, weave, pores, brush marks, wear) \+— it is what makes the reconstruction bake dense, clean geometry and a convincing, true-to-life \+texture rather than a smooth plastic one.- Prefer opaque, solid materials (metal, wood, stone, ceramic, hard plastic, skin, hair, cloth). \AVOID transparent, translucent, or mirror-reflective surfaces (glass, crystal, mirror, water) — \they produce degenerate meshes in photogrammetry reconstructors.- The silhouette must be distinct and self-contained: no thin wires, no wispy loose strands, no \fog, no overlapping objects or people. The reconstructor needs unambiguous depth cues.-- Specify soft, even studio lighting (e.g. “soft box lighting”, “diffuse white studio light”) \-and a plain white or light-grey background. Sharp shadows confuse depth estimation.+- Specify soft, even, neutral studio lighting (e.g. “soft even softbox lighting”, “diffuse white \+studio light, no harsh shadows”) and a plain white or light-grey SEAMLESS background. Even, \+shadowless lighting on a seamless sweep is what reconstructs cleanly; hard shadows and busy \+backdrops confuse depth estimation.- Keep the subject in a neutral, fully-visible resting pose (a person: standing, arms at sides or \loosely crossed, facing the camera). No actions, no motion blur, no interacting with other people \or objects, no scenes or environments.-- Stay a compact noun phrase (10–40 words). No camera brands, resolution tags, artist names, \-or quotation marks.${styleBlock}${realismBlock}+- Stay a compact noun phrase (10 to 40 words). No camera brands, resolution tags, artist names, \+or quotation marks.${subjectBlock}${styleBlock}${realismBlock}Output ONLY the rewritten prompt as a single line of plain text. No preamble, no explanation, \no markdown, no extra lines.`;@@ -128,6 +263,47 @@ function cleanPrompt(text) {return t;}+// Preferred director lane: Vertex Gemini text, billed to the platform's GCP+// credits (standing owner-approved spend). It outdraws the free 70B rungs on a+// nuanced rewrite like this, and it has no third-party free-tier quota to+// exhaust. Kept strictly OPTIONAL and fail-soft: any failure (no GCP project,+// token-exchange error, safety block, timeout, empty reply) returns null and the+// caller falls through to the existing free-first llmComplete chain unchanged, so+// the director never hard-depends on Vertex. Enabled by default when+// GOOGLE_CLOUD_PROJECT is set; force off with FORGE_ENHANCE_VERTEX=0.+function vertexDirectorEnabled() {+ if (!process.env.GOOGLE_CLOUD_PROJECT) return false;+ return !/^(0|false|no|off)$/i.test(String(process.env.FORGE_ENHANCE_VERTEX ?? '').trim() || 'on');+}++async function vertexDirect({ system, user, maxTokens = 200, timeoutMs = 8_000 }) {+ const project = process.env.GOOGLE_CLOUD_PROJECT;+ const location = process.env.GOOGLE_CLOUD_LOCATION_GEMINI || 'global';+ const model = process.env.VERTEX_GEMINI_MODEL || 'google/gemini-2.5-flash';+ const host =+ location === 'global' ? 'aiplatform.googleapis.com' : `${location}-aiplatform.googleapis.com`;+ const token = await getGcpAccessToken();+ const url = `https://${host}/v1beta1/projects/${project}/locations/${location}/endpoints/openapi/chat/completions`;+ const res = await fetch(url, {+ method: 'POST',+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },+ body: JSON.stringify({+ model,+ max_tokens: maxTokens,+ messages: [+ { role: 'system', content: system },+ { role: 'user', content: user },+ ],+ }),+ signal: AbortSignal.timeout(timeoutMs),+ });+ if (!res.ok) throw new Error(`vertex-gemini ${res.status}: ${(await res.text().catch(() => '')).slice(0, 160)}`);+ const data = await res.json();+ const text = data?.choices?.[0]?.message?.content || '';+ if (!text.trim()) throw new Error('vertex-gemini returned empty');+ return { text: text.trim(), provider: 'vertex-gemini', model };+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS' })) return;if (!method(req, res, ['POST'])) return;@@ -152,21 +328,40 @@ export default wrap(async (req, res) => {// pipeline asks for this). Still falls back to the free chain on failure.const preferNvidia = body?.engine === 'nemotron';+ // Detect the subject class so the system prompt reaches for the right realism+ // language and the negative prompt targets the right failure modes.+ const subject = classifySubject(raw);+ const system = buildSystem(style, subject);+ const userPrompt = raw.slice(0, MAX_IN);+let result;- try {- result = await llmComplete({- system: buildSystem(style),- user: raw.slice(0, MAX_IN),- maxTokens: 200,- preferNvidia,- track: { tool: 'forge-enhance', clientId: clientIp(req) },- });- } catch (err) {- if (err instanceof LlmUnavailableError) {- return error(res, 503, 'llm_unavailable', 'Prompt enhancement is not available right now.');+ // Preferred lane: Vertex Gemini on GCP credits for a higher-quality rewrite —+ // but only when the caller did not opt into the Nemotron lane, and always with+ // automatic fallthrough to the free-first chain below. A Vertex failure here is+ // swallowed so it can never regress the endpoint.+ if (!preferNvidia && vertexDirectorEnabled()) {+ try {+ result = await vertexDirect({ system, user: userPrompt, maxTokens: 200 });+ } catch (err) {+ console.warn('[forge-enhance] vertex director lane failed, using free chain:', err?.message);+ }+ }+ if (!result) {+ try {+ result = await llmComplete({+ system,+ user: userPrompt,+ maxTokens: 200,+ preferNvidia,+ track: { tool: 'forge-enhance', clientId: clientIp(req) },+ });+ } catch (err) {+ if (err instanceof LlmUnavailableError) {+ return error(res, 503, 'llm_unavailable', 'Prompt enhancement is not available right now.');+ }+ console.error('[forge-enhance] LLM failed', err.status || '', err.message);+ return error(res, 502, 'llm_failed', 'Could not enhance the prompt. Try again.');}- console.error('[forge-enhance] LLM failed', err.status || '', err.message);- return error(res, 502, 'llm_failed', 'Could not enhance the prompt. Try again.');}let prompt = cleanPrompt(result.text);@@ -176,14 +371,16 @@ export default wrap(async (req, res) => {if (prompt.length < 3) prompt = raw;const isRealistic = !style || style === 'photorealistic';- const negativePrompt = isRealistic- ? `${FORGE_NEGATIVE_PROMPT}, ${FORGE_PHOTOREAL_NEGATIVE_PROMPT}`- : FORGE_NEGATIVE_PROMPT;+ // Universal + photoreal (when realistic) + subject-specific failure modes,+ // assembled in one place (subjectNegativePrompt) so this response and the+ // reference-image module never disagree on what to steer away from.+ const negativePrompt = subjectNegativePrompt(raw, { realistic: isRealistic });return json(res, 200, {prompt,original: raw,negative_prompt: negativePrompt,+ subject,style_applied: style,provider: result.provider,model: result.model,diff --git a/api/forge-quality-check.js b/api/forge-quality-check.jsnew file mode 100644index 000000000..a8bc7c9de--- /dev/null+++ b/api/forge-quality-check.js@@ -0,0 +1,120 @@+// POST /api/forge-quality-check — score a generated 3D model's realism / quality.+//+// A thin HTTP surface over the reusable gate in api/_lib/forge-quality-gate.js.+// All provider policy (Vertex Gemini first, free NVIDIA NIM vision backup),+// rendering, the subject-aware rubric, fail-open behavior, and the retry-directive+// logic live in the lib — this file only reads the request, meters it, and shapes+// the response. The generation router (api/forge.js) imports the lib directly; this+// endpoint exists so a client, an external agent, or an ops probe can score any+// GLB (or an existing render) on demand.+//+// Request (JSON body):+// { glbUrl?, renderUrl?, image?, imageType?, prompt?, subject?, passScore?,+// tier?, path?, attempt? }+// Supply ONE of glbUrl (rendered here), renderUrl (public image URL), or image+// (base64 / data URI of a render). prompt steers the rubric + the retry hint.+// tier/path/attempt (optional) let the response include a ready-to-run retry+// directive when the model fails the gate.+// Response:+// { verdict, retry } where verdict is the structured gate result and retry is a+// buildRetryDirective() object (or null). A GET returns a capability probe.+//+// Fail-open: a scoring/render/provider outage returns 200 with+// verdict.qa_available:false and verdict.pass:true — the gate never blocks a+// generation, and neither does this endpoint.++import { cors, method, readJson, error, json, wrap, rateLimited } from './_lib/http.js';+import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import {+ runQualityGate,+ buildRetryDirective,+ qualityGateConfigured,+ vertexQualityConfigured,+ QUALITY_GATE_DEFAULTS,+} from './_lib/forge-quality-gate.js';++export const maxDuration = 60;++// base64 render inflates ~33%; a 640px PNG is well under this even before that.+const MAX_BODY_BYTES = 20 * 1024 * 1024;++export default wrap(async function handler(req, res) {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ // Capability probe — lets a UI decide whether to surface a "check quality"+ // affordance, and reports which lane will serve.+ if (req.method === 'GET' || req.method === 'HEAD') {+ return json(+ res,+ 200,+ {+ configured: qualityGateConfigured(),+ provider: vertexQualityConfigured() ? 'vertex' : (qualityGateConfigured() ? 'platform-vision' : null),+ model: vertexQualityConfigured() ? QUALITY_GATE_DEFAULTS.model : null,+ passScore: QUALITY_GATE_DEFAULTS.passScore,+ maxRetries: QUALITY_GATE_DEFAULTS.maxRetries,+ },+ { 'cache-control': 'public, max-age=60' },+ );+ }++ // Metered like the other free vision lanes (this can burn a Vertex call).+ const session = await getSessionUser(req);+ const bearer = session ? null : await authenticateBearer(extractBearer(req));+ const userId = session?.id ?? bearer?.userId ?? null;+ if (userId) {+ const rl = await limits.visionUser(userId);+ if (!rl.success) return rateLimited(res, rl, 'Quality-check rate limit exceeded, try again later');+ } else {+ const rl = await limits.visionIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl, 'Quality-check rate limit exceeded, sign in for a higher limit');+ }++ let body;+ try {+ body = await readJson(req, MAX_BODY_BYTES);+ } catch (e) {+ if (e?.status === 413) return error(res, 413, 'payload_too_large', 'request body exceeds the 20 MB limit');+ return error(res, 400, 'bad_request', e?.message || 'could not read JSON body');+ }++ const glbUrl = typeof body?.glbUrl === 'string' && body.glbUrl.trim() ? body.glbUrl.trim() : null;+ const renderUrl = typeof body?.renderUrl === 'string' && body.renderUrl.trim() ? body.renderUrl.trim() : null;+ const renderBase64 = typeof body?.image === 'string' && body.image ? body.image : null;+ if (!glbUrl && !renderUrl && !renderBase64) {+ return error(res, 400, 'bad_request', 'supply one of glbUrl, renderUrl, or image (base64 / data URI)');+ }++ const prompt = typeof body?.prompt === 'string' ? body.prompt.slice(0, 2000) : null;+ const subject = typeof body?.subject === 'string' ? body.subject : null;+ const passScore = Number.isFinite(Number(body?.passScore)) ? Number(body.passScore) : QUALITY_GATE_DEFAULTS.passScore;+ const mimeType = typeof body?.imageType === 'string' ? body.imageType : 'image/png';++ const verdict = await runQualityGate({+ glbUrl,+ renderUrl,+ renderBase64,+ mimeType,+ prompt,+ subject,+ passScore,+ track: { userId, tool: 'api/forge-quality-check' },+ });++ // When the model failed the gate (and QA is available), hand back a concrete+ // retry directive the caller can feed straight into a regeneration. tier/path/+ // attempt come from the request so the caller can drive a real retry loop.+ const retry = !verdict.pass && verdict.qa_available+ ? buildRetryDirective(verdict, {+ prompt: prompt || '',+ tier: typeof body?.tier === 'string' ? body.tier : 'standard',+ path: typeof body?.path === 'string' ? body.path : 'image',+ attempt: Number.isFinite(Number(body?.attempt)) ? Number(body.attempt) : 0,+ maxRetries: QUALITY_GATE_DEFAULTS.maxRetries,+ })+ : null;++ return json(res, 200, { verdict, retry }, { 'cache-control': 'no-store' });+});diff --git a/api/forge.js b/api/forge.jsindex 589383c91..aedf4ce9c 100644--- a/api/forge.js+++ b/api/forge.js@@ -68,6 +68,7 @@ import {resolveBackendId,resolveBackendIdWithHealth,freeLaneCandidates,+ classifyForgeSubject,isSelfHostBackend,coldStartSecondsFor,estimateEtaSeconds,@@ -336,6 +337,199 @@ function isPaidCreditFailure(err) {return /insufficient credit|purchase credit|account\/billing|out of credit|not enough credit/.test(text);}+// ── Realism modules (land concurrently; imported lazily + fail-open) ───────────+// Two dedicated modules sharpen the realism path without ever becoming a hard+// dependency of it:+// • forge-reference-image.js — seeds text→3D reconstruction with a Vertex-Gemini+// photoreal reference image (falls back to the standing text→image provider).+// • forge-quality-gate.js — scores a finished generation (vision QA) and+// supplies the retry hint that drives a bounded auto-retry.+// Both are consumed through the lazy, fail-open shims below: an absent module (not+// yet deployed) or a down Vertex backend degrades to the standing behaviour, so+// the free/default lane never regresses and a delivered model is never blocked.+// These shims are the ONLY coupling forge.js has to those modules.++function readForgeEnv(name) {+ if (typeof process !== 'undefined' && process.env && process.env[name] != null && process.env[name] !== '') {+ return process.env[name];+ }+ return null;+}++// Photoreal reconstruction reference. Prefers the dedicated Vertex-Gemini module;+// falls back to the standing text→image provider (the FLUX/Imagen/NIM chain) when+// the module is absent or Vertex is unavailable. Returns { imageUrl, model } —+// exactly textToImage()'s shape — so the call site is a drop-in swap.+async function seedReferenceImage({ prompt, aspect, seed, skipNim }) {+ if (readForgeEnv('FORGE_REFERENCE_IMAGE') !== 'off') {+ try {+ const mod = await import('./_lib/forge-reference-image.js');+ const fn =+ mod.generateReferenceImage ||+ mod.reconstructionReferenceImage ||+ mod.photorealReferenceImage ||+ mod.referenceImageForPrompt ||+ (typeof mod.default === 'function' ? mod.default : null);+ if (typeof fn === 'function') {+ const out = await fn({ prompt, aspect, aspectRatio: aspect, seed, skipNim });+ const imageUrl =+ (out && (out.imageUrl || out.image_url || out.url)) ||+ (typeof out === 'string' ? out : null);+ if (imageUrl) {+ return { imageUrl, model: (out && (out.model || out.provider)) || 'vertex-reference', referenceModule: true };+ }+ }+ } catch (err) {+ // Module not landed yet, or Vertex down — fall through to the standing lane.+ console.warn(`[forge] reference-image module unavailable, using standing provider: ${err?.message || err}`);+ }+ }+ const synthesized = await textToImage(prompt, { aspectRatio: aspect, skipNim, seed });+ return { imageUrl: synthesized.imageUrl, model: synthesized.model, referenceModule: false };+}++// Quality-gate scope: 'high' (default — only the paid/realism ceiling pays the+// vision-QA latency, so the free draft/standard default lane is left untouched),+// 'all' (score every tier), or 'off'. Env-tunable so ops widen/disable with no+// code change.+function qualityGateScope() {+ const v = (readForgeEnv('FORGE_QUALITY_GATE') || 'high').toLowerCase();+ return v === 'all' || v === 'off' ? v : 'high';+}+function qualityGateAppliesTo(tierId) {+ const s = qualityGateScope();+ if (s === 'off') return false;+ if (s === 'all') return true;+ return tierId === 'high';+}+// Bounded retry cap — default 1, clamped 0..2 so a quality retry can never turn one+// generation into an unbounded credit/latency sink.+function qualityGateMaxRetries() {+ const n = Number(readForgeEnv('FORGE_QUALITY_GATE_MAX_RETRIES'));+ if (!Number.isFinite(n)) return 1;+ return Math.max(0, Math.min(2, Math.floor(n)));+}++// Score a finished generation via the dedicated vision-QA module. Fail-open: an+// absent module or a vision outage returns a passing verdict, so scoring can never+// block or fail a delivered model. Returns the module's verdict object+// ({ score, pass, defects, suggested_retry_hint, ... }) or a skipped pass.+async function scoreQualityGate({ glbUrl, prompt, tier, backend, referenceImageUrl }) {+ try {+ const mod = await import('./_lib/forge-quality-gate.js');+ const fn =+ mod.scoreForgeQuality ||+ mod.scoreGeneration ||+ mod.qualityGateScore ||+ mod.gradeGeneration ||+ (typeof mod.default === 'function' ? mod.default : null);+ if (typeof fn === 'function') {+ const verdict = await fn({+ glbUrl,+ glb_url: glbUrl,+ prompt: prompt || null,+ tier: tier?.id || tier || null,+ backend: backend || null,+ referenceImageUrl: referenceImageUrl || null,+ });+ if (verdict && typeof verdict === 'object') return verdict;+ }+ } catch (err) {+ console.warn(`[forge] quality-gate scoring unavailable (fail-open pass): ${err?.message || err}`);+ }+ return { pass: true, skipped: true };+}++// True only for an explicit failing verdict — a skipped/absent gate never retries.+function qualityGateFailed(verdict) {+ return Boolean(verdict) && verdict.skipped !== true && verdict.pass === false;+}+// Numeric quality score used to keep the best result across retries. A passing+// verdict floors at 1; an explicit numeric score wins; a bare fail is 0.+function qualityScoreValue(verdict) {+ const n = Number(verdict?.score);+ if (Number.isFinite(n)) return n;+ if (verdict?.pass === true) return 1;+ return 0;+}++// Post-generation quality stage for the synchronous lanes: score the delivered+// model and, on a failing verdict, run a bounded best-of retry that keeps the+// higher-scoring result. `regenerate({ hint })` re-runs the SAME lane and returns+// { glbUrl, durable }; it is called at most qualityGateMaxRetries() times. When+// the module exposes its own auto-retry helper it owns the loop instead (it holds+// the hint interpretation); either way this is fail-open and never discards a+// delivered model for a worse one. Returns { durable, verdict, retried }.+async function qualityGateFinalize({ tierId, prompt, backend, referenceImageUrl, durable, regenerate }) {+ if (!qualityGateAppliesTo(tierId) || !durable?.glbUrl) {+ return { durable, verdict: null, retried: false };+ }+ let bestDurable = durable;+ let bestVerdict = await scoreQualityGate({ glbUrl: durable.glbUrl, prompt, tier: tierId, backend, referenceImageUrl });+ let bestScore = qualityScoreValue(bestVerdict);+ let retried = false;+ const maxRetries = qualityGateMaxRetries();++ // Prefer the module's own auto-retry helper when present — it owns the cap ++ // hint interpretation. It receives the verdict, context, the same bounded+ // regenerate closure, and the cap; a returned improved result is adopted.+ try {+ const mod = await import('./_lib/forge-quality-gate.js');+ const helper =+ mod.autoRetryForQuality || mod.withQualityRetry || mod.runQualityRetry || mod.qualityAutoRetry || null;+ if (typeof helper === 'function' && qualityGateFailed(bestVerdict) && maxRetries > 0) {+ const out = await helper({+ verdict: bestVerdict,+ glbUrl: bestDurable.glbUrl,+ prompt: prompt || null,+ tier: tierId,+ backend,+ referenceImageUrl: referenceImageUrl || null,+ maxRetries,+ regenerate,+ });+ if (out && (out.glbUrl || out.durable)) {+ return {+ durable: out.durable || bestDurable,+ verdict: out.verdict || bestVerdict,+ retried: Boolean(out.retried ?? true),+ };+ }+ }+ } catch {+ // No helper / module absent — fall through to the local bounded loop below.+ }++ let attempts = 0;+ while (qualityGateFailed(bestVerdict) && attempts < maxRetries && typeof regenerate === 'function') {+ attempts += 1;+ let next;+ try {+ next = await regenerate({ hint: bestVerdict?.suggested_retry_hint || null });+ } catch (err) {+ console.warn(`[forge] quality-gate retry regenerate failed, keeping best result: ${err?.message || err}`);+ break;+ }+ if (!next?.durable?.glbUrl) break;+ retried = true;+ const nextVerdict = await scoreQualityGate({+ glbUrl: next.durable.glbUrl,+ prompt,+ tier: tierId,+ backend,+ referenceImageUrl,+ });+ const nextScore = qualityScoreValue(nextVerdict);+ if (nextVerdict?.pass === true || nextScore > bestScore) {+ bestDurable = next.durable;+ bestVerdict = nextVerdict;+ bestScore = nextScore;+ }+ if (bestVerdict?.pass === true) break;+ }+ return { durable: bestDurable, verdict: bestVerdict, retried };+}+// Free NVIDIA NIM TRELLIS text→3D lane, extracted so it serves two callers:// 1. the draft default (backendId === 'nvidia'), and// 2. the never-dead-end fallback the paid image-intermediate TRELLIS lane@@ -756,7 +950,14 @@ async function startJob(req, res) {// expensive work below (image moderation, FLUX, reconstruction).let path = parsePath(body);const tier = resolveTier(parseTier(body));- let backendId = resolveBackendId({ path, tier, backend: body?.backend, userImages: isImageMode });+ // Subject class (organic / hard-surface / null) steers the High realism tier's+ // self-host lane order: Hunyuan3D-2.1 leads on people / creatures / detailed+ // organics, self-host TRELLIS leads on hard-surface / mechanical subjects. Pure+ // keyword heuristic on the prompt — zero latency, no LLM — and a no-op for every+ // tier below High (see freeLaneCandidates). An image submission with no guidance+ // prompt classifies to null and keeps the default order.+ const subjectClass = classifyForgeSubject(prompt);+ let backendId = resolveBackendId({ path, tier, backend: body?.backend, userImages: isImageMode, subjectClass });// Tracks whether the free NVIDIA NIM lane has already been attempted this// request, so the paid-lane fallback below never retries a lane that just// failed (draft already tries nvidia first; standard/high reach it only as a@@ -796,7 +997,7 @@ async function startJob(req, res) {const defaultByok = BACKENDS[backendId]?.byok;if (defaultByok && !(await resolveProviderKey(req, body, defaultByok))) {path = 'image';- backendId = resolveBackendId({ path, tier, userImages: isImageMode });+ backendId = resolveBackendId({ path, tier, userImages: isImageMode, subjectClass });}}@@ -810,7 +1011,7 @@ async function startJob(req, res) {// reused below to decide an honest cold-start ETA without a second probe.if (!backendExplicit && (path === 'image' || path === 'sketch')) {try {- const candidates = freeLaneCandidates(path, tier.id, isImageMode);+ const candidates = freeLaneCandidates(path, tier.id, isImageMode, subjectClass);if (candidates.length) {const snap = await laneHealthSnapshot(candidates);const healthAware = resolveBackendIdWithHealth({@@ -818,6 +1019,7 @@ async function startJob(req, res) {tier,userImages: isImageMode,health: snap.statusMap,+ subjectClass,});if (BACKENDS[healthAware]) backendId = healthAware;}@@ -1554,8 +1756,14 @@ async function startJob(req, res) {if (directed) directedPrompt = directed;}}- const synthesized = await textToImage(directedPrompt, {- aspectRatio: aspect,+ // Seed the reconstruction reference from the dedicated Vertex-Gemini+ // photoreal module when it is live, so a text prompt reconstructs from the+ // most photoreal single view we can synthesize. Fail-open: an absent module+ // or a Vertex outage transparently falls back to the standing text→image+ // provider (FLUX/Imagen/NIM), so this path runs identically either way.+ const synthesized = await seedReferenceImage({+ prompt: directedPrompt,+ aspect,skipNim: nimGatewayDegraded,seed: opts.seed ?? undefined,});diff --git a/docs/api-reference.md b/docs/api-reference.mdindex c546c0611..8cd59dca8 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -801,6 +801,93 @@ labeled with the prompt.| `502` | `generation_failed` | The lane could not start the job; retry is free || `503` | `not_configured` / `lane_timeout`| Lane unavailable on this deployment, or slow to accept; retry later |+### Model quality gate — `POST /api/forge-quality-check`++```+GET /api/forge-quality-check → capability probe+POST /api/forge-quality-check → score a model's realism / quality+```++Public, CORS-open, metered on the free vision buckets (sign in for a higher+limit). Scores how photoreal and complete a generated 3D model is, so a bad+result (a plastic toy, a melted blob, an incomplete or duplicated mesh) can be+caught and regenerated before a user ever sees it. It renders the GLB, sends the+render to **Vertex Gemini** (`gemini-2.5-flash`, GCP-credit-funded) with a+subject-aware photoreal rubric, and returns a structured verdict. When Vertex is+unconfigured it falls back to the free NVIDIA NIM vision lane; when no vision+provider answers at all it **fails open** (`verdict.pass: true`,+`verdict.qa_available: false`) so quality gating can never block a generation.++**Request body** — supply exactly one of `glbUrl`, `renderUrl`, or `image`:++```json+{+ "glbUrl": "https://cdn.three.ws/forge/anon/<id>.glb",+ "prompt": "a medieval knight in full plate steel armor",+ "subject": "person",+ "tier": "standard",+ "path": "image",+ "attempt": 0+}+```++- `glbUrl` — a public GLB, rendered here for scoring (preferred).+- `renderUrl` — a public image URL of an existing render.+- `image` — base64 or `data:` URI of a render.+- `prompt` — the source generation request; steers the rubric and the retry hint.+- `subject` — optional override (`person`, `animal`, `food`, `vehicle`, `plant`,+ `building`, `object`); auto-detected from the prompt otherwise.+- `tier` / `path` / `attempt` — optional; when present and the model fails the+ gate, the response includes a ready-to-run `retry` directive.++**Response**++```json+{+ "verdict": {+ "pass": false,+ "score": 34,+ "realism": 30,+ "completeness": 45,+ "subject": "person",+ "is_photoreal": false,+ "defects": ["plastic", "wrong_proportions"],+ "reason": "The armor reads as flat plastic and the proportions are off.",+ "suggested_retry_hint": "add realistic metal PBR materials and correct human proportions",+ "provider": "vertex",+ "model": "vertex-ai/gemini-2.5-flash",+ "qa_available": true,+ "render_source": "rendered_glb"+ },+ "retry": {+ "prompt": "a medieval knight in full plate steel armor, photorealistic, real photograph, high detail, accurate proportions, realistic PBR materials. Avoid: plastic or toy-like materials.",+ "tier": "standard",+ "path": "image",+ "attempt": 1,+ "reason": "retry 1/2: The armor reads as flat plastic and the proportions are off."+ }+}+```++`score` is 0-100; the pass threshold is `FORGE_QUALITY_PASS_SCORE` (default 60),+and any critical structural defect (blob, incomplete, duplicated, floating+fragments) fails the gate regardless of score. `retry` is `null` when the model+passes, when QA was unavailable (never retry on an outage), or when the retry cap+(`FORGE_QUALITY_MAX_RETRIES`, default 2) is reached. The same logic is importable+for server-side use as `runQualityGate` + `buildRetryDirective` from+`api/_lib/forge-quality-gate.js` — the generation router uses it directly.++**Errors**++| Status | Code | Meaning |+| ------ | ------------------- | ------------------------------------------------------------------------------ |+| `400` | `bad_request` | None of `glbUrl` / `renderUrl` / `image` supplied, or malformed JSON |+| `413` | `payload_too_large` | Request body over 20 MB |+| `429` | `rate_limited` | Free vision quota spent; see `X-RateLimit-Reset` (sign in for a higher limit) |++A provider or render outage does **not** error — it returns `200` with+`verdict.qa_available: false`.+### AR launch — `GET /api/ar````diff --git a/pages/forge.html b/pages/forge.htmlindex a073ec8f1..b328e933b 100644--- a/pages/forge.html+++ b/pages/forge.html@@ -1224,74 +1224,6 @@flex: 1;}- /* Idle — a live model, not a void. The newest community forge (or a- labeled first-party sample) stands here so the first thing a visitor- sees is the product's output. Markup in #state-empty; data wiring in- the inline idle-teaser module at the end of the page. */- .idle-viewer-wrap {- position: relative;- }- .idle-viewer-wrap model-viewer {- width: 100%;- height: min(52vh, 480px);- background: radial-gradient(120% 120% at 50% 0%, #1a1612 0%, #0b0a09 70%);- --poster-color: transparent;- }- html[data-theme='light'] .idle-viewer-wrap model-viewer {- background: radial-gradient(120% 120% at 50% 0%, #f3eee9 0%, #e7e2dc 70%);- }- .idle-tag {- position: absolute;- top: 10px;- left: 12px;- font-family: var(--font-mono);- font-size: 0.65rem;- text-transform: uppercase;- letter-spacing: 0.08em;- color: var(--ink-dim);- background: rgba(0, 0, 0, 0.45);- border: 1px solid var(--stroke);- border-radius: 999px;- padding: 2px 9px;- backdrop-filter: blur(4px);- }- .idle-bar {- display: flex;- align-items: center;- justify-content: space-between;- gap: var(--space-sm);- padding: var(--space-sm) var(--space-md);- border-top: 1px solid var(--stroke);- flex-wrap: wrap;- }- .idle-caption {- display: flex;- flex-direction: column;- gap: 0.15rem;- min-width: 0;- flex: 1 1 16rem;- }- .idle-kicker {- font-family: var(--font-mono);- font-size: var(--text-xs);- text-transform: uppercase;- letter-spacing: 0.06em;- color: var(--accent);- }- .idle-prompt {- color: var(--ink);- font-size: var(--text-sm);- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- }- .idle-hint {- flex-basis: 100%;- margin: 0;- color: var(--ink-dim);- font-size: var(--text-xs);- line-height: var(--leading-normal);- }.panel {background: var(--surface-glass);border: 1px solid var(--stroke);@@ -1450,6 +1382,27 @@color: var(--ink);font-weight: 600;}+ /* Lane-switch notice — shown when the server (or the client's automatic+ retry) moved this generation onto a backup engine mid-flight, so a+ failover is informative rather than silent. Filled by forge.js. */+ .gen-note {+ display: flex;+ align-items: baseline;+ gap: 0.45rem;+ margin-top: var(--space-xs);+ font-size: var(--text-xs);+ line-height: 1.5;+ color: var(--warning, #e0a93e);+ }+ .gen-note::before {+ content: '';+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--warning, #e0a93e);+ flex: none;+ transform: translateY(-1px);+ }/* Honest elapsed-vs-typical meter. The fill maps real elapsed timeagainst the engine's real catalog ETA on an asymptotic curve that@@ -2599,6 +2552,21 @@color: var(--ink-dim);margin: 0;}+ /* Starter prompts inside the empty stage — a first-time visitor sees+ exactly what to type and can generate in one click. Reuses the .chip+ look; wired in forge.js (fills the prompt and submits). */+ .forge-empty-starters {+ display: flex;+ flex-wrap: wrap;+ justify-content: center;+ gap: var(--space-xs);+ padding: 0 var(--space-md);+ }+ .forge-empty-hint {+ font-size: var(--text-xs);+ color: var(--ink-dim);+ margin: 0;+ }/* Error + unconfigured notices */.notice {diff --git a/pages/marketplace.html b/pages/marketplace.htmlindex 2f86a6c93..50ebc672b 100644--- a/pages/marketplace.html+++ b/pages/marketplace.html@@ -2103,6 +2103,12 @@color: inherit;text-decoration: none;display: block;+ /* line-height (not padding) both grows the single-line box to the+ 32px tap-target floor and keeps the text vertically centered in+ it — padding would push the text off-center against the ellipsis+ truncation. */+ min-height: 32px;+ line-height: 32px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;diff --git a/prompts/quality-campaign/01-photoreal-3d-pipeline.md b/prompts/quality-campaign/01-photoreal-3d-pipeline.mdnew file mode 100644index 000000000..ada55db4e--- /dev/null+++ b/prompts/quality-campaign/01-photoreal-3d-pipeline.md@@ -0,0 +1,80 @@+# 01 - Photoreal objects: multi-view fusion + texture fidelity++Read `README.md` in this directory first (never-stop contract, standing approvals, shared+context). Never end a turn with a question. GCP spend is pre-approved; no new third-party APIs.++## Mission++A text->3D generation on three.ws should look like a photograph of a real object from every+angle. The single-reference-image pipeline guesses the back and sides of every object; the fix+is multi-view: generate front/side/back reference views with the Vertex image model and fuse+them in TRELLIS (`run_multi_image`) and Hunyuan3D (both accept multiple input images; the+worker `/infer` already takes `images: []` as a list). Then close the texture-fidelity gap:+the final mesh texture must carry the reference image's material detail, not a blurred bake.++## Current state (verified 2026-07-16; re-verify against the tree, the swarm moves fast)++- A multi-view synthesis effort was mid-flight in the swarm on 07-16 ("multiview-fusion" tier+ blurbs landed in commit c2e07162a). FIRST ACTION: `git log --oneline -20` and+ `grep -rn "multi_image\|multiview\|multi_view" api/ workers/model-trellis/ workers/model-hunyuan3d/`+ to find what already shipped. Extend what exists; do not duplicate it.+- Reference images: `api/_mcp3d/text-to-image.js` (realism suffixes live here) over+ `api/_mcp3d/vertex-imagen.js` (`gemini-2.5-flash-image`, `:generateContent`). The Gemini+ image model accepts an input image + instruction, which is how you get consistent side/back+ views: pass the generated front view with "same exact object, rotated to a direct side view,+ same lighting and background" rather than re-prompting from text (re-prompting drifts).+- Workers: `workers/model-trellis/main.py` (TRELLIS pipeline; `run_multi_image` exists in the+ TRELLIS library), `workers/model-hunyuan3d/main.py` (`images` list already in the wire+ shape). Worker auth: Secret Manager `avatar-reconstruction-key`. Wire: POST /infer -> task_id,+ GET /tasks/:id -> result_gcs_url, /health.+- Lane plumbing: `api/_providers/gcp.js` (modes `trellis`/`hunyuan`, passes `params.quality`),+ `api/_lib/forge-tiers.js` (per-tier budgets), `api/forge.js` (routing, ~2000 lines).+- Tier semantics: draft = speed, standard = default, high = paid Hunyuan3D lane. Multi-view+ belongs on standard and high (draft stays single-view fast).++## Tasks++1. **Audit what shipped.** Map the current multi-view state end to end. If the swarm finished+ it, skip to task 3 and deepen texture fidelity instead; report which branch you took.+2. **Multi-view reference synthesis.** In `text-to-image.js` (or a sibling module), add+ `textToMultiView(prompt)`: front view from text, then side + back via image+instruction+ edits of the front view for object consistency. Store all views in R2 like single+ references. Wire through `gcp.js` so `images[]` carries all views to TRELLIS+ (`run_multi_image`) and Hunyuan3D on standard/high tiers. Flag-gate:+ `FORGE_MULTIVIEW=1` on by default in code, `0` reverts to single-view. Cost per gen is+ 2 extra Vertex images + longer GPU seconds: pre-approved.+3. **Texture fidelity.** The reconstruction's baked texture is the weak link. Options already+ in-house, in preference order: raise texture bake size where the worker clamps it (2048 is+ the current clamp; measure whether 4096 fits L4 VRAM at high tier before enabling);+ Hunyuan3D's paint/texture stage settings in `workers/model-hunyuan3d/main.py`+ (`_quality_for`); the `stylize`/`texture` workers for a detail pass. Pick what measurably+ helps; show before/after renders.+4. **Prompt treatment.** The realism suffixes are good; extend them only where evaluation shows+ drift (e.g. metallic/glass materials, text on labels). Keep the ART_STYLE_WORDS skip rule:+ a user asking for "cartoon" must never get photoreal.+5. **Verification harness (definition of done).** Generate this fixed prompt set at standard+ and high, before and after your changes: leather armchair, chrome espresso machine, worn+ hiking boot, glass perfume bottle, wooden acoustic guitar. For each: GLB size, triangle+ count, texture resolution, quality score from the pipeline, and a 4-angle render+ (front/back/left/right; `scripts/` has GLB render helpers, else use three.js headless via+ the existing test tooling). Back/side views must depict the object, not a mirrored front.+6. **Ship.** Deploy touched workers (Cloud Build, clean worktree), set env on `three-ws-api`,+ run one live production generation per tier, commit code + docs (changelog entry: holders+ care about "3D generations now look real from every angle").++## Guardrails++- Do not break the free draft lane's latency; multi-view is standard/high only.+- NVCF hosted results are consume-once (poll handling in `api/_lib/forge-failover.js`); do not+ re-fetch a hosted result URL twice.+- The swarm may be mid-deploy on these exact workers. Before deploying, `gcloud run revisions+ list` and confirm you are not clobbering a newer revision than your base; rebase your change+ on the deployed source if the repo and the deployed image diverge.++## Acceptance criteria++- [ ] Standard + high tiers fuse >= 3 reference views (proven by worker logs + payload capture).+- [ ] The 5-prompt eval set shows better back/side fidelity than baseline (renders in the report).+- [ ] `FORGE_MULTIVIEW=0` cleanly reverts to today's behavior (tested).+- [ ] One live production generation per tier completes E2E; URLs in the report.+- [ ] Committed with changelog entry + docs; `npm test` green; report contains every command and measurement.diff --git a/prompts/quality-campaign/02-photoreal-humans.md b/prompts/quality-campaign/02-photoreal-humans.mdnew file mode 100644index 000000000..1ea92fe25--- /dev/null+++ b/prompts/quality-campaign/02-photoreal-humans.md@@ -0,0 +1,70 @@+# 02 - Photoreal humans: faces, skin, hair that read as IRL people++Read `README.md` in this directory first (never-stop contract, standing approvals, shared+context). Never end a turn with a question. GCP spend is pre-approved; no new third-party APIs.++## Mission++Avatars generated on three.ws should look like actual people: skin with pores and asymmetry,+believable hair, eyes with catchlights, not glossy mannequins. The person-realism prompt work+landed 07-16 (`PERSON_REALISM_SUFFIX` in `api/_mcp3d/text-to-image.js`); this prompt finishes+the job across the whole avatar chain: reference image -> reconstruction -> rigging -> the way+skin is shaded in every viewer.++## Current state (verified 2026-07-16; re-verify against the tree)++- `PERSON_SUBJECT_RE` routes human prompts to portrait-photography language (85mm DSLR, pores,+ hair strands). ART_STYLE_WORDS still correctly suppresses realism for stylized asks.+- Avatar chain: `text_to_avatar` / `forge_avatar` MCP tools -> mesh generation -> UniRig+ auto-rig (`GCP_UNIRIG_URL`, service `unirig`, live) with humanoid gate+ (`AnimationManager.supportsCanonicalClips()` fallback, never a T-pose). Universal retarget:+ `src/glb-canonicalize.js` + `src/animation-retarget.js`.+- `avatar-reconstruction` Cloud Run service (photo->avatar) is live with L4.+- Viewers: the IRL view got ACES filmic tone mapping + cinematic lighting 07-15+ (`src/` IRL modules); avatar-result viewers were brought up to that bar in commit 8cd1be411.+- Hunyuan3D-2 (`GCP_HUNYUAN3D_URL`, live) reconstructs humans better than TRELLIS at high tier.++## Tasks++1. **Face fidelity through multi-view.** Bodies survive single-view reconstruction; faces do+ not. Reuse prompt 01's multi-view machinery (check `git log` for its state; if 01 has not+ run yet, build the person-specific slice here and leave a note in 01's file): front portrait+ plus 3/4-left and 3/4-right views via Gemini image edit ("same exact person, head turned 40+ degrees left, identical lighting"), fused in the reconstruction. The face must survive a+ 90-degree orbit without smearing.+2. **Skin shading in the viewers.** Reconstructed textures often ship flat albedo. In the+ shared viewer setup (the module 8cd1be411 touched; find it via+ `grep -rn "ACESFilmicToneMapping" src/ | head`), ensure avatar materials get: correct sRGB+ texture encoding, a modest clearcoat=0 / roughness floor (glossy skin reads mannequin),+ and environment lighting from the existing HDRI/room env. If the GLB carries PBR maps, do+ not override them.+3. **Hair.** Reconstruction collapses hair to a helmet. Mitigate at the reference stage: the+ portrait prompt should specify visible individual hair strands and avoid flyaway backlight+ halos (they reconstruct as spikes). Measure on the eval set; if reference-stage language is+ insufficient, document what a dedicated hair pass would need (do not bolt on a new model).+4. **The full-body proportion check.** Full-body prompts must produce anatomically plausible+ proportions for rigging (UniRig fails or produces bad skinning on distorted bodies). Add a+ pre-rig sanity gate if failures show up in `forge_creations` records for avatar jobs.+5. **Eval set (definition of done).** Generate at standard and high, before/after: "a+ middle-aged carpenter with a gray beard", "a young woman with curly red hair, freckles",+ "an elderly man in a linen suit", "a female astronaut, helmet off", "a teenage boy in a+ hoodie". For each: 4-angle render, rigged idle-animation check (the retarget must drive it;+ no T-pose), and the platform quality score. Faces must hold up at 90-degree orbit.+6. **Ship.** Deploy, one live production avatar per tier E2E (generation -> rig -> animated in+ the viewer), commit + changelog ("avatars now look like real people").++## Guardrails++- Never regress stylized asks: "cartoon knight" must stay cartoon (ART_STYLE_WORDS test).+- Rigging gate stays universal: no rig allowlists (CLAUDE.md stack note); a new skeleton+ convention gets a bone-name mapping in `glb-canonicalize.js` + test.+- Bone names with punctuation broke a USDZ bake once (bone-name-sanitize, memory 07-15): run+ the iOS AR bake path on one eval avatar to confirm no regression.++## Acceptance criteria++- [ ] Eval faces survive a 90-degree orbit (before/after renders in the report).+- [ ] Avatar materials render with sRGB + env lighting in the shared viewers (screenshot proof).+- [ ] All 5 eval avatars rig and play the canonical idle (no T-pose, no console errors).+- [ ] One live production avatar per tier E2E; URLs in the report.+- [ ] Committed with changelog + docs; `npm test` green; report shows every measurement.diff --git a/prompts/quality-campaign/03-presentation-lighting.md b/prompts/quality-campaign/03-presentation-lighting.mdnew file mode 100644index 000000000..6785f04e3--- /dev/null+++ b/prompts/quality-campaign/03-presentation-lighting.md@@ -0,0 +1,69 @@+# 03 - Presentation: every 3D surface renders at the cinematic bar++Read `README.md` in this directory first (never-stop contract, standing approvals, shared+context). Never end a turn with a question. GCP spend is pre-approved; no new third-party APIs.++## Mission++A photoreal mesh shown in a flat-lit viewer still looks fake. The IRL camera view set the bar+on 07-15: ACES filmic tone mapping, rich key/fill/rim lighting, soft shadows, sharp textures.+Avatar-result viewers were partially aligned (commit 8cd1be411). This prompt finishes the+sweep: every place a model or avatar renders on the platform uses the same cinematic pipeline,+and every generated asset gets a presentation-quality thumbnail.++## Current state (verified 2026-07-16; re-verify)++- The bar: IRL view modules (find via `grep -rln "ACESFilmicToneMapping" src/`). Elements:+ `renderer.toneMapping = ACESFilmicToneMapping`, physically-correct lights, environment map,+ shadow-mapped key light, `outputColorSpace = SRGBColorSpace`.+- Known viewer surfaces (enumerate more from `STRUCTURE.md` and `grep -rln "new WebGLRenderer" src/ public/`):+ the main agent viewer, /forge result viewer, /avatar and pose studio, /scene Studio, /ar,+ /irl, /walk + /play worlds, marketplace cards, agent profile pages, the `<agent-3d>` embed+ (`apps-sdk/embodiment/embodiment-stage.js`), README-3D, Shopify tour embeds.+- Thumbnails: `forge_creations` records carry thumbnail URLs; memory rule: never synthesize+ thumbnail URLs, always render real ones.+- /walk exhausted WebGL contexts with 8 iframes once (memory 07-10): shared-context or+ frugal-context patterns matter on multi-viewer pages.+- A frame governor + Eco mode shipped for /play (07-14): respect it; cinematic must not cost+ battery on low-power mode.++## Tasks++1. **Inventory.** Every renderer creation site in `src/`, `public/`, `apps-sdk/`, plus each+ page that shows a GLB. Table: surface, current tone mapping, lighting rig, env map, shadows,+ pixel ratio handling. This inventory drives the rest and goes in the report.+2. **Extract the standard.** One shared module (e.g. `src/shared/cinematic-stage.js`, or extend+ the one 8cd1be411 used) exporting the canonical setup: tone mapping, color space, light rig,+ env, shadow config, and a `quality` knob (high / balanced / eco) that the frame governor and+ embed contexts can select. Small API, no framework.+3. **Adopt everywhere.** Convert every inventoried surface. Visual check each at 320/768/1440+ widths. Embeds (`<agent-3d>`, Shopify, README-3D) must default to balanced and honor an+ explicit quality attr.+4. **Thumbnails at the same bar.** The thumbnail/OG render path for generated assets renders+ with the same stage (lighting is most of why thumbnails look cheap). Regenerate thumbnails+ for the most-viewed existing assets (query `forge_creations` by views/downloads; backfill+ cron pattern already exists in the avatar-thumbnail work, see `api/cron/`).+5. **AR parity.** iOS Quick Look uses baked USDZ (animated bake shipped 07-16 in 8b23b8d9e);+ confirm the bake inherits texture quality (no downscale below 2048 for high-tier assets) and+ the WebXR path uses the shared stage.+6. **Ship.** Deploy from a clean worktree, verify on production URLs on desktop + a phone+ viewport, commit + changelog ("every 3D view on the platform now renders with cinematic+ lighting").++## Guardrails++- No per-frame allocations in render loops; the stage must not regress the /play frame+ governor or Eco mode.+- Multi-viewer pages (/walk grid, marketplace) must not exceed ~4 live WebGL contexts; use+ poster images + lazy context creation where the inventory shows more.+- `public/*.html` pages not registered as Vite inputs ship raw `/src` (vite-raw-src trap,+ memory 07-10): if you add a page or module, register it in `vite.config.js` inputs.+- Never hand-edit generated bundles; `npx vercel build` overwriting `api/*.js` is a known trap.++## Acceptance criteria++- [ ] Inventory table in the report; every surface converted or explicitly justified.+- [ ] Same model screenshotted before/after on >= 6 surfaces (forge, avatar studio, marketplace card, agent profile, embed, IRL) showing the uplift.+- [ ] Thumbnails regenerate through the cinematic stage; top-viewed assets backfilled (count in report).+- [ ] No new console errors; frame rate on /play and /walk unchanged (measure with the existing governor stats).+- [ ] Committed with changelog + docs; `npm test` green.diff --git a/prompts/quality-campaign/04-ux-funnel-sweep.md b/prompts/quality-campaign/04-ux-funnel-sweep.mdnew file mode 100644index 000000000..cda7ed6a3--- /dev/null+++ b/prompts/quality-campaign/04-ux-funnel-sweep.md@@ -0,0 +1,70 @@+# 04 - UX sweep: the core funnels feel like a top-tier product++Read `README.md` in this directory first (never-stop contract, standing approvals, shared+context). Never end a turn with a question.++## Mission++Walk the five funnels a real user actually takes, find every rough edge, and fix all of them:+missing loading/empty/error states, dead buttons, layout jank, unlabeled controls, confusing+copy, broken mobile layouts. The bar is CLAUDE.md's UI/UX standards section (every state+designed, transitions, responsive, accessibility, microinteractions). This is a fix-everything+sweep, not an audit report.++## The five funnels (in priority order)++1. **Text -> 3D**: home -> /forge -> generate -> result viewer -> download / AR / send-to-scene.+2. **Create an agent**: /create or /create-agent -> avatar generation -> agent profile -> embed code.+3. **Markets**: /markets -> /markets/news -> article reader -> /coin/:id detail.+4. **Worlds**: /play (join, move, interact) and /walk.+5. **Wallet-money paths**: premium pass purchase page rendering and x402 paywall UX (UI states+ only; never execute real payments without the confirmation gate).++## Tooling you already have (use it, do not rebuild it)++- `npm run dev` (port 3000). Real browser verification is mandatory per CLAUDE.md.+- `npm run audit:web`: authed console sweep across 300+ pages; QA account creds already in+ `.env`. Run it before AND after; your after-run must show strictly fewer errors.+- Playwright is in the repo (e2e stage of `npm test`); write throwaway drive-the-funnel scripts+ in `scripts/` if manual walking is too slow, delete them before committing (repo-hygiene rule)+ or keep them only if they earn a place as real e2e tests in `tests/`.+- Crawler gotcha (memory 07-10): high crawler concurrency produces false texture errors; keep+ concurrency modest before believing an error.++## Method (per funnel)++1. Walk it on desktop (1440), tablet (768), and phone (320-390) viewports, signed out AND+ signed in (QA account).+2. Record every defect in a working list: state, element, expected vs actual, severity.+3. Fix them all. Patterns to hold:+ - Loading: skeletons over spinners (CLAUDE.md), no layout shift on resolve.+ - Empty: what this is + one action to take, never a blank void.+ - Error: what failed + how to recover; network errors get a retry action.+ - Interactive elements: hover/active/focus states, keyboard reachable, ARIA labels.+ - Copy: plain language, no jargon, no dead-end messages.+4. Re-walk after fixing. Then `npm run audit:web` for the regression sweep.++## Known live issues to verify fixed or fix now++- Re-check the 07-14 console-sweep fixes deployed cleanly (memory: fixes committed, deploy was+ pending; if still undeployed, deploying them is part of this prompt).+- /forge engine-switch UX shipped 07-16 (never-dead-end failover): confirm the switch control+ is discoverable and announces what happened (a lane failing over silently confuses users).+- Session-expiry mid-flow: exercise an authed page after clearing the session cookie; the UX+ must be a reauth prompt, not a silent 401 spiral (pattern from the /play 4002 fix).++## Guardrails++- Stage explicit paths only; concurrent agents share the worktree.+- No visual redesigns of brand surfaces; this is polish and correctness, not a new design+ language. Use existing design tokens/CSS variables; if a page has none, adopt the nearest+ surface's tokens.+- Every fix must hold at 320px. If a fix needs layout surgery, do the surgery.++## Acceptance criteria++- [ ] Defect list in the report: found -> fixed status for every item (target: zero open).+- [ ] `npm run audit:web` after-run error count < before-run (both counts in the report).+- [ ] Every funnel walked clean on 3 viewports, signed in and out; no console errors from platform code.+- [ ] All five funnels' interactive elements keyboard-navigable with visible focus.+- [ ] Committed with changelog entries for user-noticeable fixes; `npm test` green.diff --git a/prompts/quality-campaign/05-performance-vitals.md b/prompts/quality-campaign/05-performance-vitals.mdnew file mode 100644index 000000000..f08a3b6ef--- /dev/null+++ b/prompts/quality-campaign/05-performance-vitals.md@@ -0,0 +1,63 @@+# 05 - Performance: fast first paint, no jank, honest async++Read `README.md` in this directory first (never-stop contract, standing approvals, shared+context). Never end a turn with a question.++## Mission++Make the platform feel instant. Measure Core Web Vitals on the ten highest-traffic pages, fix+what the numbers say, and protect the wins with budgets. Perceived speed counts double: a+skeleton at 100ms beats a spinner at 400ms beats a blank page at 250ms.++## Measure first (baseline goes in the report)++- Pages: `/`, `/forge`, `/markets`, `/markets/news`, `/coins`, `/coin/bitcoin`, `/agents`,+ `/play`, `/walk`, one agent profile. Production URLs (https://three.ws), not dev.+- Tool: Lighthouse CLI is already installable via npx (`npx lighthouse <url> --preset=desktop`+ and default mobile, `--output=json`). Capture LCP, CLS, TBT, transfer size per page. Three+ runs each, take the median; single runs lie.+- Bundle: `npm run build` then read the Vite output table. Anything > 250 kB gzip in the+ initial graph of a page is a finding. `dist/` chunk names are hashed; grep the manifest, not+ the filenames (chunk-grep gotcha, memory 07-15).++## Fix what the numbers say (typical findings and their standard fixes)++- Three.js in the initial bundle of non-3D pages: dynamic-import the viewer behind first+ interaction or viewport entry (pattern exists in `src/game/wheel-station.js`: lazy-import on+ interact).+- Fonts blocking render: `font-display: swap` and preload only the weights above the fold+ (`public/fonts/fonts.css`).+- CLS from images/thumbnails: explicit width/height or aspect-ratio boxes everywhere a dynamic+ image lands (news cards, marketplace grids, coin tables).+- Uncompressed or oversized textures/posters: posters for 3D scenes should be WebP <= 100 kB;+ the full GLB loads only on interaction.+- API waterfalls: pages that fetch sequentially (profile -> then assets -> then prices) get+ `Promise.all` or a combined endpoint if one already exists (check `api/` before adding one).+- Long main-thread tasks from JSON parsing (news/markets): move to `response.json()` streaming+ patterns or slice rendering with `requestIdleCallback` batches; the tables already paginate,+ ensure initial page size is sane.++## Infrastructure lever (GCP credits, pre-approved)++- `three-ws-api` Cloud Run: check `minInstances` on the service; if cold starts show in TTFB+ (compare first-hit vs warm TTFB), raise minScale to keep 1..2 warm instances. Credits absorb it.+- Confirm CDN cache hit rates for static assets (`gcloud compute backend-services` /+ `docs/ops/gcp-production.md` runbook has the LB layout). Assets with hashed names must be+ `cache-control: immutable`; HTML must not be cached stale (deploys purge via+ `npm run deploy:gcp`, never raw `gcloud builds submit`, which skips the purge).++## Guardrails++- Never fake it: no `setTimeout` progress, no optimistic spinners that lie (hard rule 5).+- Lazy-loading must not break deep links or SEO: server-rendered/SEO-injected meta stays+ (the SEO injector stamps pages at build; do not move meta client-side).+- Do not regress the audit:web console-error count.+- `npm test` failures gate the e2e stage; run the full suite, do not pipe through `tail`.++## Acceptance criteria++- [ ] Baseline vs after table for all 10 pages (LCP, CLS, TBT, transfer), medians of 3 runs.+- [ ] Every page: mobile LCP <= 3.0s, CLS <= 0.1, or a written reason why a page is at its floor.+- [ ] Initial JS on non-3D pages excludes three.js (proven from the build manifest).+- [ ] Cold-start TTFB measured; minScale raised if it was the bottleneck (numbers in report).+- [ ] Committed with changelog entry ("the site got faster": holders notice speed); `npm test` green.diff --git a/prompts/quality-campaign/06-quality-eval-harness.md b/prompts/quality-campaign/06-quality-eval-harness.mdnew file mode 100644index 000000000..59aa2415f--- /dev/null+++ b/prompts/quality-campaign/06-quality-eval-harness.md@@ -0,0 +1,69 @@+# 06 - Quality eval harness: generation quality can never silently regress again++Read `README.md` in this directory first (never-stop contract, standing approvals, shared+context). Never end a turn with a question. GCP spend is pre-approved (this harness burns GPU+seconds nightly by design); no new third-party APIs.++## Mission++Prompts 01-03 raised generation quality. Nothing currently guarantees it stays raised: the+only organic signal is download rate, and a bad worker deploy would show up as user complaints+days later. Build the regression harness: a fixed golden-prompt set generated nightly on every+live lane, scored, trended, and alerting on regression. Run it last, after 01-03 land, so the+goldens capture the improved baseline.++## Current state (verified 2026-07-16; re-verify)++- Every generation already gets a quality score in its metadata (mesh-degeneracy check + score,+ shipped in the forge quality work; find it via `grep -rn "quality_score\|qualityScore" api/`).+- `forge_creations` table records every generation (tier, lane, score, sizes, timings).+- Cron pattern: `vercel.json` `crons` array is the source of truth; production runs Cloud+ Scheduler jobs hitting `/api/cron/<name>` with `Authorization: Bearer $CRON_SECRET`.+ IMPORTANT (memory 07-09): a NEW cron needs its Cloud Scheduler job created manually+ (`scripts/create-gcp-scheduler.mjs`); adding it to vercel.json alone does nothing in prod.+- Autonomous-agent health-check precedent to copy: the x402 Granite health check+ (every 6h, real calls, verdict recorded, public feed at `/api/x402/granite-health`).+- Lanes to cover: selfhost TRELLIS (draft/standard), Hunyuan3D (high), hosted NIM (failover),+ HF Spaces lane (failover), avatar chain (generate -> rig).++## Tasks++1. **Golden set.** 8 object prompts + 4 human prompts, fixed seeds where lanes support them+ (`seed` param exists on the forge API). Include the eval prompts from 01/02 so history is+ comparable. Store the set in `data/` as the single source.+2. **Nightly cron** `/api/cron/forge-quality-eval`: for each lane in rotation (spread lanes+ across the week if a full nightly sweep is too heavy; document the rotation), run the+ golden set through the real production path, record per-item: lane, revision (worker+ `/health` can expose image tag; add it if missing), score, tri count, texture size, GLB+ bytes, wall time. Persist to a new `forge_quality_runs` table (migration in the existing+ migrations dir; follow neighboring migration style).+3. **Regression rule.** Median score of a lane drops > 10% vs its 7-day median, or any golden+ fails to generate: mark the run regressed, write an ops alert through the existing alerting+ path (the Granite health check shows the pattern), and flag it on the internal health check.+4. **Trend surface.** Page at `/quality` (or a dashboard-next page if that fits existing+ patterns better): per-lane score trend, last-run table, per-golden thumbnails+ (rendered through the cinematic stage from prompt 03). Public is fine; it is a flex.+ Register in `data/pages.json`, row in `STRUCTURE.md`, changelog entry.+5. **Wire and prove.** Create the Scheduler job, trigger it manually once+ (`gcloud scheduler jobs run`), watch it complete, verify rows + page render from the real+ run. Then trigger a synthetic regression (temporarily point one lane's score threshold up)+ to prove the alert fires, and revert.++## Guardrails++- The eval must use the production request path (real `/api/forge` calls with an internal+ bypass key if one exists; check `api/_lib/` for the partner-key pattern), not worker-direct+ calls, so routing regressions are caught too.+- Nightly GPU cost is intentional but bounded: cap a run at ~30 generations; the rotation+ covers the rest.+- Never let eval traffic pollute user-facing galleries or `forge_creations`-driven surfaces:+ tag eval records and filter them everywhere the table feeds UI (grep every consumer).+- New cron = manual Scheduler job creation (see above). Do not assume.++## Acceptance criteria++- [ ] One full real nightly run recorded end to end (row counts + screenshots of /quality).+- [ ] Synthetic regression fired the alert and the health-check flag (evidence in report).+- [ ] Eval records invisible on all user-facing surfaces (list the consumers you checked).+- [ ] Scheduler job exists in GCP and in `vercel.json` crons; both shown in the report.+- [ ] Committed with changelog + docs (`docs/` entry for the harness, page registered); `npm test` green.diff --git a/prompts/quality-campaign/README.md b/prompts/quality-campaign/README.mdnew file mode 100644index 000000000..8c9e460ac--- /dev/null+++ b/prompts/quality-campaign/README.md@@ -0,0 +1,53 @@+# Quality Campaign: photoreal 3D + sitewide UX/UI (GCP-credit funded)++Owner directive 2026-07-16: improve the UX, UI, and quality of everything; make 3D generations+as real-looking as IRL people and objects; spend the ~$100k Google Cloud credits freely to get+there; onboard NO new third-party APIs. Run each prompt in a fresh Claude Code chat.++## The never-stop contract (applies to every prompt in this pack)++The owner's single biggest complaint is agents stopping mid-task to ask questions. Every prompt+here is written to be 100% self-contained: it names the files, the env vars, where credentials+live, the verification commands, and the standard resolution for every predictable blocker.+Read the "Self-unblock playbook" in CLAUDE.md before starting; it is binding. In short:++- Never end a turn with a question, an offer, or a plan. Finish, verify, then report.+- Missing credential: check `.env`, then `gcloud run services describe three-ws-api --region us-central1`, then `gcloud secrets list`. Only after all three may you report it missing (with the feature fully built behind the env var).+- Ambiguous choice: take the most reversible option that matches existing platform patterns, ship it, record the decision in your report.+- GCP quota wall: file the increase, then route around (lower an idle service's minScale, another region, queue on existing capacity).+- Someone else's failing test blocking your verification: root-cause and fix it; never mask, never stop.++## Standing approvals (so nothing needs asking)++- **GCP spend is pre-approved.** Project `aerial-vehicle-466722-p5`, region `us-central1`. GPU seconds, Vertex AI calls, minScale warm instances, storage: all fine. Prefer GCP over any paid third-party API.+- **No new external paid APIs.** Vertex AI, Cloud Run, GCS, Cloud Build, Secret Manager are all in-house surfaces and pre-approved. Replicate/Meshy/etc. must NOT be added or funded.+- **Commits to `main` are normal** (owner works on main, no feature branches). Stage explicit paths only (`git add <paths>`, never `-A`): concurrent agents share this worktree.+- **`git push` and social posts still require owner approval.** GCP service deploys needed to complete a prompt are approved as part of running it; use the clean-worktree recipe below.++## Shared operational context (verified 2026-07-16)++- Production: Cloud Run service `three-ws-api` (us-central1) serves frontend + `vercel.json` routes + `api/**`. Deploy: `npm run build && npm run deploy:gcp`, ideally from a clean worktree (`git worktree add /workspaces/.deploy-wt HEAD`, deploy there, `git worktree remove`), because the swarm's dirty files must not ship. `gcloud builds submit` alone skips the CDN purge; use the npm script.+- GPU fleet (all Cloud Run + NVIDIA L4, us-central1, verified live today):+ - `model-trellis` (TRELLIS image->3D, `MODEL_TRELLIS_URL`), quality knobs ss/slat 8..50 steps, simplify >= 0.5, texture <= 2048.+ - `model-hunyuan3d` (Hunyuan3D-2 image->3D, `GCP_HUNYUAN3D_URL`), high-tier lane.+ - `unirig` (auto-rigging, `GCP_UNIRIG_URL`), `avatar-reconstruction`, plus `rembg/remesh/segment/stylize` CPU helpers.+ - Worker auth: bearer key in Secret Manager secret `avatar-reconstruction-key`; wire shape `POST /infer -> {task_id}`, `GET /tasks/:id -> result_gcs_url`, health at `/health`.+- Reference images: Vertex `gemini-2.5-flash-image` via `api/_mcp3d/vertex-imagen.js` (`:generateContent`); prompt realism treatment in `api/_mcp3d/text-to-image.js` (`REALISM_SUFFIX`, `PERSON_REALISM_SUFFIX`, skipped when the user names an art style).+- Lane routing: `api/forge.js` + `api/_providers/gcp.js`; tier budgets in `api/_lib/forge-tiers.js` (`SELFHOST_TRELLIS_QUALITY`: draft 12 steps/1024tex, standard 25/2048, high 45/2048); `FORGE_SELFHOST_PRIMARY=true` is live, self-hosted L4 workers outrank hosted NVIDIA NIM (NIM is capped ~15 steps by its 30s sync window and is the old quality ceiling).+- Quality signal: `forge_creations` DB table has a quality score per generation; download rate is the only organic user signal (ratings are unused).+- Frontend: vanilla JS + Vite, `npm run dev` (port 3000). Tests: `npm test` (vitest failure gates the Playwright e2e stage; never pipe test output through `tail`, it eats exit codes). Authed console sweep across 300+ pages: `npm run audit:web` (QA account creds already in `.env`).+- Docs duties per feature: `data/pages.json` for new routes, `data/changelog.json` entry for user-visible changes, `STRUCTURE.md` row for new surfaces. `npm run build:pages` validates.++## Prompts++| # | File | Theme | Parallel-safe with |+|---|------|-------|--------------------|+| 1 | `01-photoreal-3d-pipeline.md` | Multi-view fusion + texture fidelity for objects | 3, 4, 5 |+| 2 | `02-photoreal-humans.md` | IRL-looking people: faces, skin, hair | 3, 4, 5 (after 1 is cleanest) |+| 3 | `03-presentation-lighting.md` | Every viewer renders at the IRL cinematic bar | 1, 2, 4, 5 |+| 4 | `04-ux-funnel-sweep.md` | Loading/empty/error/microinteraction sweep of the core funnels | 1, 2, 3, 5 |+| 5 | `05-performance-vitals.md` | Core Web Vitals + perceived speed | 1, 2, 3, 4 |+| 6 | `06-quality-eval-harness.md` | Nightly generation-quality regression harness | run last |++Each prompt ends with acceptance criteria. A prompt is done when every criterion passes and the+report shows the evidence (commands run, URLs, measured numbers). Not before.diff --git a/prompts/roadmap/_generated/forge-router/gate-before.txt b/prompts/roadmap/_generated/forge-router/gate-before.txtnew file mode 100644index 000000000..50f6f8e27--- /dev/null+++ b/prompts/roadmap/_generated/forge-router/gate-before.txt@@ -0,0 +1,80 @@++> [email protected] gate+> npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:hidden-guard && npm run audit:x402-catalog && npm run audit:tokens+++> [email protected] test:gate+> node scripts/test-gate.mjs++[test-gate] running 7 critical-path test files…++ RUN v4.1.9 /workspaces/three.ws+++ Test Files 7 passed (7)+ Tests 86 passed (86)+ Start at 21:26:42+ Duration 2.98s (transform 2.52s, setup 0ms, import 5.37s, tests 2.92s, environment 1ms)++[test-gate] ✓ all critical-path tests passed++> [email protected] test:gate-3d+> vitest run tests/glb-canonicalize.test.js tests/animation-retarget.test.js tests/animation-retarget-rest-pollution.test.js tests/viewer-framing.test.js+++ RUN v4.1.9 /workspaces/three.ws+++ Test Files 4 passed (4)+ Tests 244 passed (244)+ Start at 21:26:45+ Duration 509ms (transform 247ms, setup 0ms, import 632ms, tests 293ms, environment 1ms)+++> [email protected] audit:mcp+> node scripts/audit-mcp-manifests.mjs++[audit:mcp] 16 MCP manifests consistent++> [email protected] audit:mcp-golden+> node scripts/audit-mcp-golden.mjs++[audit:mcp-golden] 236 hosted MCP tool contracts match the golden fixture++> [email protected] audit:routes+> node scripts/verify-routes.mjs++Route verify — 331 catalog pages, 1112 main routes, 1 post-filesystem routes.+ modeled dist files: 1630 · canonical-covered: 331 · literal page routes checked for shadows: 481+ 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 (1764 checked)++> [email protected] audit:pages+> node scripts/audit-page-index.mjs++Route audit: 145 auditable page routes, 331 documented in pages.json.+✓ Every auditable page route is documented.++ℹ 6 manifest page(s) have no `added` date (omitted from /changelog). Fine for legacy pages; add dates as you touch them.++> [email protected] audit:hidden-guard+> node scripts/audit-hidden-guard.mjs++✓ audit-hidden-guard: all 293 pages resolve the [hidden] guard++> [email protected] audit:x402-catalog+> node scripts/audit-x402-catalog.mjs++✓ audit-x402-catalog: all 92 x402 endpoints are documented++> [email protected] audit:tokens+> node scripts/audit-token-drift.mjs++✓ token drift unchanged: 0 hardcoded token-hex(es) (baseline 0).+EXIT=0diff --git a/prompts/roadmap/_generated/forge-ux/gate-before.txt b/prompts/roadmap/_generated/forge-ux/gate-before.txtnew file mode 100644index 000000000..71dfe12be--- /dev/null+++ b/prompts/roadmap/_generated/forge-ux/gate-before.txt@@ -0,0 +1,79 @@++> [email protected] gate+> npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:hidden-guard && npm run audit:x402-catalog && npm run audit:tokens+++> [email protected] test:gate+> node scripts/test-gate.mjs++[test-gate] running 7 critical-path test files…++ RUN v4.1.9 /workspaces/three.ws+++ Test Files 7 passed (7)+ Tests 86 passed (86)+ Start at 21:25:03+ Duration 2.73s (transform 1.36s, setup 0ms, import 3.05s, tests 2.66s, environment 1ms)++[test-gate] ✓ all critical-path tests passed++> [email protected] test:gate-3d+> vitest run tests/glb-canonicalize.test.js tests/animation-retarget.test.js tests/animation-retarget-rest-pollution.test.js tests/viewer-framing.test.js+++ RUN v4.1.9 /workspaces/three.ws+++ Test Files 4 passed (4)+ Tests 244 passed (244)+ Start at 21:25:07+ Duration 578ms (transform 403ms, setup 0ms, import 891ms, tests 286ms, environment 1ms)+++> [email protected] audit:mcp+> node scripts/audit-mcp-manifests.mjs++[audit:mcp] 16 MCP manifests consistent++> [email protected] audit:mcp-golden+> node scripts/audit-mcp-golden.mjs++[audit:mcp-golden] 236 hosted MCP tool contracts match the golden fixture++> [email protected] audit:routes+> node scripts/verify-routes.mjs++Route verify — 331 catalog pages, 1112 main routes, 1 post-filesystem routes.+ modeled dist files: 1630 · canonical-covered: 331 · literal page routes checked for shadows: 481+ 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 (1764 checked)++> [email protected] audit:pages+> node scripts/audit-page-index.mjs++Route audit: 145 auditable page routes, 331 documented in pages.json.+✓ Every auditable page route is documented.++ℹ 6 manifest page(s) have no `added` date (omitted from /changelog). Fine for legacy pages; add dates as you touch them.++> [email protected] audit:hidden-guard+> node scripts/audit-hidden-guard.mjs++✓ audit-hidden-guard: all 293 pages resolve the [hidden] guard++> [email protected] audit:x402-catalog+> node scripts/audit-x402-catalog.mjs++✓ audit-x402-catalog: all 92 x402 endpoints are documented++> [email protected] audit:tokens+> node scripts/audit-token-drift.mjs++✓ token drift unchanged: 0 hardcoded token-hex(es) (baseline 0).diff --git a/public/features.json b/public/features.jsonindex 8dd35cf31..d94a52814 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-16T20:34:26.961Z",+ "generated_at": "2026-07-16T21:21:54.639Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/workers/model-trellis/README.md b/workers/model-trellis/README.mdindex be7ae3b19..49ceb85e2 100644--- a/workers/model-trellis/README.md+++ b/workers/model-trellis/README.md@@ -4,9 +4,11 @@ FastAPI inference service that turns **one image into a textured GLB** using[Microsoft TRELLIS](https://github.com/microsoft/TRELLIS) (`TRELLIS-image-large`,MIT license). TRELLIS represents shape and appearance as *structured latents*,decodes them to both a Gaussian appearance field and a mesh, then fuses the two-into a single textured GLB (`postprocessing_utils.to_glb`, `simplify=0.95`,-`texture_size=1024`, fixed `seed=42`). It runs on one NVIDIA L4 (24 GB) on Cloud-Run and is the self-hosted TRELLIS mesh backend for the `/forge` image→3D lane.+into a single textured GLB (`postprocessing_utils.to_glb`). Quality is tiered+(`draft` → `max`); the default bakes a 4096px texture and keeps most geometry,+and the `max` tier pushes the samplers to their ceiling and mattes the subject+first. It runs on one NVIDIA L4 (24 GB) on Cloud Run and is the self-hosted+TRELLIS mesh backend for the `/forge` image→3D lane.Work is asynchronous: `POST /infer` returns `202` with a `task_id`, and thecaller polls `GET /tasks/{id}` until the mesh is written to Cloud Storage. The@@ -26,16 +28,65 @@ Request:{"images": ["https://example.com/chair.png"],"body_type": "neutral",- "job_id": "abc123"+ "job_id": "abc123",+ "tier": "max",+ "matte": true,+ "rembg_model": "u2net_human_seg",+ "quality": { "texture_size": 4096 },+ "seed": 42}```- `images` — 1 to 6 entries, each a `data:image/…;base64,…` URI or an `https://`- URL. **Only the first is used.** `https` sources are pulled through the SSRF- guard in [`worker_security.py`](./worker_security.py) (https-only; private,- loopback, link-local, and cloud-metadata IPs rejected on every redirect hop).+ URL. A single image reconstructs one asset; multiple entries are FUSED as+ turnaround views (front/side/back) of the **same** subject via+ `run_multi_image`. `https` sources are pulled through the SSRF guard in+ [`worker_security.py`](./worker_security.py) (https-only; private, loopback,+ link-local, and cloud-metadata IPs rejected on every redirect hop).- `body_type` — optional, default `"neutral"` (accepted, not used by TRELLIS).- `job_id` — optional correlation string.+- `tier` — optional named quality preset: `draft` | `standard` | `high` | `max`+ (see table below). Omitted keeps the historical default (equivalent to+ `high`). A `quality` dict still overrides individual fields on top of a tier.+- `matte` — optional. Run the subject through the sibling+ [`rembg-service`](../rembg/) before reconstruction so the background stops+ bleeding into the mesh. Defaults **on** for `tier: "max"`, **off** otherwise.+ Requires `REMBG_SERVICE_URL` to be set; if unset or the call fails, TRELLIS's+ own internal background removal still runs, so matting only ever improves the+ result, never gates it.+- `rembg_model` — optional model for the pre-matte: `isnet-general-use`+ (default), `u2net`, `u2net_human_seg` (best for people/portraits), `silueta`.+- `quality` — optional per-field override of the resolved tier (`ss_steps`,+ `slat_steps`, `ss_cfg`, `slat_cfg`, `simplify`, `texture_size`), each clamped+ to a safe L4 envelope.+- `seed` — optional deterministic sampling seed (default `42`).++### Quality tiers++| tier | ss/slat steps | ss/slat cfg | simplify (tris removed) | texture | matte default | use |+|---|---|---|---|---|---|---|+| `draft` | 12 / 12 | 7.5 / 3.0 | 0.95 | 1024 | off | fast previews / latency lane |+| `standard` | 25 / 25 | 7.5 / 3.0 | 0.90 | 2048 | off | balanced |+| `high` *(default)* | 40 / 40 | 7.5 / 3.0 | 0.75 | 4096 | off | production quality bar |+| `max` | 50 / 50 | 8.5 / 4.5 | 0.50 | 4096 | on | maximum realism (photo → 3D) |++`simplify` is the **fraction of triangles removed** by `to_glb`'s decimation, so+a lower value keeps more geometry: `max` keeps ~all of it. Steps drive both+diffusion stages (structure + structured-latent) and cost scales roughly+linearly with them; `max` runs both at the sampler ceiling. Cost is not the+constraint here (the L4 runs one job at a time against the platform's GCP credit+budget) — realism is.++### Image → 3D from a real user photo++The MAX tier is built for turning a real photo of an object or a person into a+textured 3D asset. For a clean reconstruction, matte the subject first: `matte:+true` sends the image to the sibling `rembg-service`, which returns an RGBA+cutout that TRELLIS uses directly as the subject mask (its alpha channel is+respected, bypassing a second internal rembg pass). For people, pass+`rembg_model: "u2net_human_seg"`. Send a single clear, front-facing photo; add+side/back views of the same subject to the `images` array to fill in geometry+the front view cannot see.Response:@@ -71,7 +122,10 @@ stays in the container log). Unknown ids return `404`."gpu_name": "NVIDIA L4","pipeline_loaded": true,"ready": true,- "load_error": null+ "load_error": null,+ "tiers": ["draft", "standard", "high", "max"],+ "default_quality": { "ss_steps": 40, "slat_steps": 40, "ss_cfg": 7.5, "slat_cfg": 3.0, "simplify": 0.75, "texture_size": 4096 },+ "rembg_matte": true}```@@ -89,6 +143,9 @@ window wait for `ready` (up to 600 s) rather than failing.| `MAX_CONCURRENT` | no | `1` | In-flight inferences; one L4 fits exactly one || `ATTN_BACKEND` | no | `xformers` | TRELLIS attention backend, read at import time || `SPCONV_ALGO` | no | `native` | Sparse-conv algorithm, read at import time |+| `REMBG_SERVICE_URL` | no | — | Sibling [`rembg-service`](../rembg/) base URL for the `matte` pre-step. Unset disables matting (TRELLIS still removes the background internally). |+| `REMBG_MODEL` | no | `isnet-general-use` | Default rembg model for the pre-matte |+| `REMBG_TIMEOUT_S` | no | `90` | Max seconds to wait on the rembg-service round-trip before falling back to the un-matted image |Weights are **not** baked into the image — the `three-ws-model-weights` bucketis mounted at `/weights`, so refreshing weights needs no rebuild. Pre-populatediff --git a/workers/model-trellis/cloudbuild.yaml b/workers/model-trellis/cloudbuild.yamlindex ce2ea914a..0ff7e889e 100644--- a/workers/model-trellis/cloudbuild.yaml+++ b/workers/model-trellis/cloudbuild.yaml@@ -14,6 +14,11 @@ substitutions:# task-state sharing._MAX_INSTANCES: "1"_WEIGHTS_BUCKET_PREFIX: trellis-large+ # Sibling background-removal worker. Set so the MAX tier (and any matte=true+ # request) mattes the subject before reconstruction. Shares this worker's+ # bearer secret and GCS bucket. Optional: unset degrades to TRELLIS's own+ # internal background removal, never a failure.+ _REMBG_SERVICE_URL: https://rembg-service-lp642k3kpa-uc.a.run.appsteps:- id: build@@ -60,7 +65,7 @@ steps:- --allow-unauthenticated- --add-volume=name=weights,type=cloud-storage,bucket=${_WEIGHTS_BUCKET}- --add-volume-mount=volume=weights,mount-path=/weights- - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},WEIGHTS_DIR=/weights/trellis-large,MAX_CONCURRENT=1,WEIGHTS_GCS_URI=gs://${_WEIGHTS_BUCKET}/${_WEIGHTS_BUCKET_PREFIX},WEIGHTS_LOCAL_DIR=/tmp/trellis-weights+ - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},WEIGHTS_DIR=/weights/trellis-large,MAX_CONCURRENT=1,WEIGHTS_GCS_URI=gs://${_WEIGHTS_BUCKET}/${_WEIGHTS_BUCKET_PREFIX},WEIGHTS_LOCAL_DIR=/tmp/trellis-weights,REMBG_SERVICE_URL=${_REMBG_SERVICE_URL}- --set-secrets=API_KEY=avatar-reconstruction-key:latestimages:diff --git a/workers/model-trellis/main.py b/workers/model-trellis/main.pyindex f2cd727f4..23827c1ee 100644--- a/workers/model-trellis/main.py+++ b/workers/model-trellis/main.py@@ -4,16 +4,24 @@ latent representations (Microsoft, MIT license).API contract (consumed by the Pipeline Controller):POST /infer { images: [data-uri|url, ...], body_type?: str, job_id?: str,- seed?: int, quality?: {…} }+ seed?: int, quality?: {…}, tier?: str, matte?: bool,+ rembg_model?: str }→ 202 { task_id, status: "queued" }Multiple images are FUSED as multi-view conditioning of one asset(TrellisImageTo3DPipeline.run_multi_image): send turnaround views(front/side/back) of the same subject, not unrelated photos.- GET /tasks/:id → { task_id, status, result_gcs_url?, error? }+ tier selects a named quality preset (draft | standard | high | max); an+ explicit `quality` dict still overrides individual fields on top. matte runs+ the subject through the sibling rembg-service first (defaults on for tier=max)+ so the background stops bleeding into the mesh. Both are additive: with no+ tier and no matte the behaviour is byte-for-byte the historical default.- GET /health → { ok, model, gpu_available }+ GET /tasks/:id → { task_id, status, result_gcs_url?, tier?, matted_views?,+ quality?, error? }++ GET /health → { ok, model, gpu_available, tiers, rembg_matte }Model weights pre-population:pip install huggingface_hub@@ -38,6 +46,8 @@ import osimport timeimport uuid+import httpx+# TRELLIS reads its attention + sparse-conv backends from the environment at# import time. The Dockerfile sets these as ENV; default them here too so the# service still loads correctly if deployed with a bare env. xformers is chosen@@ -82,6 +92,17 @@ MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "1"))# reliability, never remove the existing path.WEIGHTS_GCS_URI = os.environ.get("WEIGHTS_GCS_URI", "") # e.g. gs://bucket/trellis-largeWEIGHTS_LOCAL_DIR = os.environ.get("WEIGHTS_LOCAL_DIR", "/tmp/trellis-weights")+# Optional sibling background-removal worker (workers/rembg). When set, the+# image path can matte the subject before reconstruction so the background stops+# leaking into the mesh. It shares this worker's bearer secret (both read the+# `avatar-reconstruction-key` Secret Manager value) and writes its cutout PNG to+# the same GCS bucket, served back as a public https URL we re-fetch. Unset, or+# unreachable, the pre-matte is skipped and TRELLIS's own internal preprocessing+# (preprocess_image=True) still removes the background — the pre-matte only ever+# improves the cut, never gates the reconstruction.+REMBG_SERVICE_URL = os.environ.get("REMBG_SERVICE_URL", "").rstrip("/")+REMBG_DEFAULT_MODEL = os.environ.get("REMBG_MODEL", "isnet-general-use")+REMBG_TIMEOUT_S = float(os.environ.get("REMBG_TIMEOUT_S", "90"))_pipeline = None_bucket: Optional[storage.Bucket] = None@@ -196,10 +217,15 @@ def _require_api_key(authorization: str) -> None:raise HTTPException(status_code=401, detail=str(exc)) from exc-def _decode_image(src: str) -> Image.Image:+def _decode_image(src: str, keep_alpha: bool = False) -> Image.Image:+ # keep_alpha=True preserves an RGBA cutout's transparency so TRELLIS uses the+ # supplied alpha as the subject mask (its preprocess_image path respects an+ # existing alpha channel and only falls back to internal rembg for RGB). The+ # text/free lane keeps the historical RGB decode.+ mode = "RGBA" if keep_alpha else "RGB"if src.startswith("data:image"):b64 = src.split(",", 1)[1]- return Image.open(io.BytesIO(base64.b64decode(b64))).convert("RGB")+ return Image.open(io.BytesIO(base64.b64decode(b64))).convert(mode)if src.startswith("https://"):# SSRF-hardened: https-only, private/loopback/link-local/metadata IPs# rejected after DNS resolution, redirects re-validated per hop, bounded.@@ -207,10 +233,50 @@ def _decode_image(src: str) -> Image.Image:data = fetch_remote_bytes(src, timeout=30)except UnsafeUrlError as exc:raise ValueError(f"refused to fetch image source: {exc}") from exc- return Image.open(io.BytesIO(data)).convert("RGB")+ return Image.open(io.BytesIO(data)).convert(mode)raise ValueError(f"unsupported image source: {src[:60]}")+async def _matte_via_rembg(src: str, model: str) -> tuple[str, bool]:+ """Send one image to the sibling rembg-service, poll it to completion, and+ return (cutout_https_url, True). On any failure return (src, False) so the+ caller reconstructs from the original image — matting is a fidelity boost,+ never a hard dependency. Never raises."""+ if not REMBG_SERVICE_URL:+ return src, False+ headers = {"Authorization": f"Bearer {API_KEY}"}+ deadline = time.time() + REMBG_TIMEOUT_S+ try:+ async with httpx.AsyncClient(timeout=30) as client:+ resp = await client.post(+ f"{REMBG_SERVICE_URL}/remove",+ headers=headers,+ json={"image": src, "model": model},+ )+ resp.raise_for_status()+ task_id = resp.json()["task_id"]+ while time.time() < deadline:+ await asyncio.sleep(2)+ poll = await client.get(+ f"{REMBG_SERVICE_URL}/tasks/{task_id}", headers=headers+ )+ poll.raise_for_status()+ state = poll.json()+ status = state.get("status")+ if status == "done":+ url = state.get("result_url")+ if url:+ log.info("rembg matte ok -> %s", url)+ return url, True+ return src, False+ if status == "failed":+ log.warning("rembg matte failed (%s); using original image", state.get("error"))+ return src, False+ except Exception as exc: # noqa: BLE001 — degrade to the un-matted image+ log.warning("rembg matte error (%s); using original image", exc)+ return src, False++def _task_blob(task_id: str):return _bucket.blob(f"tasks/{task_id}.json")@@ -263,16 +329,42 @@ _QUALITY_DEFAULTS = {"texture_size": 4096,}+# Named quality tiers. A caller sends `tier` to pick one preset; an explicit+# `quality` dict still overrides individual fields on top of it. When no tier is+# sent the base stays _QUALITY_DEFAULTS, so the existing lane's behaviour is+# byte-for-byte unchanged — tiers are purely additive.+# draft — latency lane: demo-grade steps, aggressive decimation, 1K texture.+# standard — the platform's prior default (steps 25, 2K texture, simplify 0.90).+# high — the current default (steps 40, 4K texture, simplify 0.75).+# max — maximum fidelity: steps at the sampler ceiling, near-zero geometry+# decimation (keep ~all triangles), firmer guidance, 4K texture.+# `simplify` is the FRACTION OF TRIANGLES REMOVED, so a lower value keeps MORE+# geometry. texture_size caps at 4096 (the clamp ceiling and TRELLIS's practical+# bake limit on the L4). max is meant to be paired with rembg pre-matting.+_TIER_PRESETS = {+ "draft": {"ss_steps": 12, "slat_steps": 12, "ss_cfg": 7.5, "slat_cfg": 3.0, "simplify": 0.95, "texture_size": 1024},+ "standard": {"ss_steps": 25, "slat_steps": 25, "ss_cfg": 7.5, "slat_cfg": 3.0, "simplify": 0.90, "texture_size": 2048},+ "high": {"ss_steps": 40, "slat_steps": 40, "ss_cfg": 7.5, "slat_cfg": 3.0, "simplify": 0.75, "texture_size": 4096},+ "max": {"ss_steps": 50, "slat_steps": 50, "ss_cfg": 8.5, "slat_cfg": 4.5, "simplify": 0.50, "texture_size": 4096},+}-def _clamped_quality(q: dict | None) -> dict:- src = q or {}++def _clamped_quality(q: dict | None, tier: str | None = None) -> dict:+ # Base = the named tier preset when a valid one is given, else the historical+ # defaults. An explicit `quality` dict then overrides field-by-field.+ base = dict(_QUALITY_DEFAULTS)+ if tier:+ preset = _TIER_PRESETS.get(str(tier).strip().lower())+ if preset:+ base = dict(preset)+ src = {**base, **(q or {})}def num(key, lo, hi, cast=float):raw = src.get(key)try:val = cast(raw)except (TypeError, ValueError):- return _QUALITY_DEFAULTS[key]+ return base[key]return max(lo, min(hi, val))return {@@ -291,6 +383,9 @@ async def _run_inference(body_type: str,quality: dict | None = None,seed: int | None = None,+ tier: str | None = None,+ matte: bool | None = None,+ rembg_model: str | None = None,) -> None:# Wait for the background pipeline load before touching the GPU. Warm# instances pass instantly; a cold one waits out the load rather than@@ -307,14 +402,36 @@ async def _run_inference(await _update_task(task_id, status="failed", error=f"pipeline unavailable: {_load_error}")return- q = _clamped_quality(quality)+ q = _clamped_quality(quality, tier)+ # Matting defaults on for the MAX tier (paired for maximum fidelity) and off+ # everywhere else, preserving the free/default lane. An explicit `matte`+ # value always wins. It only actually runs when REMBG_SERVICE_URL is set.+ tier_key = str(tier).strip().lower() if tier else None+ do_matte = matte if matte is not None else (tier_key == "max")async with _sem:await _update_task(task_id, status="running")loop = asyncio.get_event_loop()t0 = time.time()try:- imgs = [await loop.run_in_executor(None, _decode_image, src) for src in images]+ matted_count = 0+ sources = list(images)+ if do_matte and REMBG_SERVICE_URL:+ model = rembg_model or REMBG_DEFAULT_MODEL+ resolved = []+ for src in sources:+ new_src, ok = await _matte_via_rembg(src, model)+ resolved.append((new_src, ok))+ matted_count += 1 if ok else 0+ sources = [s for s, _ in resolved]+ # Decode a successful cutout as RGBA (its alpha is the mask);+ # anything that fell back to the original stays RGB.+ imgs = [+ await loop.run_in_executor(None, _decode_image, s, ok)+ for (s, ok) in resolved+ ]+ else:+ imgs = [await loop.run_in_executor(None, _decode_image, src) for src in sources]def _generate():# GLB export lives in trellis.utils.postprocessing_utils.to_glb —@@ -362,9 +479,15 @@ async def _run_inference(status="done",result_gcs_url=gcs_url,views_used=len(imgs),+ tier=tier_key or "default",+ matted_views=matted_count,+ quality=q,elapsed_ms=int(elapsed * 1000),)- log.info("[%s] done in %.1fs — %d bytes → %s", task_id, elapsed, len(glb_bytes), gcs_url)+ log.info(+ "[%s] done in %.1fs (tier=%s matted=%d q=%s) — %d bytes -> %s",+ task_id, elapsed, tier_key or "default", matted_count, q, len(glb_bytes), gcs_url,+ )except Exception as exc:await _update_task(@@ -383,6 +506,17 @@ class InferRequest(BaseModel):# ss_cfg, slat_cfg, simplify, texture_size) — see _clamped_quality. Omitted# or partial fields fall back to the platform quality-bar defaults.quality: dict | None = None+ # Named quality tier: draft | standard | high | max. Seeds the base quality+ # preset; an explicit `quality` dict still overrides individual fields. Omitted+ # keeps the historical default (equivalent to "high").+ tier: str | None = None+ # Run the subject through the sibling rembg-service before reconstruction.+ # Omitted defaults on for tier="max", off otherwise. A matted (RGBA) cutout+ # reconstructs with far less background bleed. Requires REMBG_SERVICE_URL.+ matte: bool | None = None+ # rembg model for the pre-matte: isnet-general-use (default), u2net,+ # u2net_human_seg (better for people/portraits), or silueta.+ rembg_model: str | None = None# Deterministic sampling seed; omitted keeps the historical default (42).seed: int | None = None@@ -400,7 +534,15 @@ async def infer(# instance has nothing in its local `_tasks` dict to fall back on.await _update_task(task_id, status="queued", model="trellis-large")background_tasks.add_task(- _run_inference, task_id, body.images, body.body_type, body.quality, body.seed+ _run_inference,+ task_id,+ body.images,+ body.body_type,+ body.quality,+ body.seed,+ body.tier,+ body.matte,+ body.rembg_model,)return {"task_id": task_id, "status": "queued"}@@ -437,4 +579,7 @@ async def health() -> dict:"pipeline_loaded": _pipeline is not None,"ready": bool(_ready and _ready.is_set()),"load_error": _load_error,+ "tiers": list(_TIER_PRESETS),+ "default_quality": _QUALITY_DEFAULTS,+ "rembg_matte": bool(REMBG_SERVICE_URL),}diff --git a/workers/model-triposg/main.py b/workers/model-triposg/main.pyindex 62eb5fbbe..909b7eb01 100644--- a/workers/model-triposg/main.py+++ b/workers/model-triposg/main.py@@ -92,6 +92,7 @@ _rmbg_net = None_scribble_lock = threading.Lock()_bucket: Optional[storage.Bucket] = None_sem: Optional[asyncio.Semaphore] = None+_ready: Optional[asyncio.Event] = None_tasks: dict[str, dict] = {}@@ -128,14 +129,31 @@ def _ensure_scribble_pipe():return _scribble_pipe+async def _load_models_bg() -> None:+ loop = asyncio.get_event_loop()+ try:+ await loop.run_in_executor(None, _load_models)+ _ready.set()+ log.info("Service ready, max_concurrent=%d", MAX_CONCURRENT)+ except Exception as exc:+ log.error("TripoSG model load FAILED: %s", exc)++@asynccontextmanagerasync def lifespan(app: FastAPI):- global _bucket, _sem+ global _bucket, _sem, _ready_bucket = storage.Client().bucket(GCS_BUCKET)_sem = asyncio.Semaphore(MAX_CONCURRENT)- loop = asyncio.get_event_loop()- await loop.run_in_executor(None, _load_models)- log.info("Service ready — max_concurrent=%d", MAX_CONCURRENT)+ _ready = asyncio.Event()+ # Load the pipelines in the BACKGROUND and yield immediately. uvicorn runs+ # the ASGI lifespan BEFORE it binds the socket, and the full load (TripoSG+ # pipeline + RMBG from the GCS FUSE mount, then the CUDA transfer) runs+ # well past Cloud Run's 240s startup TCP-probe window on a cold instance:+ # revision 00002 died exactly this way (DEADLINE_EXCEEDED mid-load).+ # Backgrounding opens the port at once; tasks that arrive before the load+ # completes wait on _ready in _run_inference. Same pattern as model-trellis.+ asyncio.create_task(_load_models_bg())+ log.info("Service starting, models loading in background (max_concurrent=%d)", MAX_CONCURRENT)yield@@ -211,6 +229,14 @@ async def _run_inference(scribble_confidence: float,target_polycount: int | None,) -> None:+ try:+ await asyncio.wait_for(_ready.wait(), timeout=600)+ except asyncio.TimeoutError:+ _tasks[task_id].update({+ "status": "failed",+ "error": "pipeline not ready (model load timed out)",+ })+ returnasync with _sem:_tasks[task_id]["status"] = "running"loop = asyncio.get_event_loop()diff --git a/workers/model-triposg/requirements.txt b/workers/model-triposg/requirements.txtindex e6adf1579..a5438d7ba 100644--- a/workers/model-triposg/requirements.txt+++ b/workers/model-triposg/requirements.txt@@ -12,6 +12,13 @@# starts (crashes before listening on $PORT).diffusers==0.31.0transformers==4.46.3+# Upstream also leaves peft and huggingface_hub unpinned; a bad transitive+# resolve of those crashed revision 00001 at import time (diffusers.loaders.peft+# raised "name 'torch' is not defined" before the server could bind $PORT).+# These two versions are proven against the pins above in a py3.10 import test+# of the full TripoSGPipeline chain: pin them so a rebuild can never regress.+peft==0.19.1+huggingface_hub==0.36.2torch>=2.3.0trimesh>=4.4.0