Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: retarget animation clips onto rigged characters with a motion proof (#5893)

Adam Eivyae2c37157196
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index d6ab449de7..9227c19c57 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -14030,6 +14030,14 @@
"server/routes/review.js"
]
},
+ {
+ "method": "GET",
+ "path": "/api/rigging/clips",
+ "mountPath": "/api/rigging",
+ "sources": [
+ "server/routes/rigging.js"
+ ]
+ },
{
"method": "POST",
"path": "/api/rigging/models/:id",
@@ -14038,6 +14046,14 @@
"server/routes/rigging.js"
]
},
+ {
+ "method": "POST",
+ "path": "/api/rigging/models/:id/retarget",
+ "mountPath": "/api/rigging",
+ "sources": [
+ "server/routes/rigging.js"
+ ]
+ },
{
"method": "GET",
"path": "/api/rigging/readiness",
@@ -17481,8 +17497,8 @@
],
"stats": {
"mounts": 147,
- "operations": 2165,
- "declarations": 2173,
+ "operations": 2167,
+ "declarations": 2175,
"sourceFiles": 230
}
}
diff --git a/server/routes/rigging.js b/server/routes/rigging.js
index 00a2bfed2c..8bad1890c8 100644
--- a/server/routes/rigging.js
+++ b/server/routes/rigging.js
@@ -4,7 +4,13 @@ import { asyncHandler } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import { rigImageTo3dModel } from '../services/rigging/autoSkin.js';
import { AUTO_SKIN_DEFAULTS, AUTO_SKIN_LIMITS } from '../services/rigging/autoSkinReport.js';
+import { buildClipCoverage } from '../services/rigging/clipCapabilities.js';
+import { listClipSources } from '../services/rigging/clipLibrary.js';
import { getRiggingReadiness } from '../services/rigging/readiness.js';
+import { retargetImageTo3dModel } from '../services/rigging/retarget.js';
+import {
+ DEFAULT_RETARGET_MODE, RETARGET_DEFAULTS, RETARGET_LIMITS, RETARGET_MODES,
+} from '../services/rigging/retargetReport.js';
import { SKELETON_BONE_MAPPINGS } from '../services/rigging/skeletonMapping.js';
const router = Router();
@@ -33,6 +39,25 @@ const rigRequestSchema = z.object({
const modelIdSchema = z.object({ id: z.string().trim().min(1).max(128) });
+/**
+ * One retarget run. `clip` names a file in the local clip library — `resolveClipSource`
+ * rejects traversal and any extension that is not a clip, so the schema only has to
+ * bound the length. `clipName` selects an animation INSIDE that file and is optional
+ * because a library drop is normally single-clip.
+ *
+ * `mode` defaults to the diagnostic one deliberately: the head-zone cleanup edits skin
+ * weights, so the user gets the measured proposal first and opts into the edit second.
+ */
+const retargetRequestSchema = z.object({
+ clip: z.string().trim().min(1).max(255),
+ clipName: z.string().trim().min(1).max(255).optional(),
+ mode: z.enum(RETARGET_MODES).default(DEFAULT_RETARGET_MODE),
+ headCleanupFraction: z.number()
+ .min(RETARGET_LIMITS.headCleanupFractionMin)
+ .max(RETARGET_LIMITS.headCleanupFractionMax)
+ .optional(),
+});
+
/**
* Whether this host can run character rigging, and — when it cannot — WHY, by a stable
* reason code the client mirrors to a label (`client/src/lib/riggingReasons.js`).
@@ -47,7 +72,24 @@ const modelIdSchema = z.object({ id: z.string().trim().min(1).max(128) });
router.get('/readiness', asyncHandler(async (req, res) => {
const { refresh } = validateRequest(readinessQuerySchema, req.query);
const readiness = await getRiggingReadiness({ refresh: Boolean(refresh) });
- res.json({ ...readiness, defaults: AUTO_SKIN_DEFAULTS, skeletons: Object.keys(SKELETON_BONE_MAPPINGS) });
+ res.json({
+ ...readiness,
+ defaults: AUTO_SKIN_DEFAULTS,
+ retargetDefaults: RETARGET_DEFAULTS,
+ skeletons: Object.keys(SKELETON_BONE_MAPPINGS),
+ });
+}));
+
+/**
+ * The animation clips this install has locally, plus which CoS states they cover.
+ *
+ * Read-only and cheap: clips are user-dropped GLB files (`clipLibrary.js`), so this is a
+ * directory listing, never a download. The coverage answer rides along so a caller sees
+ * what the roster can and cannot drive without re-deriving the vocabulary.
+ */
+router.get('/clips', asyncHandler(async (_req, res) => {
+ const clips = await listClipSources();
+ res.json({ clips, coverage: buildClipCoverage(clips.map((clip) => clip.label)) });
}));
/**
@@ -65,4 +107,18 @@ router.post('/models/:id', asyncHandler(async (req, res) => {
res.json(await rigImageTo3dModel(id, options));
}));
+/**
+ * Retarget one locally-held animation clip onto a model's published rig, publishing the
+ * animated GLB + its report only if the export demonstrably MOVES.
+ *
+ * Explicit user action only, and inline for the same reason the rig route is: the
+ * measured refusal — an incompatible skeleton, a cleanup over its cap, a zero-motion
+ * export — IS the product, and a fire-and-forget 202 would bury it.
+ */
+router.post('/models/:id/retarget', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(modelIdSchema, req.params);
+ const options = validateRequest(retargetRequestSchema, req.body ?? {});
+ res.json(await retargetImageTo3dModel(id, options));
+}));
+
export default router;
diff --git a/server/routes/rigging.test.js b/server/routes/rigging.test.js
new file mode 100644
index 0000000000..16551507b8
--- /dev/null
+++ b/server/routes/rigging.test.js
@@ -0,0 +1,116 @@
+/**
+ * The rigging routes' public boundary.
+ *
+ * The gate arithmetic lives in `retargetReport.test.js` and the publication contract in
+ * `retarget.test.js`; what this suite pins is what only the route decides:
+ *
+ * - the clip roster answers with its CoS-state coverage attached, so a caller does not
+ * re-derive the vocabulary;
+ * - a retarget request with no `clip` is a 400, never a run against an unnamed file;
+ * - `mode` DEFAULTS to the diagnostic one — the head-zone cleanup edits skin weights, so
+ * a request that says nothing must measure rather than write;
+ * - a measured refusal reaches the client as its sentence and its reason code, because
+ * that sentence is the product (a generic 500 would bury it).
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware, ServerError } from '../lib/errorHandler.js';
+
+vi.mock('../services/rigging/readiness.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ // Host-independent: the readiness probe spawns a real Blender import otherwise.
+ getRiggingReadiness: vi.fn(async () => ({ ready: true, reason: null, interpreter: '/opt/envs/rigging/bin/python' })),
+}));
+vi.mock('../services/rigging/clipLibrary.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ listClipSources: vi.fn(async () => []),
+}));
+vi.mock('../services/rigging/autoSkin.js', () => ({ rigImageTo3dModel: vi.fn() }));
+vi.mock('../services/rigging/retarget.js', () => ({ retargetImageTo3dModel: vi.fn() }));
+
+const clipLibrary = await import('../services/rigging/clipLibrary.js');
+const { retargetImageTo3dModel } = await import('../services/rigging/retarget.js');
+const { RETARGET_DEFAULTS } = await import('../services/rigging/retargetReport.js');
+const routes = (await import('./rigging.js')).default;
+
+const makeApp = () => {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/rigging', routes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+beforeEach(() => { vi.clearAllMocks(); });
+
+describe('rigging routes', () => {
+ it('GET /readiness carries the retarget defaults so the client labels its own overrides', async () => {
+ const res = await request(makeApp()).get('/api/rigging/readiness');
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ ready: true, retargetDefaults: RETARGET_DEFAULTS });
+ });
+
+ it('GET /clips answers the local roster with its CoS-state coverage attached', async () => {
+ clipLibrary.listClipSources.mockResolvedValueOnce([
+ { filename: 'Idle.glb', label: 'Idle', path: '/clips/Idle.glb', sizeBytes: 12, updatedAt: '2026-01-02T00:00:00.000Z' },
+ ]);
+ const res = await request(makeApp()).get('/api/rigging/clips');
+ expect(res.status).toBe(200);
+ expect(res.body.clips).toHaveLength(1);
+ expect(res.body.coverage).toMatchObject({
+ complete: false,
+ coverageByState: expect.objectContaining({ thinking: { covered: true, clip: 'Idle' } }),
+ });
+ });
+
+ it('GET /clips reports an empty roster as empty rather than as a missing answer', async () => {
+ const res = await request(makeApp()).get('/api/rigging/clips');
+ expect(res.status).toBe(200);
+ expect(res.body).toMatchObject({ clips: [], coverage: { complete: false } });
+ });
+
+ it('POST /models/:id/retarget defaults to diagnostic mode, so nothing is rewritten unasked', async () => {
+ retargetImageTo3dModel.mockResolvedValueOnce({ id: 'image3d-example' });
+ const res = await request(makeApp())
+ .post('/api/rigging/models/image3d-example/retarget').send({ clip: 'Walk.glb' });
+ expect(res.status).toBe(200);
+ expect(retargetImageTo3dModel).toHaveBeenCalledWith('image3d-example', { clip: 'Walk.glb', mode: 'diagnostic' });
+ });
+
+ it('POST /models/:id/retarget passes an explicit write mode and cleanup cap through', async () => {
+ retargetImageTo3dModel.mockResolvedValueOnce({ id: 'image3d-example' });
+ await request(makeApp()).post('/api/rigging/models/image3d-example/retarget').send({
+ clip: 'Walk.glb', clipName: 'Walk', mode: 'write', headCleanupFraction: 0.01,
+ });
+ expect(retargetImageTo3dModel).toHaveBeenCalledWith('image3d-example', {
+ clip: 'Walk.glb', clipName: 'Walk', mode: 'write', headCleanupFraction: 0.01,
+ });
+ });
+
+ it('POST /models/:id/retarget rejects a missing clip, an unknown mode, and an out-of-range cap', async () => {
+ const bodies = [
+ {},
+ { clip: 'Walk.glb', mode: 'overwrite-everything' },
+ { clip: 'Walk.glb', headCleanupFraction: 0.9 },
+ ];
+ for (const body of bodies) {
+ const res = await request(makeApp()).post('/api/rigging/models/image3d-example/retarget').send(body);
+ expect(res.status).toBe(400);
+ }
+ expect(retargetImageTo3dModel).not.toHaveBeenCalled();
+ });
+
+ it('POST /models/:id/retarget surfaces a measured refusal as its sentence and reason code', async () => {
+ retargetImageTo3dModel.mockRejectedValueOnce(new ServerError(
+ 'The exported animation never moves: across 8 sampled frames no joint moved more than 0.00e+0 units.',
+ { status: 422, code: 'RIGGING_RETARGET_GATE_FAILED', context: { reason: 'no-motion' } },
+ ));
+ const res = await request(makeApp())
+ .post('/api/rigging/models/image3d-example/retarget').send({ clip: 'Walk.glb' });
+ expect(res.status).toBe(422);
+ expect(res.body.error).toContain('never moves');
+ expect(res.body.code).toBe('RIGGING_RETARGET_GATE_FAILED');
+ });
+});
diff --git a/server/services/backup.js b/server/services/backup.js
index 14d24cba0b..dd1b137546 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -130,6 +130,12 @@ export const DEFAULT_EXCLUDES = [
// a provisioned Blender runtime the restore target may not have, and a rigged GLB is
// megabytes, not the gigabyte-per-render the model.obj sidecar below costs.
{ path: '/image-to-3d/*/rig/.staging/', reason: 'In-flight auto-skin staging directory — scratch for one rigging run, removed when it publishes or fails. The published rig/<rigId>/ pair IS backed up.', overridable: false },
+ // Anchored, like every entry here. Same contract one step later: scratch for ONE
+ // in-flight retarget run (services/rigging/retarget.js), including the probe pass's
+ // job/report files. The PUBLISHED animation (retarget/<retargetId>/) is NOT excluded,
+ // for the same reason the rig is not — re-deriving it needs both a Blender runtime and
+ // the clip file the run used.
+ { path: '/image-to-3d/*/retarget/.staging/', reason: 'In-flight retarget staging directory — scratch for one retarget run, removed when it publishes or fails. The published retarget/<retargetId>/ pair IS backed up.', overridable: false },
{ path: '/image-to-3d/*/model.obj', reason: 'TRELLIS.2 full-resolution mesh sidecar — ~1 GB per render, regenerable by re-rendering at the same seed. The exported model.glb and keyed source ARE backed up.', overridable: true },
// Anchored, like every entry here. Not overridable: these are another
// machine's conditioning bytes, staged for one federated render and swept on
diff --git a/server/services/rigging/autoSkin.js b/server/services/rigging/autoSkin.js
index 6a9f385ae5..a3984c543d 100644
--- a/server/services/rigging/autoSkin.js
+++ b/server/services/rigging/autoSkin.js
@@ -35,10 +35,9 @@
*/
import { randomUUID } from 'node:crypto';
-import { join } from 'node:path';
+import { basename, join } from 'node:path';
import { rm, stat } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
-import { spawn } from '../../lib/childProcess.js';
import { ServerError } from '../../lib/errorHandler.js';
import { atomicWrite, ensureDir, PATHS, readJSONFile, sha256File } from '../../lib/fileUtils.js';
import { moveWithoutReplace } from '../../lib/noReplaceMove.js';
@@ -50,9 +49,9 @@ import {
summarizeAutoSkin,
thresholdsForWorker,
} from './autoSkinReport.js';
-import { getRiggingReadiness, riggingReasonLabel } from './readiness.js';
-import { resolveRiggingPython } from './runtime.js';
+import { requireRiggingInterpreter } from './readiness.js';
import { buildHumanoidArmatureSpec } from './skeletonMapping.js';
+import { runRiggingWorker } from './workerProcess.js';
import { getModel, mutateModel } from '../imageTo3d/db.js';
/** Per-record directory holding every rig run's published pair. */
@@ -62,9 +61,6 @@ export const RIG_STAGING_DIR_NAME = '.staging';
export const RIGGED_GLB_NAME = 'character.rigged.glb';
export const RIG_REPORT_NAME = 'character.rig.json';
-/** A rig is minutes of CPU, not hours; past this the worker is wedged, not working. */
-const WORKER_TIMEOUT_MS = 20 * 60 * 1000;
-
const WORKER_SCRIPT = fileURLToPath(new URL('./autoSkinWorker.py', import.meta.url));
/**
@@ -113,7 +109,10 @@ export async function publishRigArtifacts({ paths, report }) {
await atomicWrite(paths.stagedReport, JSON.stringify({
...report,
report_version: AUTO_SKIN_REPORT_VERSION,
- output_file: RIGGED_GLB_NAME,
+ // Named from the path actually being published, not from a constant: the retarget
+ // lane publishes a differently-named GLB through this same helper, and the reader
+ // below resolves the artifact from this key rather than guessing a filename.
+ output_file: basename(paths.publishedGlb),
output_bytes: info.size,
output_sha256: sha256,
}, null, 2));
@@ -138,9 +137,12 @@ export async function publishRigArtifacts({ paths, report }) {
* @returns {Promise<{ok: boolean, reason?: string, report?: object, glbPath?: string}>}
*/
export async function readRiggedArtifact({ publishDir }) {
- const glbPath = join(publishDir, RIGGED_GLB_NAME);
const report = await readJSONFile(join(publishDir, RIG_REPORT_NAME), null, { logError: false });
if (!report || typeof report.output_sha256 !== 'string') return { ok: false, reason: 'missing-report' };
+ // The report names its own artifact, so one reader serves both the auto-skin and the
+ // retarget lane. `basename` because the report is a file on disk: a report carrying a
+ // traversing `output_file` must resolve inside the publish dir or not at all.
+ const glbPath = join(publishDir, basename(String(report.output_file || RIGGED_GLB_NAME)));
const exists = await stat(glbPath).then((info) => info.isFile(), () => false);
if (!exists) return { ok: false, reason: 'missing-glb' };
const digest = await sha256File(glbPath);
@@ -148,28 +150,6 @@ export async function readRiggedArtifact({ publishDir }) {
return { ok: true, report, glbPath };
}
-/**
- * Run the Blender worker to completion. Resolves with the exit code and a bounded tail
- * of its output — never rejects on a non-zero exit, so the caller owns the vocabulary
- * of failure rather than inheriting "exited 1".
- */
-function runWorker({ python, jobFile, spawnImpl = spawn, timeoutMs = WORKER_TIMEOUT_MS }) {
- return new Promise((resolve) => {
- const child = spawnImpl(python, [WORKER_SCRIPT, '--job', jobFile], {});
- let tail = '';
- const collect = (buf) => { tail = `${tail}${buf}`.slice(-4000); };
- child.stdout?.on('data', collect);
- child.stderr?.on('data', collect);
- const timer = setTimeout(() => {
- tail = `${tail}\nRigging worker exceeded ${Math.round(timeoutMs / 60000)} minutes and was terminated.`;
- child.kill?.('SIGTERM');
- }, timeoutMs);
- if (typeof timer.unref === 'function') timer.unref();
- child.on('error', (error) => { clearTimeout(timer); resolve({ code: -1, tail: `${tail}\n${error.message}` }); });
- child.on('close', (code) => { clearTimeout(timer); resolve({ code, tail: tail.trim() }); });
- });
-}
-
const rigError = (message, code, extra = {}) => new ServerError(message, { status: 422, code, ...extra });
/**
@@ -194,20 +174,7 @@ export async function runAutoSkin({
timeoutMs,
verify = readRiggedArtifact,
}) {
- const ready = readiness ?? await getRiggingReadiness();
- if (!ready.ready) {
- throw new ServerError(riggingReasonLabel(ready.reason), {
- status: 409,
- code: 'RIGGING_RUNTIME_UNAVAILABLE',
- context: { reason: ready.reason, detail: ready.detail },
- });
- }
- const interpreter = python ?? ready.interpreter ?? resolveRiggingPython();
- if (!interpreter) {
- throw new ServerError(riggingReasonLabel('runtime-not-installed'), {
- status: 409, code: 'RIGGING_RUNTIME_UNAVAILABLE', context: { reason: 'runtime-not-installed' },
- });
- }
+ const interpreter = await requireRiggingInterpreter({ readiness, python });
const thresholds = resolveAutoSkinThresholds(overrides);
const paths = rigRunPaths({ recordDir, rigId });
@@ -224,7 +191,9 @@ export async function runAutoSkin({
armature: buildHumanoidArmatureSpec({ skeletonHint }),
}, null, 2));
- const { code, tail } = await runWorker({ python: interpreter, jobFile: paths.jobFile, spawnImpl, timeoutMs });
+ const { code, tail } = await runRiggingWorker({
+ python: interpreter, script: WORKER_SCRIPT, jobFile: paths.jobFile, spawnImpl, timeoutMs,
+ });
const report = await readJSONFile(paths.workerReport, null, { logError: false });
// A non-zero exit with a readable report is the EXPECTED gate failure: the worker
diff --git a/server/services/rigging/readiness.js b/server/services/rigging/readiness.js
index 8f2d825e0c..bb2d1b4849 100644
--- a/server/services/rigging/readiness.js
+++ b/server/services/rigging/readiness.js
@@ -16,6 +16,7 @@
* unsupported host — is unit-testable with no real install.
*/
+import { ServerError } from '../../lib/errorHandler.js';
import {
RIGGING_INSTALL_COMMAND,
RIGGING_MODULE_REQUIREMENT,
@@ -178,3 +179,32 @@ export async function getRiggingReadiness({ refresh = false, now = Date.now, pro
console.log(`🦴 Rigging readiness: ${value.ready ? 'ready' : value.reason}`);
return value;
}
+
+/**
+ * The interpreter a rigging run may spawn, or a named 409 explaining why it may not.
+ *
+ * Both worker lanes (`autoSkin.js`, `retarget.js`) open with exactly this check, and it
+ * fails CLOSED twice: once on the readiness verdict, and once on an answer that claims
+ * ready without naming an interpreter. `readiness` is injectable so a run can reuse an
+ * answer it already has (and so tests need no Blender install).
+ *
+ * @param {{readiness?: object, python?: string|null}} [opts]
+ * @returns {Promise<string>} The interpreter path.
+ */
+export async function requireRiggingInterpreter({ readiness, python } = {}) {
+ const ready = readiness ?? await getRiggingReadiness();
+ if (!ready.ready) {
+ throw new ServerError(riggingReasonLabel(ready.reason), {
+ status: 409,
+ code: 'RIGGING_RUNTIME_UNAVAILABLE',
+ context: { reason: ready.reason, detail: ready.detail },
+ });
+ }
+ const interpreter = python ?? ready.interpreter ?? resolveRiggingPython();
+ if (!interpreter) {
+ throw new ServerError(riggingReasonLabel('runtime-not-installed'), {
+ status: 409, code: 'RIGGING_RUNTIME_UNAVAILABLE', context: { reason: 'runtime-not-installed' },
+ });
+ }
+ return interpreter;
+}
diff --git a/server/services/rigging/retarget.js b/server/services/rigging/retarget.js
new file mode 100644
index 0000000000..16a84373e0
--- /dev/null
+++ b/server/services/rigging/retarget.js
@@ -0,0 +1,404 @@
+/**
+ * Character rigging — retarget orchestration, and the motion proof.
+ *
+ * Phase 2 (`autoSkin.js`) publishes a rigged character only when its weights measured
+ * up. This module is the next step: it applies a user-supplied animation clip to that
+ * published rig and refuses to publish the result unless the exported file demonstrably
+ * MOVES. "The exporter returned" is not evidence — a GLB with no animation, or with one
+ * that holds a single pose, is exactly what a silently-failed retarget produces, and it
+ * looks identical to a working one until somebody plays it.
+ *
+ * ## The two-pass worker, and why the mapping is not in Python
+ *
+ * The skeleton compatibility contract lives in `skeletonMapping.js` (`reduceBoneMapping`,
+ * shipped by #5892) and is deliberately ALL-OR-NOTHING: every animated source bone must
+ * be understood and present on the target, or the retarget is refused. Enforcing that
+ * inside the Blender worker would mean a second copy of the bone tables in Python, free
+ * to drift from the one the rest of the app uses. So the worker runs twice:
+ *
+ * 1. **`probe`** — read-only. Opens the clip and the rigged GLB, reports the animated
+ * bone names, the clip roster, the target bone names, and the mesh's vertex count.
+ * Exports nothing.
+ * 2. **`apply`** — receives the EXPLICIT source→target bone mapping this module derived
+ * from the probe, does the head-zone cleanup, retargets, exports, and re-imports.
+ *
+ * The cost is one extra Blender startup. What it buys is that "unsupported or partial
+ * skeleton" fails before an exporter is ever opened, rather than after a partial
+ * retarget has already been written somewhere.
+ *
+ * ## Publication
+ *
+ * Identical to Phase 2 and reusing its helpers: GLB first, report last, no-replace
+ * moves, and a read-back through the same reader every consumer uses. The report is the
+ * Phase 2 report EXTENDED (`retargetReport.js`), not a second format. The source rig is
+ * opened read-only and never rewritten — a retarget is a new `retarget/<retargetId>/`
+ * directory, so re-running one never mutates a published pair.
+ *
+ * Child-process boundary outside the request lifecycle, so the worker's outcomes flow
+ * through a resolved promise and a thrown `ServerError` here — never a throw from inside
+ * a spawn callback (AGENTS.md).
+ */
+
+import { randomUUID } from 'node:crypto';
+import { basename, join } from 'node:path';
+import { rm, stat } from 'node:fs/promises';
+import { fileURLToPath } from 'node:url';
+import { ServerError } from '../../lib/errorHandler.js';
+import { atomicWrite, ensureDir, PATHS, readJSONFile } from '../../lib/fileUtils.js';
+import {
+ publishRigArtifacts,
+ readRiggedArtifact,
+ rigRunPaths,
+ RIG_REPORT_NAME,
+ RIG_STAGING_DIR_NAME,
+} from './autoSkin.js';
+import { resolveClipSource } from './clipLibrary.js';
+import { requireRiggingInterpreter } from './readiness.js';
+import {
+ DEFAULT_RETARGET_MODE,
+ describeRetargetFailure,
+ reduceRetargetGate,
+ resolveRetargetThresholds,
+ RETARGET_REPORT_KIND,
+ summarizeRetarget,
+ thresholdsForRetargetWorker,
+} from './retargetReport.js';
+import { reduceBoneMapping, SKELETON_BONE_MAPPINGS } from './skeletonMapping.js';
+import { runRiggingWorker } from './workerProcess.js';
+import { getModel, mutateModel } from '../imageTo3d/db.js';
+
+/** Per-record directory holding every retarget run's published pair. */
+export const RETARGET_DIR_NAME = 'retarget';
+export const RETARGETED_GLB_NAME = 'character.animated.glb';
+
+const WORKER_SCRIPT = fileURLToPath(new URL('./retargetWorker.py', import.meta.url));
+
+/**
+ * The joints the head-zone cleanup is allowed to re-bind TO. Everything above the neck
+ * belongs to the head/neck chain; the cleanup never invents a third destination.
+ */
+const HEAD_ZONE_JOINTS = Object.freeze(['neck', 'head']);
+
+/**
+ * Every path one retarget run touches, derived from the record id and the run id alone —
+ * pure, so the publication tests can point it at a real temp dir.
+ *
+ * @param {{recordDir: string, retargetId: string}} opts
+ */
+export function retargetRunPaths({ recordDir, retargetId }) {
+ const retargetRoot = join(recordDir, RETARGET_DIR_NAME);
+ const publishDir = join(retargetRoot, retargetId);
+ const stageDir = join(retargetRoot, RIG_STAGING_DIR_NAME, retargetId);
+ return {
+ retargetRoot,
+ publishDir,
+ stageDir,
+ stagedGlb: join(stageDir, RETARGETED_GLB_NAME),
+ stagedReport: join(stageDir, RIG_REPORT_NAME),
+ probeJobFile: join(stageDir, 'probe-job.json'),
+ probeReport: join(stageDir, 'probe-report.json'),
+ jobFile: join(stageDir, 'job.json'),
+ workerReport: join(stageDir, 'worker-report.json'),
+ publishedGlb: join(publishDir, RETARGETED_GLB_NAME),
+ publishedReport: join(publishDir, RIG_REPORT_NAME),
+ };
+}
+
+/** The served URL for a published retarget (static-mounted under `/data`). */
+export const retargetedAssetUrl = (modelId, retargetId) => `/data/image-to-3d/${modelId}/${RETARGET_DIR_NAME}/${retargetId}/${RETARGETED_GLB_NAME}`;
+
+const retargetError = (message, code, extra = {}) => new ServerError(message, { status: 422, code, ...extra });
+
+/**
+ * The bone names the head-zone cleanup treats as the zone, for the convention the rig
+ * was actually built with. Names stay owned by `skeletonMapping.js` — the worker is
+ * told which bones to look at, never asked to recognize them.
+ */
+const headZoneBones = (skeletonHint) => HEAD_ZONE_JOINTS
+ .map((joint) => SKELETON_BONE_MAPPINGS[skeletonHint]?.[joint])
+ .filter(Boolean);
+
+/**
+ * Pick the clip to apply out of the probe's roster.
+ *
+ * An explicit request wins; otherwise the first clip in the file is used, because a
+ * single-clip GLB (what a clip library drop almost always is) should not require the
+ * user to type its internal name. A requested clip the file does not contain is an
+ * error, never a silent fall back to a different animation.
+ *
+ * @param {Array<{name: string}>} clips
+ * @param {string|null} requested
+ * @returns {{ok: true, clip: object}|{ok: false, available: string[]}}
+ */
+export function selectClip(clips, requested) {
+ const roster = (Array.isArray(clips) ? clips : []).filter((clip) => typeof clip?.name === 'string' && clip.name);
+ const available = roster.map((clip) => clip.name);
+ if (!requested) return roster.length ? { ok: true, clip: roster[0] } : { ok: false, available };
+ const match = roster.find((clip) => clip.name === requested);
+ return match ? { ok: true, clip: match } : { ok: false, available };
+}
+
+/**
+ * Run the probe pass and derive the strict bone mapping from it. Throws a named 422
+ * rather than returning a partial mapping — a caller must not be able to proceed with
+ * "most of" a skeleton.
+ */
+async function probeAndMap({ interpreter, paths, clipPath, rigGlb, skeletonHint, clipName, spawnImpl, timeoutMs }) {
+ await atomicWrite(paths.probeJobFile, JSON.stringify({
+ pass: 'probe',
+ clip_glb: clipPath,
+ rig_glb: rigGlb,
+ report_path: paths.probeReport,
+ }, null, 2));
+
+ const { code, tail } = await runRiggingWorker({
+ python: interpreter, script: WORKER_SCRIPT, jobFile: paths.probeJobFile, spawnImpl, timeoutMs,
+ });
+ const probe = await readJSONFile(paths.probeReport, null, { logError: false });
+ if (code !== 0 || !probe) {
+ throw retargetError(
+ `The retarget worker could not read the clip and the rig (exit ${code}).${tail ? ` Last output: ${tail.slice(-400)}` : ''}`,
+ 'RIGGING_CLIP_UNREADABLE',
+ );
+ }
+
+ const selected = selectClip(probe.clips, clipName);
+ if (!selected.ok) {
+ throw retargetError(
+ clipName
+ ? `That clip file has no animation named "${clipName}"${selected.available.length ? ` (it has: ${selected.available.join(', ')})` : ' — it has no animations at all'}.`
+ : 'That clip file carries no animation to retarget.',
+ 'RIGGING_CLIP_NOT_FOUND',
+ { context: { available: selected.available } },
+ );
+ }
+
+ const mapping = reduceBoneMapping({
+ sourceBones: probe.clip_bones,
+ targetBones: probe.rig_bones,
+ skeletonHint,
+ });
+ if (!mapping.ok) {
+ // Refused BEFORE the apply pass exists — no exporter has been opened, so there is no
+ // partial retarget anywhere on disk to clean up or to mistake for a finished one.
+ throw retargetError(
+ mapping.reason === 'unrecognized-skeleton'
+ ? `This character is rigged to an unrecognized convention, so no clip bone could be matched.`
+ : `The clip and this character do not share a complete skeleton: ${mapping.unmappedBones.length} `
+ + `bone${mapping.unmappedBones.length === 1 ? '' : 's'} could not be matched `
+ + `(${mapping.unmappedBones.slice(0, 5).join(', ')}${mapping.unmappedBones.length > 5 ? ', …' : ''}).`,
+ 'RIGGING_SKELETON_INCOMPATIBLE',
+ { context: { reason: mapping.reason, unmappedBones: mapping.unmappedBones } },
+ );
+ }
+ return { mapping, clip: selected.clip };
+}
+
+/**
+ * Retarget one clip onto one published rig: probe, map, stage, spawn, gate, publish.
+ * Every path is injectable so the whole contract is exercisable against a real temp dir
+ * and a fake worker.
+ *
+ * @param {{modelId: string, recordDir: string, rigId: string, clipPath: string,
+ * clipName?: string|null, skeletonHint?: string, mode?: string, overrides?: object,
+ * readiness?: object, python?: string|null, spawnImpl?: Function,
+ * retargetId?: string, timeoutMs?: number, verify?: Function}} opts
+ * @returns {Promise<object>}
+ */
+export async function runRetarget({
+ modelId,
+ recordDir,
+ rigId,
+ clipPath,
+ clipName = null,
+ skeletonHint = 'mixamo',
+ mode = DEFAULT_RETARGET_MODE,
+ overrides = {},
+ readiness,
+ python,
+ spawnImpl,
+ retargetId = `retarget-${randomUUID()}`,
+ timeoutMs,
+ verify = readRiggedArtifact,
+}) {
+ const interpreter = await requireRiggingInterpreter({ readiness, python });
+
+ // The source rig is read through the SAME reader every consumer uses. A half-published
+ // or digest-mismatched pair is not a rig, and animating one would launder an
+ // interrupted run into a finished-looking character.
+ const source = await verify({ publishDir: rigRunPaths({ recordDir, rigId }).publishDir });
+ if (!source.ok) {
+ throw retargetError(`This character's rig is not readable (${source.reason}). Re-rig it before animating it.`,
+ 'RIGGING_NO_SOURCE_RIG', { context: { reason: source.reason } });
+ }
+ const clipExists = await stat(clipPath).then((info) => info.isFile(), () => false);
+ if (!clipExists) throw retargetError('That animation clip is no longer in the clip library.', 'RIGGING_CLIP_NOT_FOUND');
+
+ const thresholds = resolveRetargetThresholds(overrides);
+ const paths = retargetRunPaths({ recordDir, retargetId });
+ await ensureDir(paths.stageDir);
+ try {
+ const { mapping, clip } = await probeAndMap({
+ interpreter, paths, clipPath, rigGlb: source.glbPath, skeletonHint, clipName, spawnImpl, timeoutMs,
+ });
+
+ await atomicWrite(paths.jobFile, JSON.stringify({
+ pass: 'apply',
+ clip_glb: clipPath,
+ rig_glb: source.glbPath,
+ output_glb: paths.stagedGlb,
+ report_path: paths.workerReport,
+ clip_name: clip.name,
+ mode,
+ skeleton_hint: mapping.skeletonHint,
+ head_zone_bones: headZoneBones(mapping.skeletonHint),
+ bone_mapping: mapping.mappings.map(({ sourceBone, targetBone }) => ({ source: sourceBone, target: targetBone })),
+ thresholds: thresholdsForRetargetWorker(thresholds),
+ }, null, 2));
+
+ const { code, tail } = await runRiggingWorker({
+ python: interpreter, script: WORKER_SCRIPT, jobFile: paths.jobFile, spawnImpl, timeoutMs,
+ });
+ const report = await readJSONFile(paths.workerReport, null, { logError: false });
+
+ // A non-zero exit with a readable report is the EXPECTED gate failure: the worker
+ // measured, refused, and said why. Prefer that measured answer over the exit code.
+ const gate = report ? reduceRetargetGate(report, { thresholds, mode }) : null;
+ if (gate && !gate.ok) {
+ throw retargetError(describeRetargetFailure(gate.reason, gate.metrics), 'RIGGING_RETARGET_GATE_FAILED', {
+ context: { reason: gate.reason, metrics: gate.metrics },
+ });
+ }
+ if (code !== 0 || !report) {
+ throw retargetError(
+ `The retarget worker exited ${code} without a usable report.${tail ? ` Last output: ${tail.slice(-400)}` : ''}`,
+ 'RIGGING_WORKER_FAILED',
+ );
+ }
+ const staged = await stat(paths.stagedGlb).then((info) => info.isFile(), () => false);
+ if (!staged) throw retargetError('The retarget worker reported success but exported no file.', 'RIGGING_NO_OUTPUT');
+
+ const published = await publishRigArtifacts({
+ paths,
+ report: { ...report, kind: RETARGET_REPORT_KIND, source_rig_id: rigId, source_clip: basename(clipPath) },
+ });
+ // Read the pair back through the same reader every consumer uses, before recording
+ // the retarget as ready. A publish that does not verify is exactly the interrupted
+ // state this contract exists to make detectable.
+ const verified = await verify({ publishDir: paths.publishDir });
+ if (!verified.ok) {
+ throw retargetError(`The animation published but did not verify (${verified.reason}).`, 'RIGGING_PUBLISH_UNVERIFIED');
+ }
+ const summary = summarizeRetarget(gate.metrics);
+ console.log(`🎞️ Retargeted ${modelId} as ${retargetId}: clip ${summary.clip}, ${summary.mappedBones} bones mapped, `
+ + `${summary.changedCleanupVertices}/${summary.cleanupCapVertices} cleanup vertices in ${mode} mode`);
+ return {
+ retargetId,
+ rigId,
+ clip: summary.clip,
+ mode,
+ assetPath: retargetedAssetUrl(modelId, retargetId),
+ reportPath: published.reportPath,
+ sha256: published.sha256,
+ bytes: published.bytes,
+ summary,
+ report,
+ };
+ } finally {
+ // Scratch only — the published pair lives in a sibling directory, so a failed run
+ // leaves nothing behind and a successful one leaves only what it published.
+ await rm(paths.stageDir, { recursive: true, force: true }).catch(() => {});
+ }
+}
+
+// One retarget per record at a time. A double-click would otherwise put two Blender
+// processes on the same rig — a re-entrancy guard, not a multi-actor lock
+// (AGENTS.md single-user trust model).
+const retargetsInFlight = new Set();
+
+/**
+ * Retarget a clip onto a stored image-to-3D record's published rig and persist the
+ * result on it. The record's `retarget` field is the user-visible evidence: on success
+ * the published pair plus the measured summary, on failure the reason and the sentence
+ * naming the number that failed.
+ *
+ * @param {string} modelId
+ * @param {{clip: string, clipName?: string, mode?: string, headCleanupFraction?: number}} options
+ * @param {object} [deps] Injectable seams (`run`, `now`, `resolveClip`) for tests.
+ * @returns {Promise<object>} The updated record.
+ */
+export async function retargetImageTo3dModel(modelId, options = {}, {
+ run = runRetarget,
+ now = () => new Date().toISOString(),
+ resolveClip = resolveClipSource,
+} = {}) {
+ const model = await getModel(modelId);
+ if (!model) throw new ServerError('Image-to-3D model not found', { status: 404, code: 'NOT_FOUND' });
+ if (model.rig?.status !== 'ready' || !model.rig?.rigId) {
+ throw retargetError('Rig this model before animating it.', 'RIGGING_NO_SOURCE_RIG');
+ }
+ const clipPath = resolveClip(options.clip);
+ if (!clipPath) {
+ throw retargetError('That animation clip is not in the clip library.', 'RIGGING_CLIP_NOT_FOUND');
+ }
+ if (retargetsInFlight.has(modelId)) {
+ throw new ServerError('This model is already being animated.', { status: 409, code: 'RIGGING_IN_FLIGHT' });
+ }
+
+ const mode = options.mode || DEFAULT_RETARGET_MODE;
+ retargetsInFlight.add(modelId);
+ const startedAt = now();
+ await mutateModel(modelId, (current) => ({
+ ...current,
+ retarget: { ...(current.retarget || {}), status: 'retargeting', startedAt, error: null, reason: null },
+ }));
+ try {
+ const result = await run({
+ modelId,
+ recordDir: join(PATHS.imageTo3d, modelId),
+ rigId: model.rig.rigId,
+ clipPath,
+ clipName: options.clipName || null,
+ skeletonHint: model.rig.skeletonHint || 'mixamo',
+ mode,
+ overrides: options,
+ });
+ return await mutateModel(modelId, (current) => ({
+ ...current,
+ retarget: {
+ status: 'ready',
+ retargetId: result.retargetId,
+ rigId: result.rigId,
+ clipFile: basename(clipPath),
+ clip: result.clip,
+ mode,
+ assetPath: result.assetPath,
+ sha256: result.sha256,
+ bytes: result.bytes,
+ summary: result.summary,
+ error: null,
+ reason: null,
+ startedAt,
+ completedAt: now(),
+ },
+ }));
+ } catch (error) {
+ await mutateModel(modelId, (current) => ({
+ ...current,
+ retarget: {
+ ...(current.retarget || {}),
+ status: 'failed',
+ clipFile: basename(clipPath),
+ mode,
+ error: String(error?.message || error).slice(0, 2_000),
+ reason: error?.context?.reason || error?.code || null,
+ metrics: error?.context?.metrics || null,
+ startedAt,
+ completedAt: now(),
+ },
+ })).catch(() => {});
+ throw error;
+ } finally {
+ retargetsInFlight.delete(modelId);
+ }
+}
diff --git a/server/services/rigging/retarget.test.js b/server/services/rigging/retarget.test.js
new file mode 100644
index 0000000000..467d6e5292
--- /dev/null
+++ b/server/services/rigging/retarget.test.js
@@ -0,0 +1,242 @@
+/**
+ * The retarget orchestration contract, against a REAL temp directory.
+ *
+ * The gate arithmetic is covered by `retargetReport.test.js`; what is tested here is the
+ * half only a filesystem and a two-pass spawn can prove:
+ *
+ * - a partial skeleton is refused after the read-only PROBE pass, so the apply pass —
+ * the only one that can write a file — is never spawned at all;
+ * - a run that fails its gate publishes NEITHER artifact and leaves no staging behind;
+ * - the published pair is the animated GLB named by its own report, read back through
+ * the same reader every consumer uses;
+ * - the source rig is opened read-only and never rewritten.
+ *
+ * Blender is not installed on CI (or on most dev hosts), so the worker is a fake that
+ * writes the files a real one would and records which passes it was asked for. That is
+ * the point of the design: the contract is about what lands on disk and in what order,
+ * not about what Blender did.
+ */
+
+import { EventEmitter } from 'node:events';
+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
+import { existsSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('../imageTo3d/db.js', () => ({ getModel: vi.fn(), mutateModel: vi.fn() }));
+
+const { publishRigArtifacts, readRiggedArtifact, rigRunPaths } = await import('./autoSkin.js');
+const { RETARGET_DEFAULTS, thresholdsForRetargetWorker } = await import('./retargetReport.js');
+const { retargetRunPaths, runRetarget, RETARGETED_GLB_NAME, selectClip } = await import('./retarget.js');
+const { SKELETON_BONE_MAPPINGS } = await import('./skeletonMapping.js');
+
+const READY = { ready: true, reason: null, interpreter: '/opt/envs/rigging/bin/python' };
+const RIG_ID = 'rig-example';
+const RETARGET_ID = 'retarget-example';
+const MIXAMO_BONES = Object.values(SKELETON_BONE_MAPPINGS.mixamo);
+
+const cleanProbe = (overrides = {}) => ({
+ clips: [{ name: 'Walk', duration: 1.25 }],
+ clip_bones: MIXAMO_BONES,
+ rig_bones: MIXAMO_BONES,
+ vertices: 10_000,
+ ...overrides,
+});
+
+const cleanReport = (overrides = {}) => ({
+ report_version: 1,
+ kind: 'retarget',
+ thresholds: thresholdsForRetargetWorker(RETARGET_DEFAULTS),
+ skeleton: { hint: 'mixamo', mapped_bones: MIXAMO_BONES.length, unmapped_bones: [] },
+ vertices: { total: 10_000 },
+ head_cleanup: {
+ mode: 'diagnostic', zone_bones: ['mixamorig:Neck', 'mixamorig:Head'],
+ proposed_vertices: 40, changed_vertices: 0, cap_vertices: 200,
+ },
+ clip: { name: 'Walk', duration: 1.25 },
+ motion: { sampled_frames: 8, max_joint_translation: 0.043 },
+ armature: { name: 'PortOSHumanoid', bone_count: 17, bones: [] },
+ round_trip: {
+ mesh: true, armature: true, armature_modifier: true,
+ animation_count: 1, clip_name: 'Walk', clip_duration: 1.25,
+ },
+ ...overrides,
+});
+
+/**
+ * A two-pass worker stand-in. Records every pass it was asked for, writes what the case
+ * wants, and exits with the per-pass code. `child.on('close')` fires on a later tick,
+ * exactly as a real spawn does.
+ */
+const fakeWorker = ({ probe, report, applyCode = 0, probeCode = 0, passes }) => (_python, args) => {
+ const child = new EventEmitter();
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ const jobFile = args[args.indexOf('--job') + 1];
+ Promise.resolve()
+ .then(async () => {
+ const job = JSON.parse(await readFile(jobFile, 'utf8'));
+ passes?.push(job.pass);
+ if (job.pass === 'probe') {
+ if (probe) await writeFile(job.report_path, JSON.stringify(probe));
+ return probeCode;
+ }
+ if (report) await writeFile(job.report_path, JSON.stringify(report));
+ // A real worker exports only when its own checks pass; a gate-failing report comes
+ // with no GLB, which is what makes "published NEITHER" observable.
+ if (applyCode === 0) await writeFile(job.output_glb, 'animated-glb-bytes');
+ return applyCode;
+ })
+ .then((code) => child.emit('close', code), (error) => child.emit('error', error));
+ return child;
+};
+
+describe('retarget orchestration contract', () => {
+ let dir;
+ let recordDir;
+ let clipPath;
+
+ beforeEach(async () => {
+ dir = await mkdtemp(join(tmpdir(), 'portos-retarget-'));
+ recordDir = join(dir, 'image3d-example');
+ clipPath = join(dir, 'walk.glb');
+ await mkdir(recordDir, { recursive: true });
+ await writeFile(clipPath, 'clip-glb-bytes');
+
+ // A real published rig for the run to read: staged and published through the same
+ // helper the auto-skin lane uses, so its digest is genuine.
+ const rigPaths = rigRunPaths({ recordDir, rigId: RIG_ID });
+ await mkdir(rigPaths.stageDir, { recursive: true });
+ await writeFile(rigPaths.stagedGlb, 'rigged-glb-bytes');
+ await publishRigArtifacts({ paths: rigPaths, report: { armature: { bone_count: 17 } } });
+ });
+ afterEach(async () => { await rm(dir, { recursive: true, force: true }); });
+
+ const run = (overrides = {}) => runRetarget({
+ modelId: 'image3d-example',
+ recordDir,
+ rigId: RIG_ID,
+ clipPath,
+ readiness: READY,
+ retargetId: RETARGET_ID,
+ ...overrides,
+ });
+
+ it('publishes the animated pair, names it in its own report, and never touches the rig', async () => {
+ const passes = [];
+ const result = await run({ spawnImpl: fakeWorker({ probe: cleanProbe(), report: cleanReport(), passes }) });
+ const paths = retargetRunPaths({ recordDir, retargetId: RETARGET_ID });
+
+ expect(passes).toEqual(['probe', 'apply']);
+ const report = JSON.parse(await readFile(paths.publishedReport, 'utf8'));
+ expect(report.output_file).toBe(RETARGETED_GLB_NAME);
+ expect(report.output_sha256).toBe(result.sha256);
+ expect(report).toMatchObject({ kind: 'retarget', source_rig_id: RIG_ID, source_clip: 'walk.glb' });
+ // The same reader every consumer uses resolves the animated GLB from that key.
+ expect(await readRiggedArtifact({ publishDir: paths.publishDir })).toMatchObject({ ok: true });
+ expect(result.assetPath)
+ .toBe(`/data/image-to-3d/image3d-example/retarget/${RETARGET_ID}/${RETARGETED_GLB_NAME}`);
+ expect(result.summary).toMatchObject({ clip: 'Walk', mode: 'diagnostic', changedCleanupVertices: 0 });
+
+ const rigPaths = rigRunPaths({ recordDir, rigId: RIG_ID });
+ expect(await readFile(rigPaths.publishedGlb, 'utf8')).toBe('rigged-glb-bytes');
+ expect(existsSync(paths.stageDir)).toBe(false);
+ });
+
+ it('refuses a partial skeleton after the probe, without ever spawning the apply pass', async () => {
+ // The clip animates a finger the humanoid armature does not have — the all-or-nothing
+ // mapping contract from `skeletonMapping.js`. Nothing may be written on this path:
+ // the apply pass is the only one that can export, so it must not run at all.
+ const passes = [];
+ const probe = cleanProbe({ clip_bones: [...MIXAMO_BONES, 'mixamorig:LeftHandThumb1'] });
+ await expect(run({ spawnImpl: fakeWorker({ probe, report: cleanReport(), passes }) }))
+ .rejects.toMatchObject({ code: 'RIGGING_SKELETON_INCOMPATIBLE', status: 422 });
+
+ expect(passes).toEqual(['probe']);
+ const paths = retargetRunPaths({ recordDir, retargetId: RETARGET_ID });
+ expect(existsSync(paths.publishedGlb)).toBe(false);
+ expect(existsSync(paths.stageDir)).toBe(false);
+ });
+
+ it('refuses a clip the file does not contain rather than animating a different one', async () => {
+ const passes = [];
+ await expect(run({
+ clipName: 'Backflip',
+ spawnImpl: fakeWorker({ probe: cleanProbe(), report: cleanReport(), passes }),
+ })).rejects.toMatchObject({ code: 'RIGGING_CLIP_NOT_FOUND' });
+ expect(passes).toEqual(['probe']);
+ });
+
+ it('publishes NEITHER artifact when the gate refuses the run', async () => {
+ const failing = cleanReport();
+ failing.motion = { sampled_frames: 8, max_joint_translation: 0 };
+ await expect(run({
+ spawnImpl: fakeWorker({ probe: cleanProbe(), report: failing, applyCode: 2 }),
+ })).rejects.toThrow(/never moves/);
+
+ const paths = retargetRunPaths({ recordDir, retargetId: RETARGET_ID });
+ expect(existsSync(paths.publishedGlb)).toBe(false);
+ expect(existsSync(paths.publishedReport)).toBe(false);
+ expect(existsSync(paths.stageDir)).toBe(false);
+ });
+
+ it('refuses a write-mode run whose cleanup exceeded the cap, leaving nothing published', async () => {
+ const overCap = cleanReport();
+ overCap.head_cleanup = { ...overCap.head_cleanup, mode: 'write', proposed_vertices: 900, changed_vertices: 900 };
+ await expect(run({
+ mode: 'write',
+ spawnImpl: fakeWorker({ probe: cleanProbe(), report: overCap, applyCode: 2 }),
+ })).rejects.toMatchObject({ code: 'RIGGING_RETARGET_GATE_FAILED' });
+
+ expect(existsSync(retargetRunPaths({ recordDir, retargetId: RETARGET_ID }).publishedGlb)).toBe(false);
+ });
+
+ it('refuses to record an animation whose published pair does not read back', async () => {
+ // The publish itself succeeded, but the pair does not verify — the exact state an
+ // interrupted run leaves behind. The SOURCE rig still has to verify, or the run would
+ // fail earlier for the wrong reason.
+ const rigDir = join(recordDir, 'rig', RIG_ID);
+ await expect(run({
+ spawnImpl: fakeWorker({ probe: cleanProbe(), report: cleanReport() }),
+ verify: async ({ publishDir }) => (publishDir === rigDir
+ ? readRiggedArtifact({ publishDir })
+ : { ok: false, reason: 'digest-mismatch' }),
+ })).rejects.toMatchObject({ code: 'RIGGING_PUBLISH_UNVERIFIED' });
+ });
+
+ it('refuses to animate a rig that is not a readable published pair', async () => {
+ await rm(rigRunPaths({ recordDir, rigId: RIG_ID }).publishedGlb);
+ await expect(run({ spawnImpl: fakeWorker({ probe: cleanProbe(), report: cleanReport() }) }))
+ .rejects.toMatchObject({ code: 'RIGGING_NO_SOURCE_RIG', status: 422 });
+ });
+
+ it('reports the probe exit when the worker produced no readable probe at all', async () => {
+ await expect(run({ spawnImpl: fakeWorker({ probeCode: 3 }) }))
+ .rejects.toMatchObject({ code: 'RIGGING_CLIP_UNREADABLE' });
+ });
+
+ it('refuses to run at all when the Blender runtime is not ready', async () => {
+ await expect(run({
+ readiness: { ready: false, reason: 'module-unimportable' },
+ spawnImpl: fakeWorker({ probe: cleanProbe(), report: cleanReport() }),
+ })).rejects.toMatchObject({ code: 'RIGGING_RUNTIME_UNAVAILABLE', status: 409 });
+ });
+});
+
+describe('clip selection', () => {
+ it('defaults to the only clip in a single-clip file, so a drop needs no internal name', () => {
+ expect(selectClip([{ name: 'Walk' }], null)).toEqual({ ok: true, clip: { name: 'Walk' } });
+ });
+
+ it('honours an explicit request and refuses an absent one rather than substituting', () => {
+ const clips = [{ name: 'Walk' }, { name: 'Idle' }];
+ expect(selectClip(clips, 'Idle')).toMatchObject({ ok: true, clip: { name: 'Idle' } });
+ expect(selectClip(clips, 'Backflip')).toEqual({ ok: false, available: ['Walk', 'Idle'] });
+ });
+
+ it('refuses a file with no animations instead of returning an unnamed clip', () => {
+ expect(selectClip([], null)).toEqual({ ok: false, available: [] });
+ expect(selectClip([{ name: '' }, { duration: 1 }], null)).toEqual({ ok: false, available: [] });
+ });
+});
diff --git a/server/services/rigging/retargetReport.js b/server/services/rigging/retargetReport.js
new file mode 100644
index 0000000000..0891e99df7
--- /dev/null
+++ b/server/services/rigging/retargetReport.js
@@ -0,0 +1,302 @@
+/**
+ * Character rigging — the measured gate on publishing a RETARGETED character.
+ *
+ * Phase 2 (`autoSkinReport.js`) refuses to publish a rig whose weights did not measure
+ * up. This module is the same idea one step later: a retarget produces a file whether
+ * or not anything in it moves, so "the exporter returned" is worth nothing as evidence.
+ * What is worth something is a re-import that finds a NAMED clip of non-zero duration
+ * on the exported armature, and measured joint displacement between sampled frames. A
+ * file-only export — bytes on disk with no animation, or an animation that holds a
+ * single pose — is the exact failure this gate exists to name.
+ *
+ * ## One report format, not two
+ *
+ * The retarget report is the Phase 2 report EXTENDED, not a second format: same
+ * `report_version`, same `thresholds` echo-back, same `armature` and `round_trip`
+ * subtrees, published through the same GLB-first/report-last pair contract. It adds
+ * `skeleton`, `head_cleanup`, `clip`, and `motion`, and marks itself `kind: 'retarget'`
+ * so a reader can tell which lane produced a pair without guessing from the filename.
+ *
+ * Everything here is PURE — a reducer over an already-measured report — so every branch
+ * is unit-testable on a host with no Blender install.
+ */
+
+/**
+ * Reports carry their lane so a consumer never infers it from a filename. The version
+ * is NOT declared here: a retarget report rides the Phase 2 `AUTO_SKIN_REPORT_VERSION`
+ * that `publishRigArtifacts` stamps, because there is one rigging report format.
+ */
+export const RETARGET_REPORT_KIND = 'retarget';
+
+/**
+ * The two head-zone cleanup modes, and why both exist.
+ *
+ * `diagnostic` measures the proposed cleanup and the cap it would run under, and
+ * changes NOTHING. It is the default because the cleanup edits skin weights a
+ * human never reviewed; a user gets the number first and opts into the edit second.
+ *
+ * `write` applies the same proposal, and may not exceed the cap.
+ */
+export const RETARGET_MODES = Object.freeze(['diagnostic', 'write']);
+export const DEFAULT_RETARGET_MODE = 'diagnostic';
+
+/**
+ * The thresholds, and why each is where it is.
+ *
+ * `headCleanupFraction` — the hard cap on how much of the mesh the head-zone cleanup
+ * may re-bind, as a fraction of the mesh's vertices. Auto-skin's nearest-bone fill
+ * binds a stray head-zone vertex to whatever bone happens to be closest, which shows
+ * up as a scalp corner travelling with a shoulder. Fixing that touches the handful of
+ * vertices sitting above the neck; 2% is generous for a head-and-neck island on any
+ * humanoid mesh and far below the fraction a head actually occupies, so the pass is
+ * arithmetically incapable of re-binding a body.
+ *
+ * `minClipDuration` — below this, a "clip" is a single keyed pose with a rounding error
+ * for a duration. 50ms is shorter than any real animation and longer than the noise.
+ *
+ * `motionSampleCount` — frames sampled across the clip to prove movement. More than two
+ * because a clip whose first and last frames coincide (a loop) moves in between; eight
+ * is enough to catch that without making the check a second playback.
+ *
+ * `minMotionDistance` — the displacement, in the model's own units, that separates
+ * "animated" from "a pose plus float noise". Model space is normalized to roughly
+ * unit height by the decode lane, so 1e-4 is ~0.01% of a character's height.
+ */
+export const RETARGET_DEFAULTS = Object.freeze({
+ headCleanupFraction: 0.02,
+ minClipDuration: 0.05,
+ motionSampleCount: 8,
+ minMotionDistance: 1e-4,
+});
+
+/** Advanced-override bounds, mirrored by the route's Zod schema. */
+export const RETARGET_LIMITS = Object.freeze({
+ headCleanupFractionMin: 0,
+ headCleanupFractionMax: 0.1,
+});
+
+/**
+ * Why a retarget was refused. Codes are stable; the user-facing sentence is built by
+ * `describeRetargetFailure` below so it can name the measured numbers.
+ */
+export const RETARGET_FAILURE_REASONS = Object.freeze({
+ 'report-malformed': 'The retarget worker did not report usable measurements',
+ 'thresholds-mismatch': 'The retarget worker used different thresholds than requested',
+ 'mode-mismatch': 'The retarget worker ran a different cleanup mode than requested',
+ 'skeleton-unrecognized': 'The clip does not use a skeleton convention this install understands',
+ 'skeleton-partial': 'The clip and the rigged character do not share a complete skeleton',
+ 'head-cleanup-over-cap': 'The head-zone cleanup would change more of the mesh than the cap allows',
+ 'diagnostic-mode-wrote': 'A diagnostic run changed skin weights, which it must never do',
+ 'round-trip-failed': 'The exported file did not survive a re-import check',
+ 'clip-unnamed': 'The exported file carries no named animation',
+ 'clip-zero-duration': 'The exported animation has no duration',
+ 'no-motion': 'The exported animation never moves',
+});
+
+const isCount = (value) => Number.isInteger(value) && value >= 0;
+const isNonNegative = (value) => Number.isFinite(value) && value >= 0;
+const isNamed = (value) => typeof value === 'string' && value.trim().length > 0;
+const formatPercent = (fraction) => `${(Number(fraction) * 100).toFixed(1)}%`;
+
+/**
+ * The measurement subtree a gate decision needs, or `null` when the report cannot
+ * supply it. Keeps "the worker emitted nonsense" as ONE branch rather than a scattering
+ * of optional chaining through the decision below.
+ */
+function readMeasurements(report) {
+ const skeleton = report?.skeleton;
+ const cleanup = report?.head_cleanup;
+ const motion = report?.motion;
+ const roundTrip = report?.round_trip;
+ if (!isCount(report?.vertices?.total)) return null;
+ if (!isNamed(skeleton?.hint) || !Array.isArray(skeleton?.unmapped_bones) || !isCount(skeleton?.mapped_bones)) return null;
+ if (!isNamed(cleanup?.mode) || !isCount(cleanup?.proposed_vertices) || !isCount(cleanup?.changed_vertices)) return null;
+ if (!isCount(motion?.sampled_frames) || !isNonNegative(motion?.max_joint_translation)) return null;
+ if (!roundTrip || typeof roundTrip !== 'object') return null;
+ return { skeleton, cleanup, motion, roundTrip, totalVertices: report.vertices.total };
+}
+
+// A float threshold survives a JSON round trip through Python exactly, so an exact
+// comparison is right here — a mismatch means the worker used a DIFFERENT number, not
+// that it lost a bit of precision.
+const thresholdsAgree = (reported, requested) => Boolean(reported)
+ && reported.head_cleanup_fraction === requested.headCleanupFraction
+ && reported.min_clip_duration === requested.minClipDuration
+ && reported.motion_sample_count === requested.motionSampleCount
+ && reported.min_motion_distance === requested.minMotionDistance;
+
+/**
+ * How many vertices the head-zone cleanup may re-bind. Derived HERE rather than read
+ * from the report: the cap is the whole safety argument, so a worker that echoes a
+ * roomier one must not be able to talk the orchestrator into honouring it.
+ *
+ * @param {number} totalVertices
+ * @param {number} fraction
+ * @returns {number}
+ */
+export const headCleanupCap = (totalVertices, fraction) => Math.floor(Math.max(0, totalVertices) * Math.max(0, fraction));
+
+/**
+ * Decide whether a reported retarget may be published. Pure.
+ *
+ * Order is the point:
+ * - a report we cannot read is never "fine", it is unreadable;
+ * - thresholds and mode are checked against what the CALLER asked for, so a worker
+ * cannot relax its own cap (or quietly upgrade a diagnostic run to a write) and have
+ * the orchestrator honour it;
+ * - the skeleton contract comes before anything measured on the export, because a
+ * partial mapping means whatever was exported is a partial retarget;
+ * - the cleanup cap comes before the motion proof: weights changed beyond the cap make
+ * the exported mesh the wrong mesh, and how well it moves is then beside the point;
+ * - the clip and motion assertions are last, and they are what separate a retarget from
+ * a file: a named clip, a non-zero duration, and measured displacement.
+ *
+ * @param {object} report The worker's report JSON (snake_case, as written to disk).
+ * @param {{thresholds?: object, mode?: string}} [opts]
+ * @returns {{ok: boolean, reason: string|null, metrics: object|null}}
+ */
+export function reduceRetargetGate(report, { thresholds = RETARGET_DEFAULTS, mode = DEFAULT_RETARGET_MODE } = {}) {
+ const measured = readMeasurements(report);
+ if (!measured) return { ok: false, reason: 'report-malformed', metrics: null };
+
+ const capVertices = headCleanupCap(measured.totalVertices, thresholds.headCleanupFraction);
+ const metrics = {
+ totalVertices: measured.totalVertices,
+ skeletonHint: measured.skeleton.hint,
+ mappedBones: measured.skeleton.mapped_bones,
+ unmappedBones: measured.skeleton.unmapped_bones,
+ mode: measured.cleanup.mode,
+ proposedCleanupVertices: measured.cleanup.proposed_vertices,
+ changedCleanupVertices: measured.cleanup.changed_vertices,
+ cleanupCapVertices: capVertices,
+ cleanupOverCap: measured.cleanup.proposed_vertices > capVertices,
+ exportedClipName: isNamed(measured.roundTrip.clip_name) ? measured.roundTrip.clip_name : null,
+ exportedClipDuration: Number.isFinite(measured.roundTrip.clip_duration) ? measured.roundTrip.clip_duration : 0,
+ sampledFrames: measured.motion.sampled_frames,
+ maxJointTranslation: measured.motion.max_joint_translation,
+ boneCount: isCount(report?.armature?.bone_count) ? report.armature.bone_count : 0,
+ thresholds,
+ };
+
+ if (!thresholdsAgree(report?.thresholds, thresholds)) return { ok: false, reason: 'thresholds-mismatch', metrics };
+ if (metrics.mode !== mode) return { ok: false, reason: 'mode-mismatch', metrics };
+ if (metrics.skeletonHint === 'unknown') return { ok: false, reason: 'skeleton-unrecognized', metrics };
+ if (metrics.unmappedBones.length > 0 || metrics.mappedBones === 0) {
+ return { ok: false, reason: 'skeleton-partial', metrics };
+ }
+ if (mode === 'diagnostic' && metrics.changedCleanupVertices !== 0) {
+ return { ok: false, reason: 'diagnostic-mode-wrote', metrics };
+ }
+ if (metrics.changedCleanupVertices > capVertices) return { ok: false, reason: 'head-cleanup-over-cap', metrics };
+
+ const { roundTrip } = measured;
+ if (roundTrip.mesh !== true || roundTrip.armature !== true || roundTrip.armature_modifier !== true) {
+ return { ok: false, reason: 'round-trip-failed', metrics };
+ }
+ if (!metrics.exportedClipName) return { ok: false, reason: 'clip-unnamed', metrics };
+ if (metrics.exportedClipDuration < thresholds.minClipDuration) {
+ return { ok: false, reason: 'clip-zero-duration', metrics };
+ }
+ if (metrics.sampledFrames < 2 || metrics.maxJointTranslation < thresholds.minMotionDistance) {
+ return { ok: false, reason: 'no-motion', metrics };
+ }
+ return { ok: true, reason: null, metrics };
+}
+
+/**
+ * The sentence a user sees when a retarget is refused. It names the measured number and
+ * the threshold it missed, because "retarget failed" tells them nothing they can act on.
+ *
+ * @param {string} reason A key of `RETARGET_FAILURE_REASONS`.
+ * @param {object|null} [metrics] The metrics from `reduceRetargetGate`.
+ * @returns {string}
+ */
+export function describeRetargetFailure(reason, metrics = null) {
+ const headline = Object.hasOwn(RETARGET_FAILURE_REASONS, reason ?? '')
+ ? RETARGET_FAILURE_REASONS[reason]
+ : 'The retarget failed for an unrecognized reason';
+ if (!metrics) return `${headline}.`;
+ switch (reason) {
+ case 'skeleton-partial':
+ return `${headline}: ${metrics.mappedBones} bones mapped and `
+ + `${metrics.unmappedBones.length} did not (${metrics.unmappedBones.slice(0, 5).join(', ')}`
+ + `${metrics.unmappedBones.length > 5 ? ', …' : ''}).`;
+ case 'skeleton-unrecognized':
+ return `${headline}: the character is rigged to an unrecognized convention, so no bone could be matched.`;
+ case 'head-cleanup-over-cap':
+ return `${headline}: it would re-bind ${metrics.proposedCleanupVertices} of ${metrics.totalVertices} `
+ + `vertices, and the cap is ${metrics.cleanupCapVertices} `
+ + `(${formatPercent(metrics.thresholds.headCleanupFraction)} of the mesh).`;
+ case 'diagnostic-mode-wrote':
+ return `${headline}: ${metrics.changedCleanupVertices} vertices were changed by a run that was only asked to measure.`;
+ case 'clip-unnamed':
+ return `${headline}: the re-imported GLB had no named animation to play.`;
+ case 'clip-zero-duration':
+ return `${headline}: the re-imported clip "${metrics.exportedClipName}" lasts `
+ + `${metrics.exportedClipDuration.toFixed(3)}s, and anything under `
+ + `${metrics.thresholds.minClipDuration}s is a single pose.`;
+ case 'no-motion':
+ return `${headline}: across ${metrics.sampledFrames} sampled frames no joint moved more than `
+ + `${metrics.maxJointTranslation.toExponential(2)} units, and the minimum is `
+ + `${metrics.thresholds.minMotionDistance.toExponential(2)}.`;
+ case 'mode-mismatch':
+ return `${headline}: it reported "${metrics.mode}".`;
+ case 'thresholds-mismatch':
+ return `${headline}: the report's thresholds do not match the requested `
+ + `${formatPercent(metrics.thresholds.headCleanupFraction)} cleanup cap.`;
+ default:
+ return `${headline}.`;
+ }
+}
+
+/**
+ * The compact retarget summary stored on the model record and rendered by the client.
+ * Kept separate from the full report (which stays on disk next to the GLB) so a record
+ * read does not carry a bone list.
+ *
+ * `cleanupOverCap` rides along deliberately: it is the number a diagnostic run exists to
+ * produce, and the reason a later write run would refuse.
+ *
+ * @param {object|null} metrics
+ * @returns {object|null}
+ */
+export function summarizeRetarget(metrics) {
+ if (!metrics) return null;
+ return {
+ clip: metrics.exportedClipName,
+ clipDuration: metrics.exportedClipDuration,
+ mode: metrics.mode,
+ bones: metrics.boneCount,
+ mappedBones: metrics.mappedBones,
+ vertices: metrics.totalVertices,
+ proposedCleanupVertices: metrics.proposedCleanupVertices,
+ changedCleanupVertices: metrics.changedCleanupVertices,
+ cleanupCapVertices: metrics.cleanupCapVertices,
+ cleanupOverCap: metrics.cleanupOverCap,
+ sampledFrames: metrics.sampledFrames,
+ maxJointTranslation: metrics.maxJointTranslation,
+ };
+}
+
+/**
+ * Normalize caller-supplied advanced overrides against the defaults. Absent means "use
+ * the default"; a present value is used as given (the route's Zod schema owns range
+ * validation, so an out-of-range number never reaches here).
+ *
+ * @param {{headCleanupFraction?: number}} [overrides]
+ * @returns {object} A frozen threshold set.
+ */
+export function resolveRetargetThresholds(overrides = {}) {
+ return Object.freeze({
+ ...RETARGET_DEFAULTS,
+ ...(Number.isFinite(overrides.headCleanupFraction) ? { headCleanupFraction: overrides.headCleanupFraction } : {}),
+ });
+}
+
+/** The threshold block the worker is asked to echo back, in its own snake_case. */
+export const thresholdsForRetargetWorker = (thresholds) => ({
+ head_cleanup_fraction: thresholds.headCleanupFraction,
+ min_clip_duration: thresholds.minClipDuration,
+ motion_sample_count: thresholds.motionSampleCount,
+ min_motion_distance: thresholds.minMotionDistance,
+});
diff --git a/server/services/rigging/retargetReport.test.js b/server/services/rigging/retargetReport.test.js
new file mode 100644
index 0000000000..54e99ad9fd
--- /dev/null
+++ b/server/services/rigging/retargetReport.test.js
@@ -0,0 +1,180 @@
+/**
+ * The retarget gate arithmetic, against fixtures.
+ *
+ * Every branch here is a refusal the product depends on, and none of them is observable
+ * from an integration test on a host with no Blender: a partial skeleton, a cleanup that
+ * exceeded its cap, a diagnostic run that wrote anyway, and — the three that separate a
+ * retarget from a file — an export with no named clip, one with no duration, and one
+ * that holds a single pose.
+ *
+ * The cap in particular is re-derived HERE from the vertex count, not read from the
+ * report: that is the whole safety argument for a pass that edits skin weights, so the
+ * tests pin that a worker echoing a roomier cap cannot widen it.
+ */
+
+import { describe, expect, it } from 'vitest';
+import {
+ describeRetargetFailure,
+ headCleanupCap,
+ reduceRetargetGate,
+ resolveRetargetThresholds,
+ RETARGET_DEFAULTS,
+ RETARGET_FAILURE_REASONS,
+ summarizeRetarget,
+ thresholdsForRetargetWorker,
+} from './retargetReport.js';
+
+const cleanReport = (overrides = {}) => ({
+ report_version: 1,
+ kind: 'retarget',
+ thresholds: thresholdsForRetargetWorker(RETARGET_DEFAULTS),
+ skeleton: { hint: 'mixamo', mapped_bones: 17, unmapped_bones: [] },
+ vertices: { total: 10_000 },
+ head_cleanup: {
+ mode: 'diagnostic',
+ zone_bones: ['mixamorig:Neck', 'mixamorig:Head'],
+ proposed_vertices: 40,
+ changed_vertices: 0,
+ cap_vertices: 200,
+ },
+ clip: { name: 'Walk', duration: 1.25 },
+ motion: { sampled_frames: 8, max_joint_translation: 0.043 },
+ armature: { name: 'PortOSHumanoid', bone_count: 17, bones: [] },
+ round_trip: {
+ mesh: true, armature: true, armature_modifier: true,
+ animation_count: 1, clip_name: 'Walk', clip_duration: 1.25,
+ },
+ ...overrides,
+});
+
+const gate = (report, opts) => reduceRetargetGate(report, opts);
+
+describe('retarget gate', () => {
+ it('passes a clean diagnostic report and summarizes what it measured', () => {
+ const result = gate(cleanReport());
+ expect(result).toMatchObject({ ok: true, reason: null });
+ expect(summarizeRetarget(result.metrics)).toMatchObject({
+ clip: 'Walk', mode: 'diagnostic', mappedBones: 17,
+ proposedCleanupVertices: 40, changedCleanupVertices: 0, cleanupCapVertices: 200,
+ cleanupOverCap: false, sampledFrames: 8,
+ });
+ });
+
+ it('refuses a report it cannot read rather than treating absent measurements as fine', () => {
+ expect(gate({ ...cleanReport(), vertices: null })).toMatchObject({ ok: false, reason: 'report-malformed', metrics: null });
+ expect(gate({ ...cleanReport(), motion: { sampled_frames: 8 } })).toMatchObject({ ok: false, reason: 'report-malformed' });
+ });
+
+ it('refuses a worker that used different thresholds or a different mode than requested', () => {
+ const relaxed = cleanReport();
+ relaxed.thresholds.head_cleanup_fraction = 0.5;
+ expect(gate(relaxed)).toMatchObject({ ok: false, reason: 'thresholds-mismatch' });
+ expect(gate(cleanReport(), { mode: 'write' })).toMatchObject({ ok: false, reason: 'mode-mismatch' });
+ });
+
+ it('refuses a partial or unrecognized skeleton before anything measured on the export matters', () => {
+ const partial = cleanReport();
+ partial.skeleton = { hint: 'mixamo', mapped_bones: 15, unmapped_bones: ['mixamorig:LeftHandThumb1', 'mixamorig:RightToeBase'] };
+ // Every downstream signal in this report is clean — the refusal must still come from
+ // the skeleton, because a partial mapping means a partial retarget was exported.
+ const result = gate(partial);
+ expect(result).toMatchObject({ ok: false, reason: 'skeleton-partial' });
+ expect(describeRetargetFailure(result.reason, result.metrics))
+ .toContain('mixamorig:LeftHandThumb1');
+
+ const unknown = cleanReport();
+ unknown.skeleton = { hint: 'unknown', mapped_bones: 0, unmapped_bones: [] };
+ expect(gate(unknown)).toMatchObject({ ok: false, reason: 'skeleton-unrecognized' });
+ });
+
+ it('derives the cleanup cap from the vertex count, so a roomier reported cap cannot widen it', () => {
+ // 2% of 10,000 vertices is 200 — whatever the worker claims its own cap was.
+ expect(headCleanupCap(10_000, RETARGET_DEFAULTS.headCleanupFraction)).toBe(200);
+
+ const overCap = cleanReport();
+ overCap.head_cleanup = {
+ ...overCap.head_cleanup, mode: 'write', proposed_vertices: 900, changed_vertices: 900, cap_vertices: 9_000,
+ };
+ const result = gate(overCap, { mode: 'write' });
+ expect(result).toMatchObject({ ok: false, reason: 'head-cleanup-over-cap' });
+ expect(result.metrics.cleanupCapVertices).toBe(200);
+ expect(describeRetargetFailure(result.reason, result.metrics))
+ .toContain('re-bind 900 of 10000 vertices, and the cap is 200');
+
+ // At the cap exactly, a write run is allowed — the cap is a ceiling, not a limit
+ // that also forbids reaching it.
+ const atCap = cleanReport();
+ atCap.head_cleanup = { ...atCap.head_cleanup, mode: 'write', proposed_vertices: 200, changed_vertices: 200 };
+ expect(gate(atCap, { mode: 'write' })).toMatchObject({ ok: true });
+ });
+
+ it('refuses a diagnostic run that changed any weights at all', () => {
+ const wrote = cleanReport();
+ wrote.head_cleanup = { ...wrote.head_cleanup, changed_vertices: 3 };
+ // Well under the 200-vertex cap: the refusal is about the MODE, not the size.
+ expect(gate(wrote)).toMatchObject({ ok: false, reason: 'diagnostic-mode-wrote' });
+ });
+
+ it('reports an over-cap proposal from a diagnostic run instead of failing it', () => {
+ // Measuring the problem IS what diagnostic mode is for; a later write run is what
+ // refuses. Failing here would leave the user with no way to see the number.
+ const proposal = cleanReport();
+ proposal.head_cleanup = { ...proposal.head_cleanup, proposed_vertices: 900 };
+ const result = gate(proposal);
+ expect(result.ok).toBe(true);
+ expect(summarizeRetarget(result.metrics)).toMatchObject({
+ proposedCleanupVertices: 900, cleanupCapVertices: 200, cleanupOverCap: true, changedCleanupVertices: 0,
+ });
+ });
+
+ it('rejects a file-only export: no named clip, or one with no duration', () => {
+ const unnamed = cleanReport();
+ unnamed.round_trip = { ...unnamed.round_trip, animation_count: 0, clip_name: null, clip_duration: 0 };
+ expect(gate(unnamed)).toMatchObject({ ok: false, reason: 'clip-unnamed' });
+
+ const instant = cleanReport();
+ instant.round_trip = { ...instant.round_trip, clip_duration: 0.004 };
+ const result = gate(instant);
+ expect(result).toMatchObject({ ok: false, reason: 'clip-zero-duration' });
+ expect(describeRetargetFailure(result.reason, result.metrics)).toContain('lasts 0.004s');
+ });
+
+ it('rejects a re-import that lost the mesh, the armature, or the armature modifier', () => {
+ for (const key of ['mesh', 'armature', 'armature_modifier']) {
+ const broken = cleanReport();
+ broken.round_trip = { ...broken.round_trip, [key]: false };
+ expect(gate(broken)).toMatchObject({ ok: false, reason: 'round-trip-failed' });
+ }
+ });
+
+ it('rejects an export that holds a single pose, and one sampled too thinly to tell', () => {
+ const still = cleanReport();
+ still.motion = { sampled_frames: 8, max_joint_translation: 1e-9 };
+ const result = gate(still);
+ expect(result).toMatchObject({ ok: false, reason: 'no-motion' });
+ expect(describeRetargetFailure(result.reason, result.metrics)).toContain('8 sampled frames');
+
+ // One frame cannot demonstrate movement no matter how large the number beside it.
+ const unsampled = cleanReport();
+ unsampled.motion = { sampled_frames: 1, max_joint_translation: 5 };
+ expect(gate(unsampled)).toMatchObject({ ok: false, reason: 'no-motion' });
+ });
+
+ it('names every failure reason it can return, and falls back rather than rendering undefined', () => {
+ for (const reason of Object.keys(RETARGET_FAILURE_REASONS)) {
+ expect(describeRetargetFailure(reason, gate(cleanReport()).metrics)).toMatch(/\S/);
+ }
+ expect(describeRetargetFailure('constructor')).toBe('The retarget failed for an unrecognized reason.');
+ });
+});
+
+describe('retarget thresholds', () => {
+ it('uses the default for an absent override and the caller value for a present one', () => {
+ expect(resolveRetargetThresholds()).toEqual(RETARGET_DEFAULTS);
+ expect(resolveRetargetThresholds({ headCleanupFraction: 0.01 }))
+ .toMatchObject({ headCleanupFraction: 0.01, minClipDuration: RETARGET_DEFAULTS.minClipDuration });
+ // A zero cap is a real request (measure only, change nothing), so it must survive the
+ // "absent means default" merge rather than being read as falsy.
+ expect(resolveRetargetThresholds({ headCleanupFraction: 0 }).headCleanupFraction).toBe(0);
+ });
+});
diff --git a/server/services/rigging/retargetWorker.py b/server/services/rigging/retargetWorker.py
new file mode 100644
index 0000000000..7edce9040e
--- /dev/null
+++ b/server/services/rigging/retargetWorker.py
@@ -0,0 +1,484 @@
+#!/usr/bin/env python3
+"""Blender-side retarget worker for PortOS character rigging.
+
+Sibling of `autoSkinWorker.py` and driven the same way: the Node orchestrator
+(`retarget.js`) writes a job JSON, spawns this file with the rigging env's
+interpreter, and reads back the report this file writes.
+
+TWO PASSES, AND WHY
+-------------------
+The skeleton compatibility contract is all-or-nothing and it lives in
+`skeletonMapping.js`, not here -- a second copy of the bone tables in Python would be
+free to drift from the one the rest of the app uses. So this worker never decides
+whether a clip is compatible. It runs as:
+
+ pass "probe" -- read-only. Reports which bones the clip animates, which clips it
+ carries, which bones the rigged character has, and how many
+ vertices the mesh has. Exports nothing, writes nothing but its
+ report.
+ pass "apply" -- receives the EXPLICIT source->target bone mapping the orchestrator
+ derived from the probe, and does the work.
+
+That is what makes "unsupported or partial skeleton" fail before an exporter is ever
+opened, rather than after a partial retarget has been written somewhere.
+
+WHY THE APPLY STEPS ARE IN THIS ORDER
+-------------------------------------
+1. Open the RIGGED character. It is the target; the clip is only a source of curves.
+2. Head-zone cleanup FIRST, before any animation exists. Auto-skin's nearest-bone fill
+ binds each leftover vertex to whatever bone is closest, which above the neck can
+ mean a scalp corner travelling with a shoulder. Re-binding those vertices to the
+ head/neck chain is a weight edit, so it is capped and it is opt-in:
+ - "diagnostic" MEASURES the proposal and changes nothing (the default);
+ - "write" applies it, and refuses the whole pass if the proposal exceeds the cap.
+ All-or-nothing on purpose: a partial sweep would leave the mesh in a state neither
+ the caller nor the report describes.
+3. Copy the clip's curves onto the target armature under the mapped bone names, then
+ delete everything the clip GLB brought in. The clip's own armature and mesh must not
+ reach the export -- a file containing two skeletons is not a retargeted character.
+4. MEASURE MOTION, then decide. Sample joint world positions across the clip and take
+ the largest displacement from the first frame. A clip that never moves is a pose,
+ and exporting it as an animation is the failure this worker exists to catch.
+5. Export, then re-import and confirm the mesh, the armature, the armature modifier AND
+ a named non-zero-duration animation all survived the exporter. A file-only export
+ passes every check up to here and is still worthless.
+
+The report is written even on failure (that is the user-visible evidence naming the
+number that failed the gate); a gate failure exits non-zero with a specific message.
+The rigged GLB and the clip GLB are both opened read-only and never written back.
+"""
+
+import argparse
+import json
+import os
+import sys
+import traceback
+
+REPORT_VERSION = 1
+
+# Blender samples animation on a fixed scene FPS; the report's durations are seconds, so
+# every frame<->second conversion goes through this one value.
+SCENE_FPS = 24.0
+
+# Curve channels that are safe to copy verbatim between two skeletons sharing a joint.
+# Rotation and scale are joint-local and proportion-independent; `location` is NOT (it is
+# measured in the source rig's units), so it is copied only for the root and only after
+# being rescaled by the height ratio below.
+_POSE_CHANNEL = 'pose.bones["%s"].%s'
+_ORIENTATION_CHANNELS = ("rotation_quaternion", "rotation_euler", "scale")
+_TRANSLATION_CHANNEL = "location"
+
+
+def _fail(message, code=2):
+ """Named, non-zero exit. stderr is what the orchestrator tails."""
+ sys.stderr.write("retarget: %s\n" % message)
+ return code
+
+
+def _write_report(path, report):
+ """Report first, always -- the orchestrator prefers a measured refusal to an exit code."""
+ tmp = "%s.partial" % path
+ with open(tmp, "w", encoding="utf-8") as handle:
+ json.dump(report, handle, indent=2)
+ os.replace(tmp, path)
+
+
+def _bone_name_from_path(data_path):
+ """`pose.bones["mixamorig:Hips"].location` -> `mixamorig:Hips`, or None."""
+ if not data_path or not data_path.startswith('pose.bones["'):
+ return None
+ rest = data_path[len('pose.bones["'):]
+ end = rest.find('"]')
+ return rest[:end] if end > 0 else None
+
+
+def _action_duration(action):
+ """Clip length in seconds, from the action's own frame range."""
+ start, end = action.frame_range
+ return max(0.0, (float(end) - float(start)) / SCENE_FPS)
+
+
+def _actions_on(objects):
+ """Every action reachable from the given objects, in a stable order."""
+ seen = []
+ for obj in objects:
+ action = getattr(getattr(obj, "animation_data", None), "action", None)
+ if action is not None and action not in seen:
+ seen.append(action)
+ return seen
+
+
+def _scene_objects(bpy, kind):
+ return [o for o in bpy.data.objects if o.type == kind]
+
+
+def _armature_height(armature):
+ """World-space vertical extent of an armature's rest pose, for translation scaling."""
+ ys = []
+ for bone in armature.data.bones:
+ for point in (bone.head_local, bone.tail_local):
+ ys.append((armature.matrix_world @ point).z)
+ return max(ys) - min(ys) if ys else 0.0
+
+
+# --------------------------------------------------------------------------- probe pass
+
+
+def probe(job):
+ import bpy # noqa: PLC0415 -- Blender-only import, deferred to the runtime path
+
+ report = {"clips": [], "clip_bones": [], "rig_bones": [], "vertices": 0}
+
+ # The clip file first, in its own scene: a clip GLB commonly carries a whole rig of
+ # its own, and mixing it with the target here would make the bone lists ambiguous.
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ bpy.ops.import_scene.gltf(filepath=job["clip_glb"])
+ animated = []
+ for action in bpy.data.actions:
+ report["clips"].append({"name": action.name, "duration": _action_duration(action)})
+ for curve in action.fcurves:
+ name = _bone_name_from_path(curve.data_path)
+ if name and name not in animated:
+ animated.append(name)
+ report["clip_bones"] = animated
+
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ bpy.ops.import_scene.gltf(filepath=job["rig_glb"])
+ armatures = _scene_objects(bpy, "ARMATURE")
+ report["rig_bones"] = [b.name for b in armatures[0].data.bones] if armatures else []
+ report["vertices"] = sum(len(o.data.vertices) for o in _scene_objects(bpy, "MESH"))
+
+ _write_report(job["report_path"], report)
+ if not report["clip_bones"]:
+ return _fail("the clip file animates no bones")
+ if not report["rig_bones"]:
+ return _fail("the rigged character has no armature")
+ return 0
+
+
+# --------------------------------------------------------------- apply pass: the cleanup
+
+
+def _head_zone_candidates(mesh_object, armature, zone_bones):
+ """Vertices above the neck whose dominant deform group is OUTSIDE the head zone.
+
+ Geometric, not name-based: the zone is everything at or above the first zone bone's
+ head, so a vertex only qualifies when it BOTH sits in the head and is driven from
+ outside it. Returns `(candidate_vertex_indices, zone_bone_names_present)`.
+ """
+ present = [name for name in zone_bones if name in mesh_object.vertex_groups]
+ if not present:
+ return [], present
+ zone_indices = {mesh_object.vertex_groups[name].index for name in present}
+ heads = [armature.matrix_world @ armature.data.bones[name].head_local
+ for name in present if name in armature.data.bones]
+ if not heads:
+ return [], present
+ floor = min(head.z for head in heads)
+
+ candidates = []
+ for vert in mesh_object.data.vertices:
+ if (mesh_object.matrix_world @ vert.co).z < floor:
+ continue
+ dominant = None
+ best = 0.0
+ for group in vert.groups:
+ if group.weight > best:
+ best = group.weight
+ dominant = group.group
+ if dominant is not None and dominant not in zone_indices:
+ candidates.append(vert.index)
+ return candidates, present
+
+
+def _rebind_to_nearest_zone_bone(mesh_object, armature, zone_bones, vertex_indices):
+ """Bind each named vertex to the nearest head-zone bone at full weight, exclusively."""
+ segments = [
+ (name,
+ armature.matrix_world @ armature.data.bones[name].head_local,
+ armature.matrix_world @ armature.data.bones[name].tail_local)
+ for name in zone_bones if name in armature.data.bones
+ ]
+ if not segments:
+ return 0
+ other_groups = [g for g in mesh_object.vertex_groups if g.name not in zone_bones]
+ changed = 0
+ for index in vertex_indices:
+ point = mesh_object.matrix_world @ mesh_object.data.vertices[index].co
+ best_name = None
+ best_distance = None
+ for name, head, tail in segments:
+ axis = tail - head
+ length_sq = axis.dot(axis)
+ t = 0.0 if length_sq <= 0.0 else max(0.0, min(1.0, (point - head).dot(axis) / length_sq))
+ distance = (point - (head + axis * t)).length
+ if best_distance is None or distance < best_distance:
+ best_distance = distance
+ best_name = name
+ # Exclusive: the old weights are removed, not blended with. A vertex driven half
+ # by a shoulder is exactly the artifact this cleanup exists to remove.
+ for group in other_groups:
+ group.remove([index])
+ mesh_object.vertex_groups[best_name].add([index], 1.0, "REPLACE")
+ changed += 1
+ return changed
+
+
+# ------------------------------------------------------------ apply pass: the retarget
+
+
+def _copy_curves(source_action, target_action, name_by_source, translation_scale, root_targets):
+ """Copy the source clip's curves onto the target armature's bone names.
+
+ Orientation channels transfer verbatim. `location` is copied ONLY for a root bone,
+ and scaled by the height ratio: a translation authored against a source rig means a
+ different distance on a character of another size, and every non-root joint gets its
+ position from its parent anyway.
+ """
+ copied = 0
+ for curve in source_action.fcurves:
+ source_bone = _bone_name_from_path(curve.data_path)
+ target_bone = name_by_source.get(source_bone) if source_bone else None
+ if not target_bone:
+ continue
+ channel = curve.data_path.rsplit(".", 1)[-1]
+ if channel == _TRANSLATION_CHANNEL:
+ if target_bone not in root_targets:
+ continue
+ scale = translation_scale
+ elif channel in _ORIENTATION_CHANNELS:
+ scale = 1.0
+ else:
+ continue
+ target_curve = target_action.fcurves.new(
+ _POSE_CHANNEL % (target_bone, channel), index=curve.array_index, action_group=target_bone,
+ )
+ target_curve.keyframe_points.add(count=len(curve.keyframe_points))
+ for slot, key in zip(target_curve.keyframe_points, curve.keyframe_points):
+ slot.co = (key.co[0], key.co[1] * scale)
+ slot.interpolation = key.interpolation
+ target_curve.update()
+ copied += 1
+ return copied
+
+
+def _sample_motion(bpy, armature, action, sample_count):
+ """Largest world-space joint displacement from the first sampled frame.
+
+ Sampled rather than compared end-to-end because a looping clip returns to its start:
+ first-vs-last would report a perfectly good walk cycle as motionless.
+ """
+ start, end = action.frame_range
+ frames = max(2, int(sample_count))
+ step = (float(end) - float(start)) / (frames - 1) if end > start else 0.0
+ if step <= 0.0:
+ return 0, 0.0
+
+ reference = None
+ worst = 0.0
+ for index in range(frames):
+ bpy.context.scene.frame_set(int(round(float(start) + step * index)))
+ bpy.context.view_layer.update()
+ pose = [armature.matrix_world @ bone.head for bone in armature.pose.bones]
+ if reference is None:
+ reference = pose
+ continue
+ for current, origin in zip(pose, reference):
+ worst = max(worst, (current - origin).length)
+ return frames, worst
+
+
+def _round_trip(bpy, path):
+ """Re-import the export and confirm the animated rig survived it."""
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ bpy.ops.import_scene.gltf(filepath=path)
+ meshes = _scene_objects(bpy, "MESH")
+ armatures = _scene_objects(bpy, "ARMATURE")
+ has_modifier = any(
+ any(m.type == "ARMATURE" and m.object is not None for m in o.modifiers) for o in meshes
+ )
+ actions = _actions_on(armatures) or list(bpy.data.actions)
+ return {
+ "mesh": bool(meshes),
+ "armature": bool(armatures),
+ "armature_modifier": bool(has_modifier),
+ "animation_count": len(actions),
+ "clip_name": actions[0].name if actions else None,
+ "clip_duration": _action_duration(actions[0]) if actions else 0.0,
+ }
+
+
+def apply_clip(job): # noqa: PLR0911, PLR0915 -- one linear pipeline; each return is a named gate
+ import bpy # noqa: PLC0415 -- Blender-only import, deferred to the runtime path
+
+ thresholds = job["thresholds"]
+ mapping = job["bone_mapping"]
+ zone_bones = job.get("head_zone_bones") or []
+ mode = job["mode"]
+ report = {
+ "report_version": REPORT_VERSION,
+ "kind": "retarget",
+ "thresholds": thresholds,
+ "skeleton": {"hint": job["skeleton_hint"], "mapped_bones": 0, "unmapped_bones": []},
+ "vertices": {"total": 0},
+ "head_cleanup": {
+ "mode": mode, "zone_bones": zone_bones,
+ "proposed_vertices": 0, "changed_vertices": 0, "cap_vertices": 0,
+ },
+ "clip": {"name": job["clip_name"], "duration": 0.0},
+ "motion": {"sampled_frames": 0, "max_joint_translation": 0.0},
+ "armature": {"name": None, "bone_count": 0, "bones": []},
+ "round_trip": {
+ "mesh": False, "armature": False, "armature_modifier": False,
+ "animation_count": 0, "clip_name": None, "clip_duration": 0.0,
+ },
+ }
+
+ # (1) The rigged character is the target.
+ bpy.context.scene.render.fps = int(SCENE_FPS)
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ bpy.ops.import_scene.gltf(filepath=job["rig_glb"])
+ armatures = _scene_objects(bpy, "ARMATURE")
+ meshes = _scene_objects(bpy, "MESH")
+ if not armatures or not meshes:
+ _write_report(job["report_path"], report)
+ return _fail("the rigged character has no armature or no mesh")
+ armature = armatures[0]
+ mesh_object = meshes[0]
+ total = len(mesh_object.data.vertices)
+ report["vertices"]["total"] = total
+ report["armature"] = {
+ "name": armature.name,
+ "bone_count": len(armature.data.bones),
+ "bones": [b.name for b in armature.data.bones],
+ }
+
+ # The mapping was decided by the orchestrator against the PROBE's bone list; re-check
+ # it against the armature actually loaded here, so a target that changed underneath
+ # the probe cannot produce a silently partial retarget.
+ target_bones = {b.name for b in armature.data.bones}
+ missing = [pair["target"] for pair in mapping if pair["target"] not in target_bones]
+ report["skeleton"] = {
+ "hint": job["skeleton_hint"],
+ "mapped_bones": len(mapping) - len(missing),
+ "unmapped_bones": missing,
+ }
+ if missing:
+ _write_report(job["report_path"], report)
+ return _fail("the rigged character is missing %d mapped bones" % len(missing))
+
+ # (2) Head-zone cleanup, before anything is animated.
+ cap = int(total * float(thresholds["head_cleanup_fraction"]))
+ candidates, present_zone = _head_zone_candidates(mesh_object, armature, zone_bones)
+ report["head_cleanup"].update({
+ "zone_bones": present_zone, "proposed_vertices": len(candidates), "cap_vertices": cap,
+ })
+ if mode == "write":
+ if len(candidates) > cap:
+ _write_report(job["report_path"], report)
+ return _fail(
+ "the head-zone cleanup would re-bind %d of %d vertices, cap is %d"
+ % (len(candidates), total, cap)
+ )
+ report["head_cleanup"]["changed_vertices"] = _rebind_to_nearest_zone_bone(
+ mesh_object, armature, present_zone, candidates,
+ )
+
+ # (3) Bring in the clip, copy its curves onto the target, then remove every object it
+ # brought with it -- a file carrying two skeletons is not a retargeted character.
+ before = set(bpy.data.objects)
+ bpy.ops.import_scene.gltf(filepath=job["clip_glb"])
+ imported = [o for o in bpy.data.objects if o not in before]
+ source_action = next((a for a in bpy.data.actions if a.name == job["clip_name"]), None)
+ if source_action is None:
+ _write_report(job["report_path"], report)
+ return _fail('the clip file no longer carries an animation named "%s"' % job["clip_name"])
+ report["clip"]["duration"] = _action_duration(source_action)
+
+ source_armatures = [o for o in imported if o.type == "ARMATURE"]
+ source_height = _armature_height(source_armatures[0]) if source_armatures else 0.0
+ target_height = _armature_height(armature)
+ translation_scale = (target_height / source_height) if source_height > 0.0 else 1.0
+
+ name_by_source = {pair["source"]: pair["target"] for pair in mapping}
+ # The root is whichever mapped bone has no mapped parent -- the only joint whose
+ # translation is meaningful to carry across.
+ mapped_targets = set(name_by_source.values())
+ root_targets = {
+ name for name in mapped_targets
+ if armature.data.bones[name].parent is None or armature.data.bones[name].parent.name not in mapped_targets
+ }
+
+ target_action = bpy.data.actions.new(name=job["clip_name"])
+ if armature.animation_data is None:
+ armature.animation_data_create()
+ armature.animation_data.action = target_action
+ copied = _copy_curves(source_action, target_action, name_by_source, translation_scale, root_targets)
+
+ for obj in imported:
+ bpy.data.objects.remove(obj, do_unlink=True)
+ if source_action.users == 0:
+ bpy.data.actions.remove(source_action)
+ if not copied:
+ _write_report(job["report_path"], report)
+ return _fail("no animation curve could be transferred onto the rigged character")
+
+ # (4) Measure motion, then decide.
+ start, end = target_action.frame_range
+ bpy.context.scene.frame_start = int(start)
+ bpy.context.scene.frame_end = int(end)
+ frames, worst = _sample_motion(bpy, armature, target_action, thresholds["motion_sample_count"])
+ report["motion"] = {"sampled_frames": frames, "max_joint_translation": worst}
+ if worst < float(thresholds["min_motion_distance"]):
+ _write_report(job["report_path"], report)
+ return _fail("the retargeted clip never moves (largest joint displacement %.3e)" % worst)
+
+ # (5) Export, then re-import and confirm the animation survived.
+ os.makedirs(os.path.dirname(job["output_glb"]), exist_ok=True)
+ bpy.context.scene.frame_set(int(start))
+ bpy.ops.object.select_all(action="DESELECT")
+ mesh_object.select_set(True)
+ armature.select_set(True)
+ bpy.context.view_layer.objects.active = armature
+ bpy.ops.export_scene.gltf(
+ filepath=job["output_glb"], export_format="GLB",
+ use_selection=True, export_skins=True, export_yup=True,
+ export_animations=True, export_animation_mode="ACTIONS",
+ )
+
+ report["round_trip"] = _round_trip(bpy, job["output_glb"])
+ _write_report(job["report_path"], report)
+ if not all(report["round_trip"][k] for k in ("mesh", "armature", "armature_modifier")):
+ return _fail("the exported GLB did not survive a re-import check")
+ if not report["round_trip"]["clip_name"]:
+ return _fail("the exported GLB carries no named animation")
+ if report["round_trip"]["clip_duration"] < float(thresholds["min_clip_duration"]):
+ return _fail(
+ "the exported animation lasts %.3fs, minimum is %.3fs"
+ % (report["round_trip"]["clip_duration"], float(thresholds["min_clip_duration"]))
+ )
+ return 0
+
+
+def run(job):
+ return probe(job) if job.get("pass") == "probe" else apply_clip(job)
+
+
+def main(argv):
+ parser = argparse.ArgumentParser(description="PortOS retarget worker (Blender)")
+ parser.add_argument("--job", required=True, help="Path to the job JSON written by retarget.js")
+ args = parser.parse_args(argv)
+ with open(args.job, "r", encoding="utf-8") as handle:
+ job = json.load(handle)
+ # Top-level guard: this is a subprocess boundary, so an unexpected Blender error must
+ # become a named non-zero exit rather than an opaque traceback the orchestrator
+ # cannot classify.
+ try:
+ return run(job)
+ except Exception: # noqa: BLE001 -- see above
+ sys.stderr.write(traceback.format_exc())
+ return _fail("the retarget worker raised an unexpected error", code=3)
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/server/services/rigging/workerProcess.js b/server/services/rigging/workerProcess.js
new file mode 100644
index 0000000000..7a56fdc3b3
--- /dev/null
+++ b/server/services/rigging/workerProcess.js
@@ -0,0 +1,54 @@
+/**
+ * Character rigging — the one way this lane spawns a Blender worker.
+ *
+ * Both rigging workers (`autoSkinWorker.py`, `retargetWorker.py`) are long-running
+ * child processes outside the Express request lifecycle, so the same three rules apply
+ * to both and are implemented once here:
+ *
+ * - **Never reject.** A non-zero exit is an ANSWER, not an exception: the worker writes
+ * its measured report and exits with a code, and the caller owns the vocabulary of
+ * failure rather than inheriting "exited 1". A throw from inside a spawn callback has
+ * no `next(err)` to bubble to and would take the process down (AGENTS.md).
+ * - **Bounded output.** Only a tail is retained, so a worker that decides to print a
+ * million lines cannot grow the orchestrator's heap.
+ * - **A timeout that is a kill, not a wait.** A wedged Blender holds a CPU forever;
+ * past the budget it is terminated and the tail says so.
+ */
+
+import { spawn } from '../../lib/childProcess.js';
+
+/** A rig is minutes of CPU, not hours; past this the worker is wedged, not working. */
+export const RIGGING_WORKER_TIMEOUT_MS = 20 * 60 * 1000;
+
+/** How much worker output is kept for the failure message. */
+const TAIL_LIMIT = 4000;
+
+/**
+ * Run one Blender worker to completion.
+ *
+ * @param {{python: string, script: string, jobFile: string, spawnImpl?: Function,
+ * timeoutMs?: number}} opts
+ * @returns {Promise<{code: number, tail: string}>}
+ */
+export function runRiggingWorker({
+ python,
+ script,
+ jobFile,
+ spawnImpl = spawn,
+ timeoutMs = RIGGING_WORKER_TIMEOUT_MS,
+}) {
+ return new Promise((resolve) => {
+ const child = spawnImpl(python, [script, '--job', jobFile], {});
+ let tail = '';
+ const collect = (buf) => { tail = `${tail}${buf}`.slice(-TAIL_LIMIT); };
+ child.stdout?.on('data', collect);
+ child.stderr?.on('data', collect);
+ const timer = setTimeout(() => {
+ tail = `${tail}\nRigging worker exceeded ${Math.round(timeoutMs / 60000)} minutes and was terminated.`;
+ child.kill?.('SIGTERM');
+ }, timeoutMs);
+ if (typeof timer.unref === 'function') timer.unref();
+ child.on('error', (error) => { clearTimeout(timer); resolve({ code: -1, tail: `${tail}\n${error.message}` }); });
+ child.on('close', (code) => { clearTimeout(timer); resolve({ code, tail: tail.trim() }); });
+ });
+}