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(animations): motion signature index measured from every baked clip
nirholas4ac8033b2825
diff --git a/public/animations/registry.json b/public/animations/registry.jsonindex 63b21228c..5e56eba23 100644--- a/public/animations/registry.json+++ b/public/animations/registry.json@@ -14,7 +14,7 @@{ "name": "covereyes", "label": "Cover Eyes", "icon": "🙈", "loop": true, "clip": "public/animations/clips/covereyes.json", "source_fbx": "animation-sources/Defeat.fbx", "agent_slots": [] },{ "name": "facepalm", "label": "Facepalm", "icon": "🤦", "loop": false, "clip": "public/animations/clips/facepalm.json", "source_fbx": "animation-sources/Facepalm.glb", "agent_slots": [] },{ "name": "av-idle-breath", "label": "Idle Breath", "icon": "🧘", "loop": true, "clip": "public/animations/clips/av-idle-breath.json", "source_fbx": "animation-sources/Idle_Breath.glb", "agent_slots": [] },- { "name": "av-waiting", "label": "Waiting", "icon": "🕰️", "loop": true, "clip": "public/animations/clips/av-waiting.json", "source_fbx": "animation-sources/Standard_Waiting.glb", "agent_slots": ["fidget", "patience"] },+ { "name": "av-waiting", "label": "Waiting", "icon": "🕰️", "loop": true, "clip": "public/animations/clips/av-waiting.json", "source_fbx": "animation-sources/Standard_Waiting.glb", "agent_slots": [] },{ "name": "av-superhero-jump", "label": "Superhero Jump", "icon": "🦸", "loop": false, "clip": "public/animations/clips/av-superhero-jump.json", "source_fbx": "animation-sources/Suoerhero_Jump.glb", "agent_slots": [] },{ "name": "av-walk-crouching", "label": "Walk Crouching", "icon": "🚶", "loop": true, "clip": "public/animations/clips/av-walk-crouching.json", "source_fbx": "animation-sources/Standard_Walk_Crouching.glb", "agent_slots": [] },{ "name": "av-arm-flex", "label": "Arm Flex", "icon": "💪", "loop": false, "clip": "public/animations/clips/av-arm-flex.json", "source_fbx": "animation-sources/Arm_Flex.glb", "agent_slots": [] },@@ -25,7 +25,7 @@{ "name": "av-stand-crouch-stand", "label": "Stand-Crouch-Stand", "icon": "🦵", "loop": false, "clip": "public/animations/clips/av-stand-crouch-stand.json", "source_fbx": "animation-sources/Standard_Stand_To_Crouch_To_Stand.glb", "agent_slots": [] },{ "name": "av-smoking", "label": "Smoking", "icon": "🚬", "loop": true, "clip": "public/animations/clips/av-smoking.json", "source_fbx": "animation-sources/Standard_Smoking.glb", "agent_slots": [] },{ "name": "av-gymnastics-aerial", "label": "Gymnastics", "icon": "🤸", "loop": false, "clip": "public/animations/clips/av-gymnastics-aerial.json", "source_fbx": "animation-sources/Gymnastics_Aerial.glb", "agent_slots": [] },- { "name": "av-idle-anim", "label": "Idle (Avaturn)", "icon": "🧍", "loop": true, "clip": "public/animations/clips/av-idle-anim.json", "source_fbx": "animation-sources/idle_anim.glb", "agent_slots": [] },+ { "name": "av-idle-anim", "label": "Idle (Avaturn)", "icon": "🧍", "loop": true, "clip": "public/animations/clips/av-idle-anim.json", "source_fbx": "animation-sources/idle_anim.glb", "agent_slots": ["patience"] },{ "name": "av-back-flip", "label": "Back Flip", "icon": "🤸", "loop": false, "clip": "public/animations/clips/av-back-flip.json", "source_fbx": "animation-sources/back_flip.glb", "agent_slots": [] },{ "name": "av-idle-male", "label": "Male Idle", "icon": "🚹", "loop": true, "clip": "public/animations/clips/av-idle-male.json", "source_fbx": "animation-sources/idle_male_jan25.glb", "agent_slots": [] },{ "name": "av-idle-female", "label": "Female Idle", "icon": "🚺", "loop": true, "clip": "public/animations/clips/av-idle-female.json", "source_fbx": "animation-sources/idle_female_jan25.glb", "agent_slots": [] },@@ -44,7 +44,7 @@{ "name": "av-cheering", "label": "Cheering", "icon": "📣", "loop": false, "clip": "public/animations/clips/av-cheering.json", "source_fbx": "animation-sources/Cheering.glb", "agent_slots": [] },{ "name": "av-joy", "label": "Joy", "icon": "😊", "loop": false, "clip": "public/animations/clips/av-joy.json", "source_fbx": "animation-sources/Expressing_joy.glb", "agent_slots": [] },{ "name": "av-conductor", "label": "Conductor", "icon": "🎼", "loop": true, "clip": "public/animations/clips/av-conductor.json", "source_fbx": "animation-sources/Energic_conductor.glb", "agent_slots": ["conjure"] },- { "name": "av-listening-music", "label": "Listening To Music", "icon": "🎧", "loop": true, "clip": "public/animations/clips/av-listening-music.json", "source_fbx": "animation-sources/Listening To Music.fbx", "agent_slots": [] },+ { "name": "av-listening-music", "label": "Listening To Music", "icon": "🎧", "loop": true, "clip": "public/animations/clips/av-listening-music.json", "source_fbx": "animation-sources/Listening To Music.fbx", "agent_slots": ["fidget"] },{ "name": "av-leaning-wall", "label": "Leaning On Wall", "icon": "🧱", "loop": true, "clip": "public/animations/clips/av-leaning-wall.json", "source_fbx": "animation-sources/Leaning On A Wall.fbx", "agent_slots": [] },{ "name": "av-rap-dance", "label": "Rap Dancing", "icon": "🎤", "loop": true, "clip": "public/animations/clips/av-rap-dance.json", "source_fbx": "animation-sources/RapDancing.fbx", "agent_slots": [] },{ "name": "av-offabean-dance", "label": "Offabean Dance", "icon": "🫘", "loop": true, "clip": "public/animations/clips/av-offabean-dance.json", "source_fbx": "animation-sources/Offabean Dance.fbx", "agent_slots": [], "_note": "Source round-tripped through glTF-Transform, so its hips track is metre-scale (not Mixamo's usual centimetres) and carries a baked ~1.45m armature offset. Built with recenterHips:true; unit handling is automatic." },@@ -260,25 +260,25 @@"agent_slots": {"description": "The fixed slot vocabulary used by the agent avatar system (src/runtime/animation-slots.js). Slots are resolved to clip names from the 'clips' collection at runtime. Agents can override individual slots via meta.edits.animations.","slots": {- "idle": { "default_clip": "idle", "status": "active" },- "wave": { "default_clip": "wave", "status": "active" },- "nod": { "default_clip": "nod", "status": "active" },- "shake": { "default_clip": "xbot-head-shake", "status": "active" },- "think": { "default_clip": "think", "status": "active" },- "celebrate": { "default_clip": "celebrate", "status": "active" },- "concern": { "default_clip": "defeated", "status": "active" },- "bow": { "default_clip": "sitclap", "status": "active (approximation): no bow clip is baked; 'sitclap' reads as gratitude/applause. See known_issues: bow-slot-approximation" },- "point": { "default_clip": "point", "status": "active" },- "shrug": { "default_clip": "shrug", "status": "active" },- "fidget": { "default_clip": "av-waiting", "status": "fixed 2026-07-08, was 'Fidget' (no such clip, silent no-op); see resolved known_issues entry below" },- "dance": { "default_clip": "rumba", "status": "active" },- "inspect": { "default_clip": "lookdown", "status": "active" },- "present": { "default_clip": "av-brag-claps", "status": "active" },- "sign": { "default_clip": "xbot-agree", "status": "active" },- "curiosity": { "default_clip": "av-spy", "status": "active" },- "patience": { "default_clip": "av-waiting", "status": "active" },- "manipulate": { "default_clip": "av-push-block", "status": "active" },- "conjure": { "default_clip": "av-conductor", "status": "active" }+ "idle": { "default_clip": "idle", "status": "active" },+ "wave": { "default_clip": "wave", "status": "active" },+ "nod": { "default_clip": "nod", "status": "active" },+ "shake": { "default_clip": "xbot-head-shake", "status": "active" },+ "think": { "default_clip": "think", "status": "active" },+ "celebrate": { "default_clip": "celebrate", "status": "active" },+ "concern": { "default_clip": "defeated", "status": "active" },+ "bow": { "default_clip": "sitclap", "status": "active (approximation): no bow clip is baked; 'sitclap' reads as gratitude/applause. See known_issues: bow-slot-approximation" },+ "point": { "default_clip": "point", "status": "active" },+ "shrug": { "default_clip": "shrug", "status": "active" },+ "fidget": { "default_clip": "av-listening-music", "status": "active" },+ "dance": { "default_clip": "rumba", "status": "active" },+ "inspect": { "default_clip": "lookdown", "status": "active" },+ "present": { "default_clip": "av-brag-claps", "status": "active" },+ "sign": { "default_clip": "xbot-agree", "status": "active" },+ "curiosity": { "default_clip": "av-spy", "status": "active" },+ "patience": { "default_clip": "av-idle-anim", "status": "active" },+ "manipulate": { "default_clip": "av-push-block", "status": "active" },+ "conjure": { "default_clip": "av-conductor", "status": "active" }}},diff --git a/public/animations/signatures.json b/public/animations/signatures.jsonindex 8755ce7aa..d59bde3c8 100644--- a/public/animations/signatures.json+++ b/public/animations/signatures.json@@ -137,8 +137,8 @@"travel": 0,"path": 3.124,"rise": 0.202,- "tempo": 35,- "beat": 0.273,+ "tempo": 0,+ "beat": 0.247,"seam": 0.002,"seamRoot": 0,"loopClean": true,@@ -311,8 +311,8 @@"travel": 0.006,"path": 1.74,"rise": 0.844,- "tempo": 86,- "beat": 0.421,+ "tempo": 106,+ "beat": 0.411,"seam": 0,"seamRoot": 0.006,"loopClean": true,@@ -369,8 +369,8 @@"travel": 0.901,"path": 10.208,"rise": 0.197,- "tempo": 112,- "beat": 0.34,+ "tempo": 0,+ "beat": 0,"seam": 0.509,"seamRoot": 0.903,"loopClean": false,@@ -456,8 +456,8 @@"travel": 0.811,"path": 8.97,"rise": 0.351,- "tempo": 164,- "beat": 0.593,+ "tempo": 0,+ "beat": 0,"seam": 0.2,"seamRoot": 0.812,"loopClean": false,@@ -514,8 +514,8 @@"travel": 0,"path": 0.066,"rise": 0,- "tempo": 38,- "beat": 0.699,+ "tempo": 75,+ "beat": 0.627,"seam": 0,"seamRoot": 0,"loopClean": true,@@ -630,8 +630,8 @@"travel": 0,"path": 0.065,"rise": 0.006,- "tempo": 127,- "beat": 0.776,+ "tempo": 0,+ "beat": 0,"seam": 0,"seamRoot": 0,"loopClean": true,@@ -659,8 +659,8 @@"travel": 0,"path": 0.778,"rise": 0.018,- "tempo": 67,- "beat": 0.518,+ "tempo": 0,+ "beat": 0,"seam": 0,"seamRoot": 0,"loopClean": true,@@ -717,8 +717,8 @@"travel": 0.218,"path": 6.282,"rise": 0.405,- "tempo": 90,- "beat": 0.333,+ "tempo": 0,+ "beat": 0,"seam": 0.516,"seamRoot": 0.251,"loopClean": false,@@ -1008,7 +1008,7 @@"path": 1.507,"rise": 0.033,"tempo": 0,- "beat": 0.177,+ "beat": 0,"seam": 0.01,"seamRoot": 1.485,"loopClean": false,@@ -1037,7 +1037,7 @@"path": 0.525,"rise": 0.041,"tempo": 0,- "beat": 0.079,+ "beat": 0,"seam": 0,"seamRoot": 0,"loopClean": true,@@ -1065,8 +1065,8 @@"travel": 0,"path": 3.754,"rise": 0.161,- "tempo": 35,- "beat": 0.825,+ "tempo": 0,+ "beat": 0,"seam": 0,"seamRoot": 0,"loopClean": true,@@ -1181,8 +1181,8 @@"travel": 0,"path": 2.021,"rise": 0.119,- "tempo": 27,- "beat": 0.911,+ "tempo": 0,+ "beat": 0,"seam": 0,"seamRoot": 0,"loopClean": true,@@ -1472,7 +1472,7 @@"path": 0.313,"rise": 0.014,"tempo": 0,- "beat": 0.037,+ "beat": 0,"seam": 0.109,"seamRoot": 0.2,"loopClean": false,@@ -1529,8 +1529,8 @@"travel": 0,"path": 0.008,"rise": 0.01,- "tempo": 42,- "beat": 0.432,+ "tempo": 0,+ "beat": 0,"seam": 0,"seamRoot": 0,"loopClean": true,@@ -1587,8 +1587,8 @@"travel": 0.264,"path": 0.353,"rise": 0.012,- "tempo": 100,- "beat": 0.35,+ "tempo": 0,+ "beat": 0,"seam": 0.137,"seamRoot": 0.264,"loopClean": false,@@ -1645,8 +1645,8 @@"travel": 1.549,"path": 1.558,"rise": 0.059,- "tempo": 90,- "beat": 0.847,+ "tempo": 0,+ "beat": 0,"seam": 0.018,"seamRoot": 1.549,"loopClean": false,@@ -1674,8 +1674,8 @@"travel": 0,"path": 0.005,"rise": 0.001,- "tempo": 56,- "beat": 0.507,+ "tempo": 0,+ "beat": 0,"seam": 0,"seamRoot": 0,"loopClean": true,@@ -1703,8 +1703,8 @@"travel": 0,"path": 1.204,"rise": 0.043,- "tempo": 27,- "beat": 0.267,+ "tempo": 0,+ "beat": 0,"seam": 0,"seamRoot": 0,"loopClean": true,@@ -1877,8 +1877,8 @@"travel": 0,"path": 0.009,"rise": 0.003,- "tempo": 82,- "beat": 0.742,+ "tempo": 0,+ "beat": 0,"seam": 0,"seamRoot": 0,"loopClean": true,@@ -1906,8 +1906,8 @@"travel": 1.586,"path": 1.602,"rise": 0.068,- "tempo": 112,- "beat": 0.706,+ "tempo": 0,+ "beat": 0,"seam": 0.022,"seamRoot": 1.586,"loopClean": false,@@ -1993,8 +1993,8 @@"travel": 0,"path": 0.309,"rise": 0.125,- "tempo": 106,- "beat": 0.332,+ "tempo": 0,+ "beat": 0,"seam": 0,"seamRoot": 0,"loopClean": true,@@ -2051,8 +2051,8 @@"travel": 1.973,"path": 1.974,"rise": 0.082,- "tempo": 150,- "beat": 0.76,+ "tempo": 0,+ "beat": 0,"seam": 0,"seamRoot": 1.973,"loopClean": false,@@ -2254,8 +2254,8 @@"travel": 0,"path": 7.814,"rise": 0.281,- "tempo": 200,- "beat": 0.441,+ "tempo": 0,+ "beat": 0,"seam": 0,"seamRoot": 0,"loopClean": true,@@ -2428,8 +2428,8 @@"travel": 0,"path": 0.586,"rise": 0.063,- "tempo": 51,- "beat": 0.763,+ "tempo": 0,+ "beat": 0,"seam": 0,"seamRoot": 0,"loopClean": true,@@ -2515,8 +2515,8 @@"travel": 0,"path": 1.071,"rise": 0.115,- "tempo": 129,- "beat": 0.699,+ "tempo": 0,+ "beat": 0,"seam": 0,"seamRoot": 0,"loopClean": true,@@ -2573,8 +2573,8 @@"travel": 0,"path": 0,"rise": 0,- "tempo": 150,- "beat": 0.84,+ "tempo": 0,+ "beat": 0,"seam": 0,"seamRoot": 0,"loopClean": false,@@ -2718,8 +2718,8 @@"travel": 0,"path": 0.213,"rise": 0.085,- "tempo": 113,- "beat": 0.869,+ "tempo": 0,+ "beat": 0,"seam": 0,"seamRoot": 0,"loopClean": true,@@ -2950,8 +2950,8 @@"travel": 0.029,"path": 0.704,"rise": 0.021,- "tempo": 78,- "beat": 0.445,+ "tempo": 0,+ "beat": 0,"seam": 0.14,"seamRoot": 0.029,"loopClean": true,@@ -2979,8 +2979,8 @@"travel": 0.089,"path": 1.412,"rise": 0.301,- "tempo": 200,- "beat": 0.407,+ "tempo": 0,+ "beat": 0,"seam": 0.518,"seamRoot": 0.214,"loopClean": false,@@ -3008,8 +3008,8 @@"travel": 0,"path": 0.17,"rise": 0.044,- "tempo": 129,- "beat": 0.446,+ "tempo": 0,+ "beat": 0,"seam": 0,"seamRoot": 0,"loopClean": true,@@ -3153,8 +3153,8 @@"travel": 0,"path": 0.063,"rise": 0.094,- "tempo": 164,- "beat": 0.736,+ "tempo": 0,+ "beat": 0,"seam": 0.005,"seamRoot": 0,"loopClean": true,@@ -3240,8 +3240,8 @@"travel": 0,"path": 0.097,"rise": 0.044,- "tempo": 129,- "beat": 0.446,+ "tempo": 0,+ "beat": 0,"seam": 0,"seamRoot": 0,"loopClean": true,diff --git a/src/animation-state-machine.js b/src/animation-state-machine.jsindex 994779951..be2e5c16e 100644--- a/src/animation-state-machine.js+++ b/src/animation-state-machine.js@@ -104,7 +104,10 @@ const GESTURES = Object.freeze({cheer: { clip: 'av-cheering', label: 'Cheer', icon: '🙌', loop: false, layer: 'upper', crossfade: 0.25 },agree: { clip: 'xbot-agree', label: 'Agree', icon: '✅', loop: false, layer: 'upper', crossfade: 0.2 },disagree: { clip: 'xbot-head-shake', label: 'Disagree', icon: '🙅', loop: false, layer: 'upper', crossfade: 0.2 },- talking: { clip: 'av-vtubing', label: 'Talking', icon: '💬', loop: true, layer: 'upper', crossfade: 0.3 },+ // av-vtubing reads as talking at full body, but 63% of its motion is hips+ // and legs (signatures.json upperShare 0.372), which the upper-layer strip+ // discards; av-conductor keeps its gesticulation above the waist.+ talking: { clip: 'av-conductor', label: 'Talking', icon: '💬', loop: true, layer: 'upper', crossfade: 0.3 },// Conversational + locomotion gestures. `shrug` is a shoulder shrug, so it// overlays the base layer (shrug while walking) rather than taking the whole// body over the way the borrowed `defeated` clip had to. All clip names arediff --git a/src/runtime/animation-slots.js b/src/runtime/animation-slots.jsindex 9298e5166..fe9c14995 100644--- a/src/runtime/animation-slots.js+++ b/src/runtime/animation-slots.js@@ -55,11 +55,13 @@ export const DEFAULT_ANIMATION_MAP = {bow: 'sitclap',point: 'point',shrug: 'shrug',- // Was 'Fidget' — no such clip exists (case mismatch against the lowercase- // manifest names too), so the slot silently no-op'd on every agent that hit- // it. av-waiting is a real baked idle-fidget loop (see registry.json- // known_issues: broken-fidget-slot).- fidget: 'av-waiting',+ // Was 'Fidget', a clip that does not exist (case mismatch against the+ // lowercase manifest names too), so the slot silently no-op'd on every agent+ // that hit it (registry.json known_issues: broken-fidget-slot). av-waiting looked+ // right but measures with an open loop seam and root drift (signatures.json:+ // loopClean false), which snaps every cycle on a looping slot;+ // av-listening-music is a clean anchored loop with the same restless read.+ fidget: 'av-listening-music',dance: 'rumba',// Skill-driven slots. Each one exists because a skill emits the matching// hint; before they were slots those hints hit no clip and no-op'd silently.@@ -67,7 +69,9 @@ export const DEFAULT_ANIMATION_MAP = {present: 'av-brag-claps',sign: 'xbot-agree',curiosity: 'av-spy',- patience: 'av-waiting',+ // Looping slot, so it needs a clean anchored loop; av-waiting's open seam+ // rules it out here too.+ patience: 'av-idle-anim',manipulate: 'av-push-block',conjure: 'av-conductor',};diff --git a/src/runtime/motion-signature.js b/src/runtime/motion-signature.jsindex e76370d15..506da7ee5 100644--- a/src/runtime/motion-signature.js+++ b/src/runtime/motion-signature.js@@ -56,6 +56,24 @@ const MAX_BEAT_PERIOD = 2.5;/** A peak below this is noise, not a beat. */const BEAT_FLOOR = 0.25;+/**+ * Minimum relative spread (standard deviation over mean) of the motion-energy+ * envelope before a beat is claimed at all. A clip moving at a steady rate has+ * a flat envelope: it is continuous, not rhythmic, and any lag will correlate+ * with any other. Without this gate a constant-speed ramp reports whatever the+ * shortest searched lag happens to be.+ */+const BEAT_MIN_PULSE = 0.3;++/**+ * A candidate lag this close to the strongest peak wins if it is shorter.+ * Autocorrelation peaks at every multiple of the true period, and the estimator+ * gets noisier as the overlap shrinks, so the largest peak is regularly 2x or+ * 3x the real one. Preferring the shortest near-equal peak is the standard+ * octave-error guard from pitch detection.+ */+const BEAT_HARMONIC_TOLERANCE = 0.88;+/** Loop-seam thresholds: mean bone angle (rad) and root offset (metres). */const SEAM_ANGLE_LIMIT = 0.2;const SEAM_ROOT_LIMIT = 0.06;@@ -206,6 +224,9 @@ function findBeat(signal, dt, duration) {energy += dev[i] * dev[i];}if (energy <= 0) return { period: null, strength: 0 };+ if (mean > 0 && Math.sqrt(energy / n) / mean < BEAT_MIN_PULSE) {+ return { period: null, strength: 0 };+ }const minLag = Math.max(2, Math.round(MIN_BEAT_PERIOD / dt));const maxLag = Math.min(n - 2, Math.round(maxLagS / dt));@@ -221,13 +242,24 @@ function findBeat(signal, dt, duration) {let bestLag = 0;let best = 0;+ const peaks = [];for (let lag = minLag; lag <= maxLag; lag++) {if (acf[lag] <= acf[lag - 1] || acf[lag] < acf[lag + 1]) continue;+ peaks.push(lag);if (acf[lag] > best) {best = acf[lag];bestLag = lag;}}+ // Octave-error guard: the shortest peak within tolerance of the strongest+ // one is the true period; the strongest is regularly a multiple of it.+ for (const lag of peaks) {+ if (lag < bestLag && acf[lag] >= best * BEAT_HARMONIC_TOLERANCE) {+ bestLag = lag;+ best = acf[lag];+ break;+ }+ }if (bestLag === 0 || best < BEAT_FLOOR) {return { period: null, strength: round(Math.max(0, best)) };}diff --git a/tests/motion-signature.test.js b/tests/motion-signature.test.jsnew file mode 100644index 000000000..5fac3c321--- /dev/null+++ b/tests/motion-signature.test.js@@ -0,0 +1,363 @@+// Motion signatures are measured, not authored, so these tests check two very+// different things:+//+// 1. The analyser does the arithmetic it claims, on synthetic clips whose+// answer is known by construction.+// 2. The shipped index (public/animations/signatures.json) still agrees with+// the clips on disk, and the hand-maintained tables elsewhere in the repo+// still agree with what the motion actually does. That second half is the+// point of the whole exercise: a claim like "shrug overlays locomotion"+// stops being a comment someone has to remember to update.++import { describe, it, expect } from 'vitest';+import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import {+ analyzeClip,+ describe as describeSignature,+ distance,+ energyBand,+ leadRegion,+ regionOf,+ similarTo,+ slotFit,+ DEFAULT_OVERLAY_SLOTS,+ REGIONS,+ SIGNATURE_VERSION,+} from '../src/runtime/motion-signature.js';+import { SLOTS, DEFAULT_ANIMATION_MAP } from '../src/runtime/animation-slots.js';+import { GESTURES, GESTURE_NAMES } from '../src/animation-state-machine.js';+import { buildIndex } from '../scripts/build-motion-signatures.mjs';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const INDEX = JSON.parse(+ fs.readFileSync(path.join(ROOT, 'public/animations/signatures.json'), 'utf8'),+);++/* ── synthetic clips, where the right answer is known ──────────────────── */++const IDENTITY = [0, 0, 0, 1];++/** A quaternion rotating `angle` radians about X. */+function quatX(angle) {+ return [Math.sin(angle / 2), 0, 0, Math.cos(angle / 2)];+}++/**+ * Build a clip whose named bones each sweep through the given per-frame angles.+ * @param {{duration:number, bones:Object, hips?:number[][]}} spec+ */+function makeClip({ duration, bones, hips }) {+ const frameCount = Object.values(bones)[0].length;+ const times = Array.from({ length: frameCount }, (_, i) => (i * duration) / (frameCount - 1));+ const tracks = Object.entries(bones).map(([bone, angles]) => ({+ name: `${bone}.quaternion`,+ times,+ values: angles.flatMap((a) => (a === 0 ? IDENTITY : quatX(a))),+ type: 'quaternion',+ }));+ if (hips) {+ tracks.push({ name: 'Hips.position', times, values: hips.flat(), type: 'vector' });+ }+ return { name: 'synthetic', duration, tracks };+}++/** Every canonical bone held at rest, so unrelated regions read as zero. */+function still(frameCount) {+ return Array.from({ length: frameCount }, () => 0);+}++describe('regionOf', () => {+ it('maps the canonical skeleton onto the five regions', () => {+ expect(regionOf('Hips')).toBe('root');+ expect(regionOf('Spine2')).toBe('torso');+ expect(regionOf('Head')).toBe('head');+ expect(regionOf('LeftForeArm')).toBe('arms');+ expect(regionOf('RightToeBase')).toBe('legs');+ });++ it('excludes finger bones', () => {+ // Only some exports carry finger tracks. Counting them would score two+ // clips with identical body motion differently on export settings alone.+ expect(regionOf('LeftHandIndex2')).toBeNull();+ expect(regionOf('RightHandThumb1')).toBeNull();+ expect(regionOf('LeftHand')).toBe('arms');+ });+});++describe('analyzeClip', () => {+ it('attributes motion to the region that moved', () => {+ const sig = analyzeClip(+ makeClip({+ duration: 1,+ bones: { Head: [0, 0.5, 0], Neck: still(3), LeftArm: still(3), LeftUpLeg: still(3) },+ }),+ );+ expect(sig.lead).toBe('head');+ expect(sig.regions.head).toBeCloseTo(1, 5);+ expect(sig.regions.legs).toBe(0);+ expect(REGIONS.reduce((sum, r) => sum + sig.regions[r], 0)).toBeCloseTo(1, 5);+ });++ it('scores a faster sweep as more energetic', () => {+ const slow = analyzeClip(makeClip({ duration: 4, bones: { LeftArm: [0, 1, 0] } }));+ const fast = analyzeClip(makeClip({ duration: 1, bones: { LeftArm: [0, 1, 0] } }));+ expect(fast.energy).toBeGreaterThan(slow.energy);+ expect(energyBand(fast)).not.toBe(energyBand(slow));+ });++ it('flags a single-frame export as a held pose', () => {+ const sig = analyzeClip({+ name: 'pose',+ duration: 0.04,+ tracks: [{ name: 'Head.quaternion', times: [0], values: IDENTITY, type: 'quaternion' }],+ });+ expect(sig.static).toBe(true);+ expect(sig.frames).toBe(1);+ expect(describeSignature(sig)).toMatch(/single held pose/i);+ });++ it('measures root travel and reports a drifting clip as unanchored', () => {+ const frames = 11;+ const hips = Array.from({ length: frames }, (_, i) => [i * 0.05, 0.94, 0]);+ const sig = analyzeClip(+ makeClip({ duration: 1, bones: { LeftUpLeg: Array.from({ length: frames }, (_, i) => (i % 2) * 0.3) }, hips }),+ );+ expect(sig.travel).toBeCloseTo(0.5, 2);+ expect(sig.anchored).toBe(false);+ });++ it('treats a clip that returns to its start as anchored', () => {+ const frames = 11;+ const hips = Array.from({ length: frames }, (_, i) => [Math.sin((i / (frames - 1)) * Math.PI * 2) * 0.1, 0.94, 0]);+ const sig = analyzeClip(makeClip({ duration: 1, bones: { LeftUpLeg: still(frames) }, hips }));+ expect(sig.travel).toBeLessThan(0.01);+ expect(sig.anchored).toBe(true);+ });++ it('detects the period of a repeating motion', () => {+ // Four seconds at 30fps, one full cycle per second: a 60 BPM beat.+ const frames = 121;+ const angles = Array.from({ length: frames }, (_, i) => 0.6 * Math.sin((i / 30) * Math.PI * 2));+ const sig = analyzeClip(makeClip({ duration: 4, bones: { LeftArm: angles } }));+ // The energy envelope of a sine peaks twice per cycle, so the measured+ // beat is the half-cycle: what a listener would tap along to.+ expect([60, 120]).toContain(sig.tempo);+ expect(sig.beat).toBeGreaterThan(0.3);+ });++ it('reports no beat for a one-shot', () => {+ const frames = 61;+ const angles = Array.from({ length: frames }, (_, i) => (i < 30 ? i / 30 : (60 - i) / 30));+ const sig = analyzeClip(makeClip({ duration: 2, bones: { LeftArm: angles } }));+ expect(sig.tempo).toBe(0);+ });++ it('measures the loop seam between the last frame and the first', () => {+ const closed = analyzeClip(makeClip({ duration: 1, bones: { LeftArm: [0, 0.8, 0] } }));+ expect(closed.seam).toBeCloseTo(0, 5);+ expect(closed.loopClean).toBe(true);++ const open = analyzeClip(makeClip({ duration: 1, bones: { LeftArm: [0, 0.4, 0.8] } }));+ expect(open.seam).toBeGreaterThan(0.2);+ expect(open.loopClean).toBe(false);+ });++ it('scores a one-sided motion as unbalanced and a mirrored one as balanced', () => {+ const oneSided = analyzeClip(+ makeClip({ duration: 1, bones: { LeftArm: [0, 0.8, 0], RightArm: still(3) } }),+ );+ expect(oneSided.balance).toBeCloseTo(0, 5);++ const mirrored = analyzeClip(+ makeClip({ duration: 1, bones: { LeftArm: [0, 0.8, 0], RightArm: [0, 0.8, 0] } }),+ );+ expect(mirrored.balance).toBeCloseTo(1, 5);+ });++ it('marks an upper-body clip as overlay-safe and a leg-led one as not', () => {+ const upper = analyzeClip(+ makeClip({ duration: 1, bones: { LeftArm: [0, 0.9, 0], Head: [0, 0.4, 0], LeftUpLeg: still(3) } }),+ );+ expect(upper.overlay).toBe(true);++ const lower = analyzeClip(+ makeClip({ duration: 1, bones: { LeftUpLeg: [0, 0.9, 0], LeftLeg: [0, 0.7, 0], LeftArm: still(3) } }),+ );+ expect(lower.overlay).toBe(false);+ });+});++describe('distance and similarTo', () => {+ it('scores a clip as identical to itself and further from a different shape', () => {+ const arms = analyzeClip(makeClip({ duration: 1, bones: { LeftArm: [0, 0.8, 0] } }));+ const alsoArms = analyzeClip(makeClip({ duration: 1, bones: { RightArm: [0, 0.8, 0] } }));+ const legs = analyzeClip(makeClip({ duration: 1, bones: { LeftUpLeg: [0, 0.8, 0] } }));+ expect(distance(arms, arms)).toBe(0);+ expect(distance(arms, alsoArms)).toBeLessThan(distance(arms, legs));+ });++ it('never returns the query clip among its own neighbours', () => {+ const matches = similarTo('wave', INDEX.clips, 5);+ expect(matches.length).toBe(5);+ expect(matches.map((m) => m.clip)).not.toContain('wave');+ // Sorted nearest-first.+ for (let i = 1; i < matches.length; i++) {+ expect(matches[i].distance).toBeGreaterThanOrEqual(matches[i - 1].distance);+ }+ });++ it('returns nothing for a clip that is not in the index', () => {+ expect(similarTo('not-a-clip', INDEX.clips)).toEqual([]);+ });+});++describe('leadRegion', () => {+ it('picks the largest share', () => {+ expect(leadRegion({ head: 0.1, arms: 0.2, torso: 0.05, root: 0.05, legs: 0.6 })).toBe('legs');+ });+});++describe('slotFit', () => {+ const upperGesture = analyzeClip(+ makeClip({ duration: 1, bones: { LeftArm: [0, 0.9, 0], Head: [0, 0.3, 0] } }),+ );++ it('accepts an upper-body clip for an overlay slot', () => {+ expect(slotFit('wave', upperGesture).level).toBe('ok');+ });++ it('rejects a leg-led clip for an overlay slot, and says why', () => {+ const legs = analyzeClip(+ makeClip({ duration: 1, bones: { LeftUpLeg: [0, 0.9, 0], LeftLeg: [0, 0.8, 0] } }),+ );+ const fit = slotFit('shrug', legs);+ expect(fit.level).toBe('warn');+ expect(fit.message).toMatch(/below the waist/);+ });++ it('rejects a clip with an open seam for a looping slot', () => {+ const open = analyzeClip(makeClip({ duration: 1, bones: { LeftArm: [0, 0.4, 0.9] } }));+ expect(slotFit('idle', open).level).toBe('warn');+ });++ it('rejects a held pose for any slot', () => {+ const pose = analyzeClip({+ name: 'pose',+ duration: 0.04,+ tracks: [{ name: 'Head.quaternion', times: [0], values: IDENTITY, type: 'quaternion' }],+ });+ expect(slotFit('celebrate', pose).message).toMatch(/held pose/i);+ });++ it('warns about a drifting clip even in a slot with no other constraint', () => {+ const frames = 11;+ const drift = analyzeClip(+ makeClip({+ duration: 1,+ bones: { LeftArm: Array.from({ length: frames }, (_, i) => (i % 2) * 0.4) },+ hips: Array.from({ length: frames }, (_, i) => [i * 0.06, 0.94, 0]),+ }),+ );+ const fit = slotFit('celebrate', drift);+ expect(fit.level).toBe('warn');+ expect(fit.message).toMatch(/slides/);+ });++ it('returns null when there is no signature to judge', () => {+ expect(slotFit('wave', null)).toBeNull();+ });+});++/* ── the shipped index, held to the clips on disk ──────────────────────── */++describe('signatures.json', () => {+ it('is current: re-measuring every clip reproduces the shipped index', () => {+ // The index is a build artifact. If a clip is rebaked and this is not+ // regenerated, every fingerprint on /gestures describes the old motion.+ const fresh = buildIndex();+ expect(fresh.version).toBe(SIGNATURE_VERSION);+ expect(fresh).toEqual(INDEX);+ });++ it('covers every clip in the manifest', () => {+ const manifest = JSON.parse(+ fs.readFileSync(path.join(ROOT, 'public/animations/manifest.json'), 'utf8'),+ );+ for (const entry of manifest) {+ expect(INDEX.clips[entry.name], `no signature for ${entry.name}`).toBeTruthy();+ }+ });++ it('gives every slot default a measured signature', () => {+ for (const slot of SLOTS) {+ expect(INDEX.clips[DEFAULT_ANIMATION_MAP[slot]], `slot ${slot}`).toBeTruthy();+ }+ });+});++/* ── the hand-maintained tables, held to the measurements ──────────────── */++describe('the walk gesture table agrees with the motion', () => {+ it('lists the same overlay slots the fit rules assume', () => {+ // DEFAULT_OVERLAY_SLOTS drives every "this will not survive the strip"+ // warning. It is a copy of the `upper` layer in the state machine, so it+ // has to be checked against the original rather than trusted.+ const upperClips = new Set(+ GESTURE_NAMES.filter((n) => GESTURES[n].layer === 'upper').map((n) => GESTURES[n].clip),+ );+ for (const slot of DEFAULT_OVERLAY_SLOTS) {+ const clip = DEFAULT_ANIMATION_MAP[slot];+ expect(clip, `overlay slot ${slot} has no default clip`).toBeTruthy();+ // Every overlay slot's default clip is one the walk layer also plays+ // as an upper-body overlay, or is the sign-language agree clip.+ expect(+ upperClips.has(clip) || slot === 'sign',+ `${slot} → ${clip} is not played on the upper layer anywhere`,+ ).toBe(true);+ }+ });++ it('does not put a clip on the upper layer that has nothing above the waist', () => {+ // _buildOverlayClip strips hips/legs/feet before blending. A clip whose+ // motion is mostly below the waist becomes a near no-op on that layer.+ for (const name of GESTURE_NAMES) {+ const def = GESTURES[name];+ if (def.layer !== 'upper') continue;+ const sig = INDEX.clips[def.clip];+ expect(sig, `${name} → ${def.clip} has no signature`).toBeTruthy();+ expect(+ sig.upperShare,+ `${name} plays ${def.clip} on the upper layer, but only ${Math.round(sig.upperShare * 100)}% of it is above the waist`,+ ).toBeGreaterThan(0.4);+ }+ });++ it('never puts a held pose in the gesture table', () => {+ for (const name of GESTURE_NAMES) {+ const sig = INDEX.clips[GESTURES[name].clip];+ expect(sig?.static, `${name} plays a single-frame clip`).toBe(false);+ }+ });+});++describe('the slot defaults are playable', () => {+ it('never resolves a slot to a held pose', () => {+ // Four clips in the library are single-frame exports. A slot pointed at+ // one of them freezes the avatar instead of animating it.+ for (const slot of SLOTS) {+ const clip = DEFAULT_ANIMATION_MAP[slot];+ expect(INDEX.clips[clip].static, `${slot} → ${clip} is a held pose`).toBe(false);+ }+ });++ it('never resolves a looping slot to a clip with an open seam', () => {+ for (const slot of ['idle', 'fidget', 'patience']) {+ const clip = DEFAULT_ANIMATION_MAP[slot];+ const fit = slotFit(slot, INDEX.clips[clip]);+ expect(fit.level, `${slot} → ${clip}: ${fit.message}`).toBe('ok');+ }+ });+});