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): document the seeding run and cover the clip gate with tests

nirholas470b5df55431
diff --git a/docs/animation-seeding.md b/docs/animation-seeding.md
new file mode 100644
index 000000000..4657c570b
--- /dev/null
+++ b/docs/animation-seeding.md
@@ -0,0 +1,127 @@
+# Generated animation seeding
+
+three.ws generates its own animation clips. A prompt from `data/motion-prompts.json`
+goes to our self-hosted text-to-motion GPU worker, the result is measured against a
+quality gate, and the keepers are published into the same clip library the curated
+Mixamo import already serves.
+
+This document covers what the gate measures and why, because the "why" is the part
+that is easy to get catastrophically wrong.
+
+## The pieces
+
+| Piece | What it does |
+|---|---|
+| `data/motion-prompts.json` | The prompt library: 137 prompts across 10 categories. Data, never a hardcoded list. |
+| `workers/model-text2motion/` | The GPU worker. Samples a motion-diffusion model and returns a three.js `AnimationClip` JSON. |
+| `api/forge-motion.js` | The public route: `POST` a prompt, poll for a clip. Rate limited per IP. |
+| `api/_lib/motion-seed.js` | The prompt loader, the quality gate, the publishing shape, the free-subset rotation. |
+| `scripts/gcp/seed-motion.mjs` | The resumable bulk runner. |
+| `api/animations/library.js` | Serves the clip manifest that generated clips are merged into. |
+
+Generated clips are named `gen-<prompt id>-<hash>`, so they are distinguishable from
+the `mx-` Mixamo import everywhere: in the manifest, the gallery, and any report.
+
+## Format: nothing to convert
+
+The worker already emits clips on the canonical skeleton, and a generated clip's
+track names are a strict **subset** of the library's: the 23 body bones, with no
+finger tracks and no foreign bone names. An unanimated finger holds bind pose, which
+is correct rather than a defect. So publishing is a rename plus a `userData`
+provenance record, not a format conversion.
+
+## The gate
+
+Run `gateMotionClip(clip, { expectedDuration })`. It returns
+`{ ok, reasons[], metrics }`, and every threshold in `MOTION_GATE` was derived by
+measuring a 60-clip sample of the authored Mixamo library, not chosen by taste.
+
+### Judge positions, not rotations
+
+This is the important part.
+
+The sampler routinely emits a **180 degree twist about a bone's own axis which the
+child bone immediately cancels**. Measured on the local quaternion tracks that looks
+like a catastrophic pop: in one "idle breathing" clip the left shoulder and left
+forearm each flipped a half turn on 39 of 119 frames. Measured where it matters, the
+hand never moved more than 1.1 cm in a single frame. The flip is a property of the
+representation, not of the animation, and it is invisible on a rendered mesh.
+
+A first version of this gate tested adjacent local quaternions and **rejected 100% of
+generated clips** while the motion was in fact fine. So the gate runs forward
+kinematics over `src/animation-canonical-rest.js` and judges world-space joint
+positions, which is what a viewer actually sees:
+
+- **`world_discontinuity`**: the largest single-frame step of any witness joint
+ (hands, feet, toes, head, hips), divided by that joint's own 95th-percentile step.
+ Dividing by the clip's own scale makes the test speed-independent, so a sprint and
+ an idle are held to the same standard. Authored clips score a median of 1.69 and a
+ worst case of 5.79 (a heavy push), so the ceiling is **6.5**.
+- **`frozen_clip`**: the longest path any witness joint walks, in metres. The
+ library's static *pose* assets score 0.00 and its quietest real animation 0.11, so
+ the floor is **0.35**.
+- **`foot_sliding`**: real foot contact. A foot counts as planted only when it is
+ within 6 cm of the clip's own floor level **and** the hips are at least 0.55 m above
+ that floor. Without the upright test, floor work (a fall, a crawl, a breakdance
+ flair) reads as skating, because the "lower" foot is merely the one that happens to
+ be less high. Slide is then scored against the stride the clip actually covers.
+- Plus the cheap structural checks: NaN or infinite keyframes, non-monotonic times,
+ quaternions off the unit sphere, missing body bones, bones the canonical skeleton
+ does not have, frame count, and a duration that does not match what was ordered.
+
+`maxFrameJumpRad` and `totalMotionRad` are still **reported** in `metrics`, because
+they are useful for spotting worker regressions. They are deliberately **not gated**.
+
+### Calibration
+
+Against 60 authored library clips the gate accepts 87%. The rejects are all clips
+that are legitimately out of spec for *generated* content rather than gate errors:
+sliced sub-clips a few frames long, static pose assets with zero motion, and one hit
+reaction that genuinely slides. Generated clips are held to a duration we ordered and
+motion we asked for, so those rules are correct where they are applied.
+
+Re-run the calibration whenever a threshold changes, and inspect rejected clips before
+touching a number. A broken pipeline looks exactly like a strict gate.
+
+## Running a batch
+
+```bash
+# Measure quality without publishing. Needs no credentials.
+node scripts/gcp/seed-motion.mjs --count 20 --dry-run
+
+# A real run, where R2 and DATABASE_URL live.
+node scripts/gcp/seed-motion.mjs --count 200 --concurrency 6
+```
+
+Useful flags: `--categories locomotion,dance` to seed one slice, `--checkpoint PATH`
+to keep runs separate, `--price` and `--free-size` to set the listing terms.
+
+**Use the in-process transport for anything bulk.** `/api/forge-motion` is a public
+endpoint rate limited per IP: a 40-clip run through it generates two clips and then
+takes a 429 with a 49 minute `retry_after`. With `GCP_TEXT2MOTION_URL` set the runner
+calls the provider directly and no limiter applies. `--origin` forces the HTTP path,
+which is worth doing on a handful of clips to prove the deployed route works.
+
+The run is **resumable**: every prompt's outcome is written to the checkpoint as it
+lands, and a re-run skips anything already terminal, so killing the process costs at
+most the clips in flight.
+
+The run is **lane-asserted**. `/api/forge-motion` and the provider both return a job
+id that names the worker the job was dispatched to, and the runner decodes it and
+aborts the entire batch unless the host is our own `model-text2motion` Cloud Run
+service. Bulk generation must never fall through to a paid third party.
+
+## Pricing and the rotating free subset
+
+Generated clips are listed in the marketplace under the platform creator (`three`)
+and are paid by default. A fixed-size subset is free for one epoch at a time.
+
+The subset is chosen by hashing each clip name together with the epoch number
+(`freeClipNames`). That makes it deterministic, so every server instance agrees
+without coordination or a database write; stable for a whole epoch, so a visitor
+never watches a price flicker on reload; and evenly spread, because each clip's hash
+ordering differs per epoch, so the free slot rotates instead of favouring the same
+names. The epoch is one week and the subset is 12 clips (`FREE_ROTATION`).
+
+The subset is computed over the **whole** generated collection rather than the current
+batch, so a later batch cannot hand out a second set of free clips.
diff --git a/scripts/gcp/seed-motion.mjs b/scripts/gcp/seed-motion.mjs
index 3e8ca765b..a05f8d89b 100644
--- a/scripts/gcp/seed-motion.mjs
+++ b/scripts/gcp/seed-motion.mjs
@@ -16,6 +16,13 @@
// # real run: needs R2 + DATABASE_URL, so it runs where those live
// node scripts/gcp/seed-motion.mjs --count 200 --concurrency 6
//
+// Transport: with GCP_TEXT2MOTION_URL set the runner calls the provider in
+// process, which is the only way a bulk run works. /api/forge-motion is rate
+// limited per IP (it is a public endpoint), so driving a few hundred clips
+// through it earns a 429 with a 49 minute retry-after after roughly the first
+// two. Pass --origin to force the HTTP path anyway, which is useful for proving
+// the deployed route end to end on a handful of clips.
+//
// 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
@@ -51,6 +58,8 @@ function parseArgs(argv) {
dryRun: false,
origin: process.env.SEED_MOTION_ORIGIN || 'https://three.ws',
checkpoint: resolve(REPO, '.seed-motion-checkpoint.json'),
+ // Default to the provider directly when this process can reach it.
+ transport: process.env.GCP_TEXT2MOTION_URL ? 'in-process' : 'http',
price: 0.75,
currency: 'USDC',
freeSize: FREE_ROTATION.SIZE,
@@ -65,13 +74,17 @@ function parseArgs(argv) {
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 '--origin':
+ out.origin = String(next() || out.origin).replace(/\/$/, '');
+ out.transport = 'http';
+ break;
+ case '--in-process': out.transport = 'in-process'; 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]');
+ console.log('Usage: seed-motion.mjs [--count N] [--concurrency N] [--categories a,b] [--dry-run] [--in-process] [--origin URL] [--price N] [--free-size N] [--checkpoint PATH]');
process.exit(0);
break;
default:
@@ -145,17 +158,77 @@ export function assertSelfHostedLane(jobId) {
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+let providerPromise = null;
+function motionProvider() {
+ if (!providerPromise) {
+ providerPromise = import('../../api/_providers/gcp.js').then(({ createRegenProvider }) => {
+ const provider = createRegenProvider();
+ if (!provider.supportsMode('text2motion')) {
+ throw new Error('the text2motion lane is not configured: set GCP_TEXT2MOTION_URL and GCP_RECONSTRUCTION_KEY');
+ }
+ return provider;
+ });
+ }
+ return providerPromise;
+}
+
+/** Submit + poll straight against the provider, with no public endpoint in between. */
+async function generateInProcess(prompt, opts, duration, fps) {
+ const provider = await motionProvider();
+ const job = await provider.submit({
+ mode: 'text2motion',
+ sourceUrl: null,
+ params: { prompt: prompt.prompt, duration_seconds: duration, fps },
+ });
+ const lane = assertSelfHostedLane(job.extJobId);
+
+ 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 state = await provider.poll(job.extJobId);
+ if (state.status === 'done' || state.status === 'succeeded') {
+ // The provider surfaces a finished motion job as resultClipUrl (a
+ // three.js AnimationClip JSON), alongside the frame count and fps the
+ // worker actually produced.
+ const clipUrl = state.resultClipUrl;
+ if (!clipUrl) throw new Error('worker reported done with no clip');
+ const res = await fetch(clipUrl, { signal: AbortSignal.timeout(60_000) });
+ if (!res.ok) throw new Error(`clip fetch failed: HTTP ${res.status}`);
+ return {
+ clip: await res.json(),
+ lane,
+ duration,
+ fps: typeof state.fps === 'number' ? state.fps : fps,
+ clipUrl,
+ };
+ }
+ if (state.status === 'failed' || state.status === 'error') {
+ throw new Error(`worker failed: ${state.error || 'unknown'}`);
+ }
+ }
+ throw new Error('timed out waiting for the worker');
+}
+
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;
+ if (opts.transport === 'in-process') return generateInProcess(prompt, opts, duration, fps);
+
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 === 429) {
+ throw new Error(
+ 'rate limited by /api/forge-motion: run with --in-process (GCP_TEXT2MOTION_URL) for a bulk batch',
+ );
+ }
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();
@@ -290,8 +363,9 @@ async function main() {
return;
}
+ const via = opts.transport === 'in-process' ? 'the provider in process' : opts.origin;
console.log(
- `seeding ${todo.length} clips via ${opts.origin} (concurrency ${opts.concurrency}, ${opts.dryRun ? 'DRY RUN, nothing published' : 'publishing'})`,
+ `seeding ${todo.length} clips via ${via} (concurrency ${opts.concurrency}, ${opts.dryRun ? 'DRY RUN, nothing published' : 'publishing'})`,
);
const accepted = [];
diff --git a/tests/motion-seed.test.js b/tests/motion-seed.test.js
new file mode 100644
index 000000000..80126c6f7
--- /dev/null
+++ b/tests/motion-seed.test.js
@@ -0,0 +1,342 @@
+/**
+ * Motion seeding: gate, publishing shape, free rotation, lane assertion.
+ *
+ * Clips are built in-memory from the canonical rest skeleton, so the suite is
+ * fast, deterministic and needs no fixtures on disk. The synthetic clips are
+ * built the way the text2motion worker builds real ones (a quaternion track per
+ * canonical body bone plus a Hips.position track), which is what lets these
+ * tests assert the gate's real behaviour rather than a simplified stand-in.
+ *
+ * The thresholds these tests pin were derived from a 60-clip sample of the
+ * authored Mixamo library: see docs/animation-seeding.md.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ gateMotionClip,
+ MOTION_GATE,
+ worldMotionMetrics,
+ footContactMetrics,
+ toLibraryClip,
+ manifestEntryFor,
+ mergeManifest,
+ libraryClipName,
+ isGeneratedClipName,
+ freeClipNames,
+ rotationEpoch,
+ motionPrompts,
+ motionPromptById,
+} from '../api/_lib/motion-seed.js';
+import { assertSelfHostedLane, decodeJobEnvelope } from '../scripts/gcp/seed-motion.mjs';
+
+const BODY_BONES = [
+ 'Hips', 'Spine', 'Spine1', 'Spine2', 'Neck', 'Head',
+ 'LeftShoulder', 'LeftArm', 'LeftForeArm', 'LeftHand',
+ 'RightShoulder', 'RightArm', 'RightForeArm', 'RightHand',
+ 'LeftUpLeg', 'LeftLeg', 'LeftFoot', 'LeftToeBase',
+ 'RightUpLeg', 'RightLeg', 'RightFoot', 'RightToeBase',
+];
+
+/** A rotation of `angle` radians about X, as [x,y,z,w]. */
+function quatX(angle) {
+ return [Math.sin(angle / 2), 0, 0, Math.cos(angle / 2)];
+}
+
+/**
+ * Build a clip whose bones swing smoothly, so it reads as real motion.
+ * `swing` scales how far the limbs travel; `hipsTravel` moves the root forward.
+ */
+function buildClip({
+ frames = 120,
+ fps = 30,
+ swing = 0.35,
+ hipsTravel = 0,
+ bones = BODY_BONES,
+ mutate = null,
+} = {}) {
+ const times = Array.from({ length: frames }, (_, i) => i / fps);
+ const tracks = [];
+ for (const bone of bones) {
+ const values = [];
+ for (let i = 0; i < frames; i += 1) {
+ // Each bone gets its own phase so the whole body is not one rigid unit.
+ const phase = (bone.length % 7) * 0.4;
+ values.push(...quatX(swing * Math.sin((i / frames) * Math.PI * 4 + phase)));
+ }
+ tracks.push({ type: 'quaternion', name: `${bone}.quaternion`, times: [...times], values });
+ }
+ const hips = [];
+ for (let i = 0; i < frames; i += 1) {
+ hips.push(0, 0.984 + 0.02 * Math.sin((i / frames) * Math.PI * 4), (hipsTravel * i) / frames);
+ }
+ tracks.push({ type: 'vector', name: 'Hips.position', times: [...times], values: hips });
+
+ const clip = {
+ name: 'synthetic',
+ duration: (frames - 1) / fps,
+ tracks,
+ uuid: '11111111-2222-3333-4444-555555555555',
+ blendMode: 0,
+ };
+ if (mutate) mutate(clip);
+ return clip;
+}
+
+describe('motion prompt library', () => {
+ it('loads prompts as data, each with the fields the seeder needs', () => {
+ const prompts = motionPrompts();
+ expect(prompts.length).toBeGreaterThan(50);
+ for (const p of prompts) {
+ expect(typeof p.id).toBe('string');
+ expect(p.prompt.length).toBeGreaterThan(10);
+ expect(typeof p.category).toBe('string');
+ }
+ });
+
+ it('ids are unique, so a checkpoint can key on them', () => {
+ const ids = motionPrompts().map((p) => p.id);
+ expect(new Set(ids).size).toBe(ids.length);
+ });
+
+ it('looks a prompt up by id', () => {
+ const first = motionPrompts()[0];
+ expect(motionPromptById(first.id)).toEqual(first);
+ expect(motionPromptById('no-such-prompt')).toBeNull();
+ });
+});
+
+describe('gateMotionClip', () => {
+ it('accepts a smooth, lively clip', () => {
+ const verdict = gateMotionClip(buildClip({ hipsTravel: 1.2 }), { expectedDuration: 4 });
+ expect(verdict.reasons).toEqual([]);
+ expect(verdict.ok).toBe(true);
+ });
+
+ it('rejects a clip with no tracks', () => {
+ expect(gateMotionClip({ duration: 4, tracks: [] }).reasons).toContain('no_tracks');
+ });
+
+ it('rejects NaN keyframes rather than publishing an avatar-breaking clip', () => {
+ const clip = buildClip({
+ mutate: (c) => {
+ c.tracks[0].values[8] = Number.NaN;
+ },
+ });
+ expect(gateMotionClip(clip).reasons).toContain('non_finite_keyframes');
+ });
+
+ it('rejects a clip missing the body chain a retarget needs', () => {
+ const clip = buildClip({ bones: ['Hips', 'Spine', 'Head'] });
+ const verdict = gateMotionClip(clip);
+ expect(verdict.ok).toBe(false);
+ expect(verdict.reasons.some((r) => r.startsWith('missing_bones'))).toBe(true);
+ });
+
+ it('rejects tracks naming bones the canonical skeleton does not have', () => {
+ const clip = buildClip();
+ clip.tracks.push({ type: 'quaternion', name: 'Tail.quaternion', times: [0], values: [0, 0, 0, 1] });
+ expect(gateMotionClip(clip).reasons.some((r) => r.startsWith('foreign_bones'))).toBe(true);
+ });
+
+ it('rejects a frozen clip, measured in world space', () => {
+ const clip = buildClip({ swing: 0 });
+ expect(gateMotionClip(clip).reasons).toContain('frozen_clip');
+ });
+
+ it('rejects a clip the sampler returned at the wrong length', () => {
+ const verdict = gateMotionClip(buildClip({ frames: 120 }), { expectedDuration: 9 });
+ expect(verdict.reasons).toContain('duration_mismatch');
+ });
+
+ it('rejects quaternions that drifted off the unit sphere', () => {
+ const clip = buildClip({
+ mutate: (c) => {
+ for (let i = 0; i < c.tracks[0].values.length; i += 1) c.tracks[0].values[i] *= 1.2;
+ },
+ });
+ expect(gateMotionClip(clip).reasons).toContain('quaternions_not_normalized');
+ });
+
+ it('rejects a real world-space discontinuity', () => {
+ // Teleport the root mid-clip: every joint jumps together, which is exactly
+ // the visible defect the continuity test exists to catch.
+ const clip = buildClip({
+ mutate: (c) => {
+ const hips = c.tracks.find((t) => t.name === 'Hips.position');
+ for (let i = 60; i < hips.values.length / 3; i += 1) hips.values[i * 3] += 3;
+ },
+ });
+ const verdict = gateMotionClip(clip);
+ expect(verdict.ok).toBe(false);
+ expect(verdict.reasons.some((r) => r.startsWith('world_discontinuity'))).toBe(true);
+ });
+
+ it('does NOT reject a 180 degree local twist the child bone cancels', () => {
+ // The sampler emits these constantly. They are invisible on the mesh, so a
+ // gate that rejects them rejects everything: this test pins that lesson.
+ const clip = buildClip({ hipsTravel: 1.2 });
+ const shoulder = clip.tracks.find((t) => t.name === 'LeftShoulder.quaternion');
+ const forearm = clip.tracks.find((t) => t.name === 'LeftForeArm.quaternion');
+ for (const track of [shoulder, forearm]) {
+ for (let i = 40; i < track.values.length / 4; i += 2) {
+ // Rotate a half turn about the bone's own axis on alternating frames.
+ const [x, y, z, w] = track.values.slice(i * 4, i * 4 + 4);
+ const half = quatX(Math.PI);
+ track.values[i * 4] = w * half[0] + x * half[3];
+ track.values[i * 4 + 1] = y * half[3] + z * half[0];
+ track.values[i * 4 + 2] = z * half[3] - y * half[0];
+ track.values[i * 4 + 3] = w * half[3] - x * half[0];
+ }
+ }
+ const verdict = gateMotionClip(clip);
+ expect(verdict.reasons.some((r) => r.startsWith('world_discontinuity'))).toBe(false);
+ });
+
+ it('reports metrics even when it rejects, so a batch can be tuned', () => {
+ const verdict = gateMotionClip(buildClip({ swing: 0 }));
+ expect(verdict.metrics.frames).toBe(120);
+ expect(verdict.metrics.trackCount).toBeGreaterThan(20);
+ expect(typeof verdict.metrics.worldTravel).toBe('number');
+ });
+});
+
+describe('foot contact', () => {
+ it('ignores floor work, where no foot bears weight', () => {
+ // Hips pinned below the upright height: a fall or a breakdance flair. The
+ // feet may travel freely without that counting as skating.
+ const clip = buildClip({ hipsTravel: 2 });
+ const hips = clip.tracks.find((t) => t.name === 'Hips.position');
+ for (let i = 0; i < hips.values.length / 3; i += 1) hips.values[i * 3 + 1] = 0.15;
+ expect(footContactMetrics(clip).plantedFrames).toBe(0);
+ });
+
+ it('derives the floor from the clip rather than assuming y = 0', () => {
+ const metrics = footContactMetrics(buildClip());
+ expect(Number.isFinite(metrics.floorY)).toBe(true);
+ });
+});
+
+describe('worldMotionMetrics', () => {
+ it('is scale free: a fast clip is not punished for being fast', () => {
+ const slow = worldMotionMetrics(buildClip({ swing: 0.15 }));
+ const fast = worldMotionMetrics(buildClip({ swing: 0.6 }));
+ expect(fast.travel).toBeGreaterThan(slow.travel);
+ expect(fast.continuity).toBeLessThan(MOTION_GATE.MAX_WORLD_STEP_RATIO);
+ expect(slow.continuity).toBeLessThan(MOTION_GATE.MAX_WORLD_STEP_RATIO);
+ });
+
+ it('degrades safely on a clip too short to measure', () => {
+ expect(worldMotionMetrics({ tracks: [] }).continuity).toBe(0);
+ });
+});
+
+describe('publishing shape', () => {
+ it('names generated clips apart from the mixamo import', () => {
+ const name = libraryClipName('walk-forward-relaxed', 'task-abc');
+ expect(name.startsWith('gen-')).toBe(true);
+ expect(isGeneratedClipName(name)).toBe(true);
+ expect(isGeneratedClipName('mx-135-degree-left-turn-c9cd')).toBe(false);
+ });
+
+ it('is stable for the same task and distinct across tasks', () => {
+ expect(libraryClipName('a', 't1')).toBe(libraryClipName('a', 't1'));
+ expect(libraryClipName('a', 't1')).not.toBe(libraryClipName('a', 't2'));
+ });
+
+ it('keeps the exact top-level shape the library already serves', () => {
+ const raw = buildClip();
+ const out = toLibraryClip(raw, {
+ name: 'gen-x-1',
+ promptId: 'x',
+ prompt: 'a person waves',
+ category: 'emote',
+ loop: true,
+ taskId: 't1',
+ });
+ expect(Object.keys(out).sort()).toEqual(['blendMode', 'duration', 'name', 'tracks', 'userData', 'uuid']);
+ expect(out.tracks).toBe(raw.tracks);
+ expect(out.userData.source).toBe('text2motion');
+ });
+
+ it('builds a manifest row matching the served entry shape', () => {
+ const clip = toLibraryClip(buildClip(), {
+ name: 'gen-x-1', promptId: 'x', prompt: 'p', category: 'emote', loop: false, taskId: 't',
+ });
+ const entry = manifestEntryFor(clip, { label: 'Wave', icon: '👋', loop: false, bytes: 10, url: 'https://cdn/x.json', thumb: null });
+ expect(Object.keys(entry).sort()).toEqual(['bytes', 'duration', 'icon', 'label', 'loop', 'name', 'thumb', 'url']);
+ });
+});
+
+describe('mergeManifest', () => {
+ it('appends new rows and leaves the existing order untouched', () => {
+ const existing = [{ name: 'mx-a' }, { name: 'mx-b' }];
+ const merged = mergeManifest(existing, [{ name: 'gen-c' }]);
+ expect(merged.map((e) => e.name)).toEqual(['mx-a', 'mx-b', 'gen-c']);
+ });
+
+ it('replaces a row in place on a re-run rather than duplicating it', () => {
+ const merged = mergeManifest([{ name: 'gen-a', bytes: 1 }], [{ name: 'gen-a', bytes: 2 }]);
+ expect(merged).toEqual([{ name: 'gen-a', bytes: 2 }]);
+ });
+
+ it('survives a missing manifest', () => {
+ expect(mergeManifest(null, [{ name: 'gen-a' }])).toEqual([{ name: 'gen-a' }]);
+ });
+});
+
+describe('rotating free subset', () => {
+ const names = Array.from({ length: 60 }, (_, i) => `gen-clip-${i}`);
+
+ it('picks a fixed-size subset', () => {
+ expect(freeClipNames(names, { size: 12 })).toHaveLength(12);
+ });
+
+ it('is stable within an epoch, so a price does not flicker on reload', () => {
+ const now = Date.UTC(2026, 8, 2);
+ expect(freeClipNames(names, { now })).toEqual(freeClipNames(names, { now }));
+ });
+
+ it('rotates between epochs', () => {
+ const a = freeClipNames(names, { now: Date.UTC(2026, 8, 2) });
+ const b = freeClipNames(names, { now: Date.UTC(2026, 9, 2) });
+ expect(a).not.toEqual(b);
+ });
+
+ it('never returns a name that is not in the collection', () => {
+ for (const name of freeClipNames(names, { size: 12 })) expect(names).toContain(name);
+ });
+
+ it('advances the epoch weekly', () => {
+ const t = Date.UTC(2026, 8, 2);
+ expect(rotationEpoch(t + 7 * 24 * 3600 * 1000)).toBe(rotationEpoch(t) + 1);
+ });
+});
+
+describe('lane assertion', () => {
+ const envelope = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url');
+
+ it('accepts our own text2motion Cloud Run worker', () => {
+ const id = envelope({ mode: 'text2motion', taskId: 't1', baseUrl: 'https://model-text2motion-9374185604.us-east4.run.app' });
+ expect(assertSelfHostedLane(id)).toEqual({ host: 'model-text2motion-9374185604.us-east4.run.app', taskId: 't1' });
+ });
+
+ it('refuses a paid third-party lane so bulk spend cannot leave the credits', () => {
+ const id = envelope({ mode: 'text2motion', taskId: 't1', baseUrl: 'https://api.some-vendor.com' });
+ expect(() => assertSelfHostedLane(id)).toThrow(/not a self-hosted Cloud Run lane/);
+ });
+
+ it('refuses another Cloud Run service that is not the motion worker', () => {
+ const id = envelope({ mode: 'text2motion', taskId: 't1', baseUrl: 'https://model-trellis-123.us-central1.run.app' });
+ expect(() => assertSelfHostedLane(id)).toThrow(/unexpected worker/);
+ });
+
+ it('refuses a job that is not a motion job', () => {
+ const id = envelope({ mode: 'text23d', taskId: 't1', baseUrl: 'https://model-text2motion-1.us-east4.run.app' });
+ expect(() => assertSelfHostedLane(id)).toThrow(/mode text23d/);
+ });
+
+ it('refuses an unreadable job id', () => {
+ expect(decodeJobEnvelope('not-base64-json')).toBeNull();
+ expect(() => assertSelfHostedLane('not-base64-json')).toThrow(/not a provider envelope/);
+ });
+});