Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(preserve-contract): verify an edit kept what it promised to keep
nirholas9de6ae072fa7
diff --git a/api/_lib/preserve-contract.js b/api/_lib/preserve-contract.jsnew file mode 100644index 000000000..c8483b289--- /dev/null+++ b/api/_lib/preserve-contract.js@@ -0,0 +1,155 @@+// The "preserve" contract an edit operation declares before it touches a GLB:+// which of topology, UVs, skeleton, skin and clips it promises to keep intact.+// verifyPreserved() checks that promise against the REAL output with+// @three-ws/glb-diff instead of trusting the operation's own say-so: an+// operation that promises `uv` but hands back a GLB whose UVs moved never+// gets to report success; it throws a PreserveViolationError instead.+//+// Isomorphic (only depends on @three-ws/glb-diff, which takes bytes), so the+// same contract runs in a Node API handler, a Cloud Run worker, or a browser+// tab, wherever the before/after bytes of an edit happen to meet.++import { describeModel, diffDescriptions } from '@three-ws/glb-diff';++export const PRESERVE_KINDS = ['topology', 'uv', 'skeleton', 'skin', 'clips'];++export class PreserveViolationError extends Error {+ constructor(message, { status = 502, code = 'preserve_violation', violations = [] } = {}) {+ super(message);+ this.name = 'PreserveViolationError';+ this.status = status;+ this.code = code;+ this.violations = violations;+ }+}++function assertKnownKinds(kinds) {+ const unknown = kinds.filter((k) => !PRESERVE_KINDS.includes(k));+ if (unknown.length) {+ throw new Error(`preserve-contract: unknown kind(s) ${unknown.join(', ')}, known: ${PRESERVE_KINDS.join(', ')}`);+ }+}++// Mesh-section fields each geometry-level kind depends on. 'skin' here means+// the per-vertex JOINTS_0/WEIGHTS_0 binding baked into the mesh, as distinct+// from the Skin *resource* (joint list, bind matrices) checked below.+const MESH_FIELDS = {+ topology: ['topology', 'vertices', 'triangles', 'primitives'],+ uv: ['uv'],+ skin: ['skinWeights'],+};++function meshViolations(sections, kind) {+ const fields = MESH_FIELDS[kind];+ const out = [];+ for (const mesh of sections.meshes.modified) {+ for (const change of mesh.changes) {+ if (fields.includes(change.field)) {+ out.push({ kind, section: 'meshes', name: mesh.name, field: change.field, detail: change.note || `${change.field} changed` });+ }+ }+ }+ for (const mesh of sections.meshes.removed) {+ out.push({ kind, section: 'meshes', name: mesh.name, field: 'removed', detail: mesh.detail || 'mesh removed' });+ }+ for (const mesh of sections.meshes.added) {+ out.push({ kind, section: 'meshes', name: mesh.name, field: 'added', detail: mesh.detail || 'mesh added' });+ }+ return out;+}++// The skeleton itself: which joints exist, their names, and where the skin is+// rooted: the shape every clip and every attachment addresses by name.+function skeletonViolations(sections) {+ const out = [];+ for (const skin of sections.skins.modified) {+ for (const change of skin.changes) {+ if (change.field === 'joints' || change.field === 'jointCount' || change.field === 'skeleton') {+ out.push({ kind: 'skeleton', section: 'skins', name: skin.name, field: change.field, detail: change.note || `${change.field} changed` });+ }+ }+ }+ for (const skin of sections.skins.removed) {+ out.push({ kind: 'skeleton', section: 'skins', name: skin.name, field: 'removed', detail: skin.detail || 'skeleton removed' });+ }+ for (const skin of sections.skins.added) {+ out.push({ kind: 'skeleton', section: 'skins', name: skin.name, field: 'added', detail: skin.detail || 'skeleton added' });+ }+ for (const node of sections.nodes.modified) {+ for (const change of node.changes) {+ if (change.field === 'skin') {+ out.push({ kind: 'skeleton', section: 'nodes', name: node.name, field: 'skin', detail: 'node skin assignment changed' });+ }+ }+ }+ return out;+}++// The skin BINDING: the bind pose (inverse bind matrices) plus the per-vertex+// weights baked into the mesh. Either one changing deforms the same clip+// differently, even when the skeleton's joint names are untouched.+function skinBindViolations(sections) {+ const out = [];+ for (const skin of sections.skins.modified) {+ for (const change of skin.changes) {+ if (change.field === 'inverseBindMatrices') {+ out.push({ kind: 'skin', section: 'skins', name: skin.name, field: change.field, detail: change.note || 'bind pose changed' });+ }+ }+ }+ return [...out, ...meshViolations(sections, 'skin')];+}++function clipViolations(sections) {+ const out = [];+ for (const clip of sections.animations.removed) {+ out.push({ kind: 'clips', section: 'animations', name: clip.name, field: 'removed', detail: clip.detail || 'animation removed' });+ }+ for (const clip of sections.animations.modified) {+ for (const change of clip.changes) {+ out.push({ kind: 'clips', section: 'animations', name: clip.name, field: change.field, detail: change.note || `${change.field} changed` });+ }+ }+ return out;+}++const KIND_CHECKS = {+ topology: (sections) => meshViolations(sections, 'topology'),+ uv: (sections) => meshViolations(sections, 'uv'),+ skeleton: skeletonViolations,+ skin: skinBindViolations,+ clips: clipViolations,+};++/**+ * Check that an edit kept the properties it promised to keep.+ *+ * @param {Uint8Array|Buffer} beforeBytes the GLB before the edit+ * @param {Uint8Array|Buffer} afterBytes the GLB after the edit+ * @param {string[]} kinds which PRESERVE_KINDS the edit declares it keeps+ * @param {{ label?: string }} [opts] a short name for the operation, used in the thrown message+ * @returns {Promise<{ changes: object, violations: [] }>} the full glb-diff change set when every declared kind held+ * @throws {PreserveViolationError} when any declared kind changed+ */+export async function verifyPreserved(beforeBytes, afterBytes, kinds, { label } = {}) {+ const list = Array.isArray(kinds) ? [...new Set(kinds)] : [];+ assertKnownKinds(list);+ if (!list.length) return { changes: null, violations: [] };++ const [before, after] = await Promise.all([+ describeModel(beforeBytes, { name: 'before' }),+ describeModel(afterBytes, { name: 'after' }),+ ]);+ const changes = diffDescriptions(before, after);++ const violations = list.flatMap((kind) => KIND_CHECKS[kind](changes.sections));+ if (violations.length) {+ const kindsHit = [...new Set(violations.map((v) => v.kind))].join(', ');+ const detail = violations.map((v) => `${v.kind}:${v.section}/${v.name}.${v.field}`).join('; ');+ throw new PreserveViolationError(+ `${label ? `${label}: ` : ''}edit did not preserve ${kindsHit} (${detail})`,+ { violations },+ );+ }+ return { changes, violations: [] };+}diff --git a/tests/api/preserve-contract.test.js b/tests/api/preserve-contract.test.jsnew file mode 100644index 000000000..2d7844009--- /dev/null+++ b/tests/api/preserve-contract.test.js@@ -0,0 +1,167 @@+/**+ * Tests for api/_lib/preserve-contract.js: the shared "preserve" contract+ * every retexture and part edit declares before touching a GLB, verified for+ * real against @three-ws/glb-diff rather than trusted on say-so (work order+ * 078: "keep the rig").+ *+ * Every model here is a real glTF-Transform Document, written to real GLB+ * bytes with NodeIO and read back through describeModel: no mocked diff+ * output anywhere in this file.+ */++import { describe, it, expect } from 'vitest';+import { Document, NodeIO } from '@gltf-transform/core';+import { verifyPreserved, PreserveViolationError, PRESERVE_KINDS } from '../../api/_lib/preserve-contract.js';++const io = new NodeIO();++// A rigged, animated triangle: one mesh skinned to two joints, textured with+// UVs, driven by one clip. Every preserve kind has something real to check.+function buildGlb(overrides = {}) {+ const {+ positions = [0, 0, 0, 1, 0, 0, 0, 1, 0],+ uv = [0, 0, 1, 0, 0, 1],+ jointIndices = [0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],+ jointWeights = [0.5, 0.5, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0],+ baseColor = [1, 1, 1, 1],+ joints = ['Hips', 'Spine'],+ clipName = 'idle',+ } = overrides;++ const doc = new Document();+ const buffer = doc.createBuffer();++ const position = doc.createAccessor().setType('VEC3').setArray(new Float32Array(positions)).setBuffer(buffer);+ const texcoord = doc.createAccessor().setType('VEC2').setArray(new Float32Array(uv)).setBuffer(buffer);+ const jointsAccessor = doc.createAccessor().setType('VEC4').setArray(new Uint16Array(jointIndices)).setBuffer(buffer);+ const weightsAccessor = doc.createAccessor().setType('VEC4').setArray(new Float32Array(jointWeights)).setBuffer(buffer);++ const material = doc.createMaterial('Skin').setBaseColorFactor(baseColor);+ const prim = doc+ .createPrimitive()+ .setAttribute('POSITION', position)+ .setAttribute('TEXCOORD_0', texcoord)+ .setAttribute('JOINTS_0', jointsAccessor)+ .setAttribute('WEIGHTS_0', weightsAccessor)+ .setMaterial(material);+ const mesh = doc.createMesh('Body').addPrimitive(prim);++ const root = doc.createNode('Root').setMesh(mesh);+ const jointNodes = joints.map((name) => doc.createNode(name));+ const skin = doc.createSkin('Armature');+ for (const joint of jointNodes) skin.addJoint(joint);+ if (jointNodes[0]) skin.setSkeleton(jointNodes[0]);+ root.setSkin(skin);++ if (clipName) {+ const input = doc.createAccessor().setType('SCALAR').setArray(new Float32Array([0, 1])).setBuffer(buffer);+ const output = doc.createAccessor().setType('VEC3').setArray(new Float32Array([0, 0, 0, 0, 0, 0])).setBuffer(buffer);+ const sampler = doc.createAnimationSampler().setInput(input).setOutput(output).setInterpolation('LINEAR');+ const channel = doc.createAnimationChannel().setTargetNode(jointNodes[0] || root).setTargetPath('translation').setSampler(sampler);+ doc.createAnimation(clipName).addSampler(sampler).addChannel(channel);+ }++ const scene = doc.createScene('Scene');+ scene.addChild(root);+ for (const joint of jointNodes) scene.addChild(joint);++ return io.writeBinary(doc);+}++const ALL_KINDS = PRESERVE_KINDS;++describe('verifyPreserved', () => {+ it('passes every kind when nothing changed', async () => {+ const before = await buildGlb();+ const after = await buildGlb();+ const result = await verifyPreserved(before, after, ALL_KINDS);+ expect(result.violations).toEqual([]);+ expect(result.changes.identical).toBe(true);+ });++ it('is a no-op for an empty kinds list', async () => {+ const before = await buildGlb();+ const after = await buildGlb({ positions: [0, 0, 0, 5, 0, 0, 0, 9, 0] });+ const result = await verifyPreserved(before, after, []);+ expect(result).toEqual({ changes: null, violations: [] });+ });++ it('only restyling the material (no geometry/UV/skin/clip touch) preserves everything', async () => {+ const before = await buildGlb();+ const after = await buildGlb({ baseColor: [0.2, 0.1, 0.05, 1] });+ const result = await verifyPreserved(before, after, ALL_KINDS);+ expect(result.violations).toEqual([]);+ });++ it('throws when topology is declared preserved but a vertex moved', async () => {+ const before = await buildGlb();+ const after = await buildGlb({ positions: [0, 0, 0, 1, 0, 0, 0, 9, 0] });+ await expect(verifyPreserved(before, after, ['topology'], { label: 'retexture' })).rejects.toMatchObject({+ name: 'PreserveViolationError',+ code: 'preserve_violation',+ });+ });++ it('names the failing kind and field in the thrown message', async () => {+ const before = await buildGlb();+ const after = await buildGlb({ positions: [0, 0, 0, 1, 0, 0, 0, 9, 0] });+ try {+ await verifyPreserved(before, after, ['topology'], { label: 'retexture' });+ throw new Error('expected verifyPreserved to throw');+ } catch (err) {+ expect(err).toBeInstanceOf(PreserveViolationError);+ expect(err.message).toContain('retexture');+ expect(err.message).toContain('topology');+ expect(err.violations[0]).toMatchObject({ kind: 'topology', section: 'meshes', name: 'Body' });+ }+ });++ it('does not flag topology when only UVs moved', async () => {+ const before = await buildGlb();+ const after = await buildGlb({ uv: [1, 1, 0, 1, 1, 0] });+ await expect(verifyPreserved(before, after, ['topology'])).resolves.toMatchObject({ violations: [] });+ await expect(verifyPreserved(before, after, ['uv'])).rejects.toBeInstanceOf(PreserveViolationError);+ });++ it('does not flag UV when only skin weights moved', async () => {+ const before = await buildGlb();+ const after = await buildGlb({ jointWeights: [1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0] });+ await expect(verifyPreserved(before, after, ['uv'])).resolves.toMatchObject({ violations: [] });+ await expect(verifyPreserved(before, after, ['skin'])).rejects.toBeInstanceOf(PreserveViolationError);+ });++ it('throws when a joint is removed from the skeleton', async () => {+ const before = await buildGlb();+ const after = await buildGlb({ joints: ['Hips'], jointIndices: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] });+ await expect(verifyPreserved(before, after, ['skeleton'])).rejects.toMatchObject({+ violations: expect.arrayContaining([expect.objectContaining({ kind: 'skeleton', section: 'skins', field: 'joints' })]),+ });+ });++ it('throws when the animation clip is removed', async () => {+ const before = await buildGlb();+ const after = await buildGlb({ clipName: null });+ await expect(verifyPreserved(before, after, ['clips'])).rejects.toMatchObject({+ violations: [expect.objectContaining({ kind: 'clips', section: 'animations', field: 'removed' })],+ });+ });++ it('only reports violations for declared kinds, ignoring unrelated changes', async () => {+ // Clip removed AND a vertex moved, but only 'clips' was declared: the+ // topology change is real but out of scope for this call's contract.+ const before = await buildGlb();+ const after = await buildGlb({ clipName: null, positions: [0, 0, 0, 1, 0, 0, 0, 9, 0] });+ try {+ await verifyPreserved(before, after, ['clips']);+ throw new Error('expected verifyPreserved to throw');+ } catch (err) {+ expect(err.violations).toHaveLength(1);+ expect(err.violations[0].kind).toBe('clips');+ }+ });++ it('rejects an unknown preserve kind before describing anything', async () => {+ const before = await buildGlb();+ await expect(verifyPreserved(before, before, ['topology', 'bogus'])).rejects.toThrow(/unknown kind/);+ });+});