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
test: make the animation, IMU, path and clock-bound suites pass on any machine
nirholas821771220a21
diff --git a/tests/check-event-window.test.js b/tests/check-event-window.test.jsindex 11055bf2a..0b250fa96 100644--- a/tests/check-event-window.test.js+++ b/tests/check-event-window.test.js@@ -1,5 +1,7 @@import { describe, it, expect } from 'vitest';import { existsSync, readFileSync } from 'node:fs';+import { spawnSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';import {validateEventConfig, isNoEventSentinel, NO_EVENT_DOC, CONFIG_PATH, isoOf, zoneLines,} from '../scripts/check-event-window.mjs';@@ -19,6 +21,8 @@ const BASE = {],};+const CHECK_SCRIPT = fileURLToPath(new URL('../scripts/check-event-window.mjs', import.meta.url));+const BEFORE = Date.parse('2026-08-09T12:00:00Z');const DURING = Date.parse('2026-08-09T18:00:00Z');const AFTER = Date.parse('2026-08-10T00:00:00Z');@@ -165,7 +169,44 @@ describe.skipIf(!existsSync(CONFIG_PATH) || shippedIsResting())('the configuredexpect(failures).toEqual([]);});- it('has not already ended', () => {- expect(Date.parse(shippedEvent().endsAt)).toBeGreaterThan(Date.now());+ // Judged on an injected clock, never today's: whether the shipped event is+ // still ahead is a fact about the calendar, which `npm run check:event` (in+ // gate) reports at run time. What this suite pins is that the guard reads+ // the shipped window the way every surface does: live for its whole span,+ // and flagged ENDED from the instant it closes, so a finished event left in+ // the file fails the gate until it is rescheduled or cleared.+ it('reads as live for its whole window and as ENDED from the instant it closes', () => {+ const doc = shippedEvent();+ const { window: win } = validateEventConfig(doc, Date.parse(doc.startsAt));+ expect(win).not.toBeNull();+ for (const at of [win.startsAt, win.endsAt - 1]) {+ const judged = validateEventConfig(doc, at);+ expect(judged.state).toBe('live');+ expect(judged.failures).toEqual([]);+ }+ const closed = validateEventConfig(doc, win.endsAt);+ expect(closed.state).toBe('over');+ expect(closed.failures.join(' | ')).toMatch(/ENDED/);+ });++ it('passes the gate CLI at the event\'s start and fails it once the event is over', () => {+ const doc = shippedEvent();+ const run = (at) => spawnSync(process.execPath, [CHECK_SCRIPT, '--at', at], { encoding: 'utf8' });+ const atStart = run(doc.startsAt);+ expect(atStart.status, atStart.stderr).toBe(0);+ expect(atStart.stdout).toMatch(/OK: the configured event is coherent/);+ const dayAfter = run(isoOf(validateEventConfig(doc, Date.parse(doc.startsAt)).window.endsAt + 24 * 3600 * 1000));+ expect(dayAfter.status).toBe(1);+ expect(dayAfter.stderr).toMatch(/the event window ENDED 24h ago/);+ });+});++describe.skipIf(!existsSync(CONFIG_PATH) || !shippedIsResting())('the resting config that ships', () => {+ it('passes the gate CLI at any instant, since there is no window to expire', () => {+ for (const at of ['2020-01-01T00:00:00Z', '2099-01-01T00:00:00Z']) {+ const r = spawnSync(process.execPath, [CHECK_SCRIPT, '--at', at], { encoding: 'utf8' });+ expect(r.status, r.stderr).toBe(0);+ expect(r.stdout).toMatch(/explicit no-event state/);+ }});});diff --git a/tests/clean-deploy-worktrees.test.js b/tests/clean-deploy-worktrees.test.jsindex dda901ec4..6ffe48888 100644--- a/tests/clean-deploy-worktrees.test.js+++ b/tests/clean-deploy-worktrees.test.js@@ -13,21 +13,21 @@ import { parseWorktrees, dirtyCount, isAgentWorktreeBranch } from '../scripts/cldescribe('parseWorktrees', () => {it('separates the main worktree from detached deploy scratch trees', () => {const porcelain = [- 'worktree /workspaces/three.ws',+ 'worktree /srv/three.ws','HEAD 87e5c4cf5e577c9d7a36740b0ee22d16ea2ee43b','branch refs/heads/main','',- 'worktree /workspaces/.deploy-wt',+ 'worktree /srv/.deploy-wt','HEAD d7d9035d0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa','detached','',].join('\n');const wts = parseWorktrees(porcelain);expect(wts).toHaveLength(2);- expect(wts[0].path).toBe('/workspaces/three.ws');+ expect(wts[0].path).toBe('/srv/three.ws');expect(wts[0].branch).toBe('refs/heads/main');expect(wts[0].detached).toBe(false);- expect(wts[1].path).toBe('/workspaces/.deploy-wt');+ expect(wts[1].path).toBe('/srv/.deploy-wt');expect(wts[1].detached).toBe(true);expect(wts[1].branch).toBe(null);});diff --git a/tests/eidon-imu-clip.test.js b/tests/eidon-imu-clip.test.jsindex c0449aba4..688069aeb 100644--- a/tests/eidon-imu-clip.test.js+++ b/tests/eidon-imu-clip.test.js@@ -29,6 +29,12 @@ import { CANONICAL_REST_POSITION, CANONICAL_REST_WORLD } from '../src/animation-const idle = JSON.parse(readFileSync(new URL('../public/animations/clips/idle.json', import.meta.url), 'utf8'));const DEG = 180 / Math.PI;+// The simulated recorder stamps every sample this many milliseconds after the+// routine time it measured, like a real logger whose clock does not start at+// zero. Truth lookups have to subtract it, or a comparison at a step in the+// routine reads the sample on the far side of the step.+const CLOCK_OFFSET_MS = 42;+const v = (x, y, z) => new Vector3(x, y, z);const columns = (a, b, c) => new Quaternion().setFromRotationMatrix(new Matrix4().makeBasis(a, b, c));const axisAngle = (axis, deg) => new Quaternion().setFromAxisAngle(axis.clone().normalize(), deg / DEG);@@ -47,7 +53,8 @@ function mounting(distalPrior, secondaryPrior, tiltDeg) {const secondary = perp(v(...secondaryPrior).applyQuaternion(tilt), distal);// Columns [distal, secondary, distal × secondary] map segment coordinates to// sensor coordinates; the sensor's orientation is the segment's times the inverse.- return columns(distal, secondary, new Vector3().crossVectors(distal, secondary)).invert();+ const toSensor = columns(distal, secondary, new Vector3().crossVectors(distal, secondary));+ return { quat: toSensor.clone().invert(), distal, secondary };}/** Scripted routine: returns shoulder flexion, elbow flexion and wrist wobble (degrees) at time t. */@@ -65,20 +72,23 @@ function routine(t) {function simulate(seconds = 40) {const up = v(0, 0, 1);const rows = [];- const mounts = {- [SLOT.chest]: axisAngle(v(0.3, 1, 0.2), 140),+ const segmentMounts = {[SLOT.leftArm]: mounting(HARNESS_PRIOR.distal[SLOT.leftArm], HARNESS_PRIOR.anterior[SLOT.leftArm], 12),[SLOT.rightArm]: mounting(HARNESS_PRIOR.distal[SLOT.rightArm], HARNESS_PRIOR.anterior[SLOT.rightArm], -15),[SLOT.leftForeArm]: mounting(HARNESS_PRIOR.distal[SLOT.leftForeArm], HARNESS_PRIOR.dorsal[SLOT.leftForeArm], 18),[SLOT.rightForeArm]: mounting(HARNESS_PRIOR.distal[SLOT.rightForeArm], HARNESS_PRIOR.dorsal[SLOT.rightForeArm], -9),+ };+ const mounts = {+ [SLOT.chest]: axisAngle(v(0.3, 1, 0.2), 140),[SLOT.leftHand]: axisAngle(v(1, -0.5, 0.7), 75),[SLOT.rightHand]: axisAngle(v(-0.4, 0.9, 0.3), -50),};+ for (const [slot, m] of Object.entries(segmentMounts)) mounts[slot] = m.quat;const truth = [];const frames = Math.round(seconds * SAMPLE_HZ);for (let i = 0; i < frames; i++) {const t = i / SAMPLE_HZ;- const timeMs = Math.round(t * 1000) + 42;+ const timeMs = Math.round(t * 1000) + CLOCK_OFFSET_MS;const { shoulder, elbow, wrist } = routine(t);// Body: a constant heading plus a lean about the left axis and a small yaw wobble.const lean = 6 * Math.sin(t * 0.5);@@ -91,7 +101,7 @@ function simulate(seconds = 40) {rows.push({ recording_id: 1, time_ms: timeMs, slot, quat_x: q.x, quat_y: q.y, quat_z: q.z, quat_w: q.w });};push(SLOT.chest, body);- const perSide = {};+ const arms = {};for (const side of ['left', 'right']) {// Upper arm hangs (distal = -up, anterior = forward) and flexes forward at the shoulder.const flex = axisAngle(left, -shoulder);@@ -111,11 +121,30 @@ function simulate(seconds = 40) {push(slots.arm, columns(armDistal, armAnterior, armThird));push(slots.foreArm, foreWorld);push(slots.hand, handWorld);- perSide[side] = { armDistal, foreDistal };+ arms[side] = { armDistal, foreDistal };}- truth.push({ t, shoulder, elbow, wrist, lean, forward, left, bodyUp, ...perSide });+ // The per-arm truth lives under its own key: spread at the top level, the+ // `left` arm would overwrite the wearer's `left` axis.+ truth.push({ t, shoulder, elbow, wrist, lean, forward, left, bodyUp, arms });}- return { rows, truth };+ return { rows, truth, segmentMounts };+}++/** Truth sample behind recording time `seconds` (sample stamps carry CLOCK_OFFSET_MS). */+function truthAtRecordingTime(truth, seconds) {+ const index = Math.round((seconds - CLOCK_OFFSET_MS / 1000) * SAMPLE_HZ);+ return truth[Math.min(truth.length - 1, Math.max(0, index))];+}++/**+ * Where an upper arm points on the character for a truth sample: straight down,+ * swung forward by the shoulder flexion and back by the torso's forward lean,+ * since the simulated arm hangs along the leaning body. Character frame: +y up,+ * +z forward.+ */+function expectedArmDirection(sample) {+ const swing = (sample.shoulder - sample.lean) / DEG;+ return v(0, -Math.cos(swing), Math.sin(swing));}/** World rotation of every bone in a clip frame, composed from the clip's own local tracks. */@@ -142,7 +171,7 @@ function boneDirection(world, bone, child) {}describe('eidon imu clip: calibration from a synthetic wearer', () => {- const { rows, truth } = simulate();+ const { rows, truth, segmentMounts } = simulate();const frames = alignFrames(rows);const cal = calibrate(frames);@@ -152,6 +181,17 @@ describe('eidon imu clip: calibration from a synthetic wearer', () => {expect(frames.times[1] - frames.times[0]).toBeCloseTo(1 / SAMPLE_HZ, 3);});+ it('maps every recording timestamp back to the truth sample it was simulated from', () => {+ // Both sides of the step at t = 20 s and t = 30 s, where reading the+ // neighbouring sample swaps a 90 degree elbow for a straight one.+ for (const i of [0, 479, 480, 719, 720, truth.length - 1]) {+ expect(truthAtRecordingTime(truth, frames.times[i])).toBe(truth[i]);+ }+ // The wearer's axes stay vectors; the per-arm truth must not shadow them.+ for (const key of ['forward', 'left', 'bodyUp']) expect(truth[0][key].isVector3).toBe(true);+ expect(Object.keys(truth[0].arms)).toEqual(['left', 'right']);+ });+it('finds the wearer\'s up, forward and left in the chest sensor frame', () => {const chestInv = cal.chestMean.clone().invert();const meanForward = truth.reduce((acc, f) => acc.add(f.forward), new Vector3()).normalize().applyQuaternion(chestInv);@@ -162,14 +202,35 @@ describe('eidon imu clip: calibration from a synthetic wearer', () => {});it('measures every arm axis from the data instead of echoing the prior', () => {- for (const side of ['left', 'right']) {- const q = cal.sides[side].quality;+ const sides = {+ left: { arm: SLOT.leftArm, foreArm: SLOT.leftForeArm },+ right: { arm: SLOT.rightArm, foreArm: SLOT.rightForeArm },+ };+ for (const [side, slots] of Object.entries(sides)) {+ const est = cal.sides[side];+ const q = est.quality;expect(q.hangingSeconds).toBeGreaterThan(3);expect(q.anteriorFromPrior).not.toBeNull();expect(q.dorsalFromPrior).not.toBeNull();for (const value of Object.values(q.distalFromPrior)) expect(value).not.toBeNull();- // The mountings were tilted 9-18 degrees off the prior, and the estimate should follow the tilt, not the prior.- expect(q.anteriorFromPrior).toBeGreaterThan(4);+ // Each long axis lands near the true mounting and far closer to it than+ // the prior it started from (the mountings sit 9-18 degrees off the+ // prior). The few degrees left over are the wearer's torso lean, which+ // the hanging arm follows while gravity, the estimator's reference, does not.+ for (const slot of [slots.arm, slots.foreArm]) {+ const trueDistal = segmentMounts[slot].distal;+ const error = angle(est.distal[slot], trueDistal);+ expect(error).toBeLessThan(4);+ expect(error).toBeLessThan(angle(v(...HARNESS_PRIOR.distal[slot]), trueDistal) / 2);+ }+ // The roll axes follow the true mounting too. The anterior estimate is+ // re-projected onto the measured long axis, so what it can differ from+ // the prior by is the tilt's twist about that axis, not the whole tilt.+ const trueAnterior = segmentMounts[slots.arm].secondary;+ expect(angle(est.anterior, trueAnterior)).toBeLessThan(3);+ const trueTwist = angle(trueAnterior, perp(v(...HARNESS_PRIOR.anterior[slots.arm]), segmentMounts[slots.arm].distal));+ expect(Math.abs(q.anteriorFromPrior - trueTwist)).toBeLessThan(0.5);+ expect(angle(est.dorsal, segmentMounts[slots.foreArm].secondary)).toBeLessThan(4);}});@@ -187,7 +248,7 @@ describe('eidon imu clip: baked motion on the canonical rig', () => {const cal = calibrate(frames);const clip = bakeClip(frames, cal, { name: 'synthetic', idle, start: 2, end: 36, loop: false });const fps = 30;- const truthAt = (clipTime) => truth[Math.round((2 + clipTime) * SAMPLE_HZ)];+ const truthAt = (clipTime) => truthAtRecordingTime(truth, 2 + clipTime);it('has every idle track, at 30 fps, over the requested window', () => {expect(clip.tracks.map((t) => t.name)).toEqual(idle.tracks.map((t) => t.name));@@ -210,14 +271,19 @@ describe('eidon imu clip: baked motion on the canonical rig', () => {expect(worst).toBeLessThan(4);});- it('hangs the arms straight down and raises them forward when the wearer reaches', () => {+ it('hangs the arms down along the body and raises them forward when the wearer reaches', () => {const at = (clipTime) => worldRotations(clip, Math.round(clipTime * fps));+ // t = 3 s in the routine: arms hanging while the torso leans 6 degrees+ // forward, so the arms hang 6 degrees behind vertical, exactly as simulated.const hanging = at(1);- expect(angle(boneDirection(hanging, 'LeftArm', 'LeftForeArm'), v(0, -1, 0))).toBeLessThan(4);- expect(angle(boneDirection(hanging, 'RightArm', 'RightForeArm'), v(0, -1, 0))).toBeLessThan(4);+ const hangingArm = expectedArmDirection(truthAt(1));+ expect(angle(hangingArm, v(0, -1, 0))).toBeGreaterThan(5);+ expect(angle(boneDirection(hanging, 'LeftArm', 'LeftForeArm'), hangingArm)).toBeLessThan(4);+ expect(angle(boneDirection(hanging, 'RightArm', 'RightForeArm'), hangingArm)).toBeLessThan(4);// t = 23 s in the routine (21 s into the clip): shoulder 60 degrees forward, elbow about 90.const reaching = at(21);- const expectedArm = v(0, -Math.cos(60 / DEG), Math.sin(60 / DEG));+ expect(truthAt(21).shoulder).toBe(60);+ const expectedArm = expectedArmDirection(truthAt(21));expect(angle(boneDirection(reaching, 'LeftArm', 'LeftForeArm'), expectedArm)).toBeLessThan(5);expect(angle(boneDirection(reaching, 'RightArm', 'RightForeArm'), expectedArm)).toBeLessThan(5);// The flexed forearm points up and forward (elbow flexes toward the anterior side), never backward.@@ -227,9 +293,13 @@ describe('eidon imu clip: baked motion on the canonical rig', () => {});it('keeps the level forearm palm-down: its dorsal side faces up', () => {- // t = 14.8 s: elbow near 100 degrees with the upper arm hanging, so the forearm is roughly level.- const frame = Math.round((14.8 - 2) * fps);- const world = worldRotations(clip, frame);+ // t = 13.25 s: the elbow peaks at 100 degrees while the shoulder is back+ // at rest, so the upper arm hangs and the forearm sits 10 degrees above level.+ const clipTime = 13.25 - 2;+ const sample = truthAt(clipTime);+ expect(sample.elbow).toBeGreaterThan(97);+ expect(sample.shoulder).toBeLessThan(1);+ const world = worldRotations(clip, Math.round(clipTime * fps));const restDorsal = v(0, 1, 0).applyQuaternion(new Quaternion().fromArray(CANONICAL_REST_WORLD.LeftForeArm).invert());const dorsal = restDorsal.applyQuaternion(world.LeftForeArm);expect(dorsal.y).toBeGreaterThan(0.85);@@ -237,16 +307,29 @@ describe('eidon imu clip: baked motion on the canonical rig', () => {it('leans the torso with the chest sensor and leaves the legs on the idle clip', () => {const spine2 = (clipTime) => worldRotations(clip, Math.round(clipTime * fps)).Spine2;+ // The bake time-warps the idle so it completes whole cycles inside the+ // window; compare against the idle at that same warped time.+ const duration = clip.duration;+ const cycles = Math.max(1, Math.round(duration / idle.duration));const idleSpine2 = (clipTime) => {- const idleClip = { ...idle, tracks: idle.tracks };- const frame = Math.round(clipTime * fps) % idle.tracks[0].times.length;- return worldRotations(idleClip, frame).Spine2;+ const idleTime = ((clipTime / duration) * cycles * idle.duration) % idle.duration;+ return worldRotations(idle, Math.round(idleTime * fps)).Spine2;+ };+ // The torso turn the chest sensor added, about the character's left axis+ // (+x): positive tips the chest toward +z (forward), negative leans back.+ const pitch = (clipTime) => {+ const turn = spine2(clipTime).multiply(idleSpine2(clipTime).invert());+ if (turn.w < 0) turn.set(-turn.x, -turn.y, -turn.z, -turn.w);+ return 2 * Math.asin(Math.max(-1, Math.min(1, turn.x))) * DEG;};- // The lean is 6 degrees at its peak around t = 3.14 s (1.14 s into the clip) and reverses at t = 9.4 s.- const forwardLean = spine2(1.14).angleTo(idleSpine2(1.14)) * DEG;- const backLean = spine2(7.4).angleTo(idleSpine2(7.4)) * DEG;- expect(forwardLean).toBeGreaterThan(3);- expect(backLean).toBeGreaterThan(3);+ // The lean peaks at 6 degrees forward at t = 3.14 s (1.14 s into the clip)+ // and 6 degrees back at t = 9.42 s (7.42 s into the clip).+ const forwardLean = pitch(1.14);+ const backLean = pitch(7.42);+ expect(forwardLean).toBeGreaterThan(4.5);+ expect(forwardLean).toBeLessThan(7.5);+ expect(backLean).toBeLessThan(-4.5);+ expect(backLean).toBeGreaterThan(-7.5);const legs = clip.tracks.find((t) => t.name === 'LeftUpLeg.quaternion');const idleLegs = idle.tracks.find((t) => t.name === 'LeftUpLeg.quaternion');expect(legs.values.slice(0, 4)).toEqual(idleLegs.values.slice(0, 4).map((n) => Number(n.toPrecision(7))));diff --git a/tests/prepare-deploy-worktree.test.js b/tests/prepare-deploy-worktree.test.jsindex 214bc4972..c6d0032e9 100644--- a/tests/prepare-deploy-worktree.test.js+++ b/tests/prepare-deploy-worktree.test.js@@ -9,6 +9,8 @@import { describe, it, expect } from 'vitest';import { execFileSync } from 'node:child_process';+import { existsSync, statSync } from 'node:fs';+import { tmpdir } from 'node:os';import path from 'node:path';import { fileURLToPath } from 'node:url';@@ -17,6 +19,16 @@ import { ARTIFACTS, planArtifacts, cpArgsFor } from '../scripts/prepare-deploy-wconst ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');const SCRIPT = path.join(ROOT, 'scripts/prepare-deploy-worktree.mjs');+// Plan-mode targets derived from this checkout, never from one machine's layout+// (the default /workspaces/.deploy-wt only exists in a codespace).+const sameDevice = (dir) => existsSync(dir) && statSync(dir).dev === statSync(ROOT).dev;+// A directory beside the checkout when that shares its filesystem, else one+// inside it; either way a path that does not exist yet, so plan mode can run.+const PLAN_PARENT = sameDevice(path.dirname(ROOT)) ? path.dirname(ROOT) : ROOT;+const UNUSED_TARGET = path.join(PLAN_PARENT, `.deploy-wt-vitest-unused-${process.pid}`);+// A mount that is certainly not the checkout's, for the cross-filesystem guard.+const FOREIGN_FS = ['/dev', '/proc', '/sys', tmpdir()].find((dir) => existsSync(dir) && !sameDevice(dir));+/** Run the script in plan mode. It writes nothing, so this is safe in CI. */function plan(args) {try {@@ -106,7 +118,8 @@ describe('cpArgsFor', () => {describe('guards (plan mode, writes nothing)', () => {it('refuses a target on another filesystem, where cp -al cannot hardlink', () => {- const r = plan(['--path', '/tmp/deploy-wt-vitest-probe']);+ expect(FOREIGN_FS, 'no mount on this host differs from the checkout').toBeTruthy();+ const r = plan(['--path', path.join(FOREIGN_FS, 'deploy-wt-vitest-probe')]);expect(r.code).toBe(1);expect(r.out).toMatch(/different filesystem/);});@@ -124,9 +137,11 @@ describe('guards (plan mode, writes nothing)', () => {});it('plans without applying by default, and says so', () => {- const r = plan(['--path', '/workspaces/.deploy-wt-vitest-unused']);+ expect(existsSync(UNUSED_TARGET)).toBe(false);+ const r = plan(['--path', UNUSED_TARGET]);expect(r.code).toBe(0);expect(r.out).toMatch(/Plan only\. Re-run with --apply/);for (const a of ARTIFACTS.filter((x) => !x.optional)) expect(r.out).toContain(a.rel);+ expect(existsSync(UNUSED_TARGET)).toBe(false);});});diff --git a/tests/server-api-traversal.test.js b/tests/server-api-traversal.test.jsindex 52b182ecc..e43ec0c1d 100644--- a/tests/server-api-traversal.test.js+++ b/tests/server-api-traversal.test.js@@ -29,7 +29,7 @@ afterAll(() => {describe('api dispatcher rejects path traversal', () => {it('encoded ../ escape to a repo-root .js returns 404, not 200/500', async () => {- // Would resolve to /workspaces/three.ws/vite.config.js and import()+invoke it.+ // Would resolve to <repo root>/vite.config.js and import()+invoke it.const res = await fetch(`${BASE}/api/x%2f..%2f..%2fvite.config`, { redirect: 'manual' });expect(res.status).toBe(404);}, 15000);diff --git a/tests/src/animation-canonical-support.test.js b/tests/src/animation-canonical-support.test.jsindex 44f252cfa..53ae82c3d 100644--- a/tests/src/animation-canonical-support.test.js+++ b/tests/src/animation-canonical-support.test.js@@ -1,27 +1,90 @@import { describe, it, expect } from 'vitest';+import { fileURLToPath } from 'node:url';+import { Bone, BufferGeometry, Group, Object3D, PropertyBinding, Skeleton, SkinnedMesh, Vector3 } from 'three';import { AnimationManager } from '../../src/animation-manager.js';import { CANONICAL_BONES } from '../../src/glb-canonicalize.js';+import { canonicalRestDirectionMapFromObject } from '../../src/animation-retarget.js';+import { CANONICAL_PARENT, CANONICAL_REST_POSITION } from '../../src/animation-canonical-rest.js';+import { loadBoneGraph } from '../_helpers/glb-bone-graph.js';-// AnimationManager.attach() builds a three AnimationMixer over the model but-// only ever reads `.traverse`, `.isSkinnedMesh`, and `.name` for the canonical-// support check — so a lightweight fake tree exercises the logic without-// loading real GLB assets.-function fakeModel(nodes) {- const all = [{ name: 'root' }, ...nodes];- return {- name: 'root',- traverse(cb) {- for (const n of all) cb(n);- },- };+// AnimationManager.attach() is only ever handed a real three.js scene graph (a+// GLTFLoader result), and every rest-frame capture it runs reads that graph's+// world matrices. So these fixtures are real Object3D/Bone/SkinnedMesh graphs,+// laid out on the canonical reference skeleton, never duck-typed stand-ins: a+// plain `{ traverse }` object stopped being a valid model the day attach()+// began measuring limb rest directions (8561d5c5d).++const CZ_GLB = fileURLToPath(new URL('../../public/avatars/cz.glb', import.meta.url));++// Nearest ancestor of `bone` on the canonical skeleton that the fixture+// actually carries, so a partial rig still nests the way a real export does.+function presentParent(bone, present, rename) {+ for (let p = CANONICAL_PARENT[bone]; p; p = CANONICAL_PARENT[p]) {+ if (present.has(p)) return rename(p);+ }+ return null;}-function boneNodes(names, { skinned = true } = {}) {- const nodes = names.map((name) => ({ name }));- if (skinned) nodes.push({ name: 'Body', isSkinnedMesh: true });- return nodes;+/**+ * Build a real bone graph for a set of canonical bones, at the reference rig's+ * bind positions (identity rotations, so world position == authored position).+ *+ * @param {string[]} canonicalNames canonical bones to include+ * @param {object} [opts]+ * @param {(name: string) => string} [opts.rename] node name for a canonical bone+ * @param {boolean} [opts.skinned] bind a SkinnedMesh to the bones+ * @param {(name: string) => number[]} [opts.position] world bind position override+ */+function humanoid(canonicalNames, { rename = (n) => n, skinned = true, position } = {}) {+ const root = new Group();+ root.name = 'root';+ const present = new Set(canonicalNames);+ const nodes = new Map();+ const worldOf = (name) => new Vector3().fromArray(position?.(name) || CANONICAL_REST_POSITION[name]);+ for (const name of canonicalNames) {+ const node = skinned ? new Bone() : new Object3D();+ node.name = rename(name);+ nodes.set(node.name, { node, world: worldOf(name) });+ }+ for (const name of canonicalNames) {+ const { node, world } = nodes.get(rename(name));+ const parentName = presentParent(name, present, rename);+ const parent = parentName ? nodes.get(parentName) : null;+ node.position.copy(parent ? world.clone().sub(parent.world) : world);+ (parent ? parent.node : root).add(node);+ }+ if (skinned) {+ const bones = [...nodes.values()].map((e) => e.node);+ const mesh = new SkinnedMesh(new BufferGeometry());+ mesh.name = 'Body';+ mesh.bind(new Skeleton(bones));+ root.add(mesh);+ }+ root.updateMatrixWorld(true);+ return root;}+// A skinned chain of bones whose names map to no canonical joint.+function creature() {+ const root = new Group();+ let parent = root;+ const bones = [];+ for (const name of ['tail_01', 'tail_02', 'wing_L', 'wing_R', 'jaw']) {+ const bone = new Bone();+ bone.name = name;+ bone.position.set(0, 0.1, 0);+ parent.add(bone);+ bones.push(bone);+ parent = bone;+ }+ const mesh = new SkinnedMesh(new BufferGeometry());+ mesh.bind(new Skeleton(bones));+ root.add(mesh);+ return root;+}++const DEG = 180 / Math.PI;+describe('AnimationManager.supportsCanonicalClips', () => {it('is false before any model is attached', () => {const mgr = new AnimationManager();@@ -30,35 +93,90 @@ describe('AnimationManager.supportsCanonicalClips', () => {it('is true for a skinned humanoid matching the canonical rig', () => {const mgr = new AnimationManager();- mgr.attach(fakeModel(boneNodes(CANONICAL_BONES.slice())));+ mgr.attach(humanoid(CANONICAL_BONES.slice()));expect(mgr.supportsCanonicalClips()).toBe(true);});it('is true for a Mixamo-prefixed humanoid (names canonicalize)', () => {const mgr = new AnimationManager();- const mixamo = CANONICAL_BONES.slice(0, 12).map((b) => `mixamorig:${b}`);- mgr.attach(fakeModel(boneNodes(mixamo)));+ // GLTFLoader sanitizes `mixamorig:Hips` to `mixamorigHips`; mirror it.+ const rename = (b) => PropertyBinding.sanitizeNodeName(`mixamorig:${b}`);+ mgr.attach(humanoid(CANONICAL_BONES.slice(0, 12), { rename }));expect(mgr.supportsCanonicalClips()).toBe(true);});it('is false for a static mesh with no skeleton', () => {const mgr = new AnimationManager();- // Canonical bone *names* present, but nothing is a SkinnedMesh.- mgr.attach(fakeModel(boneNodes(CANONICAL_BONES.slice(), { skinned: false })));+ // Canonical node *names* present, but nothing is a SkinnedMesh.+ mgr.attach(humanoid(CANONICAL_BONES.slice(), { skinned: false }));expect(mgr.supportsCanonicalClips()).toBe(false);});it('is false for a skinned non-humanoid rig (few canonical bones)', () => {const mgr = new AnimationManager();- mgr.attach(fakeModel(boneNodes(['tail_01', 'tail_02', 'wing_L', 'wing_R', 'jaw'])));+ mgr.attach(creature());expect(mgr.supportsCanonicalClips()).toBe(false);});it('resets to false after detach', () => {const mgr = new AnimationManager();- mgr.attach(fakeModel(boneNodes(CANONICAL_BONES.slice())));+ mgr.attach(humanoid(CANONICAL_BONES.slice()));expect(mgr.supportsCanonicalClips()).toBe(true);mgr.detach();expect(mgr.supportsCanonicalClips()).toBe(false);});++ it('attaches the committed cz.glb skeleton and admits it to the clip library', () => {+ const mgr = new AnimationManager();+ const { root } = loadBoneGraph(CZ_GLB);+ mgr.attach(root);+ expect(mgr.supportsCanonicalClips()).toBe(true);+ });+});++// Direct coverage for the rest-direction capture attach() runs on every model.+// It had none, which is how a fixture that could not answer updateMatrixWorld()+// sat red without anyone noticing what the new capture assumed.+describe('canonicalRestDirectionMapFromObject', () => {+ it('reads a T-posed arm as pointing straight out along the side axis', () => {+ const dirs = canonicalRestDirectionMapFromObject(humanoid(CANONICAL_BONES.slice()));+ for (const bone of ['LeftArm', 'LeftForeArm', 'RightArm', 'RightForeArm']) {+ expect(dirs.has(bone)).toBe(true);+ }+ expect(dirs.get('LeftArm').angleTo(new Vector3(1, 0, 0)) * DEG).toBeLessThan(5);+ expect(dirs.get('RightArm').angleTo(new Vector3(-1, 0, 0)) * DEG).toBeLessThan(5);+ expect(dirs.get('LeftUpLeg').y).toBeLessThan(-0.9);+ });++ it('reads an A-posed arm as dropped 45 degrees, which is what the re-aim corrects', () => {+ const shoulder = new Vector3().fromArray(CANONICAL_REST_POSITION.LeftArm);+ const drop = (name) => {+ const p = new Vector3().fromArray(CANONICAL_REST_POSITION[name]);+ if (!['LeftForeArm', 'LeftHand'].includes(name)) return p.toArray();+ const reach = p.x - shoulder.x;+ return [shoulder.x + reach * Math.SQRT1_2, shoulder.y - reach * Math.SQRT1_2, p.z];+ };+ const dirs = canonicalRestDirectionMapFromObject(humanoid(CANONICAL_BONES.slice(), { position: drop }));+ const tilt = dirs.get('LeftArm').angleTo(new Vector3(1, 0, 0)) * DEG;+ expect(tilt).toBeGreaterThan(40);+ expect(tilt).toBeLessThan(50);+ expect(dirs.get('LeftArm').y).toBeLessThan(0);+ });++ it('measures in the model frame, so moving or turning the scene around it changes nothing', () => {+ const model = humanoid(CANONICAL_BONES.slice());+ const still = canonicalRestDirectionMapFromObject(model).get('LeftArm').clone();+ const parent = new Group();+ parent.position.set(4, -2, 7);+ parent.rotation.set(0.3, 1.1, -0.2);+ parent.add(model);+ parent.updateMatrixWorld(true);+ const moved = canonicalRestDirectionMapFromObject(model).get('LeftArm');+ expect(moved.angleTo(still) * DEG).toBeLessThan(0.01);+ });++ it('returns an empty map for a graph with no canonical limbs', () => {+ expect(canonicalRestDirectionMapFromObject(creature()).size).toBe(0);+ expect(canonicalRestDirectionMapFromObject(null).size).toBe(0);+ });});diff --git a/tests/src/usdz-pipeline.test.js b/tests/src/usdz-pipeline.test.jsindex 4d622a8b0..bc494c7c0 100644--- a/tests/src/usdz-pipeline.test.js+++ b/tests/src/usdz-pipeline.test.js@@ -16,7 +16,7 @@import { describe, it, expect, beforeAll } from 'vitest';import { readFileSync } from 'node:fs';-import * as path from 'node:path';+import { resolve } from 'node:path';// jsdom doesn't provide URL.createObjectURL with Blob support — GLTFLoader// uses it for embedded textures. Polyfill enough of it to round-trip blobs@@ -130,7 +130,10 @@ if (typeof HTMLCanvasElement !== 'undefined') {};}-const GLB_PATH = path.resolve('/workspaces/three.ws/public/avatars/cz.glb');+// The committed reference avatar, resolved from this file so the suite runs in+// any checkout, not just the one it was written in. import.meta.url is not a+// file: URL under the jsdom environment; import.meta.dirname is.+const GLB_PATH = resolve(import.meta.dirname, '../../public/avatars/cz.glb');let glbBlobToUsdzBlob;let glbBlobToHalfBodyBlob;diff --git a/tests/vanity-grinder-batch.test.js b/tests/vanity-grinder-batch.test.jsindex 255723cab..a8eda5baf 100644--- a/tests/vanity-grinder-batch.test.js+++ b/tests/vanity-grinder-batch.test.js@@ -22,6 +22,7 @@import { describe, it, expect, beforeAll, afterAll } from 'vitest';import { execFile } from 'node:child_process';+import { createServer } from 'node:http';import { mkdtempSync, rmSync, readFileSync, writeFileSync, existsSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';@@ -283,13 +284,60 @@ describe('GCE MIG shard resolution', () => {expect(new Set(names.map((n) => hashShardIndex(n, 8))).size).toBeGreaterThan(1);});+ // The resolver honours GCE_METADATA_HOST (the override Google's client+ // libraries read), so these run the same on a laptop and on a GCE VM, where+ // the real metadata server would otherwise answer and change the outcome.+ const withMetadataHost = async (host, fn) => {+ const prior = process.env.GCE_METADATA_HOST;+ process.env.GCE_METADATA_HOST = host;+ try {+ return await fn();+ } finally {+ if (prior === undefined) delete process.env.GCE_METADATA_HOST;+ else process.env.GCE_METADATA_HOST = prior;+ }+ };+ const listen = (handler) => new Promise((resolve) => {+ const server = createServer(handler);+ server.listen(0, '127.0.0.1', () => resolve(server));+ });+ const close = (server) => new Promise((resolve) => server.close(resolve));+it('falls back to shard 0 off GCE rather than blocking on the metadata server', async () => {const { resolveGceShardIndex } = await import('../workers/vanity-grinder/gce-shard.mjs');+ // A port nothing listens on: exactly what a non-GCE host's metadata lookup meets.+ const vacant = await listen(() => {});+ const { port } = vacant.address();+ await close(vacant);const t0 = performance.now();- const resolved = await resolveGceShardIndex(4, () => {});+ const resolved = await withMetadataHost(`127.0.0.1:${port}`, () => resolveGceShardIndex(4, () => {}));expect(resolved.source).toBe('unavailable');expect(resolved.index).toBe(0);// The metadata probe is bounded; a hung DNS lookup must not stall a run.expect(performance.now() - t0).toBeLessThan(15_000);});++ it('hashes the instance name on a VM whose instance-group listing is unavailable', async () => {+ const { resolveGceShardIndex, hashShardIndex } = await import('../workers/vanity-grinder/gce-shard.mjs');+ const seen = [];+ // A VM outside any managed group: the metadata server knows its name but+ // has no created-by attribute, so there is no group to list.+ const metadata = await listen((req, res) => {+ seen.push({ url: req.url, flavor: req.headers['metadata-flavor'] });+ if (req.url === '/computeMetadata/v1/instance/name') return res.end('vanity-grinder-q7zk\n');+ res.statusCode = 404;+ res.end('not found');+ });+ try {+ const { port } = metadata.address();+ const logs = [];+ const resolved = await withMetadataHost(`127.0.0.1:${port}`, () => resolveGceShardIndex(4, (m) => logs.push(m)));+ expect(resolved).toEqual({ index: hashShardIndex('vanity-grinder-q7zk', 4), source: 'name-hash', instance: 'vanity-grinder-q7zk' });+ expect(logs.join('\n')).toMatch(/instance-group listing unavailable/);+ expect(seen.map((r) => r.url)).toEqual(['/computeMetadata/v1/instance/name', '/computeMetadata/v1/instance/attributes/created-by']);+ expect(seen.every((r) => r.flavor === 'Google')).toBe(true);+ } finally {+ await close(metadata);+ }+ });});diff --git a/tests/zz-probe.test.js b/tests/zz-probe.test.jsindex 60f8a08af..fcdf10d75 100644--- a/tests/zz-probe.test.js+++ b/tests/zz-probe.test.js@@ -1,7 +1,15 @@import { describe, it, expect } from 'vitest';++// Load-time probe for the Coin Wars combat module: it must import cleanly+// (stylesheet side effect included) and export its CombatSystem class. No other+// test imports src/game/combat-system.js, so this is what catches a load-time+// throw before the play page does. Resolved from this file, never from one+// machine's checkout path.+const COMBAT_SYSTEM = new URL('../src/game/combat-system.js', import.meta.url).href;+describe('import probe', () => {- it('imports combat-system', async () => {- const m = await import('/workspaces/three.ws/src/game/combat-system.js');- expect(typeof m.CombatSystem).toBe('function');- });+ it('imports combat-system', async () => {+ const m = await import(COMBAT_SYSTEM);+ expect(typeof m.CombatSystem).toBe('function');+ });});diff --git a/vitest.config.js b/vitest.config.jsindex 147582a50..f748a4a00 100644--- a/vitest.config.js+++ b/vitest.config.js@@ -1,5 +1,7 @@import { defineConfig } from 'vitest/config';import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';// @three-ws/solana-agent (the symlinked `file:solana-agent-sdk` workspace SDK)// is only ever loaded LAZILY — every importer (api/_lib/agora-human.js,@@ -29,6 +31,30 @@ function externalizeSolanaAgentSdk() {};}+// Same transform-time trap, for a relative specifier: avatar-sdk/src/agent.js+// lazily imports the prebuilt <agent-3d> monolith at avatar-sdk/dist/index.mjs,+// which is gitignored and only exists after `npm run build:lib:full && npm run+// build:avatar-sdk`. Import-analysis resolves that dynamic import when it+// transforms agent.js, so in any checkout that has not run the build (a fresh+// clone, the evolve worktree) tests/avatar-sdk-api.test.js died with "Failed to+// resolve import" before reaching its ensureAgent3D guard, which never loads the+// monolith at all. Externalizing exactly that one edge leaves it to native+// import at runtime: a test that really executes it gets the real module when+// it is built, and a real ERR_MODULE_NOT_FOUND when it is not.+function externalizeAvatarSdkMonolith() {+ const MONOLITH = fileURLToPath(new URL('./avatar-sdk/dist/index.mjs', import.meta.url));+ return {+ name: 'externalize-avatar-sdk-monolith',+ enforce: 'pre',+ resolveId(source, importer) {+ if (!importer || !source.endsWith('/dist/index.mjs')) return null;+ const from = path.dirname(importer.split('?')[0]);+ if (path.resolve(from, source) !== MONOLITH) return null;+ return { id: MONOLITH, external: true };+ },+ };+}+// Cold dynamic `import()` of API handlers that pull in heavy SDKs (@coinbase/x402,// neon-serverless, jsdom, the Solana toolchain, etc.) routinely takes 5–30s on// the first hit in constrained CI/Codespace environments. Individual tests that@@ -48,7 +74,7 @@ const _cpus = Math.max(1, (os.availableParallelism?.() ?? os.cpus().length) - 1)const MAX_FORKS = _cpus <= 3 ? 2 : Math.min(6, _cpus);export default defineConfig({- plugins: [externalizeSolanaAgentSdk()],+ plugins: [externalizeSolanaAgentSdk(), externalizeAvatarSdkMonolith()],// packages/avatar-agent-mcp ships its own nested @grpc/* copies (it is a// standalone publishable package). Without deduping, the package's lazy// `import('@grpc/grpc-js')` resolves to that nested copy while a test'sdiff --git a/workers/vanity-grinder/README.md b/workers/vanity-grinder/README.mdindex 1916f87d8..88833133b 100644--- a/workers/vanity-grinder/README.md+++ b/workers/vanity-grinder/README.md@@ -95,6 +95,7 @@ WALLET_ENCRYPTION_KEY=… TARGETS_FILE=/tmp/targets.json \| `RUNNER` | `local` | `local` / `cloud-run-job` / `gce-spot-mig` || `WRITE_DB` | `0` | `1` to upsert into `vanity_inventory` (needs `DATABASE_URL`) || `SHARD_INDEX` / `SHARD_COUNT` | `0` / `1` | partition targets across parallel instances |+| `GCE_METADATA_HOST` | `metadata.google.internal` | metadata server `host[:port]` the MIG shard resolver reads (the override Google's client libraries honour) |## Shardingdiff --git a/workers/vanity-grinder/gce-shard.mjs b/workers/vanity-grinder/gce-shard.mjsindex 39fb70fb2..e64608be6 100644--- a/workers/vanity-grinder/gce-shard.mjs+++ b/workers/vanity-grinder/gce-shard.mjs@@ -22,7 +22,7 @@// which spreads VMs across shards without coordination (some shards may collide),// and never to the silent all-VMs-on-shard-0 behaviour this replaces.-const METADATA_ROOT = 'http://metadata.google.internal/computeMetadata/v1';+const METADATA_HOST = 'metadata.google.internal';const METADATA_TIMEOUT_MS = 2_000;const API_TIMEOUT_MS = 10_000;@@ -36,6 +36,17 @@ async function fetchWithTimeout(url, init, timeoutMs) {}}+/**+ * Base URL of the metadata server. GCE_METADATA_HOST is the override Google's+ * own client libraries honour (gcp-metadata, google-auth-library): an emulator,+ * a sidecar, or an address that answers nothing, which is how a host that IS a+ * GCE VM can still exercise the off-GCE path. Read per call, not at import.+ */+function metadataRoot() {+ const host = String(process.env.GCE_METADATA_HOST || '').trim() || METADATA_HOST;+ return `http://${host}/computeMetadata/v1`;+}+/*** Read one key from the GCE metadata server.* @param {string} path - path under computeMetadata/v1, e.g. 'instance/name'.@@ -43,7 +54,7 @@ async function fetchWithTimeout(url, init, timeoutMs) {*/async function metadata(path) {const res = await fetchWithTimeout(- `${METADATA_ROOT}/${path}`,+ `${metadataRoot()}/${path}`,{ headers: { 'Metadata-Flavor': 'Google' } },METADATA_TIMEOUT_MS,);