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: auto-skin generated characters behind a measured weight-coverage gate (#5753)

Adam Eivy3d0dd95eb3c7
diff --git a/client/src/components/media/RigPanel.jsx b/client/src/components/media/RigPanel.jsx
new file mode 100644
index 0000000000..d533bad81b
--- /dev/null
+++ b/client/src/components/media/RigPanel.jsx
@@ -0,0 +1,127 @@
+import { useCallback, useEffect, useState } from 'react';
+import { AlertTriangle, Bone, Loader2 } from 'lucide-react';
+import { getRiggingReadiness, rigImageTo3dModel } from '../../services/api';
+import { riggingReasonLabel } from '../../lib/riggingReasons.js';
+import useMounted from '../../hooks/useMounted';
+import { useInstanceFeatures } from '../../hooks/useInstanceFeatures';
+import { formatBytes } from '../../utils/formatters';
+import toast from '../ui/Toast';
+
+/**
+ * "Rig this character" plus the rig-status panel on `/3d/:id`.
+ *
+ * Gated on BOTH the `rigging` instance feature and the Phase 1 runtime readiness
+ * probe — the feature flag is the user's choice, readiness is the machine's answer, and
+ * a host with no Blender must say so by name rather than offering a button that spawns
+ * a mysterious failure. The readiness fetch is deliberately made HERE and only when the
+ * feature is on, so a 3D page on an install without rigging pays nothing for it.
+ *
+ * A refused rig renders the SERVER's sentence, which names the measured number and the
+ * threshold it missed ("automatic weighting left 4.2% of vertices unweighted, ceiling
+ * is 0.5%"). That is the whole point of the gate; collapsing it to "Rigging failed"
+ * would throw away the only thing the user can act on.
+ */
+export default function RigPanel({ record, onRecordChange }) {
+ const mountedRef = useMounted();
+ const { isFeatureEnabled } = useInstanceFeatures();
+ const enabled = isFeatureEnabled('rigging');
+ const [readiness, setReadiness] = useState(null);
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => {
+ if (!enabled) return;
+ let active = true;
+ // Silent: this panel renders on every 3D detail visit, so an unreadable probe
+ // belongs inline rather than as an unprompted toast.
+ getRiggingReadiness({ silent: true })
+ .then((value) => { if (active) setReadiness(value); })
+ .catch(() => { if (active) setReadiness({ ready: false, reason: 'runtime-probe-failed' }); });
+ return () => { active = false; };
+ }, [enabled]);
+
+ const handleRig = useCallback(async () => {
+ if (busy) return;
+ setBusy(true);
+ const next = await rigImageTo3dModel(record.id, {}, { silent: true }).catch((err) => {
+ // The gate's sentence IS the error message — surface it verbatim.
+ toast.error(err?.message || 'Rigging failed.');
+ return null;
+ });
+ if (mountedRef.current) setBusy(false);
+ if (next && mountedRef.current) {
+ onRecordChange(next);
+ toast.success('Character rigged.');
+ }
+ }, [busy, record.id, onRecordChange, mountedRef]);
+
+ if (!enabled) return null;
+
+ const rig = record.rig || null;
+ const rigging = busy || rig?.status === 'rigging';
+ const canRig = record.status === 'ready' && Boolean(record.assetPath) && readiness?.ready === true;
+ const blockedReason = readiness && !readiness.ready ? riggingReasonLabel(readiness.reason) : null;
+
+ return (
+ <section className="mt-4 rounded-lg border border-port-border bg-port-card p-3">
+ <div className="flex flex-wrap items-center justify-between gap-3">
+ <div className="flex items-center gap-2">
+ <Bone className="h-4 w-4 text-port-accent" />
+ <h2 className="text-sm font-semibold text-white">Character rig</h2>
+ </div>
+ <button
+ type="button"
+ onClick={handleRig}
+ disabled={!canRig || rigging}
+ title={blockedReason || (record.status === 'ready' ? undefined : 'Render this model first')}
+ className="inline-flex min-h-[44px] items-center gap-1.5 rounded-md border border-port-border px-3 py-1.5 text-xs text-gray-300 hover:border-port-accent hover:text-white disabled:cursor-not-allowed disabled:opacity-40"
+ >
+ {rigging ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Bone className="h-3.5 w-3.5" />}
+ {rigging ? 'Rigging…' : 'Rig this character'}
+ </button>
+ </div>
+
+ {!readiness && <p className="mt-2 text-xs text-gray-500">Checking the rigging runtime…</p>}
+ {blockedReason && (
+ <p className="mt-2 text-xs text-port-warning">
+ {blockedReason}. Provision it from Settings &gt; Features.
+ </p>
+ )}
+
+ {rig?.status === 'failed' && rig.error && (
+ <div className="mt-2 flex items-start gap-1.5 rounded-md border border-port-error/30 bg-port-error/10 px-3 py-2 text-xs text-port-error">
+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
+ <span>{rig.error}</span>
+ </div>
+ )}
+
+ {rig?.status === 'ready' && rig.assetPath && (
+ <div className="mt-2 space-y-1 text-xs text-gray-400">
+ <p className="text-port-success">
+ Rigged against {rig.summary?.bones ?? 0} bones
+ {rig.summary?.vertices ? ` · ${rig.summary.vertices.toLocaleString()} vertices` : ''}
+ {rig.bytes ? ` · ${formatBytes(rig.bytes)}` : ''}
+ </p>
+ <p>
+ Automatic weighting left{' '}
+ {`${((rig.summary?.unweightedFractionAfterHeat ?? 0) * 100).toFixed(1)}%`} unweighted
+ {' '}(ceiling {`${((rig.summary?.unweightedCeiling ?? 0) * 100).toFixed(1)}%`}); the nearest-bone pass
+ completed {rig.summary?.nearestBoneCompleted ?? 0}.
+ </p>
+ <a
+ href={rig.assetPath}
+ className="inline-block underline decoration-dotted hover:text-gray-200"
+ >
+ Download rigged .glb
+ </a>
+ </div>
+ )}
+
+ {!rig && canRig && (
+ <p className="mt-2 text-xs text-gray-500">
+ Not rigged yet. Rigging welds the decoded mesh, applies bone-heat weighting, and
+ publishes only if the unweighted fraction clears the measured gate.
+ </p>
+ )}
+ </section>
+ );
+}
diff --git a/client/src/components/media/RigPanel.test.jsx b/client/src/components/media/RigPanel.test.jsx
new file mode 100644
index 0000000000..c5fcf1f282
--- /dev/null
+++ b/client/src/components/media/RigPanel.test.jsx
@@ -0,0 +1,83 @@
+import { describe, expect, it, beforeEach, vi } from 'vitest';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+
+const mock = vi.hoisted(() => ({ getRiggingReadiness: vi.fn(), rigImageTo3dModel: vi.fn() }));
+vi.mock('../../services/api', () => mock);
+
+const features = vi.hoisted(() => ({ enabled: true }));
+vi.mock('../../hooks/useInstanceFeatures', () => ({
+ useInstanceFeatures: () => ({ isFeatureEnabled: () => features.enabled }),
+}));
+
+const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));
+vi.mock('../ui/Toast', () => ({ default: toast }));
+
+import RigPanel from './RigPanel';
+
+const READY_RECORD = { id: 'image3d-example', status: 'ready', assetPath: '/data/image-to-3d/image3d-example/model.glb' };
+const RUNTIME_READY = { ready: true, reason: null };
+
+describe('RigPanel', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ features.enabled = true;
+ mock.getRiggingReadiness.mockResolvedValue(RUNTIME_READY);
+ });
+
+ it('stays out of the page entirely when the rigging feature is off', () => {
+ features.enabled = false;
+ const { container } = render(<RigPanel record={READY_RECORD} onRecordChange={() => {}} />);
+ expect(container).toBeEmptyDOMElement();
+ expect(mock.getRiggingReadiness).not.toHaveBeenCalled();
+ });
+
+ it('names the blocker instead of offering a button that would fail', async () => {
+ mock.getRiggingReadiness.mockResolvedValue({ ready: false, reason: 'module-unimportable' });
+ render(<RigPanel record={READY_RECORD} onRecordChange={() => {}} />);
+
+ expect(await screen.findByText(/only half installed/i)).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: /rig this character/i })).toBeDisabled();
+ });
+
+ it('rigs on click and hands the updated record back to the page', async () => {
+ const rigged = {
+ ...READY_RECORD,
+ rig: {
+ status: 'ready',
+ assetPath: '/data/image-to-3d/image3d-example/rig/rig-example/character.rigged.glb',
+ bytes: 2_400_000,
+ summary: {
+ vertices: 10000, bones: 17, unweightedFractionAfterHeat: 0.002,
+ nearestBoneCompleted: 20, unweightedCeiling: 0.005,
+ },
+ },
+ };
+ mock.rigImageTo3dModel.mockResolvedValue(rigged);
+ const onRecordChange = vi.fn();
+ const { rerender } = render(<RigPanel record={READY_RECORD} onRecordChange={onRecordChange} />);
+
+ await waitFor(() => expect(screen.getByRole('button', { name: /rig this character/i })).toBeEnabled());
+ fireEvent.click(screen.getByRole('button', { name: /rig this character/i }));
+
+ await waitFor(() => expect(onRecordChange).toHaveBeenCalledWith(rigged));
+ expect(mock.rigImageTo3dModel).toHaveBeenCalledWith('image3d-example', {}, { silent: true });
+
+ rerender(<RigPanel record={rigged} onRecordChange={onRecordChange} />);
+ expect(screen.getByText(/Rigged against 17 bones/)).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: /download rigged/i }))
+ .toHaveAttribute('href', rigged.rig.assetPath);
+ });
+
+ it('shows the measured sentence a refused rig came back with, not a generic error', async () => {
+ const failed = {
+ ...READY_RECORD,
+ rig: {
+ status: 'failed',
+ error: 'Automatic weighting left too much of the mesh unweighted: automatic weighting left 4.2% of 10000 '
+ + 'vertices unweighted, ceiling is 0.5%.',
+ },
+ };
+ render(<RigPanel record={failed} onRecordChange={() => {}} />);
+ expect(await screen.findByText(/4\.2% of 10000 vertices unweighted, ceiling is 0\.5%/)).toBeInTheDocument();
+ });
+});
diff --git a/client/src/pages/Media3DDetail.jsx b/client/src/pages/Media3DDetail.jsx
index 0b08c0cea2..f436051a2c 100644
--- a/client/src/pages/Media3DDetail.jsx
+++ b/client/src/pages/Media3DDetail.jsx
@@ -9,6 +9,7 @@ import GlbViewer from '../components/media/GlbViewer';
import MediaImage from '../components/MediaImage';
import InlineConfirmRow from '../components/ui/InlineConfirmRow';
import ImageTo3dRenderOptions from '../components/media/ImageTo3dRenderOptions';
+import RigPanel from '../components/media/RigPanel';
import { fieldsFromRun, renderOptionsBody, runWantsTransparency } from '../lib/imageTo3dRenderOptions';
import { imageTo3dStatusMeta } from '../components/media/imageTo3dStatus';
import toast from '../components/ui/Toast';
@@ -267,6 +268,8 @@ export default function Media3DDetail() {
)}
</div>
</section>
+
+ <RigPanel record={record} onRecordChange={setRecord} />
</div>
);
}
diff --git a/client/src/pages/Media3DDetail.test.jsx b/client/src/pages/Media3DDetail.test.jsx
index 262f6025a4..c108a2ecf9 100644
--- a/client/src/pages/Media3DDetail.test.jsx
+++ b/client/src/pages/Media3DDetail.test.jsx
@@ -21,6 +21,9 @@ vi.mock('../components/media/GlbViewer', () => ({
),
}));
vi.mock('../components/MediaImage', () => ({ default: ({ alt, src }) => <img alt={alt} src={src} /> }));
+// The rig panel owns its own readiness fetch + feature gate (covered by
+// RigPanel.test.jsx); stubbing it keeps this suite about the page.
+vi.mock('../components/media/RigPanel', () => ({ default: () => <div data-testid="rig-panel" /> }));
vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));
const record = (over = {}) => ({
diff --git a/client/src/services/README.md b/client/src/services/README.md
index f18917880e..84de8aefd5 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -149,4 +149,4 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `uiInteract.js` | Execute voice `ui_click` / `ui_fill` / `ui_select` against live DOM. |
| `domIndex.js` | DOM indexer for voice accessibility mode. |
| `staleBuildToast.jsx` | Sticky toast shown when server's build id differs from client's. |
-| `apiRigging.js` | Character rigging (`GET /rigging/readiness`): whether this install's Blender runtime is provisioned, the resolved interpreter, the module version, and the install command when it is not. |
+| `apiRigging.js` | Character rigging. `getRiggingReadiness()` (`GET /rigging/readiness`): whether this install's Blender runtime is provisioned, the resolved interpreter, the module version, the install command when it is not, and the auto-skin threshold defaults. `rigImageTo3dModel(id, body)` (`POST /rigging/models/:id`): auto-skin a rendered mesh behind the measured weight-coverage gate, resolving with the updated model record. |
diff --git a/client/src/services/apiRigging.js b/client/src/services/apiRigging.js
index 591a1d4205..d55c95b35e 100644
--- a/client/src/services/apiRigging.js
+++ b/client/src/services/apiRigging.js
@@ -6,3 +6,15 @@ import { request } from './apiCore.js';
export const getRiggingReadiness = ({ refresh = false, ...options } = {}) =>
request(`/rigging/readiness${refresh ? '?refresh=1' : ''}`, options);
+
+// Auto-skin a rendered image-to-3D mesh. Runs INLINE (minutes of local Blender CPU) and
+// resolves with the updated model record, so a refusal arrives as an error carrying the
+// measured sentence — "automatic weighting left 4.2% of vertices unweighted, ceiling is
+// 0.5%" — rather than a generic failure the user cannot act on. `input` may carry the
+// advanced overrides (`skeletonHint`, `weldDistance`, `unweightedCeiling`).
+export const rigImageTo3dModel = (id, input = {}, options) =>
+ request(`/rigging/models/${encodeURIComponent(id)}`, {
+ method: 'POST',
+ body: JSON.stringify(input),
+ ...options,
+ });
diff --git a/server/lib/README.md b/server/lib/README.md
index f2cbb3f35e..48c4a49600 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -395,6 +395,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `migrationMarker.js` | Shared marker-file helpers for one-time migration/repair/reconcile scripts — `markerExists(filename)` (boolean gate), `readMarker(filename)` (parsed payload or null), `writeMarker(filename, payload)` (atomic write). All anchor `filename` under `PATHS.data` and use `tryReadFile`/`atomicWrite` so a crash can't leave a truncated marker. |
| `goalFeatureMap.js` | Deterministic goal `category` → PortOS feature-area map (deep-links sourced from `NAV_COMMANDS`). `getGoalFeatureAreas(goal)` honors the per-goal `featureAreas` override, else the category default. Mirrored byte-for-byte to `client/src/lib/`. |
| `navManifest.js` | Single source of truth for nav (`⌘K` palette + voice). Add an entry when you add a page. |
+| `noReplaceMove.js` | `moveWithoutReplace(from, to)` — publish a staged file into its final name WITHOUT ever clobbering an existing one. `fs.rename` silently replaces its destination, which is the wrong default for a derived artifact; this uses `link(2)` + `unlink(2)`, so an existing destination fails atomically with `MOVE_DEST_EXISTS` and both files survive. Refuses rather than degrading when the filesystem cannot express it (`MOVE_CROSS_DEVICE`, `MOVE_NO_REPLACE_UNSUPPORTED`) — a `stat`-then-`rename` fallback would be a race. Used by the rigging publication contract (`services/rigging/autoSkin.js`). |
| `personaTraitBlend.js` | Digital-twin persona trait-blending (M34 P7). Blends a persona's `traitAdjustments` against the base twin's communication profile + Big-Five into a "Communication Calibration" directive. Mirrored to `client/src/lib/`. |
| `textUtils.js` | Pure dependency-free prose helpers. `countWords(text)` is the canonical whitespace-token count (`\S+`); `trimTo(value, max)` trims and bounds strings without coercing non-strings, and is safe for shared modules consumed by the browser; `escapeRegExp(value)` is the one to import instead of re-inlining the escape (a guard in `textUtils.test.js` fails the suite when a copy reappears in any non-test source under `server/`); `kebabCase(text)` is the canonical ASCII slug transform (PLAN.md `[slug]` ids and `planner:<model>` labels). |
| `pipelineIssueOrder.js` | Pure renumber algorithm for pipeline issues. |
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index 14a07b9dc9..66cf135e26 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -13989,6 +13989,14 @@
"server/routes/review.js"
]
},
+ {
+ "method": "POST",
+ "path": "/api/rigging/models/:id",
+ "mountPath": "/api/rigging",
+ "sources": [
+ "server/routes/rigging.js"
+ ]
+ },
{
"method": "GET",
"path": "/api/rigging/readiness",
@@ -17424,8 +17432,8 @@
],
"stats": {
"mounts": 146,
- "operations": 2158,
- "declarations": 2166,
+ "operations": 2159,
+ "declarations": 2167,
"sourceFiles": 229
}
}
diff --git a/server/lib/index.js b/server/lib/index.js
index 33359dbfa2..1f7b650221 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -367,6 +367,7 @@ export * from './assetProvenance.js';
export * from './migrationMarker.js';
export * from './modelPricing.js';
export * from './navManifest.js';
+export * from './noReplaceMove.js';
export * from './instanceFeatureRegistry.js';
export * from './credentialRegistry.js';
export * from './usageRange.js';
diff --git a/server/lib/noReplaceMove.js b/server/lib/noReplaceMove.js
new file mode 100644
index 0000000000..f5ab4edd09
--- /dev/null
+++ b/server/lib/noReplaceMove.js
@@ -0,0 +1,79 @@
+/**
+ * Move a file into place WITHOUT ever replacing what is already there.
+ *
+ * `fs.rename` is the wrong primitive for publishing a derived artifact: POSIX
+ * `rename(2)` silently clobbers an existing destination, so a second run that
+ * collides on a name destroys the first run's output with no error to report. What a
+ * publication step wants is the opposite default — a collision is a BUG, and the
+ * correct response is to fail loudly and leave both files intact.
+ *
+ * Node exposes no `RENAME_NOREPLACE` flag, so the portable POSIX way to get that
+ * guarantee is `link(2)` + `unlink(2)`: `link` fails atomically with `EEXIST` when the
+ * destination exists, and there is no window in which the destination is absent. The
+ * source is unlinked only after the link succeeds, so an interruption leaves the
+ * source in place rather than losing the bytes.
+ *
+ * Hard links only exist within one filesystem and only on filesystems that implement
+ * them. Rather than degrading to a `stat`-then-`rename` (which is a race — another
+ * writer can create the destination between the two calls, and `rename` would then
+ * eat it), this FAILS with a named code. A caller that genuinely wants replacement
+ * should call `rename` itself and say so.
+ *
+ * Errors carry a stable `.code` so callers can branch without string matching:
+ * `MOVE_DEST_EXISTS` — the destination is already published (never overwritten)
+ * `MOVE_CROSS_DEVICE` — source and destination are on different filesystems
+ * `MOVE_NO_REPLACE_UNSUPPORTED` — this filesystem cannot express a no-replace move
+ */
+
+import { link, unlink } from 'node:fs/promises';
+
+/** A collision: the destination already exists and was NOT touched. */
+export const MOVE_DEST_EXISTS = 'MOVE_DEST_EXISTS';
+/** Source and destination live on different filesystems — stage inside the target dir. */
+export const MOVE_CROSS_DEVICE = 'MOVE_CROSS_DEVICE';
+/** The filesystem has no no-replace primitive; refusing rather than racing a rename. */
+export const MOVE_NO_REPLACE_UNSUPPORTED = 'MOVE_NO_REPLACE_UNSUPPORTED';
+
+// `link` reports "this filesystem does not do hard links" through several different
+// errnos depending on the OS and the mount (FAT/exFAT/SMB/some FUSE mounts).
+const UNSUPPORTED_ERRNOS = new Set(['EPERM', 'ENOSYS', 'EOPNOTSUPP', 'ENOTSUP', 'EACCES']);
+
+const fail = (code, message, cause) => {
+ const error = new Error(message);
+ error.code = code;
+ if (cause) error.cause = cause;
+ return error;
+};
+
+/**
+ * Link `from` to `to`, then unlink `from`. Never replaces an existing `to`.
+ *
+ * @param {string} from Source path (typically a file staged in a temp dir).
+ * @param {string} to Destination path. Its parent directory must already exist.
+ * @param {{linkImpl?: Function, unlinkImpl?: Function}} [io] Injectable fs seam for tests.
+ * @returns {Promise<string>} The destination path.
+ */
+export async function moveWithoutReplace(from, to, { linkImpl = link, unlinkImpl = unlink } = {}) {
+ await linkImpl(from, to).catch((error) => {
+ if (error?.code === 'EEXIST') {
+ throw fail(MOVE_DEST_EXISTS, `Refusing to replace an existing file: ${to}`, error);
+ }
+ if (error?.code === 'EXDEV') {
+ throw fail(MOVE_CROSS_DEVICE, `Cannot publish across filesystems: ${from} → ${to}`, error);
+ }
+ if (UNSUPPORTED_ERRNOS.has(error?.code)) {
+ throw fail(
+ MOVE_NO_REPLACE_UNSUPPORTED,
+ `This filesystem cannot move a file without risking a replace (${error.code}): ${to}`,
+ error,
+ );
+ }
+ throw error;
+ });
+ // The bytes are already reachable at `to`; a failure to drop the staged name leaves
+ // scratch behind but must not fail a completed publication.
+ await unlinkImpl(from).catch((error) => {
+ console.warn(`⚠️ Published ${to} but could not remove the staged copy ${from}: ${error.message}`);
+ });
+ return to;
+}
diff --git a/server/lib/noReplaceMove.test.js b/server/lib/noReplaceMove.test.js
new file mode 100644
index 0000000000..9978489574
--- /dev/null
+++ b/server/lib/noReplaceMove.test.js
@@ -0,0 +1,65 @@
+/**
+ * `moveWithoutReplace` exists because `fs.rename` clobbers its destination, so the one
+ * behavior worth pinning is the refusal — against a REAL temp directory, since the
+ * guarantee comes from `link(2)`'s errno rather than from any logic here. The injected
+ * seams cover only the two errnos a normal filesystem will not produce on demand.
+ */
+
+import { mkdtemp, readFile, rm, writeFile, stat } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import {
+ MOVE_CROSS_DEVICE,
+ MOVE_DEST_EXISTS,
+ MOVE_NO_REPLACE_UNSUPPORTED,
+ moveWithoutReplace,
+} from './noReplaceMove.js';
+
+describe('moveWithoutReplace', () => {
+ let dir;
+ beforeEach(async () => { dir = await mkdtemp(join(tmpdir(), 'portos-no-replace-')); });
+ afterEach(async () => { await rm(dir, { recursive: true, force: true }); });
+
+ it('moves the bytes and drops the staged name', async () => {
+ const from = join(dir, 'staged.glb');
+ const to = join(dir, 'published.glb');
+ await writeFile(from, 'rigged-bytes');
+
+ expect(await moveWithoutReplace(from, to)).toBe(to);
+ expect(await readFile(to, 'utf8')).toBe('rigged-bytes');
+ await expect(stat(from)).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
+ it('refuses a collision and leaves BOTH files byte-intact', async () => {
+ const from = join(dir, 'staged.glb');
+ const to = join(dir, 'published.glb');
+ await writeFile(from, 'new');
+ await writeFile(to, 'already-published');
+
+ await expect(moveWithoutReplace(from, to)).rejects.toMatchObject({ code: MOVE_DEST_EXISTS });
+ expect(await readFile(to, 'utf8')).toBe('already-published');
+ expect(await readFile(from, 'utf8')).toBe('new');
+ });
+
+ it('fails cleanly rather than degrading when the filesystem cannot express a no-replace move', async () => {
+ const unsupported = Object.assign(new Error('operation not permitted'), { code: 'EPERM' });
+ await expect(moveWithoutReplace('/a', '/b', { linkImpl: async () => { throw unsupported; } }))
+ .rejects.toMatchObject({ code: MOVE_NO_REPLACE_UNSUPPORTED });
+
+ const crossDevice = Object.assign(new Error('cross-device link'), { code: 'EXDEV' });
+ await expect(moveWithoutReplace('/a', '/b', { linkImpl: async () => { throw crossDevice; } }))
+ .rejects.toMatchObject({ code: MOVE_CROSS_DEVICE });
+ });
+
+ it('keeps the publication when only the staged-name cleanup fails', async () => {
+ const from = join(dir, 'staged.glb');
+ const to = join(dir, 'published.glb');
+ await writeFile(from, 'rigged-bytes');
+
+ await expect(moveWithoutReplace(from, to, {
+ unlinkImpl: async () => { throw new Error('unlink refused'); },
+ })).resolves.toBe(to);
+ expect(await readFile(to, 'utf8')).toBe('rigged-bytes');
+ });
+});
diff --git a/server/routes/rigging.js b/server/routes/rigging.js
index b3c7b6deb1..00a2bfed2c 100644
--- a/server/routes/rigging.js
+++ b/server/routes/rigging.js
@@ -2,7 +2,10 @@ import { Router } from 'express';
import { z } from 'zod';
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 { getRiggingReadiness } from '../services/rigging/readiness.js';
+import { SKELETON_BONE_MAPPINGS } from '../services/rigging/skeletonMapping.js';
const router = Router();
@@ -12,6 +15,24 @@ const readinessQuerySchema = z.object({
refresh: z.enum(['1', 'true']).optional(),
});
+/**
+ * Advanced overrides for one auto-skin run. Both are ABSENT by default: the ceiling and
+ * the weld distance are defended thresholds (`autoSkinReport.js` documents why each
+ * number is where it is), so a request that omits them gets the defended value, and one
+ * that supplies a number gets it validated against the range the gate can still reason
+ * about. Nothing here persists between runs.
+ */
+const rigRequestSchema = z.object({
+ skeletonHint: z.enum(Object.keys(SKELETON_BONE_MAPPINGS)).optional(),
+ weldDistance: z.number().min(AUTO_SKIN_LIMITS.weldDistanceMin).max(AUTO_SKIN_LIMITS.weldDistanceMax).optional(),
+ unweightedCeiling: z.number()
+ .min(AUTO_SKIN_LIMITS.unweightedCeilingMin)
+ .max(AUTO_SKIN_LIMITS.unweightedCeilingMax)
+ .optional(),
+});
+
+const modelIdSchema = z.object({ id: z.string().trim().min(1).max(128) });
+
/**
* 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`).
@@ -19,10 +40,29 @@ const readinessQuerySchema = z.object({
* Read-only and on-demand: the Blender import probe runs from here (and from the
* instance-feature detector), never from `server/index.js` boot, so a fresh install
* pays nothing at startup for a feature nobody has asked for.
+ *
+ * `defaults` rides along so the client can label the advanced overrides with the real
+ * thresholds instead of hardcoding a second copy of them.
*/
router.get('/readiness', asyncHandler(async (req, res) => {
const { refresh } = validateRequest(readinessQuerySchema, req.query);
- res.json(await getRiggingReadiness({ refresh: Boolean(refresh) }));
+ const readiness = await getRiggingReadiness({ refresh: Boolean(refresh) });
+ res.json({ ...readiness, defaults: AUTO_SKIN_DEFAULTS, skeletons: Object.keys(SKELETON_BONE_MAPPINGS) });
+}));
+
+/**
+ * Auto-skin one rendered image-to-3D model against a humanoid armature, publishing the
+ * rigged GLB + its report only if the measured weight coverage clears the gate.
+ *
+ * Explicit user action only — a rig is minutes of local CPU, so nothing here runs from
+ * boot or on a schedule. Runs inline (the gate answer is the response) rather than as a
+ * background job: refusing to publish is the product, and a fire-and-forget 202 would
+ * bury the number that explains the refusal.
+ */
+router.post('/models/:id', asyncHandler(async (req, res) => {
+ const { id } = validateRequest(modelIdSchema, req.params);
+ const options = validateRequest(rigRequestSchema, req.body ?? {});
+ res.json(await rigImageTo3dModel(id, options));
}));
export default router;
diff --git a/server/services/backup.js b/server/services/backup.js
index e6c2610854..14d24cba0b 100644
--- a/server/services/backup.js
+++ b/server/services/backup.js
@@ -122,6 +122,14 @@ export const DEFAULT_EXCLUDES = [
// copies of a fixture that ships in the repo — restoring one would restore a
// half-finished agent edit, which is worse than not having it.
{ path: '/model-tests/sandboxes/', reason: 'Capability-test agent sandboxes — throwaway working copies of a repo fixture, recreated per run', overridable: false },
+ // Anchored, like every entry here. Scratch for ONE in-flight auto-skin run: the
+ // worker's staging copy of the rigged GLB plus its job/report files, deleted the
+ // moment the run publishes or fails (services/rigging/autoSkin.js). A snapshot that
+ // caught it mid-run would restore a half-written mesh next to the published pair.
+ // The PUBLISHED rig (rig/<rigId>/) is deliberately NOT excluded: re-deriving it needs
+ // 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 },
{ 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/imageTo3d/db.js b/server/services/imageTo3d/db.js
index 55fcfa1b27..a1775bb2f7 100644
--- a/server/services/imageTo3d/db.js
+++ b/server/services/imageTo3d/db.js
@@ -66,6 +66,12 @@ export async function createModel(input) {
},
status: 'draft',
assetPath: null,
+ // The published auto-skin artifact for this mesh, or `null` when it has never been
+ // rigged (`services/rigging/autoSkin.js` owns the shape). The whole record lives in
+ // the `data` JSONB column, so this needs no table change — but every install that
+ // predates rigging has records with the key ABSENT, so readers must treat absent and
+ // `null` the same and never assume the field exists.
+ rig: null,
error: null,
generationOperationId: null,
runs: [],
diff --git a/server/services/rigging/autoSkin.js b/server/services/rigging/autoSkin.js
new file mode 100644
index 0000000000..6fe700920b
--- /dev/null
+++ b/server/services/rigging/autoSkin.js
@@ -0,0 +1,333 @@
+/**
+ * Character rigging — auto-skin orchestration and the publication contract.
+ *
+ * Phase 1 (`runtime.js` / `readiness.js`) answers whether this host can run Blender at
+ * all. This module is what actually rigs a generated mesh, and — more to the point —
+ * what refuses to publish one that did not measure up. The gate itself is a pure
+ * reducer in `autoSkinReport.js`; everything here is the plumbing around it.
+ *
+ * ## The publication contract
+ *
+ * A rig produces two files that are only meaningful as a PAIR: the GLB, and the JSON
+ * report carrying the GLB's SHA-256. Both are written into a staging directory inside
+ * the record's own render dir and then moved into place, and the ORDER and the MOVE
+ * are both load-bearing:
+ *
+ * - **GLB first, report last.** The report is the commit marker. A consumer treats
+ * the pair as usable only when the report exists AND its digest matches the GLB on
+ * disk, so a run interrupted between the two moves is *detectable* rather than
+ * silently loaded as a finished rig.
+ * - **No-replace moves.** `moveWithoutReplace` (`server/lib/noReplaceMove.js`) uses
+ * `link(2)`, which fails atomically on an existing destination. A name collision is
+ * an error, never an overwrite — and on a filesystem that cannot express that, the
+ * publish fails cleanly instead of degrading to a racy `rename`.
+ * - **Nothing published is mutated afterward.** Each run gets its own `rig/<rigId>/`
+ * directory, so a re-rig is a new directory rather than a rewrite of the last one.
+ * The single exception is the rollback below, which unlinks a GLB whose report never
+ * landed — that pair was never publishable in the first place.
+ * - **The source `model.glb` is never touched**, the same rule `sourceKeying.js`
+ * follows for the shared gallery file. The worker opens it read-only and exports to
+ * the staging dir.
+ *
+ * Child-process boundary outside the request lifecycle, so the worker's outcomes flow
+ * through a resolved promise and a thrown `ServerError` at the orchestration layer —
+ * never a throw from inside a spawn callback (AGENTS.md).
+ */
+
+import { randomUUID } from 'node:crypto';
+import { 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';
+import {
+ AUTO_SKIN_REPORT_VERSION,
+ describeAutoSkinFailure,
+ reduceAutoSkinGate,
+ resolveAutoSkinThresholds,
+ summarizeAutoSkin,
+ thresholdsForWorker,
+} from './autoSkinReport.js';
+import { getRiggingReadiness, riggingReasonLabel } from './readiness.js';
+import { resolveRiggingPython } from './runtime.js';
+import { buildHumanoidArmatureSpec } from './skeletonMapping.js';
+import { getModel, mutateModel } from '../imageTo3d/db.js';
+
+/** Per-record directory holding every rig run's published pair. */
+export const RIG_DIR_NAME = 'rig';
+/** Scratch root inside `rig/`. Excluded from backups — see `services/backup.js`. */
+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));
+
+/**
+ * Every path one rig 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, rigId: string}} opts
+ */
+export function rigRunPaths({ recordDir, rigId }) {
+ const rigRoot = join(recordDir, RIG_DIR_NAME);
+ const publishDir = join(rigRoot, rigId);
+ const stageDir = join(rigRoot, RIG_STAGING_DIR_NAME, rigId);
+ return {
+ rigRoot,
+ publishDir,
+ stageDir,
+ inputGlb: join(recordDir, 'model.glb'),
+ stagedGlb: join(stageDir, RIGGED_GLB_NAME),
+ stagedReport: join(stageDir, RIG_REPORT_NAME),
+ workerReport: join(stageDir, 'worker-report.json'),
+ jobFile: join(stageDir, 'job.json'),
+ publishedGlb: join(publishDir, RIGGED_GLB_NAME),
+ publishedReport: join(publishDir, RIG_REPORT_NAME),
+ };
+}
+
+/** The served URL for a published rig (static-mounted under `/data`). */
+export const riggedAssetUrl = (modelId, rigId) => `/data/image-to-3d/${modelId}/${RIG_DIR_NAME}/${rigId}/${RIGGED_GLB_NAME}`;
+
+/**
+ * Publish the staged pair. GLB first, report last, neither replacing anything.
+ *
+ * The report is finalized HERE rather than by the worker, because the digest can only
+ * be taken once the bytes the worker will actually publish are final — a worker-written
+ * digest would describe a file the worker could still have rewritten.
+ *
+ * If the report move fails after the GLB landed, the GLB is unlinked: that pair was
+ * never publishable, and leaving a half-pair behind would block the retry with a
+ * permanent collision on a file no reader will ever accept.
+ *
+ * @param {{paths: object, report: object}} opts
+ * @returns {Promise<{glbPath: string, reportPath: string, sha256: string, bytes: number}>}
+ */
+export async function publishRigArtifacts({ paths, report }) {
+ const [sha256, info] = await Promise.all([sha256File(paths.stagedGlb), stat(paths.stagedGlb)]);
+ await atomicWrite(paths.stagedReport, JSON.stringify({
+ ...report,
+ report_version: AUTO_SKIN_REPORT_VERSION,
+ output_file: RIGGED_GLB_NAME,
+ output_bytes: info.size,
+ output_sha256: sha256,
+ }, null, 2));
+
+ await ensureDir(paths.publishDir);
+ await moveWithoutReplace(paths.stagedGlb, paths.publishedGlb);
+ await moveWithoutReplace(paths.stagedReport, paths.publishedReport).catch(async (error) => {
+ await rm(paths.publishedGlb, { force: true }).catch(() => {});
+ throw error;
+ });
+ return { glbPath: paths.publishedGlb, reportPath: paths.publishedReport, sha256, bytes: info.size };
+}
+
+/**
+ * Read a published rig, refusing anything that is not a matched pair.
+ *
+ * This is the consumer half of the contract: a report without its GLB, a GLB without
+ * its report, or a digest that disagrees are all `{ ok: false }` with a named reason —
+ * never a partially-loaded rig. Callers must not fall back to "well, the GLB is there".
+ *
+ * @param {{publishDir: string}} opts
+ * @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' };
+ const exists = await stat(glbPath).then((info) => info.isFile(), () => false);
+ if (!exists) return { ok: false, reason: 'missing-glb' };
+ const digest = await sha256File(glbPath);
+ if (digest !== report.output_sha256) return { ok: false, reason: 'digest-mismatch' };
+ 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 });
+
+/**
+ * Rig one mesh: 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, skeletonHint?: string, overrides?: object,
+ * readiness?: object, python?: string|null, spawnImpl?: Function, rigId?: string,
+ * timeoutMs?: number}} opts
+ * @returns {Promise<{rigId: string, assetPath: string, reportPath: string, sha256: string,
+ * bytes: number, summary: object, report: object}>}
+ */
+export async function runAutoSkin({
+ modelId,
+ recordDir,
+ skeletonHint = 'mixamo',
+ overrides = {},
+ readiness,
+ python,
+ spawnImpl,
+ rigId = `rig-${randomUUID()}`,
+ timeoutMs,
+}) {
+ 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 thresholds = resolveAutoSkinThresholds(overrides);
+ const paths = rigRunPaths({ recordDir, rigId });
+ const sourceExists = await stat(paths.inputGlb).then((info) => info.isFile(), () => false);
+ if (!sourceExists) throw rigError('This model has no rendered mesh to rig yet.', 'RIGGING_NO_SOURCE_MESH');
+
+ await ensureDir(paths.stageDir);
+ try {
+ await atomicWrite(paths.jobFile, JSON.stringify({
+ input_glb: paths.inputGlb,
+ output_glb: paths.stagedGlb,
+ report_path: paths.workerReport,
+ thresholds: thresholdsForWorker(thresholds),
+ armature: buildHumanoidArmatureSpec({ skeletonHint }),
+ }, null, 2));
+
+ const { code, tail } = await runWorker({ python: interpreter, 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 ? reduceAutoSkinGate(report, thresholds) : null;
+ if (gate && !gate.ok) {
+ throw rigError(describeAutoSkinFailure(gate.reason, gate.metrics), 'RIGGING_GATE_FAILED', {
+ context: { reason: gate.reason, metrics: gate.metrics },
+ });
+ }
+ if (code !== 0 || !report) {
+ throw rigError(
+ `The rigging 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 rigError('The rigging worker reported success but exported no mesh.', 'RIGGING_NO_OUTPUT');
+
+ const published = await publishRigArtifacts({ paths, report });
+ console.log(`🦴 Rigged ${modelId} as ${rigId}: ${gate.metrics.boneCount} bones, `
+ + `${gate.metrics.verticesAfterWeld} vertices, ${gate.metrics.nearestBoneCompleted} filled by nearest bone`);
+ return {
+ rigId,
+ assetPath: riggedAssetUrl(modelId, rigId),
+ reportPath: published.reportPath,
+ sha256: published.sha256,
+ bytes: published.bytes,
+ summary: summarizeAutoSkin(gate.metrics),
+ 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 rig per record at a time. A double-click would otherwise put two Blender
+// processes on the same mesh — a re-entrancy guard, not a multi-actor lock
+// (AGENTS.md single-user trust model).
+const rigsInFlight = new Set();
+
+/**
+ * Rig a stored image-to-3D record and persist the result on it. The record's `rig`
+ * 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 {{skeletonHint?: string, weldDistance?: number, unweightedCeiling?: number}} [options]
+ * @param {object} [deps] Injectable seams (`run`, `now`) for tests.
+ * @returns {Promise<object>} The updated record.
+ */
+export async function rigImageTo3dModel(modelId, options = {}, { run = runAutoSkin, now = () => new Date().toISOString() } = {}) {
+ const model = await getModel(modelId);
+ if (!model) throw new ServerError('Image-to-3D model not found', { status: 404, code: 'NOT_FOUND' });
+ if (model.status !== 'ready' || !model.assetPath) {
+ throw rigError('Render this model before rigging it.', 'RIGGING_NO_SOURCE_MESH');
+ }
+ if (rigsInFlight.has(modelId)) {
+ throw new ServerError('This model is already being rigged.', { status: 409, code: 'RIGGING_IN_FLIGHT' });
+ }
+
+ rigsInFlight.add(modelId);
+ const startedAt = now();
+ await mutateModel(modelId, (current) => ({ ...current, rig: { ...(current.rig || {}), status: 'rigging', startedAt, error: null, reason: null } }));
+ try {
+ const result = await run({
+ modelId,
+ recordDir: join(PATHS.imageTo3d, modelId),
+ skeletonHint: options.skeletonHint,
+ overrides: options,
+ });
+ return await mutateModel(modelId, (current) => ({
+ ...current,
+ rig: {
+ status: 'ready',
+ rigId: result.rigId,
+ assetPath: result.assetPath,
+ sha256: result.sha256,
+ bytes: result.bytes,
+ summary: result.summary,
+ skeletonHint: options.skeletonHint || 'mixamo',
+ error: null,
+ reason: null,
+ startedAt,
+ completedAt: now(),
+ },
+ }));
+ } catch (error) {
+ await mutateModel(modelId, (current) => ({
+ ...current,
+ rig: {
+ ...(current.rig || {}),
+ status: 'failed',
+ 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 {
+ rigsInFlight.delete(modelId);
+ }
+}
diff --git a/server/services/rigging/autoSkin.test.js b/server/services/rigging/autoSkin.test.js
new file mode 100644
index 0000000000..59847036a0
--- /dev/null
+++ b/server/services/rigging/autoSkin.test.js
@@ -0,0 +1,172 @@
+/**
+ * The publication contract, against a REAL temp directory.
+ *
+ * The gate arithmetic is covered by `autoSkinReport.test.js`; what is tested here is
+ * the half that only a filesystem can prove: that a collision refuses instead of
+ * overwriting, that an aborted run publishes NEITHER artifact, and that a reader
+ * rejects a pair whose digest disagrees. Those are the three failure modes the whole
+ * "GLB first, report last, no-replace move" design exists to make detectable.
+ *
+ * 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. That is the point of the design: the contract is
+ * about what lands on disk, 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 { AUTO_SKIN_DEFAULTS, thresholdsForWorker } = await import('./autoSkinReport.js');
+const {
+ publishRigArtifacts, readRiggedArtifact, rigRunPaths, runAutoSkin, RIGGED_GLB_NAME, RIG_REPORT_NAME,
+} = await import('./autoSkin.js');
+
+const READY = { ready: true, reason: null, interpreter: '/opt/envs/rigging/bin/python' };
+
+const cleanReport = () => ({
+ report_version: 1,
+ thresholds: thresholdsForWorker(AUTO_SKIN_DEFAULTS),
+ vertices: { before_weld: 30_000, after_weld: 10_000, welded: 20_000 },
+ removed_components: { count: 1, vertices: 4, fraction: 0.0004 },
+ weighting: {
+ after_heat: { weighted: 9_990, unweighted: 10, unweighted_fraction: 0.001 },
+ nearest_bone_completed: 10,
+ after_fill: { weighted: 10_000, unweighted: 0, unweighted_fraction: 0 },
+ },
+ armature: { name: 'PortOSHumanoid', bone_count: 17, bones: [] },
+ round_trip: { mesh: true, armature: true, armature_modifier: true },
+});
+
+/**
+ * A worker stand-in: writes whatever the case wants on disk, then exits with `code`.
+ * `child.on('close')` fires on a later tick, exactly as a real spawn does.
+ */
+const fakeWorker = ({ code = 0, write }) => (_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'));
+ if (write) await write(job);
+ })
+ .then(() => child.emit('close', code), (error) => child.emit('error', error));
+ return child;
+};
+
+const publishCleanRig = (report = cleanReport()) => fakeWorker({
+ write: async (job) => {
+ await writeFile(job.output_glb, 'rigged-glb-bytes');
+ await writeFile(job.report_path, JSON.stringify(report));
+ },
+});
+
+describe('rigging publication contract', () => {
+ let dir;
+ let recordDir;
+ beforeEach(async () => {
+ dir = await mkdtemp(join(tmpdir(), 'portos-rig-'));
+ recordDir = join(dir, 'image3d-example');
+ await mkdir(recordDir, { recursive: true });
+ await writeFile(join(recordDir, 'model.glb'), 'source-mesh');
+ });
+ afterEach(async () => { await rm(dir, { recursive: true, force: true }); });
+
+ const run = (overrides = {}) => runAutoSkin({
+ modelId: 'image3d-example', recordDir, readiness: READY, rigId: 'rig-example', ...overrides,
+ });
+
+ it('publishes a matched pair whose report carries the GLB digest, and never touches the source', async () => {
+ const result = await run({ spawnImpl: publishCleanRig() });
+ const paths = rigRunPaths({ recordDir, rigId: 'rig-example' });
+
+ const report = JSON.parse(await readFile(paths.publishedReport, 'utf8'));
+ expect(report.output_file).toBe(RIGGED_GLB_NAME);
+ expect(report.output_sha256).toBe(result.sha256);
+ expect(await readRiggedArtifact({ publishDir: paths.publishDir })).toMatchObject({ ok: true });
+ expect(result.assetPath).toBe(`/data/image-to-3d/image3d-example/rig/rig-example/${RIGGED_GLB_NAME}`);
+ expect(await readFile(join(recordDir, 'model.glb'), 'utf8')).toBe('source-mesh');
+ // The staging directory is scratch and must not survive a completed run.
+ expect(existsSync(paths.stageDir)).toBe(false);
+ });
+
+ it('refuses a name collision rather than overwriting a published rig', async () => {
+ const paths = rigRunPaths({ recordDir, rigId: 'rig-example' });
+ await mkdir(paths.publishDir, { recursive: true });
+ await writeFile(paths.publishedGlb, 'an-earlier-rig');
+
+ await expect(run({ spawnImpl: publishCleanRig() })).rejects.toMatchObject({ code: 'MOVE_DEST_EXISTS' });
+ expect(await readFile(paths.publishedGlb, 'utf8')).toBe('an-earlier-rig');
+ });
+
+ it('publishes NEITHER artifact when the gate refuses the run', async () => {
+ const failing = cleanReport();
+ failing.weighting.after_heat = { weighted: 9_580, unweighted: 420, unweighted_fraction: 0.042 };
+ const spawnImpl = fakeWorker({
+ code: 2,
+ write: async (job) => { await writeFile(job.report_path, JSON.stringify(failing)); },
+ });
+
+ await expect(run({ spawnImpl })).rejects.toThrow(
+ /automatic weighting left 4\.2% of 10000 vertices unweighted, ceiling is 0\.5%/,
+ );
+ const paths = rigRunPaths({ recordDir, rigId: 'rig-example' });
+ expect(existsSync(paths.publishedGlb)).toBe(false);
+ expect(existsSync(paths.publishedReport)).toBe(false);
+ expect(existsSync(paths.stageDir)).toBe(false);
+ });
+
+ it('reports the worker exit when it produced no readable report at all', async () => {
+ const spawnImpl = fakeWorker({ code: 3, write: async () => {} });
+ await expect(run({ spawnImpl })).rejects.toMatchObject({ code: 'RIGGING_WORKER_FAILED' });
+ });
+
+ it('refuses to run at all when the Blender runtime is not ready', async () => {
+ await expect(run({ readiness: { ready: false, reason: 'module-unimportable' }, spawnImpl: publishCleanRig() }))
+ .rejects.toMatchObject({ code: 'RIGGING_RUNTIME_UNAVAILABLE', status: 409 });
+ });
+});
+
+describe('published rig reader', () => {
+ let dir;
+ beforeEach(async () => { dir = await mkdtemp(join(tmpdir(), 'portos-rig-read-')); });
+ afterEach(async () => { await rm(dir, { recursive: true, force: true }); });
+
+ const stage = async (rigId) => {
+ const recordDir = join(dir, 'image3d-example');
+ const paths = rigRunPaths({ recordDir, rigId });
+ await mkdir(paths.stageDir, { recursive: true });
+ await writeFile(paths.stagedGlb, 'rigged-glb-bytes');
+ return { recordDir, paths };
+ };
+
+ it('rejects a report whose digest disagrees with the GLB on disk', async () => {
+ const { paths } = await stage('rig-digest');
+ await publishRigArtifacts({ paths, report: cleanReport() });
+ // Simulate the file changing under a published report — the pair is no longer the
+ // one the digest describes, so it must not load as a finished rig.
+ await writeFile(paths.publishedGlb, 'different-bytes');
+ expect(await readRiggedArtifact({ publishDir: paths.publishDir }))
+ .toEqual({ ok: false, reason: 'digest-mismatch' });
+ });
+
+ it('rejects a half-published pair in either direction', async () => {
+ const { paths } = await stage('rig-half');
+ await publishRigArtifacts({ paths, report: cleanReport() });
+
+ await rm(paths.publishedGlb);
+ expect(await readRiggedArtifact({ publishDir: paths.publishDir }))
+ .toEqual({ ok: false, reason: 'missing-glb' });
+
+ await writeFile(paths.publishedGlb, 'rigged-glb-bytes');
+ await rm(join(paths.publishDir, RIG_REPORT_NAME));
+ expect(await readRiggedArtifact({ publishDir: paths.publishDir }))
+ .toEqual({ ok: false, reason: 'missing-report' });
+ });
+});
diff --git a/server/services/rigging/autoSkinReport.js b/server/services/rigging/autoSkinReport.js
new file mode 100644
index 0000000000..d9c6f96eee
--- /dev/null
+++ b/server/services/rigging/autoSkinReport.js
@@ -0,0 +1,246 @@
+/**
+ * Character rigging — the measured gate on publishing an auto-skinned mesh.
+ *
+ * The point of this lane is NOT that it calls Blender's automatic weighting. It is
+ * that it treats "how much of this mesh actually ended up bound to a bone" as a
+ * measured precondition for publication, the way `imageTo3d/sourceKeying.js` refuses
+ * to key a background it cannot confidently identify. A neural image-to-3D decoder
+ * emits a triangle soup with duplicated vertices; naive bone-heat weighting on that
+ * mesh leaves chunks of geometry bound to nothing, and the user does not find out
+ * until the character animates and a hand stays behind.
+ *
+ * Everything here is PURE — a reducer over an already-measured report — so every
+ * branch is unit-testable against fixtures on a host with no Blender install. The
+ * worker (`autoSkinWorker.py`) applies the same gate itself and exits non-zero rather
+ * than exporting a mesh that fails it; this module re-runs the gate over what the
+ * worker REPORTED before anything is published. That is deliberate defense in depth:
+ * the worker's job is to not export, this module's job is to not publish, and a worker
+ * that miscounts (or is replaced by an older copy) must not be able to talk the
+ * orchestrator into publishing a broken rig.
+ */
+
+/** Report schema version. Bump when a key's meaning changes, not when one is added. */
+export const AUTO_SKIN_REPORT_VERSION = 1;
+
+/**
+ * The thresholds, and why each is where it is.
+ *
+ * `weldDistance` — tight enough that only *coincident* vertices merge. A decoded mesh
+ * duplicates a vertex per incident triangle at bit-identical positions; 1e-6 in the
+ * mesh's own units collapses exactly those and cannot pull two genuinely distinct
+ * surface points together at any plausible model scale.
+ *
+ * `unweightedCeiling` — the number that makes this a gate rather than a hope. Bone-heat
+ * weighting either converges over a manifold or fails over a specific region; a
+ * converged solve leaves a few isolated vertices (interior pockets, degenerate
+ * slivers), never a percent of the mesh. 0.5% is comfortably above the former and an
+ * order of magnitude below "a hand did not get weighted" on any mesh worth rigging.
+ *
+ * `maxRemovedComponentFraction` / `maxComponentVertices` — the conservative pre-pass.
+ * Stray specks defeat heat weighting, so tiny disconnected islands are deleted first;
+ * but a threshold that can eat a limb is worse than the problem. A component must be
+ * both tiny in itself (<= 8 vertices) AND the combined removal must stay under 0.2%
+ * of the mesh, so the pre-pass is arithmetically incapable of removing a body part.
+ */
+export const AUTO_SKIN_DEFAULTS = Object.freeze({
+ weldDistance: 1e-6,
+ unweightedCeiling: 0.005,
+ maxRemovedComponentFraction: 0.002,
+ maxComponentVertices: 8,
+});
+
+/** Advanced-override bounds, mirrored by the route's Zod schema. */
+export const AUTO_SKIN_LIMITS = Object.freeze({
+ weldDistanceMin: 1e-9,
+ weldDistanceMax: 1e-3,
+ unweightedCeilingMin: 0,
+ unweightedCeilingMax: 0.25,
+});
+
+/**
+ * Why a rig was refused. Codes are stable; the user-facing sentence is built by
+ * `describeAutoSkinFailure` below so it can name the measured numbers — a generic
+ * "rigging failed" is exactly the outcome this feature exists to avoid.
+ */
+export const AUTO_SKIN_FAILURE_REASONS = Object.freeze({
+ 'report-malformed': 'The rigging worker did not report usable measurements',
+ 'thresholds-mismatch': 'The rigging worker used different thresholds than requested',
+ 'empty-mesh': 'The mesh had no vertices left to rig',
+ 'component-removal-over-ceiling': 'The cleanup pass removed too much of the mesh',
+ 'unweighted-over-ceiling': 'Automatic weighting left too much of the mesh unweighted',
+ 'fill-incomplete': 'The nearest-bone pass did not finish weighting the mesh',
+ 'no-armature': 'The rig produced no armature',
+ 'round-trip-failed': 'The exported file did not survive a re-import check',
+});
+
+const isCount = (value) => Number.isInteger(value) && value >= 0;
+const isFraction = (value) => Number.isFinite(value) && value >= 0 && value <= 1;
+
+// Percent with one decimal — the form every gate message quotes.
+const formatPercent = (fraction) => `${(Number(fraction) * 100).toFixed(1)}%`;
+
+/**
+ * The measurement subtree a gate decision needs, or `null` when the report cannot
+ * supply it. Pulled out so "the worker emitted nonsense" is one branch rather than a
+ * scattering of optional chaining.
+ */
+function readMeasurements(report) {
+ const vertices = report?.vertices;
+ const removed = report?.removed_components;
+ const heat = report?.weighting?.after_heat;
+ const fill = report?.weighting?.after_fill;
+ if (!isCount(vertices?.before_weld) || !isCount(vertices?.after_weld) || !isCount(vertices?.welded)) return null;
+ if (!isCount(removed?.count) || !isCount(removed?.vertices) || !isFraction(removed?.fraction)) return null;
+ if (!isCount(heat?.weighted) || !isCount(heat?.unweighted) || !isFraction(heat?.unweighted_fraction)) return null;
+ if (!isCount(fill?.weighted) || !isCount(fill?.unweighted) || !isFraction(fill?.unweighted_fraction)) return null;
+ if (!isCount(report?.weighting?.nearest_bone_completed)) return null;
+ return { vertices, removed, heat, fill, nearestBoneCompleted: report.weighting.nearest_bone_completed };
+}
+
+// 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.weld_distance === requested.weldDistance
+ && reported.unweighted_ceiling === requested.unweightedCeiling
+ && reported.max_removed_component_fraction === requested.maxRemovedComponentFraction
+ && reported.max_component_vertices === requested.maxComponentVertices;
+
+/**
+ * Decide whether a reported rig may be published. Pure.
+ *
+ * Order is the point:
+ * - a report we cannot read is never "fine", it is unreadable;
+ * - thresholds are checked against what the CALLER asked for, so a worker cannot
+ * relax its own gate and have the orchestrator honour the relaxed number;
+ * - the empty mesh is separated from the coverage gate, because 0 of 0 vertices
+ * unweighted is a fraction of 0 and would otherwise pass every check;
+ * - the pre-pass ceiling comes before the coverage gate: if cleanup ate geometry,
+ * the coverage number is measured against the wrong mesh and means nothing;
+ * - the post-fill assertion is last and absolute — after the nearest-bone completion
+ * there must be ZERO unweighted vertices, not "few".
+ *
+ * @param {object} report The worker's report JSON (snake_case, as written to disk).
+ * @param {object} [thresholds] The thresholds the caller requested.
+ * @returns {{ok: boolean, reason: string|null, metrics: object|null}}
+ */
+export function reduceAutoSkinGate(report, thresholds = AUTO_SKIN_DEFAULTS) {
+ const measured = readMeasurements(report);
+ if (!measured) return { ok: false, reason: 'report-malformed', metrics: null };
+
+ const metrics = {
+ verticesBeforeWeld: measured.vertices.before_weld,
+ verticesAfterWeld: measured.vertices.after_weld,
+ welded: measured.vertices.welded,
+ removedComponents: measured.removed.count,
+ removedComponentVertices: measured.removed.vertices,
+ removedComponentFraction: measured.removed.fraction,
+ unweightedAfterHeat: measured.heat.unweighted,
+ unweightedFractionAfterHeat: measured.heat.unweighted_fraction,
+ nearestBoneCompleted: measured.nearestBoneCompleted,
+ unweightedAfterFill: measured.fill.unweighted,
+ unweightedFractionAfterFill: measured.fill.unweighted_fraction,
+ boneCount: Number.isInteger(report?.armature?.bone_count) ? report.armature.bone_count : 0,
+ thresholds,
+ };
+
+ if (!thresholdsAgree(report?.thresholds, thresholds)) return { ok: false, reason: 'thresholds-mismatch', metrics };
+ if (metrics.verticesAfterWeld === 0) return { ok: false, reason: 'empty-mesh', metrics };
+ if (metrics.boneCount === 0) return { ok: false, reason: 'no-armature', metrics };
+ if (metrics.removedComponentFraction > thresholds.maxRemovedComponentFraction) {
+ return { ok: false, reason: 'component-removal-over-ceiling', metrics };
+ }
+ if (metrics.unweightedFractionAfterHeat > thresholds.unweightedCeiling) {
+ return { ok: false, reason: 'unweighted-over-ceiling', metrics };
+ }
+ if (metrics.unweightedAfterFill !== 0) return { ok: false, reason: 'fill-incomplete', metrics };
+
+ const roundTrip = report?.round_trip;
+ if (roundTrip?.armature !== true || roundTrip?.armature_modifier !== true || roundTrip?.mesh !== true) {
+ return { ok: false, reason: 'round-trip-failed', metrics };
+ }
+ return { ok: true, reason: null, metrics };
+}
+
+/**
+ * The sentence a user sees when a rig is refused. It names the measured number and the
+ * threshold it missed, because "rigging failed" tells them nothing they can act on.
+ *
+ * @param {string} reason A key of `AUTO_SKIN_FAILURE_REASONS`.
+ * @param {object|null} [metrics] The metrics from `reduceAutoSkinGate`.
+ * @returns {string}
+ */
+export function describeAutoSkinFailure(reason, metrics = null) {
+ const headline = Object.hasOwn(AUTO_SKIN_FAILURE_REASONS, reason ?? '')
+ ? AUTO_SKIN_FAILURE_REASONS[reason]
+ : 'Rigging failed for an unrecognized reason';
+ if (!metrics) return `${headline}.`;
+ switch (reason) {
+ case 'unweighted-over-ceiling':
+ return `${headline}: automatic weighting left ${formatPercent(metrics.unweightedFractionAfterHeat)} of `
+ + `${metrics.verticesAfterWeld} vertices unweighted, ceiling is `
+ + `${formatPercent(metrics.thresholds.unweightedCeiling)}.`;
+ case 'component-removal-over-ceiling':
+ return `${headline}: the pre-pass removed ${metrics.removedComponentVertices} vertices across `
+ + `${metrics.removedComponents} disconnected pieces (${formatPercent(metrics.removedComponentFraction)}), `
+ + `ceiling is ${formatPercent(metrics.thresholds.maxRemovedComponentFraction)}.`;
+ case 'fill-incomplete':
+ return `${headline}: ${metrics.unweightedAfterFill} of ${metrics.verticesAfterWeld} vertices were still `
+ + 'unweighted after the nearest-bone pass, which must leave none.';
+ case 'empty-mesh':
+ return `${headline}: ${metrics.verticesBeforeWeld} vertices went in and ${metrics.verticesAfterWeld} came out `
+ + 'of the weld.';
+ case 'no-armature':
+ return `${headline}: the worker reported no bones, so nothing could be weighted.`;
+ case 'thresholds-mismatch':
+ return `${headline}: the report's thresholds do not match the requested `
+ + `${formatPercent(metrics.thresholds.unweightedCeiling)} unweighted ceiling / `
+ + `${metrics.thresholds.weldDistance} weld distance.`;
+ default:
+ return `${headline}.`;
+ }
+}
+
+/**
+ * The compact rig 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.
+ *
+ * @param {object|null} metrics
+ * @returns {object|null}
+ */
+export function summarizeAutoSkin(metrics) {
+ if (!metrics) return null;
+ return {
+ vertices: metrics.verticesAfterWeld,
+ welded: metrics.welded,
+ bones: metrics.boneCount,
+ unweightedFractionAfterHeat: metrics.unweightedFractionAfterHeat,
+ nearestBoneCompleted: metrics.nearestBoneCompleted,
+ unweightedCeiling: metrics.thresholds.unweightedCeiling,
+ };
+}
+
+/**
+ * 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 {{weldDistance?: number, unweightedCeiling?: number}} [overrides]
+ * @returns {object} A frozen threshold set.
+ */
+export function resolveAutoSkinThresholds(overrides = {}) {
+ return Object.freeze({
+ ...AUTO_SKIN_DEFAULTS,
+ ...(Number.isFinite(overrides.weldDistance) ? { weldDistance: overrides.weldDistance } : {}),
+ ...(Number.isFinite(overrides.unweightedCeiling) ? { unweightedCeiling: overrides.unweightedCeiling } : {}),
+ });
+}
+
+/** The threshold block the worker is asked to echo back, in its own snake_case. */
+export const thresholdsForWorker = (thresholds) => ({
+ weld_distance: thresholds.weldDistance,
+ unweighted_ceiling: thresholds.unweightedCeiling,
+ max_removed_component_fraction: thresholds.maxRemovedComponentFraction,
+ max_component_vertices: thresholds.maxComponentVertices,
+});
diff --git a/server/services/rigging/autoSkinReport.test.js b/server/services/rigging/autoSkinReport.test.js
new file mode 100644
index 0000000000..d886fc2b5d
--- /dev/null
+++ b/server/services/rigging/autoSkinReport.test.js
@@ -0,0 +1,145 @@
+/**
+ * The gate reducer is the part of this lane that decides whether a rig is publishable,
+ * and it is the part no Blender-less host can exercise any other way. These cases are
+ * fixture-driven measurements, not re-implementations of the arithmetic: each names a
+ * distinct way a rig can be wrong and asserts the decision, not the computation.
+ */
+
+import { describe, expect, it } from 'vitest';
+import {
+ AUTO_SKIN_DEFAULTS,
+ describeAutoSkinFailure,
+ reduceAutoSkinGate,
+ resolveAutoSkinThresholds,
+ summarizeAutoSkin,
+ thresholdsForWorker,
+} from './autoSkinReport.js';
+
+/** A clean 10,000-vertex rig: welded, fully weighted, round-tripped. */
+const cleanReport = (overrides = {}) => ({
+ report_version: 1,
+ thresholds: thresholdsForWorker(AUTO_SKIN_DEFAULTS),
+ vertices: { before_weld: 30_000, after_weld: 10_000, welded: 20_000 },
+ removed_components: { count: 2, vertices: 9, fraction: 0.0009 },
+ weighting: {
+ after_heat: { weighted: 9_980, unweighted: 20, unweighted_fraction: 0.002 },
+ nearest_bone_completed: 20,
+ after_fill: { weighted: 10_000, unweighted: 0, unweighted_fraction: 0 },
+ },
+ armature: { name: 'PortOSHumanoid', bone_count: 17, bones: [] },
+ round_trip: { mesh: true, armature: true, armature_modifier: true },
+ ...overrides,
+});
+
+const withHeat = (unweighted, total = 10_000) => cleanReport({
+ weighting: {
+ after_heat: { weighted: total - unweighted, unweighted, unweighted_fraction: unweighted / total },
+ nearest_bone_completed: unweighted,
+ after_fill: { weighted: total, unweighted: 0, unweighted_fraction: 0 },
+ },
+});
+
+describe('auto-skin publication gate', () => {
+ it('publishes a rig that welded, weighted, filled and round-tripped', () => {
+ expect(reduceAutoSkinGate(cleanReport())).toMatchObject({ ok: true, reason: null });
+ });
+
+ it('holds the ceiling in both directions', () => {
+ // 0.5% of 10,000 is exactly 50 — at the ceiling passes, one vertex past it fails.
+ expect(reduceAutoSkinGate(withHeat(50))).toMatchObject({ ok: true });
+ expect(reduceAutoSkinGate(withHeat(51))).toMatchObject({ ok: false, reason: 'unweighted-over-ceiling' });
+ });
+
+ it('refuses an empty mesh instead of reading 0-of-0 as full coverage', () => {
+ const empty = cleanReport({
+ vertices: { before_weld: 12, after_weld: 0, welded: 12 },
+ weighting: {
+ after_heat: { weighted: 0, unweighted: 0, unweighted_fraction: 0 },
+ nearest_bone_completed: 0,
+ after_fill: { weighted: 0, unweighted: 0, unweighted_fraction: 0 },
+ },
+ });
+ expect(reduceAutoSkinGate(empty)).toMatchObject({ ok: false, reason: 'empty-mesh' });
+ });
+
+ it('refuses when the nearest-bone pass still left vertices unweighted', () => {
+ const leftover = cleanReport({
+ weighting: {
+ after_heat: { weighted: 9_980, unweighted: 20, unweighted_fraction: 0.002 },
+ nearest_bone_completed: 17,
+ after_fill: { weighted: 9_997, unweighted: 3, unweighted_fraction: 0.0003 },
+ },
+ });
+ const result = reduceAutoSkinGate(leftover);
+ expect(result).toMatchObject({ ok: false, reason: 'fill-incomplete' });
+ // The assertion is absolute — a fraction well under the ceiling is still a failure.
+ expect(result.metrics.unweightedFractionAfterFill).toBeLessThan(AUTO_SKIN_DEFAULTS.unweightedCeiling);
+ });
+
+ it('refuses a cleanup pass that removed more of the mesh than the guard allows', () => {
+ const greedy = cleanReport({ removed_components: { count: 40, vertices: 300, fraction: 0.03 } });
+ expect(reduceAutoSkinGate(greedy)).toMatchObject({ ok: false, reason: 'component-removal-over-ceiling' });
+ // …and the guard is not simply "any removal": the clean fixture removes 9 vertices.
+ expect(reduceAutoSkinGate(cleanReport())).toMatchObject({ ok: true });
+ });
+
+ it('refuses a worker that gated itself against different thresholds', () => {
+ const relaxed = cleanReport({
+ thresholds: { ...thresholdsForWorker(AUTO_SKIN_DEFAULTS), unweighted_ceiling: 0.2 },
+ });
+ expect(reduceAutoSkinGate(relaxed)).toMatchObject({ ok: false, reason: 'thresholds-mismatch' });
+ });
+
+ it('refuses a report it cannot read rather than treating absence as success', () => {
+ expect(reduceAutoSkinGate(null)).toMatchObject({ ok: false, reason: 'report-malformed', metrics: null });
+ expect(reduceAutoSkinGate(cleanReport({ vertices: { before_weld: 10 } })))
+ .toMatchObject({ ok: false, reason: 'report-malformed' });
+ });
+
+ it('refuses an export that did not survive re-import, and a rig with no bones', () => {
+ expect(reduceAutoSkinGate(cleanReport({ round_trip: { mesh: true, armature: true, armature_modifier: false } })))
+ .toMatchObject({ ok: false, reason: 'round-trip-failed' });
+ expect(reduceAutoSkinGate(cleanReport({ armature: { name: null, bone_count: 0, bones: [] } })))
+ .toMatchObject({ ok: false, reason: 'no-armature' });
+ });
+
+ it('honors an advanced ceiling override on both sides of the new line', () => {
+ const thresholds = resolveAutoSkinThresholds({ unweightedCeiling: 0.02 });
+ const report = cleanReport({ thresholds: thresholdsForWorker(thresholds) });
+ expect(reduceAutoSkinGate({
+ ...report,
+ weighting: { ...report.weighting, after_heat: { weighted: 9_850, unweighted: 150, unweighted_fraction: 0.015 } },
+ }, thresholds)).toMatchObject({ ok: true });
+ expect(reduceAutoSkinGate({
+ ...report,
+ weighting: { ...report.weighting, after_heat: { weighted: 9_700, unweighted: 300, unweighted_fraction: 0.03 } },
+ }, thresholds)).toMatchObject({ ok: false, reason: 'unweighted-over-ceiling' });
+ });
+});
+
+describe('auto-skin failure prose', () => {
+ it('names the measured number and the threshold it missed', () => {
+ const { reason, metrics } = reduceAutoSkinGate(withHeat(420));
+ expect(describeAutoSkinFailure(reason, metrics))
+ .toContain('automatic weighting left 4.2% of 10000 vertices unweighted, ceiling is 0.5%');
+ });
+
+ it('degrades to the headline rather than rendering an unknown code', () => {
+ expect(describeAutoSkinFailure('brand-new-code', null)).toBe('Rigging failed for an unrecognized reason.');
+ });
+});
+
+describe('auto-skin record summary', () => {
+ it('carries the evidence the UI shows and nothing that belongs in the on-disk report', () => {
+ const { metrics } = reduceAutoSkinGate(cleanReport());
+ expect(summarizeAutoSkin(metrics)).toEqual({
+ vertices: 10_000,
+ welded: 20_000,
+ bones: 17,
+ unweightedFractionAfterHeat: 0.002,
+ nearestBoneCompleted: 20,
+ unweightedCeiling: AUTO_SKIN_DEFAULTS.unweightedCeiling,
+ });
+ expect(summarizeAutoSkin(null)).toBeNull();
+ });
+});
diff --git a/server/services/rigging/autoSkinWorker.py b/server/services/rigging/autoSkinWorker.py
new file mode 100644
index 0000000000..fc89694051
--- /dev/null
+++ b/server/services/rigging/autoSkinWorker.py
@@ -0,0 +1,380 @@
+#!/usr/bin/env python3
+"""Blender-side auto-skin worker for PortOS character rigging.
+
+Sited alongside the other Python workers in `server/services/imageTo3d/`
+(`trellis2NormalBake.py`, `trellis2RestoreFillHoles.py`): the Node orchestrator
+(`autoSkin.js`) writes a job JSON, spawns this file with the rigging env's
+interpreter, and reads back the report this file writes.
+
+WHY THE STEPS ARE IN THIS ORDER
+-------------------------------
+A neural image-to-3D decoder emits a triangle soup: every triangle carries its own
+copy of each corner vertex, at bit-identical positions. That mesh *looks* watertight
+and is topologically dust, which is exactly the input on which Blender's automatic
+(bone-heat) weighting quietly gives up over whole regions. So:
+
+1. Weld coincident vertices at a tight distance. This is what makes heat weighting
+ converge at all -- it is not a cleanup nicety, it is the precondition.
+2. Drop any weights that arrived with the mesh. A re-derived rig must have ONE
+ provenance; blending a decoder's guess with a fresh solve produces a result
+ nobody can reason about later.
+3. Delete tiny disconnected components -- but only specks, and only while the
+ combined removal stays under a hard fraction of the mesh. Stray specks defeat
+ heat weighting; a threshold loose enough to eat a hand is worse than the problem
+ it solves, so this pass is arithmetically incapable of removing a body part.
+4. Bone-heat weight against the humanoid armature the orchestrator specified.
+5. MEASURE, then decide. Count vertices carrying a positive deform weight. If the
+ unweighted fraction exceeds the configured ceiling, FAIL -- do not export. Below
+ it, complete the remainder with a nearest-bone fill and assert zero unweighted.
+6. Round-trip validate: re-import the exported GLB and confirm the armature, the
+ armature modifier, and the mesh all survived the exporter.
+
+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 input GLB is opened read-only and never written back.
+"""
+
+import argparse
+import json
+import os
+import sys
+import traceback
+
+REPORT_VERSION = 1
+
+
+def _fail(message, code=2):
+ """Named, non-zero exit. stderr is what the orchestrator tails."""
+ sys.stderr.write("auto-skin: %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 _bounds(mesh_objects):
+ """Axis-aligned world-space bounds over every mesh object."""
+ import mathutils # noqa: PLC0415 -- Blender-only import, deferred to the runtime path
+
+ lo = [float("inf")] * 3
+ hi = [float("-inf")] * 3
+ for obj in mesh_objects:
+ for corner in obj.bound_box:
+ world = obj.matrix_world @ mathutils.Vector(corner)
+ for axis in range(3):
+ lo[axis] = min(lo[axis], world[axis])
+ hi[axis] = max(hi[axis], world[axis])
+ return lo, hi
+
+
+def _weld(bmesh, mesh_object, distance):
+ """Merge coincident vertices; returns (before, after)."""
+ mesh = mesh_object.data
+ before = len(mesh.vertices)
+ bm = bmesh.new()
+ bm.from_mesh(mesh)
+ bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=distance)
+ bm.to_mesh(mesh)
+ bm.free()
+ mesh.update()
+ return before, len(mesh.vertices)
+
+
+def _linked_components(bmesh, mesh_object):
+ """Vertex-index sets for each edge-connected component."""
+ bm = bmesh.new()
+ bm.from_mesh(mesh_object.data)
+ bm.verts.ensure_lookup_table()
+ seen = set()
+ components = []
+ for vert in bm.verts:
+ if vert.index in seen:
+ continue
+ stack = [vert]
+ component = set()
+ while stack:
+ current = stack.pop()
+ if current.index in component:
+ continue
+ component.add(current.index)
+ for edge in current.link_edges:
+ other = edge.other_vert(current)
+ if other.index not in component:
+ stack.append(other)
+ seen |= component
+ components.append(component)
+ bm.free()
+ return components
+
+
+def _remove_specks(bmesh, mesh_object, max_component_vertices, max_fraction):
+ """Delete tiny islands, refusing the whole pass if it would exceed `max_fraction`.
+
+ All-or-nothing on purpose: a partial sweep would leave the mesh in a state neither
+ the caller nor the report describes.
+ """
+ total = len(mesh_object.data.vertices)
+ components = _linked_components(bmesh, mesh_object)
+ specks = [c for c in components if len(c) <= max_component_vertices]
+ # Never delete the whole mesh: if every component is speck-sized the mesh IS specks,
+ # and the coverage gate below is the right place for that to fail.
+ if len(specks) == len(components):
+ return 0, 0, 0.0
+ doomed = set().union(*specks) if specks else set()
+ fraction = (len(doomed) / total) if total else 0.0
+ if not doomed or fraction > max_fraction:
+ return 0, 0, fraction
+
+ bm = bmesh.new()
+ bm.from_mesh(mesh_object.data)
+ bm.verts.ensure_lookup_table()
+ bmesh.ops.delete(bm, geom=[bm.verts[i] for i in sorted(doomed)], context="VERTS")
+ bm.to_mesh(mesh_object.data)
+ bm.free()
+ mesh_object.data.update()
+ return len(specks), len(doomed), fraction
+
+
+def _build_armature(bpy, spec, lo, hi):
+ """Create the humanoid armature from the orchestrator's unit-space spec.
+
+ Head/tail arrive as fractions of the mesh's own bounding box, so one spec fits any
+ character proportion and the bone NAMES stay owned by `skeletonMapping.js` rather
+ than being duplicated here.
+ """
+ import mathutils # noqa: PLC0415 -- Blender-only import, deferred to the runtime path
+
+ size = [max(hi[axis] - lo[axis], 1e-6) for axis in range(3)]
+
+ def place(unit):
+ return tuple(lo[axis] + unit[axis] * size[axis] for axis in range(3))
+
+ armature_data = bpy.data.armatures.new("PortOSHumanoid")
+ armature = bpy.data.objects.new("PortOSHumanoid", armature_data)
+ bpy.context.collection.objects.link(armature)
+ bpy.context.view_layer.objects.active = armature
+ bpy.ops.object.mode_set(mode="EDIT")
+ created = {}
+ for bone_spec in spec["bones"]:
+ bone = armature_data.edit_bones.new(bone_spec["name"])
+ bone.head = place(bone_spec["head"])
+ bone.tail = place(bone_spec["tail"])
+ # A zero-length bone is silently discarded by Blender, which would turn a
+ # placement bug into a mysteriously short bone list.
+ if (bone.tail - bone.head).length < 1e-6:
+ bone.tail = bone.head + mathutils.Vector((0.0, size[1] * 0.02, 0.0))
+ created[bone_spec["name"]] = bone
+ for bone_spec in spec["bones"]:
+ parent = bone_spec.get("parent")
+ if parent and parent in created:
+ created[bone_spec["name"]].parent = created[parent]
+ bpy.ops.object.mode_set(mode="OBJECT")
+ return armature
+
+
+def _count_weighted(mesh_object, deform_group_indices):
+ """Vertices carrying a positive weight in at least one DEFORM group."""
+ weighted = 0
+ for vert in mesh_object.data.vertices:
+ for group in vert.groups:
+ if group.group in deform_group_indices and group.weight > 0.0:
+ weighted += 1
+ break
+ return weighted
+
+
+def _nearest_bone_fill(mesh_object, armature, deform_group_indices):
+ """Bind each still-unweighted vertex to the nearest bone at full weight."""
+ import mathutils # noqa: PLC0415 -- only importable inside the Blender runtime
+
+ bones = [b for b in armature.pose.bones if b.name in mesh_object.vertex_groups]
+ if not bones:
+ return 0
+ segments = [
+ (b.name, armature.matrix_world @ b.head, armature.matrix_world @ b.tail)
+ for b in bones
+ ]
+ completed = 0
+ for vert in mesh_object.data.vertices:
+ if any(g.group in deform_group_indices and g.weight > 0.0 for g in vert.groups):
+ continue
+ point = mesh_object.matrix_world @ vert.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
+ mesh_object.vertex_groups[best_name].add([vert.index], 1.0, "REPLACE")
+ completed += 1
+ return completed
+
+
+def _round_trip(bpy, path, armature_name):
+ """Re-import the export and confirm the rig survived it."""
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ bpy.ops.import_scene.gltf(filepath=path)
+ meshes = [o for o in bpy.data.objects if o.type == "MESH"]
+ armatures = [o for o in bpy.data.objects if o.type == "ARMATURE"]
+ has_modifier = any(
+ any(m.type == "ARMATURE" and m.object is not None for m in o.modifiers) for o in meshes
+ )
+ return {
+ "mesh": bool(meshes),
+ "armature": bool(armatures),
+ "armature_modifier": bool(has_modifier),
+ "imported_armature": armatures[0].name if armatures else None,
+ "expected_armature": armature_name,
+ }
+
+
+def run(job):
+ import bmesh # noqa: PLC0415 -- Blender-only imports stay inside the runtime path
+ import bpy # noqa: PLC0415
+
+ thresholds = job["thresholds"]
+ report = {
+ "report_version": REPORT_VERSION,
+ "thresholds": thresholds,
+ "vertices": {"before_weld": 0, "after_weld": 0, "welded": 0},
+ "removed_components": {"count": 0, "vertices": 0, "fraction": 0.0},
+ "weighting": {
+ "after_heat": {"weighted": 0, "unweighted": 0, "unweighted_fraction": 0.0},
+ "nearest_bone_completed": 0,
+ "after_fill": {"weighted": 0, "unweighted": 0, "unweighted_fraction": 0.0},
+ },
+ "armature": {"name": None, "bone_count": 0, "bones": []},
+ "round_trip": {"mesh": False, "armature": False, "armature_modifier": False},
+ }
+
+ bpy.ops.wm.read_factory_settings(use_empty=True)
+ bpy.ops.import_scene.gltf(filepath=job["input_glb"])
+ meshes = [o for o in bpy.data.objects if o.type == "MESH"]
+ if not meshes:
+ _write_report(job["report_path"], report)
+ return _fail("the source GLB contains no mesh")
+
+ # One mesh object to rig. A decoder emits a single surface; joining any extras keeps
+ # the weight measurement over the whole thing rather than an arbitrary first object.
+ bpy.ops.object.select_all(action="DESELECT")
+ for obj in meshes:
+ obj.select_set(True)
+ bpy.context.view_layer.objects.active = meshes[0]
+ if len(meshes) > 1:
+ bpy.ops.object.join()
+ mesh_object = bpy.context.view_layer.objects.active
+
+ # (1) Weld, (2) discard inherited weights -- one provenance, not a blend.
+ before, after = _weld(bmesh, mesh_object, thresholds["weld_distance"])
+ report["vertices"] = {"before_weld": before, "after_weld": after, "welded": before - after}
+ for group in list(mesh_object.vertex_groups):
+ mesh_object.vertex_groups.remove(group)
+
+ if after == 0:
+ _write_report(job["report_path"], report)
+ return _fail("the mesh had no vertices left after welding")
+
+ # (3) Conservative speck removal.
+ removed_count, removed_vertices, removed_fraction = _remove_specks(
+ bmesh, mesh_object,
+ thresholds["max_component_vertices"], thresholds["max_removed_component_fraction"],
+ )
+ report["removed_components"] = {
+ "count": removed_count, "vertices": removed_vertices, "fraction": removed_fraction,
+ }
+
+ # (4) Bone-heat weighting against the humanoid armature.
+ lo, hi = _bounds([mesh_object])
+ armature = _build_armature(bpy, job["armature"], lo, hi)
+ report["armature"] = {
+ "name": armature.name,
+ "bone_count": len(armature.data.bones),
+ "bones": [b.name for b in armature.data.bones],
+ }
+ 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.object.parent_set(type="ARMATURE_AUTO")
+
+ deform_group_indices = {
+ mesh_object.vertex_groups[b.name].index
+ for b in armature.data.bones
+ if b.name in mesh_object.vertex_groups
+ }
+ total = len(mesh_object.data.vertices)
+
+ # (5) Measure, then decide.
+ weighted = _count_weighted(mesh_object, deform_group_indices)
+ unweighted = total - weighted
+ fraction = (unweighted / total) if total else 0.0
+ report["weighting"]["after_heat"] = {
+ "weighted": weighted, "unweighted": unweighted, "unweighted_fraction": fraction,
+ }
+ if fraction > thresholds["unweighted_ceiling"]:
+ _write_report(job["report_path"], report)
+ return _fail(
+ "automatic weighting left %.1f%% of vertices unweighted, ceiling is %.1f%%"
+ % (fraction * 100.0, thresholds["unweighted_ceiling"] * 100.0)
+ )
+
+ completed = _nearest_bone_fill(mesh_object, armature, deform_group_indices)
+ weighted_after = _count_weighted(mesh_object, deform_group_indices)
+ unweighted_after = total - weighted_after
+ report["weighting"]["nearest_bone_completed"] = completed
+ report["weighting"]["after_fill"] = {
+ "weighted": weighted_after,
+ "unweighted": unweighted_after,
+ "unweighted_fraction": (unweighted_after / total) if total else 0.0,
+ }
+ if unweighted_after != 0:
+ _write_report(job["report_path"], report)
+ return _fail(
+ "the nearest-bone pass left %d of %d vertices unweighted, which must be zero"
+ % (unweighted_after, total)
+ )
+
+ os.makedirs(os.path.dirname(job["output_glb"]), exist_ok=True)
+ bpy.ops.object.select_all(action="DESELECT")
+ mesh_object.select_set(True)
+ armature.select_set(True)
+ bpy.ops.export_scene.gltf(
+ filepath=job["output_glb"], export_format="GLB",
+ use_selection=True, export_skins=True, export_yup=True,
+ )
+
+ # (6) Round-trip validate before calling it done.
+ report["round_trip"] = _round_trip(bpy, job["output_glb"], report["armature"]["name"])
+ _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")
+ return 0
+
+
+def main(argv):
+ parser = argparse.ArgumentParser(description="PortOS auto-skin worker (Blender)")
+ parser.add_argument("--job", required=True, help="Path to the job JSON written by autoSkin.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 rigging worker raised an unexpected error", code=3)
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/server/services/rigging/rigging.test.js b/server/services/rigging/rigging.test.js
index 6a135e6517..1475fc856c 100644
--- a/server/services/rigging/rigging.test.js
+++ b/server/services/rigging/rigging.test.js
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import { buildClipCoverage } from './clipCapabilities.js';
-import { reduceBoneMapping, SKELETON_BONE_MAPPINGS } from './skeletonMapping.js';
+import { buildHumanoidArmatureSpec, HUMANOID_JOINT_PARENTS, reduceBoneMapping, SKELETON_BONE_MAPPINGS } from './skeletonMapping.js';
describe('rigging skeleton compatibility', () => {
const cc3Bones = Object.values(SKELETON_BONE_MAPPINGS.cc3);
@@ -33,3 +33,27 @@ describe('clip capability report', () => {
expect(result).toMatchObject({ complete: false, missingStates: expect.arrayContaining(['coding']) });
});
});
+
+describe('humanoid armature spec', () => {
+ // The worker builds its armature from this spec, so a bone whose parent is emitted
+ // AFTER it (or a leaf whose head equals its tail) would be silently dropped by
+ // Blender on a host nobody testing this has — the failure would only ever surface as
+ // a short bone list in a rig report.
+ it('names bones by the requested convention and emits every parent before its child', () => {
+ const spec = buildHumanoidArmatureSpec({ skeletonHint: 'cc3' });
+ expect(spec.skeletonHint).toBe('cc3');
+ const seen = new Set();
+ for (const bone of spec.bones) {
+ expect(bone.name).toBe(SKELETON_BONE_MAPPINGS.cc3[bone.joint]);
+ if (bone.parent) expect(seen.has(bone.parent)).toBe(true);
+ expect(bone.head).not.toEqual(bone.tail);
+ seen.add(bone.name);
+ }
+ expect(seen.size).toBe(Object.keys(HUMANOID_JOINT_PARENTS).length);
+ });
+
+ it('falls back to a known convention rather than emitting unnamed bones', () => {
+ expect(buildHumanoidArmatureSpec({ skeletonHint: 'not-a-convention' }).skeletonHint).toBe('mixamo');
+ expect(buildHumanoidArmatureSpec().bones.every((bone) => typeof bone.name === 'string' && bone.name)).toBe(true);
+ });
+});
diff --git a/server/services/rigging/skeletonMapping.js b/server/services/rigging/skeletonMapping.js
index 634398a9cf..f614c3a530 100644
--- a/server/services/rigging/skeletonMapping.js
+++ b/server/services/rigging/skeletonMapping.js
@@ -58,3 +58,72 @@ export function reduceBoneMapping({ sourceBones, targetBones, skeletonHint } = {
}
export const REQUIRED_RETARGET_JOINTS = JOINTS;
+
+/**
+ * Parent joint for every canonical joint (`null` = root). The armature the auto-skin
+ * worker builds is derived from this, so the hierarchy lives with the bone names it
+ * has to stay consistent with rather than being duplicated in the Python worker.
+ */
+export const HUMANOID_JOINT_PARENTS = Object.freeze({
+ hips: null, spine: 'hips', chest: 'spine', neck: 'chest', head: 'neck',
+ leftUpperArm: 'chest', leftLowerArm: 'leftUpperArm', leftHand: 'leftLowerArm',
+ rightUpperArm: 'chest', rightLowerArm: 'rightUpperArm', rightHand: 'rightLowerArm',
+ leftUpperLeg: 'hips', leftLowerLeg: 'leftUpperLeg', leftFoot: 'leftLowerLeg',
+ rightUpperLeg: 'hips', rightLowerLeg: 'rightUpperLeg', rightFoot: 'rightLowerLeg',
+});
+
+/**
+ * Joint heads in UNIT space over the mesh's own bounding box: x across (0 = the
+ * mesh's -X face, 1 = +X), y up, z depth. The worker maps these onto the measured
+ * bounds, so one spec fits any character proportion without the Node side needing to
+ * know the mesh. Numbers are the standard bipedal proportions (hips at ~53% of height,
+ * shoulders at ~82%, arms spanning to ~20%/~80% of width).
+ */
+export const HUMANOID_JOINT_PLACEMENT = Object.freeze({
+ hips: [0.50, 0.53, 0.50], spine: [0.50, 0.62, 0.50], chest: [0.50, 0.72, 0.50],
+ neck: [0.50, 0.84, 0.50], head: [0.50, 0.90, 0.50],
+ leftUpperArm: [0.62, 0.82, 0.50], leftLowerArm: [0.72, 0.82, 0.50], leftHand: [0.82, 0.82, 0.50],
+ rightUpperArm: [0.38, 0.82, 0.50], rightLowerArm: [0.28, 0.82, 0.50], rightHand: [0.18, 0.82, 0.50],
+ leftUpperLeg: [0.57, 0.52, 0.50], leftLowerLeg: [0.57, 0.28, 0.50], leftFoot: [0.57, 0.03, 0.50],
+ rightUpperLeg: [0.43, 0.52, 0.50], rightLowerLeg: [0.43, 0.28, 0.50], rightFoot: [0.43, 0.03, 0.50],
+});
+
+// A leaf joint has no child to take its tail from, so it extends along a fixed unit
+// direction. Without this a leaf bone would have zero length and Blender would drop it.
+const LEAF_TAIL_OFFSET = Object.freeze({
+ head: [0, 0.08, 0], leftHand: [0.06, 0, 0], rightHand: [-0.06, 0, 0],
+ leftFoot: [0, 0, 0.08], rightFoot: [0, 0, 0.08],
+});
+
+/**
+ * The armature the auto-skin worker builds, in unit-bbox space: bone names from the
+ * requested convention, hierarchy from `HUMANOID_JOINT_PARENTS`, head/tail from
+ * `HUMANOID_JOINT_PLACEMENT`. Pure — no mesh needed, so it is fixture-testable.
+ *
+ * A joint's tail is its FIRST child's head, which is what makes the chain continuous;
+ * a leaf extends by its own offset. Bones are emitted parents-first so the worker can
+ * create them in one pass.
+ *
+ * @param {{skeletonHint?: string}} [opts]
+ * @returns {{skeletonHint: string, bones: Array<{joint: string, name: string, parent: string|null, head: number[], tail: number[]}>}}
+ */
+export function buildHumanoidArmatureSpec({ skeletonHint = 'mixamo' } = {}) {
+ const hint = knownSkeletonHint(skeletonHint) === 'unknown' ? 'mixamo' : knownSkeletonHint(skeletonHint);
+ const names = SKELETON_BONE_MAPPINGS[hint];
+ const firstChild = new Map();
+ for (const joint of JOINTS) {
+ const parent = HUMANOID_JOINT_PARENTS[joint];
+ if (parent && !firstChild.has(parent)) firstChild.set(parent, joint);
+ }
+ const bones = JOINTS.map((joint) => {
+ const head = HUMANOID_JOINT_PLACEMENT[joint];
+ const child = firstChild.get(joint);
+ const offset = LEAF_TAIL_OFFSET[joint] || [0, 0.05, 0];
+ const tail = child
+ ? HUMANOID_JOINT_PLACEMENT[child]
+ : head.map((value, axis) => value + offset[axis]);
+ const parentJoint = HUMANOID_JOINT_PARENTS[joint];
+ return { joint, name: names[joint], parent: parentJoint ? names[parentJoint] : null, head: [...head], tail: [...tail] };
+ });
+ return { skeletonHint: hint, bones };
+}