Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(motion): seed generated clips from GCP and publish the print catalog

nirholas3ab644cfe28b
diff --git a/api/_lib/motion-seed.js b/api/_lib/motion-seed.js
new file mode 100644
index 000000000..218df89bb
--- /dev/null
+++ b/api/_lib/motion-seed.js
@@ -0,0 +1,591 @@
+// @ts-check
+// Motion seeding: turn a text prompt from data/motion-prompts.json into a clip
+// the animation library can serve, and refuse the ones that would embarrass us.
+//
+// The text2motion worker (workers/model-text2motion) already returns a three.js
+// AnimationClip JSON on the canonical Wolf3D skeleton, so no format conversion
+// is needed: a generated clip's track names are a strict subset of the Mixamo
+// library's (the 23 body bones, no finger bones). What IS needed is a gate.
+// A motion-diffusion sampler fails in ways that look fine in JSON and terrible
+// on a rig: a frozen clip with no motion, a limb that snaps a full turn between
+// two frames, a "walk" whose planted foot slides across the floor, quaternions
+// that drifted off the unit sphere, a NaN that turns the whole avatar inside
+// out. Every one of those is measurable here, before anything is published.
+//
+// The foot-slide check is real forward kinematics, not a heuristic on the hips:
+// CANONICAL_REST_POSITION + CANONICAL_PARENT + CANONICAL_REST_WORLD
+// (src/animation-canonical-rest.js, generated from the reference rig) are enough
+// to replay a clip's world-space joint positions frame by frame. We find the
+// planted foot per frame (the lower toe), measure how far it travels across the
+// floor while planted, and compare that against the stride the clip actually
+// covers. A clip whose planted foot outruns its own stride is skating.
+
+import { readFileSync } from 'node:fs';
+import { createHash } from 'node:crypto';
+import { fileURLToPath } from 'node:url';
+import {
+ CANONICAL_REST,
+ CANONICAL_REST_WORLD,
+ CANONICAL_REST_POSITION,
+ CANONICAL_PARENT,
+} from '../../src/animation-canonical-rest.js';
+
+const PROMPTS_PATH = fileURLToPath(new URL('../../data/motion-prompts.json', import.meta.url));
+
+/** The prompt library is data, never a hardcoded list (work order B6). */
+function loadPromptLibrary() {
+ const parsed = JSON.parse(readFileSync(PROMPTS_PATH, 'utf8'));
+ const prompts = Array.isArray(parsed?.prompts) ? parsed.prompts : [];
+ return Object.freeze({
+ version: parsed?.version ?? null,
+ defaults: Object.freeze(parsed?.defaults ?? {}),
+ categories: Object.freeze(parsed?.categories ?? {}),
+ prompts: Object.freeze(prompts.map((p) => Object.freeze({ ...p }))),
+ });
+}
+
+let cachedLibrary = null;
+export function motionPromptLibrary() {
+ if (!cachedLibrary) cachedLibrary = loadPromptLibrary();
+ return cachedLibrary;
+}
+export function motionPrompts() {
+ return motionPromptLibrary().prompts;
+}
+export function motionPromptById(id) {
+ return motionPrompts().find((p) => p.id === id) ?? null;
+}
+
+// Generated clips carry their own prefix so the library, the gallery and every
+// report can tell a sampled clip from the `mx-` Mixamo import at a glance.
+export const GENERATED_PREFIX = 'gen-';
+export const GENERATED_CLIP_DIR = 'animations/library/clips/';
+export const LIBRARY_MANIFEST_KEY = 'animations/library/manifest.json';
+
+/** Stable, collision-free clip name: gen-<prompt id>-<12 hex of the task id>. */
+export function libraryClipName(promptId, taskId) {
+ const slug = String(promptId)
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-|-$/g, '')
+ .slice(0, 48);
+ const hash = createHash('sha256').update(String(taskId)).digest('hex').slice(0, 12);
+ return `${GENERATED_PREFIX}${slug}-${hash}`;
+}
+
+export function isGeneratedClipName(name) {
+ return typeof name === 'string' && name.startsWith(GENERATED_PREFIX);
+}
+
+// ── Minimal quaternion / vector math ────────────────────────────────────────
+// Four operations on 4 floats each. three.js is a browser dependency and far
+// too heavy to pull into a cron for this, and a dependency for four functions
+// is the kind of thing CLAUDE.md tells us to just write.
+
+function quatMul(a, b) {
+ const [ax, ay, az, aw] = a;
+ const [bx, by, bz, bw] = b;
+ return [
+ aw * bx + ax * bw + ay * bz - az * by,
+ aw * by - ax * bz + ay * bw + az * bx,
+ aw * bz + ax * by - ay * bx + az * bw,
+ aw * bw - ax * bx - ay * by - az * bz,
+ ];
+}
+
+function quatConjugate(q) {
+ return [-q[0], -q[1], -q[2], q[3]];
+}
+
+function quatApply(q, v) {
+ const [qx, qy, qz, qw] = q;
+ const [vx, vy, vz] = v;
+ // t = 2 * cross(q.xyz, v); v' = v + qw * t + cross(q.xyz, t)
+ const tx = 2 * (qy * vz - qz * vy);
+ const ty = 2 * (qz * vx - qx * vz);
+ const tz = 2 * (qx * vy - qy * vx);
+ return [
+ vx + qw * tx + (qy * tz - qz * ty),
+ vy + qw * ty + (qz * tx - qx * tz),
+ vz + qw * tz + (qx * ty - qy * tx),
+ ];
+}
+
+function quatLength(q) {
+ return Math.hypot(q[0], q[1], q[2], q[3]);
+}
+
+/** Angle in radians between two unit quaternions, sign-insensitive (q and -q are the same rotation). */
+function quatAngleBetween(a, b) {
+ const dot = Math.abs(a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]);
+ return 2 * Math.acos(Math.min(1, dot));
+}
+
+// ── Clip access ─────────────────────────────────────────────────────────────
+
+function tracksByName(clip) {
+ const map = new Map();
+ for (const track of clip?.tracks ?? []) {
+ if (track && typeof track.name === 'string') map.set(track.name, track);
+ }
+ return map;
+}
+
+function boneOf(trackName) {
+ const dot = trackName.lastIndexOf('.');
+ return dot === -1 ? trackName : trackName.slice(0, dot);
+}
+
+/**
+ * Sample a quaternion track at frame index i, falling back to the bone's rest
+ * rotation when the clip does not animate it (an unanimated bone holds bind
+ * pose, exactly as three.js plays it).
+ */
+function quatAt(track, i, restQuat) {
+ if (!track) return restQuat;
+ const n = Math.floor(track.values.length / 4);
+ if (n === 0) return restQuat;
+ const k = Math.min(Math.max(i, 0), n - 1) * 4;
+ return [track.values[k], track.values[k + 1], track.values[k + 2], track.values[k + 3]];
+}
+
+function vec3At(track, i, fallback) {
+ if (!track) return fallback;
+ const n = Math.floor(track.values.length / 3);
+ if (n === 0) return fallback;
+ const k = Math.min(Math.max(i, 0), n - 1) * 3;
+ return [track.values[k], track.values[k + 1], track.values[k + 2]];
+}
+
+// Bone-local rest offset, expressed in the parent's world rest frame. The
+// generated table stores WORLD rest positions, so the local offset is the world
+// delta rotated back into the parent's bind orientation.
+const LOCAL_REST_OFFSET = (() => {
+ const out = {};
+ for (const bone of Object.keys(CANONICAL_REST_POSITION)) {
+ const parent = CANONICAL_PARENT[bone];
+ const here = CANONICAL_REST_POSITION[bone];
+ if (!parent) {
+ out[bone] = [...here];
+ continue;
+ }
+ const there = CANONICAL_REST_POSITION[parent];
+ const delta = [here[0] - there[0], here[1] - there[1], here[2] - there[2]];
+ const parentWorld = CANONICAL_REST_WORLD[parent] ?? [0, 0, 0, 1];
+ out[bone] = quatApply(quatConjugate(parentWorld), delta);
+ }
+ return Object.freeze(out);
+})();
+
+/** Bones ordered parents-before-children so one pass of FK is enough. */
+const FK_ORDER = (() => {
+ const order = [];
+ const seen = new Set();
+ const visit = (bone) => {
+ if (seen.has(bone)) return;
+ const parent = CANONICAL_PARENT[bone];
+ if (parent) visit(parent);
+ seen.add(bone);
+ order.push(bone);
+ };
+ for (const bone of Object.keys(CANONICAL_PARENT)) visit(bone);
+ return Object.freeze(order);
+})();
+
+/**
+ * World-space joint positions for one frame of a clip.
+ * @returns {Record<string, [number, number, number]>}
+ */
+export function forwardKinematicsFrame(clip, frameIndex) {
+ const tracks = tracksByName(clip);
+ const worldQuat = {};
+ const worldPos = {};
+ for (const bone of FK_ORDER) {
+ const local = quatAt(tracks.get(`${bone}.quaternion`), frameIndex, CANONICAL_REST[bone] ?? [0, 0, 0, 1]);
+ const parent = CANONICAL_PARENT[bone];
+ if (!parent) {
+ worldQuat[bone] = local;
+ worldPos[bone] = vec3At(tracks.get(`${bone}.position`), frameIndex, CANONICAL_REST_POSITION[bone] ?? [0, 0, 0]);
+ continue;
+ }
+ const pq = worldQuat[parent] ?? [0, 0, 0, 1];
+ const pp = worldPos[parent] ?? [0, 0, 0];
+ const offset = quatApply(pq, LOCAL_REST_OFFSET[bone] ?? [0, 0, 0]);
+ worldQuat[bone] = quatMul(pq, local);
+ worldPos[bone] = [pp[0] + offset[0], pp[1] + offset[1], pp[2] + offset[2]];
+ }
+ return worldPos;
+}
+
+function frameCount(clip) {
+ let frames = 0;
+ for (const track of clip?.tracks ?? []) {
+ const times = track?.times;
+ if (Array.isArray(times) || ArrayBuffer.isView(times)) frames = Math.max(frames, times.length);
+ }
+ return frames;
+}
+
+/**
+ * Foot-contact metrics over the whole clip.
+ *
+ * For each frame the lower toe is treated as the planted foot. While a foot
+ * stays planted across consecutive frames, the horizontal distance it covers is
+ * slide. `slidePerStride` compares that slide against the horizontal distance
+ * the hips actually travelled: a clip that moves the body forward earns its foot
+ * travel, a clip that pins the body and skates the feet does not.
+ */
+export function footContactMetrics(clip) {
+ const frames = frameCount(clip);
+ if (frames < 2) {
+ return { frames, slide: 0, stride: 0, slidePerStride: 0, plantedFrames: 0, floorY: 0 };
+ }
+
+ // One FK pass, kept, so the floor level can be derived from the whole clip
+ // before any frame is judged against it.
+ const lower = new Array(frames);
+ const hipsY = new Array(frames);
+ const hips = new Array(frames);
+ for (let i = 0; i < frames; i += 1) {
+ const world = forwardKinematicsFrame(clip, i);
+ const left = world.LeftToeBase ?? world.LeftFoot;
+ const right = world.RightToeBase ?? world.RightFoot;
+ hips[i] = world.Hips ?? null;
+ hipsY[i] = world.Hips ? world.Hips[1] : Number.NaN;
+ if (!left || !right) {
+ lower[i] = null;
+ continue;
+ }
+ lower[i] = left[1] <= right[1] ? { side: 'Left', pos: left } : { side: 'Right', pos: right };
+ }
+
+ // The floor is where this clip's feet actually get to, not y=0: a clip can be
+ // authored with any root offset, and the reference rig's toes sit above zero.
+ let floorY = Infinity;
+ for (const entry of lower) {
+ if (entry && Number.isFinite(entry.pos[1])) floorY = Math.min(floorY, entry.pos[1]);
+ }
+ if (!Number.isFinite(floorY)) floorY = 0;
+
+ let slide = 0;
+ let plantedFrames = 0;
+ let prevPlanted = null;
+ let prevPos = null;
+ let hipsPath = 0;
+ let hipsFirst = null;
+ let hipsLast = null;
+ let prevHips = null;
+
+ for (let i = 0; i < frames; i += 1) {
+ const h = hips[i];
+ if (h) {
+ if (!hipsFirst) hipsFirst = h;
+ hipsLast = h;
+ if (prevHips) hipsPath += Math.hypot(h[0] - prevHips[0], h[2] - prevHips[2]);
+ prevHips = h;
+ }
+
+ const entry = lower[i];
+ // A foot only counts as planted when it is actually down on the floor AND
+ // the body is upright over it. Without that test a breakdance flair, a
+ // fall, a crawl or any aerial reads as a foot skating across the ground,
+ // because the "lower" foot is simply the one that happens to be less high.
+ const grounded =
+ entry != null &&
+ entry.pos[1] - floorY <= MOTION_GATE.PLANT_BAND &&
+ Number.isFinite(hipsY[i]) &&
+ hipsY[i] - floorY >= MOTION_GATE.UPRIGHT_HIP_HEIGHT;
+ if (!grounded) {
+ prevPlanted = null;
+ prevPos = null;
+ continue;
+ }
+
+ if (entry.side === prevPlanted && prevPos) {
+ slide += Math.hypot(entry.pos[0] - prevPos[0], entry.pos[2] - prevPos[2]);
+ plantedFrames += 1;
+ }
+ prevPlanted = entry.side;
+ prevPos = entry.pos;
+ }
+
+ // Stride credit is the greater of net displacement and the path the hips
+ // walked: a clip that turns in place still travels, and a clip that moves out
+ // and back should not be scored as if it never moved.
+ const net =
+ hipsFirst && hipsLast ? Math.hypot(hipsLast[0] - hipsFirst[0], hipsLast[2] - hipsFirst[2]) : 0;
+ const stride = Math.max(net, hipsPath);
+ // A stationary clip (an idle, a wave) has no stride to earn slide against, so
+ // it is scored on absolute slide instead of a ratio against roughly zero.
+ const slidePerStride = stride > 0.05 ? slide / stride : slide;
+ return { frames, slide, stride, slidePerStride, plantedFrames, floorY };
+}
+
+// ── The gate ────────────────────────────────────────────────────────────────
+
+// Every threshold is a measured property of a clip that plays correctly on the
+// reference rig, not a taste call.
+export const MOTION_GATE = Object.freeze({
+ // The body chain a retarget needs to produce a readable pose. Fingers are
+ // deliberately absent: the sampler does not animate them and a bind-pose hand
+ // is correct, not a defect.
+ REQUIRED_BONES: Object.freeze([
+ 'Hips',
+ 'Spine',
+ 'Spine1',
+ 'Spine2',
+ 'Neck',
+ 'Head',
+ 'LeftArm',
+ 'LeftForeArm',
+ 'RightArm',
+ 'RightForeArm',
+ 'LeftUpLeg',
+ 'LeftLeg',
+ 'LeftFoot',
+ 'RightUpLeg',
+ 'RightLeg',
+ 'RightFoot',
+ ]),
+ MIN_FRAMES: 16,
+ MIN_DURATION: 0.5,
+ MAX_DURATION: 12,
+ // The sampler is asked for a duration; more than a second off means the clip
+ // is not the clip we ordered.
+ DURATION_TOLERANCE: 1.0,
+ // Unit-quaternion drift. Past this the rotation is no longer a rotation and
+ // three.js renders a sheared limb.
+ QUAT_NORM_EPSILON: 0.02,
+ // A limb that rotates more than this between two adjacent frames is a pop,
+ // not motion. Set above the worst step measured across a 60-clip sample of
+ // the authored library (2.124 rad, in a violent fall), and well below the
+ // 180 degree snap a collapsed sampler produces, which is the actual defect.
+ MAX_FRAME_JUMP_RAD: 2.62,
+ // Total rotational travel below this is a frozen clip: the sampler collapsed.
+ MIN_TOTAL_MOTION_RAD: 1.5,
+ // How close to the clip's own floor a foot must be to count as planted.
+ PLANT_BAND: 0.06,
+ // How high the hips must sit above that floor for the body to be standing on
+ // the planted foot at all. Below this the clip is floor work (a fall, a
+ // crawl, a breakdance flair) where no foot bears weight and foot travel is
+ // choreography rather than skating.
+ UPRIGHT_HIP_HEIGHT: 0.55,
+ // Planted-foot slide, as a multiple of the stride the clip actually covers.
+ MAX_SLIDE_PER_STRIDE: 0.85,
+ // Absolute slide ceiling in metres for a clip that does not travel.
+ MAX_STATIONARY_SLIDE: 0.55,
+});
+
+function isFiniteSeq(seq) {
+ for (let i = 0; i < seq.length; i += 1) {
+ if (!Number.isFinite(seq[i])) return false;
+ }
+ return true;
+}
+
+/**
+ * Decide whether a generated clip is fit to publish.
+ *
+ * @param {any} clip raw AnimationClip JSON from the text2motion worker
+ * @param {{ expectedDuration?: number, loop?: boolean }} [opts]
+ * @returns {{ ok: boolean, reasons: string[], metrics: Record<string, number> }}
+ */
+export function gateMotionClip(clip, opts = {}) {
+ const reasons = [];
+ const metrics = {};
+
+ const tracks = Array.isArray(clip?.tracks) ? clip.tracks : null;
+ if (!tracks || tracks.length === 0) {
+ return { ok: false, reasons: ['no_tracks'], metrics };
+ }
+
+ const duration = Number(clip?.duration);
+ metrics.duration = Number.isFinite(duration) ? duration : 0;
+ if (!Number.isFinite(duration) || duration < MOTION_GATE.MIN_DURATION || duration > MOTION_GATE.MAX_DURATION) {
+ reasons.push('duration_out_of_range');
+ }
+ const expected = Number(opts.expectedDuration);
+ if (Number.isFinite(expected) && Number.isFinite(duration)) {
+ metrics.durationDelta = Math.abs(duration - expected);
+ if (metrics.durationDelta > MOTION_GATE.DURATION_TOLERANCE) reasons.push('duration_mismatch');
+ }
+
+ const names = new Set(tracks.map((t) => t?.name).filter((n) => typeof n === 'string'));
+ const bones = new Set([...names].map(boneOf));
+ const missing = MOTION_GATE.REQUIRED_BONES.filter((b) => !bones.has(b));
+ metrics.trackCount = tracks.length;
+ metrics.missingBones = missing.length;
+ if (missing.length) reasons.push(`missing_bones:${missing.slice(0, 4).join(',')}`);
+
+ // A track naming a bone the canonical skeleton does not have would land on
+ // nothing after retarget, so it is a format failure rather than a quality one.
+ const foreign = [...bones].filter((b) => !(b in CANONICAL_PARENT));
+ metrics.foreignBones = foreign.length;
+ if (foreign.length) reasons.push(`foreign_bones:${foreign.slice(0, 3).join(',')}`);
+
+ let frames = 0;
+ let worstNormDrift = 0;
+ let worstJump = 0;
+ let totalMotion = 0;
+ let nonFinite = false;
+ let nonMonotonic = false;
+
+ for (const track of tracks) {
+ const times = track?.times ?? [];
+ const values = track?.values ?? [];
+ if (!isFiniteSeq(times) || !isFiniteSeq(values)) {
+ nonFinite = true;
+ continue;
+ }
+ frames = Math.max(frames, times.length);
+ for (let i = 1; i < times.length; i += 1) {
+ if (times[i] < times[i - 1]) {
+ nonMonotonic = true;
+ break;
+ }
+ }
+ if (track.type !== 'quaternion') continue;
+
+ let prev = null;
+ const n = Math.floor(values.length / 4);
+ for (let i = 0; i < n; i += 1) {
+ const q = [values[i * 4], values[i * 4 + 1], values[i * 4 + 2], values[i * 4 + 3]];
+ worstNormDrift = Math.max(worstNormDrift, Math.abs(quatLength(q) - 1));
+ if (prev) {
+ const step = quatAngleBetween(prev, q);
+ worstJump = Math.max(worstJump, step);
+ totalMotion += step;
+ }
+ prev = q;
+ }
+ }
+
+ metrics.frames = frames;
+ metrics.quatNormDrift = worstNormDrift;
+ metrics.maxFrameJumpRad = worstJump;
+ metrics.totalMotionRad = totalMotion;
+
+ if (nonFinite) reasons.push('non_finite_keyframes');
+ if (nonMonotonic) reasons.push('non_monotonic_times');
+ if (frames < MOTION_GATE.MIN_FRAMES) reasons.push('too_few_frames');
+ if (worstNormDrift > MOTION_GATE.QUAT_NORM_EPSILON) reasons.push('quaternions_not_normalized');
+ if (worstJump > MOTION_GATE.MAX_FRAME_JUMP_RAD) reasons.push('frame_pop');
+ if (totalMotion < MOTION_GATE.MIN_TOTAL_MOTION_RAD) reasons.push('frozen_clip');
+
+ // Foot contact only means something once the skeleton itself is sane, and
+ // running FK over NaN values would only produce NaN metrics.
+ if (!nonFinite && !missing.length && !foreign.length) {
+ const foot = footContactMetrics(clip);
+ metrics.footSlide = foot.slide;
+ metrics.stride = foot.stride;
+ metrics.slidePerStride = foot.slidePerStride;
+ const travels = foot.stride > 0.05;
+ if (travels && foot.slidePerStride > MOTION_GATE.MAX_SLIDE_PER_STRIDE) reasons.push('foot_sliding');
+ if (!travels && foot.slide > MOTION_GATE.MAX_STATIONARY_SLIDE) reasons.push('foot_sliding_in_place');
+ }
+
+ return { ok: reasons.length === 0, reasons, metrics };
+}
+
+// ── Publishing shape ────────────────────────────────────────────────────────
+
+/**
+ * Rewrite a raw generated clip into the exact object the library already serves:
+ * same top-level keys, same track shape, library-style name, and a userData
+ * record of where the clip came from (the Mixamo import carries an empty
+ * userData object, so the key is expected and the extra provenance is additive).
+ */
+export function toLibraryClip(raw, { name, promptId, prompt, category, loop, taskId }) {
+ return {
+ name,
+ duration: raw.duration,
+ tracks: raw.tracks,
+ uuid: raw.uuid,
+ blendMode: raw.blendMode ?? 0,
+ userData: {
+ source: 'text2motion',
+ prompt_id: promptId,
+ prompt,
+ category,
+ loop: Boolean(loop),
+ task_id: taskId,
+ generated_at: new Date().toISOString(),
+ },
+ };
+}
+
+/** A manifest row in the shape api/animations/library.js already returns. */
+export function manifestEntryFor(clip, { label, icon, loop, bytes, url, thumb }) {
+ return {
+ name: clip.name,
+ label,
+ icon: icon || '🎬',
+ loop: Boolean(loop),
+ duration: clip.duration,
+ bytes,
+ url,
+ thumb: thumb ?? null,
+ };
+}
+
+/**
+ * Merge generated rows into the existing manifest without disturbing the Mixamo
+ * import: entries are matched by name, so re-running a batch replaces a row
+ * rather than duplicating it, and the array stays stably ordered (the library
+ * endpoint pages it by index, so a reorder would shuffle every caller's page).
+ */
+export function mergeManifest(existing, additions) {
+ const out = Array.isArray(existing) ? [...existing] : [];
+ const index = new Map(out.map((entry, i) => [entry?.name, i]));
+ for (const entry of additions) {
+ const at = index.get(entry.name);
+ if (at === undefined) {
+ index.set(entry.name, out.length);
+ out.push(entry);
+ } else {
+ out[at] = entry;
+ }
+ }
+ return out;
+}
+
+// ── Rotating free subset (work order B8) ────────────────────────────────────
+//
+// Policy: the generated collection is paid by default, and a fixed-size subset
+// is free for one epoch at a time. The subset is chosen by hashing the clip name
+// together with the epoch number, so it is deterministic (every server instance
+// and the client agree without coordination or a DB write), stable for the whole
+// epoch (a visitor does not watch a clip's price flicker on reload), and evenly
+// spread over time (each clip's hash ordering differs per epoch, so the free
+// slot rotates rather than favouring the same names).
+
+export const FREE_ROTATION = Object.freeze({
+ EPOCH_MS: 7 * 24 * 60 * 60 * 1000,
+ SIZE: 12,
+});
+
+export function rotationEpoch(now = Date.now()) {
+ return Math.floor(now / FREE_ROTATION.EPOCH_MS);
+}
+
+function rotationRank(name, epoch) {
+ const digest = createHash('sha256').update(`${epoch}:${name}`).digest();
+ return digest.readUInt32BE(0);
+}
+
+/**
+ * The names free this epoch, given every generated clip name in the collection.
+ * @param {string[]} names
+ */
+export function freeClipNames(names, { now = Date.now(), size = FREE_ROTATION.SIZE } = {}) {
+ const epoch = rotationEpoch(now);
+ return [...new Set(names)]
+ .map((name) => ({ name, rank: rotationRank(name, epoch) }))
+ .sort((a, b) => a.rank - b.rank || (a.name < b.name ? -1 : 1))
+ .slice(0, Math.max(0, size))
+ .map((entry) => entry.name);
+}
+
+export function isFreeThisEpoch(name, allNames, opts = {}) {
+ return freeClipNames(allNames, opts).includes(name);
+}
diff --git a/data/print-catalog.json b/data/print-catalog.json
new file mode 100644
index 000000000..6449b7ebd
--- /dev/null
+++ b/data/print-catalog.json
@@ -0,0 +1,226 @@
+{
+ "version": 1,
+ "currency": "USDC",
+ "chain": "solana",
+ "_note": "Single source of truth for every Materialize price. The quote engine (api/_lib/print/quote.js) is pure and reads only this file; no price is ever computed in a frontend module or a handler. Owner-tunable: change a number here and every surface follows.",
+ "_sources": [
+ {
+ "retrieved": "2026-09-02",
+ "url": "https://support.shapeways.com/hc/en-us/articles/360008363353-Designing-for-Full-Color-Sandstone",
+ "note": "Full-colour sandstone published at $0.99 per cm3 plus a $1.50 per-model startup fee, 2 mm minimum wall."
+ },
+ {
+ "retrieved": "2026-09-02",
+ "url": "https://3dprinting.com/how-much-does-3d-printing-cost/",
+ "note": "Bureau bands used as the sanity check on every rate below: FDM $0.05-$0.15 per gram plus $3-$10 setup, SLA resin $0.20-$0.50 per gram plus $3-$10 setup, SLS and metal $1-$10 per cm3 through a bureau."
+ },
+ {
+ "retrieved": "2026-09-02",
+ "url": "https://specialty-polymer.com/sls-3d-printing-cost-a-complete-quoting-guide/",
+ "note": "SLS PA12 quoted from about $0.60 per cm3, rising for filled nylons."
+ },
+ {
+ "retrieved": "2026-09-02",
+ "url": "https://blog.met3dp.com/blog/metal-3d-printing-cost-vs-cnc-in-2026-pricing-benchmarks-for-buyers/",
+ "note": "Metal powder-bed benchmarks span $10-$100 per cm3 depending on alloy and run size, which is why the metal entry is quote-on-request rather than instantly priced."
+ }
+ ],
+ "pricing": {
+ "marginFraction": 0.35,
+ "_marginNote": "Declared platform margin already inside every rate below, so a rate can be compared against a bureau's published price directly. Buyer-facing output never includes this field.",
+ "holderDiscount": {
+ "maxBps": 1500,
+ "appliesTo": ["setup", "material", "finish"],
+ "_note": "$THREE holder tiers (api/_lib/three-tier.js) discount platform compute up to 30 percent. A physical print carries real fulfillment cost, so the same tier bps is capped at 15 percent here and never touches shipping, which is passed through."
+ },
+ "quantityBreaks": [
+ { "minQuantity": 5, "discountBps": 800 },
+ { "minQuantity": 20, "discountBps": 1500 }
+ ],
+ "_quantityNote": "A repeat of the same object reuses the same build setup and the same prepared file, so the break applies to setup, material and finish, not to shipping.",
+ "quoteTtlSeconds": 86400,
+ "minOrderUsdc": 12
+ },
+ "materials": [
+ {
+ "id": "resin-standard",
+ "name": "Standard resin",
+ "class": "resin",
+ "blurb": "Crisp SLA detail with a smooth, slightly glossy surface. The default for figures, busts and anything where the sculpt is the point.",
+ "densityGramsPerCm3": 1.1,
+ "ratePerCm3": 0.55,
+ "setupFee": 6,
+ "minWallMm": 0.6,
+ "minHeightMm": 15,
+ "maxHeightMm": 180,
+ "maxBoundingBoxMm": { "x": 190, "y": 180, "z": 190 },
+ "leadTimeDays": 5,
+ "hollow": { "supported": true, "wallMm": 1.6, "drainHoles": 2 },
+ "colorCapable": false,
+ "swatch": { "base": "#d9d5cf", "sheen": "gloss" },
+ "finishes": [
+ { "id": "as-printed", "name": "As printed", "fee": 0, "default": true },
+ { "id": "primed", "name": "Primed and smoothed", "fee": 12, "leadTimeDays": 2 }
+ ]
+ },
+ {
+ "id": "resin-tough",
+ "name": "Tough resin",
+ "class": "resin",
+ "blurb": "Impact-resistant SLA for parts that get handled, snapped together or dropped. Holds an edge without shattering.",
+ "densityGramsPerCm3": 1.15,
+ "ratePerCm3": 0.85,
+ "setupFee": 8,
+ "minWallMm": 1,
+ "minHeightMm": 15,
+ "maxHeightMm": 180,
+ "maxBoundingBoxMm": { "x": 190, "y": 180, "z": 190 },
+ "leadTimeDays": 6,
+ "hollow": { "supported": true, "wallMm": 2, "drainHoles": 2 },
+ "colorCapable": false,
+ "swatch": { "base": "#5b6068", "sheen": "satin" },
+ "finishes": [
+ { "id": "as-printed", "name": "As printed", "fee": 0, "default": true },
+ { "id": "primed", "name": "Primed and smoothed", "fee": 14, "leadTimeDays": 2 }
+ ]
+ },
+ {
+ "id": "nylon-sls",
+ "name": "SLS nylon (PA12)",
+ "class": "sls_nylon",
+ "blurb": "Powder-bed nylon: no support scars, prints interlocking and unsupported geometry other processes refuse. Matte, slightly grainy, very tough.",
+ "densityGramsPerCm3": 1.01,
+ "ratePerCm3": 0.95,
+ "setupFee": 9,
+ "minWallMm": 0.8,
+ "minHeightMm": 12,
+ "maxHeightMm": 280,
+ "maxBoundingBoxMm": { "x": 300, "y": 280, "z": 300 },
+ "leadTimeDays": 7,
+ "hollow": { "supported": false },
+ "colorCapable": false,
+ "swatch": { "base": "#e8e6e1", "sheen": "matte" },
+ "finishes": [
+ { "id": "natural", "name": "Natural white", "fee": 0, "default": true },
+ { "id": "dyed-black", "name": "Dyed black", "fee": 9, "leadTimeDays": 1 }
+ ]
+ },
+ {
+ "id": "sandstone-full-color",
+ "name": "Full-colour sandstone",
+ "class": "full_color",
+ "blurb": "Binder-jetted gypsum printed in full colour, straight from the model's own texture. The only material here that reproduces what you see in the viewer.",
+ "densityGramsPerCm3": 1.7,
+ "ratePerCm3": 1.15,
+ "setupFee": 4,
+ "minWallMm": 2,
+ "minHeightMm": 20,
+ "maxHeightMm": 200,
+ "maxBoundingBoxMm": { "x": 250, "y": 200, "z": 250 },
+ "leadTimeDays": 8,
+ "hollow": { "supported": false },
+ "colorCapable": true,
+ "requiresTexture": true,
+ "swatch": { "base": "#cfc3ae", "sheen": "matte" },
+ "finishes": [
+ { "id": "sealed", "name": "Sealed", "fee": 0, "default": true },
+ { "id": "coated-gloss", "name": "Gloss coated", "fee": 6, "leadTimeDays": 1 }
+ ]
+ },
+ {
+ "id": "pla-draft",
+ "name": "PLA draft",
+ "class": "fdm_draft",
+ "blurb": "The cheapest way to hold the thing. Visible layer lines, generous tolerances, fastest turnaround: print it, look at it, then order the real one.",
+ "densityGramsPerCm3": 1.24,
+ "ratePerCm3": 0.3,
+ "setupFee": 4,
+ "minWallMm": 1.2,
+ "minHeightMm": 20,
+ "maxHeightMm": 250,
+ "maxBoundingBoxMm": { "x": 250, "y": 250, "z": 210 },
+ "leadTimeDays": 3,
+ "hollow": { "supported": true, "wallMm": 2.4, "drainHoles": 0 },
+ "colorCapable": false,
+ "swatch": { "base": "#8ba2b8", "sheen": "matte" },
+ "finishes": [{ "id": "as-printed", "name": "As printed", "fee": 0, "default": true }]
+ },
+ {
+ "id": "steel-316l",
+ "name": "316L stainless steel",
+ "class": "metal",
+ "blurb": "Powder-bed stainless, machined off the plate and bead blasted. Priced by an engineer against the actual geometry, not by the calculator.",
+ "densityGramsPerCm3": 7.9,
+ "ratePerCm3": 18,
+ "rateEstimate": true,
+ "setupFee": 45,
+ "minWallMm": 1,
+ "minHeightMm": 10,
+ "maxHeightMm": 120,
+ "maxBoundingBoxMm": { "x": 120, "y": 120, "z": 120 },
+ "leadTimeDays": 15,
+ "quoteOnRequest": true,
+ "hollow": { "supported": false },
+ "colorCapable": false,
+ "swatch": { "base": "#9aa0a6", "sheen": "metal" },
+ "finishes": [{ "id": "bead-blast", "name": "Bead blasted", "fee": 0, "default": true }]
+ }
+ ],
+ "sizePresets": [
+ { "id": "desk", "name": "Desk", "heightMm": 80, "blurb": "Sits beside a keyboard." },
+ { "id": "shelf", "name": "Shelf", "heightMm": 140, "blurb": "Reads across a room." },
+ { "id": "keychain", "name": "Keychain", "heightMm": 35, "blurb": "Pocket size." },
+ { "id": "statement", "name": "Statement", "heightMm": 200, "blurb": "The centrepiece." }
+ ],
+ "scaleReferences": [
+ { "id": "coin", "name": "A coin", "heightMm": 24 },
+ { "id": "mug", "name": "Coffee mug", "heightMm": 95 },
+ { "id": "hand", "name": "A hand", "heightMm": 180 },
+ { "id": "person", "name": "A person", "heightMm": 1750 }
+ ],
+ "shipping": {
+ "volumetricDivisor": 5000,
+ "_volumetricNote": "Air-freight convention: chargeable kg is the greater of real mass and (length x width x height in cm) / 5000. A hollow resin figure ships on its box, not its grams.",
+ "packagingMm": 25,
+ "minChargeableKg": 0.25,
+ "zones": [
+ {
+ "id": "cn",
+ "name": "Mainland China",
+ "countries": ["CN"],
+ "baseFee": 4,
+ "perKg": 3,
+ "transitDays": 3
+ },
+ {
+ "id": "us",
+ "name": "United States and Canada",
+ "countries": ["US", "CA"],
+ "baseFee": 9,
+ "perKg": 11,
+ "transitDays": 7
+ },
+ {
+ "id": "eu",
+ "name": "Europe and the UK",
+ "countries": [
+ "GB", "IE", "DE", "FR", "ES", "IT", "NL", "BE", "LU", "AT", "CH", "PT", "DK",
+ "SE", "NO", "FI", "IS", "PL", "CZ", "SK", "HU", "SI", "HR", "RO", "BG", "GR",
+ "EE", "LV", "LT", "MT", "CY"
+ ],
+ "baseFee": 11,
+ "perKg": 13,
+ "transitDays": 9
+ },
+ {
+ "id": "row",
+ "name": "Rest of world",
+ "countries": [],
+ "default": true,
+ "baseFee": 14,
+ "perKg": 17,
+ "transitDays": 14
+ }
+ ]
+ }
+}
diff --git a/scripts/gcp/seed-motion.mjs b/scripts/gcp/seed-motion.mjs
new file mode 100644
index 000000000..3e8ca765b
--- /dev/null
+++ b/scripts/gcp/seed-motion.mjs
@@ -0,0 +1,408 @@
+#!/usr/bin/env node
+// Bulk text-to-motion seeding for the animation library (work order GCP-05, B).
+//
+// Generates clips from data/motion-prompts.json on our own Cloud Run GPU lane,
+// gates every one of them (api/_lib/motion-seed.js), publishes the keepers to
+// the R2 clip library, and lists them in the marketplace under the platform
+// creator with a rotating free subset.
+//
+// The run is resumable: every prompt's outcome is written to a checkpoint file
+// as it lands, and a re-run skips anything already terminal. Killing the process
+// costs at most the clips currently in flight.
+//
+// # measure quality without publishing anything (no credentials needed)
+// node scripts/gcp/seed-motion.mjs --count 20 --dry-run
+//
+// # real run: needs R2 + DATABASE_URL, so it runs where those live
+// node scripts/gcp/seed-motion.mjs --count 200 --concurrency 6
+//
+// Safety: the lane is asserted per job. /api/forge-motion returns a base64url
+// envelope naming the worker it dispatched to, and a job that did not land on
+// our own self-hosted Cloud Run text2motion service aborts the whole run rather
+// than quietly billing a paid third party for a few hundred clips.
+
+import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
+import { dirname, resolve } from 'node:path';
+import process from 'node:process';
+import {
+ motionPrompts,
+ motionPromptLibrary,
+ gateMotionClip,
+ toLibraryClip,
+ manifestEntryFor,
+ mergeManifest,
+ libraryClipName,
+ freeClipNames,
+ rotationEpoch,
+ FREE_ROTATION,
+ LIBRARY_MANIFEST_KEY,
+ GENERATED_CLIP_DIR,
+} from '../../api/_lib/motion-seed.js';
+
+const REPO = resolve(dirname(new URL(import.meta.url).pathname), '../..');
+
+// ── CLI ─────────────────────────────────────────────────────────────────────
+
+function parseArgs(argv) {
+ const out = {
+ count: 25,
+ concurrency: 4,
+ categories: null,
+ dryRun: false,
+ origin: process.env.SEED_MOTION_ORIGIN || 'https://three.ws',
+ checkpoint: resolve(REPO, '.seed-motion-checkpoint.json'),
+ price: 0.75,
+ currency: 'USDC',
+ freeSize: FREE_ROTATION.SIZE,
+ pollTimeoutMs: 300_000,
+ retry: 1,
+ };
+ for (let i = 2; i < argv.length; i += 1) {
+ const arg = argv[i];
+ const next = () => argv[++i];
+ switch (arg) {
+ case '--count': out.count = Math.max(1, Number(next()) || out.count); break;
+ case '--concurrency': out.concurrency = Math.min(12, Math.max(1, Number(next()) || out.concurrency)); break;
+ case '--categories': out.categories = String(next() || '').split(',').map((s) => s.trim()).filter(Boolean); break;
+ case '--dry-run': out.dryRun = true; break;
+ case '--origin': out.origin = String(next() || out.origin).replace(/\/$/, ''); break;
+ case '--checkpoint': out.checkpoint = resolve(String(next())); break;
+ case '--price': out.price = Math.max(0, Number(next()) || 0); break;
+ case '--free-size': out.freeSize = Math.max(0, Number(next()) || 0); break;
+ case '--retry': out.retry = Math.max(0, Math.min(3, Number(next()) || 0)); break;
+ case '--help':
+ console.log('Usage: seed-motion.mjs [--count N] [--concurrency N] [--categories a,b] [--dry-run] [--price N] [--free-size N] [--checkpoint PATH]');
+ process.exit(0);
+ break;
+ default:
+ if (arg.startsWith('--')) {
+ console.error(`unknown flag: ${arg}`);
+ process.exit(2);
+ }
+ }
+ }
+ return out;
+}
+
+// ── Checkpoint ──────────────────────────────────────────────────────────────
+
+function loadCheckpoint(path) {
+ if (!existsSync(path)) return { version: 1, started_at: new Date().toISOString(), results: {} };
+ try {
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
+ if (parsed && typeof parsed.results === 'object') return parsed;
+ } catch (err) {
+ console.error(`[checkpoint] unreadable (${err.message}), starting a fresh one`);
+ }
+ return { version: 1, started_at: new Date().toISOString(), results: {} };
+}
+
+function saveCheckpoint(path, state) {
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, `${JSON.stringify(state, null, '\t')}\n`);
+}
+
+const TERMINAL = new Set(['published', 'accepted', 'rejected', 'failed']);
+
+// ── Lane assertion ──────────────────────────────────────────────────────────
+
+// The provider packs its job id as base64url JSON: { mode, taskId, baseUrl, ... }
+// (packJobId in api/_providers/gcp.js). Reading the baseUrl back out is how a
+// bulk run proves it is spending credits on our own fleet and not on a hosted
+// lane that happens to be configured as a fallback.
+export function decodeJobEnvelope(jobId) {
+ try {
+ const json = Buffer.from(String(jobId), 'base64url').toString('utf8');
+ const parsed = JSON.parse(json);
+ return parsed && typeof parsed === 'object' ? parsed : null;
+ } catch {
+ return null;
+ }
+}
+
+export function assertSelfHostedLane(jobId) {
+ const env = decodeJobEnvelope(jobId);
+ if (!env) throw new Error('lane assertion failed: job id is not a provider envelope');
+ if (env.mode !== 'text2motion') throw new Error(`lane assertion failed: mode ${env.mode}`);
+ let host;
+ try {
+ host = new URL(env.baseUrl).host;
+ } catch {
+ throw new Error(`lane assertion failed: unusable baseUrl ${env.baseUrl}`);
+ }
+ // Our own Cloud Run services only. Anything else is a paid third party and a
+ // bulk run must never reach one.
+ if (!/\.run\.app$/.test(host)) {
+ throw new Error(`lane assertion failed: ${host} is not a self-hosted Cloud Run lane`);
+ }
+ if (!/^model-text2motion/.test(host)) {
+ throw new Error(`lane assertion failed: unexpected worker ${host}`);
+ }
+ return { host, taskId: env.taskId };
+}
+
+// ── Generation ──────────────────────────────────────────────────────────────
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+async function generateOne(prompt, opts) {
+ const defaults = motionPromptLibrary().defaults ?? {};
+ const duration = Number(prompt.duration_seconds) || Number(defaults.duration_seconds) || 4;
+ const fps = Number(defaults.fps) || 30;
+
+ const started = await fetch(`${opts.origin}/api/forge-motion`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ prompt: prompt.prompt, duration_seconds: duration, fps }),
+ signal: AbortSignal.timeout(60_000),
+ });
+ if (started.status === 503) throw new Error('text2motion lane is unconfigured (GCP_TEXT2MOTION_URL)');
+ if (!started.ok) throw new Error(`submit failed: HTTP ${started.status} ${(await started.text()).slice(0, 160)}`);
+ const job = await started.json();
+ const lane = assertSelfHostedLane(job.job_id);
+
+ const deadline = Date.now() + opts.pollTimeoutMs;
+ let delay = 4_000;
+ while (Date.now() < deadline) {
+ await sleep(delay);
+ delay = Math.min(delay * 1.3, 12_000);
+ const res = await fetch(`${opts.origin}/api/forge-motion?job=${encodeURIComponent(job.job_id)}`, {
+ signal: AbortSignal.timeout(30_000),
+ });
+ if (!res.ok) continue;
+ const state = await res.json();
+ if (state.status === 'done' || state.status === 'succeeded') {
+ if (!state.clip_url) throw new Error('worker reported done with no clip');
+ const clipRes = await fetch(state.clip_url, { signal: AbortSignal.timeout(60_000) });
+ if (!clipRes.ok) throw new Error(`clip fetch failed: HTTP ${clipRes.status}`);
+ return { clip: await clipRes.json(), lane, duration, fps, clipUrl: state.clip_url };
+ }
+ if (state.status === 'failed' || state.status === 'error') {
+ throw new Error(`worker failed: ${state.error || 'unknown'}`);
+ }
+ }
+ throw new Error('timed out waiting for the worker');
+}
+
+// ── Publishing ──────────────────────────────────────────────────────────────
+
+async function publishAccepted(accepted, opts) {
+ const { putObject, getObjectBuffer, publicUrl, objectStorageConfigured } = await import('../../api/_lib/r2.js');
+ if (!objectStorageConfigured()) {
+ throw new Error('object storage is not configured: set the R2 credentials or pass --dry-run');
+ }
+
+ const entries = [];
+ for (const item of accepted) {
+ const body = Buffer.from(JSON.stringify(item.libraryClip));
+ const key = `${GENERATED_CLIP_DIR}${item.name}.json`;
+ await putObject({ key, body, contentType: 'application/json', metadata: { prompt_id: item.prompt.id } });
+ entries.push(
+ manifestEntryFor(item.libraryClip, {
+ label: item.prompt.label,
+ icon: item.prompt.icon,
+ loop: item.prompt.loop,
+ bytes: body.byteLength,
+ url: publicUrl(key),
+ thumb: null,
+ }),
+ );
+ item.storageKey = key;
+ item.bytes = body.byteLength;
+ }
+
+ let existing = [];
+ try {
+ const buf = await getObjectBuffer(LIBRARY_MANIFEST_KEY);
+ const parsed = JSON.parse(buf.toString('utf8'));
+ existing = Array.isArray(parsed) ? parsed : parsed.clips ?? [];
+ } catch (err) {
+ if (err?.name !== 'NoSuchKey' && err?.$metadata?.httpStatusCode !== 404) throw err;
+ }
+ const merged = mergeManifest(existing, entries);
+ await putObject({
+ key: LIBRARY_MANIFEST_KEY,
+ body: Buffer.from(JSON.stringify({ generated_at: new Date().toISOString(), clips: merged })),
+ contentType: 'application/json',
+ });
+ return { manifestTotal: merged.length, published: entries.length };
+}
+
+async function listInMarketplace(accepted, opts) {
+ const { sql } = await import('../../api/_lib/db.js');
+ const owner = (await sql`select id from users where username = 'three' limit 1`)[0];
+ if (!owner) throw new Error('platform creator "three" not found; create it before listing');
+
+ // The free subset is decided over the whole generated collection, not just
+ // this batch, so a later batch cannot hand out a second set of free clips.
+ const allNames = (
+ await sql`select slug from animation_clips where format = 'three.ws.animation.v1' and slug like 'gen-%' and deleted_at is null`
+ ).map((r) => r.slug);
+ const names = [...new Set([...allNames, ...accepted.map((a) => a.name)])];
+ const free = new Set(freeClipNames(names, { size: opts.freeSize }));
+
+ let listed = 0;
+ for (const item of accepted) {
+ const isFree = free.has(item.name);
+ const clip = item.libraryClip;
+ await sql`
+ insert into animation_clips (
+ owner_id, slug, name, description, kind, format, duration_ms, frame_count, fps,
+ loop, storage_key, artifact_key, artifact_bytes, artifact_mime, tags, visibility,
+ price_amount, price_currency, listed
+ ) values (
+ ${owner.id}, ${item.name}, ${item.prompt.label},
+ ${item.prompt.prompt}, 'animation', 'three.ws.animation.v1',
+ ${Math.round(clip.duration * 1000)}, ${item.gate.metrics.frames || 0}, ${item.fps},
+ ${Boolean(item.prompt.loop)}, ${item.storageKey}, ${item.storageKey}, ${item.bytes},
+ 'application/json', ${item.prompt.tags ?? []}, 'public',
+ ${isFree ? 0 : opts.price}, ${opts.currency}, true
+ )
+ on conflict (slug) do update set
+ name = excluded.name,
+ description = excluded.description,
+ duration_ms = excluded.duration_ms,
+ frame_count = excluded.frame_count,
+ storage_key = excluded.storage_key,
+ artifact_key = excluded.artifact_key,
+ artifact_bytes = excluded.artifact_bytes,
+ price_amount = excluded.price_amount,
+ listed = true,
+ updated_at = now()
+ `;
+ listed += 1;
+ }
+ return { listed, freeCount: [...free].length, epoch: rotationEpoch() };
+}
+
+// ── Main ────────────────────────────────────────────────────────────────────
+
+async function main() {
+ const opts = parseArgs(process.argv);
+ const state = loadCheckpoint(opts.checkpoint);
+
+ let pool = motionPrompts();
+ if (opts.categories) pool = pool.filter((p) => opts.categories.includes(p.category));
+ const todo = pool.filter((p) => !TERMINAL.has(state.results[p.id]?.status)).slice(0, opts.count);
+
+ if (todo.length === 0) {
+ console.log('nothing to do: every selected prompt is already terminal in the checkpoint');
+ return;
+ }
+
+ console.log(
+ `seeding ${todo.length} clips via ${opts.origin} (concurrency ${opts.concurrency}, ${opts.dryRun ? 'DRY RUN, nothing published' : 'publishing'})`,
+ );
+
+ const accepted = [];
+ const rejected = [];
+ const failed = [];
+ let aborted = null;
+ let cursor = 0;
+
+ const worker = async () => {
+ while (cursor < todo.length && !aborted) {
+ const prompt = todo[cursor++];
+ let lastErr = null;
+ for (let attempt = 0; attempt <= opts.retry && !aborted; attempt += 1) {
+ try {
+ const out = await generateOne(prompt, opts);
+ const gate = gateMotionClip(out.clip, { expectedDuration: out.duration, loop: prompt.loop });
+ const name = libraryClipName(prompt.id, out.lane.taskId);
+ const record = {
+ status: gate.ok ? 'accepted' : 'rejected',
+ name,
+ task_id: out.lane.taskId,
+ lane: out.lane.host,
+ reasons: gate.reasons,
+ metrics: gate.metrics,
+ at: new Date().toISOString(),
+ };
+ state.results[prompt.id] = record;
+ saveCheckpoint(opts.checkpoint, state);
+ if (gate.ok) {
+ accepted.push({
+ prompt,
+ name,
+ fps: out.fps,
+ gate,
+ libraryClip: toLibraryClip(out.clip, {
+ name,
+ promptId: prompt.id,
+ prompt: prompt.prompt,
+ category: prompt.category,
+ loop: prompt.loop,
+ taskId: out.lane.taskId,
+ }),
+ });
+ console.log(` accept ${prompt.id}`);
+ } else {
+ rejected.push({ prompt, reasons: gate.reasons, metrics: gate.metrics });
+ console.log(` reject ${prompt.id} ${gate.reasons.join(',')}`);
+ }
+ lastErr = null;
+ break;
+ } catch (err) {
+ lastErr = err;
+ if (/lane assertion failed/.test(err.message)) {
+ aborted = err;
+ break;
+ }
+ }
+ }
+ if (lastErr && !aborted) {
+ failed.push({ prompt, error: lastErr.message });
+ state.results[prompt.id] = { status: 'failed', error: lastErr.message, at: new Date().toISOString() };
+ saveCheckpoint(opts.checkpoint, state);
+ console.log(` fail ${prompt.id} ${lastErr.message}`);
+ }
+ }
+ };
+
+ await Promise.all(Array.from({ length: Math.min(opts.concurrency, todo.length) }, worker));
+
+ if (aborted) {
+ console.error(`\nABORTED: ${aborted.message}`);
+ console.error('No bulk generation may run on a lane that is not our own. Nothing was published.');
+ process.exitCode = 3;
+ return;
+ }
+
+ const attempted = accepted.length + rejected.length;
+ const rate = attempted ? (100 * accepted.length) / attempted : 0;
+ console.log(
+ `\ngenerated ${attempted} (${failed.length} infrastructure failures), accepted ${accepted.length}, accept rate ${rate.toFixed(1)}%`,
+ );
+ const reasonCounts = {};
+ for (const r of rejected) for (const reason of r.reasons) {
+ const key = reason.split(':')[0];
+ reasonCounts[key] = (reasonCounts[key] ?? 0) + 1;
+ }
+ if (Object.keys(reasonCounts).length) console.log('reject reasons:', reasonCounts);
+
+ if (opts.dryRun) {
+ console.log('\ndry run: no clips uploaded, no marketplace rows written');
+ return;
+ }
+ if (accepted.length === 0) {
+ console.log('\nnothing accepted, so nothing to publish');
+ return;
+ }
+
+ const pub = await publishAccepted(accepted, opts);
+ console.log(`published ${pub.published} clips, manifest now holds ${pub.manifestTotal}`);
+ const listing = await listInMarketplace(accepted, opts);
+ console.log(`listed ${listing.listed} in the marketplace, ${listing.freeCount} free this epoch (#${listing.epoch})`);
+ for (const item of accepted) {
+ state.results[item.prompt.id] = { ...state.results[item.prompt.id], status: 'published' };
+ }
+ saveCheckpoint(opts.checkpoint, state);
+}
+
+// Only run when invoked directly, so the lane assertion stays unit-testable.
+if (process.argv[1] && import.meta.url === `file://${process.argv[1]}`) {
+ main().catch((err) => {
+ console.error(err);
+ process.exit(1);
+ });
+}