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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: tie a declared Three.js attachment to what it hangs from, and check it is there (#4631)
[._.]/ Adam Eivya46496474090
diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 4cf19243f0..a05a49a217 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -185,7 +185,7 @@ grep -i "what you want to do" client/src/lib/README.md| `threejsAnimation.js` | Pure pose evaluator for the declarative clip contract in `server/lib/threejsModel.js`, used by the Three.js Models preview transport. `evaluateThreejsClipPose(clip, timeSeconds)` → `{ timeSeconds, pose, activeSequenceIds, activePartIds }` where `pose` is a null-prototype partId → `{ position?, rotationDegrees?, scale?, opacity?, visible? }` map: each part+channel resolves from the one sequence that owns the instant (the window containing it, else the most recent behind it, else the next ahead), `visible` steps at the window's end rather than interpolating, and a part no sequence drives is absent so the spec renders as authored. `collectThreejsCues(clip, from, to)` returns the data-only sound cues a play loop crossed in the half-open `[from, to)` interval — a scrub calls it never, which is what makes scrubbing silent. `listThreejsClips` / `listThreejsCues` / `resolveThreejsClip` / `getThreejsClipDuration` read a spec that may have no `animation` key at all. || `threejsEnvironment.js` | Image-based lighting for the procedural sculpt spec, used by the Three.js Models preview. `spec.lights` are punctual — they light a surface but give it nothing to REFLECT, so `metalness`, `transmission`, `clearcoat` and `iridescence` read off an environment or read off nothing, and a plausible conductor renders near-black without one. `createSculptEnvironmentTarget(renderer, preset)` builds a preset locally from three's own primitives and prefilters it through `PMREMGenerator` — `neutral` is three's bundled `RoomEnvironment`, `studio` a dark shell with three emissive softbox panels plus a floor bounce — returning null for `none`; the caller owns the render TARGET and disposes it (disposing only `.texture` leaks the framebuffer behind it). `THREEJS_RENDER_PROFILE` mirrors the server's colour-space/tone-map/exposure contract so the preview renders at what the export stamps on the model. Deliberately NOT drei's `<Environment preset=…>`, which fetches an HDR from a CDN: rendering a local model makes no outbound request. `resolveSculptEnvironment(spec)` is the client mirror of `resolveThreejsEnvironment` in `server/lib/threejsModel.js`, reading a spec with no `environment` key as the `none` it was actually authored against. || `threejsExplode.js` | Disassembly + part-picking maths for the procedural sculpt spec, shared by the Three.js Models preview so explode and the picker agree on what "a part" is. `computeExplodeLayout(parts, amount)` → `{ offsets, meshOffsets, unitIds, growth }`: separation is a layout **scale about the model centre** (≈2× at full explode) plus a base clearance for parts sitting at the centre — never a uniform outward push, which slides the arrangement without opening gaps — where `offsets` add to a unit's own `position` and `meshOffsets` apply to a group around a container's own geometry (moving its group instead would drag its child units along), and `growth` measures how much the layout actually grew so the camera re-fits on real change. `buildPartSelectionIndex(parts)` → `{ owners, ancestry, names }` for click resolution, subtree highlight, and the selection label. All maps are null-prototype — part ids are provider-authored and `idSchema` accepts `toString`. `isReliefPart` / `isContainerPart` expose the shared part definition: a part flagged `explodeWithParent` is surface relief that rides its parent and resolves selection up to it (unless it has no parent to ride), every other geometry-bearing part is both a movable unit and a selectable component, a part whose descendants carry geometry is additionally descended through, and a part with no geometry in its subtree moves nothing. |-| `threejsRig.js` | `summarizeThreejsArticulation(spec)` → `{ articulationReady, jointCount, socketCount, attachmentCount, jointsByPartId }` — client mirror of the readiness rule in `server/lib/threejsModelRig.js`, used by the Three.js Models preview, which is handed a bare spec rather than the record's stored report (and gets none at all for a model generated before rig readiness shipped). A spec with no `articulation` key reads as a static assembly; a graph is ready only when it carries more than a lone root and every child joint names a pivot socket. `jointsByPartId` is null-prototype so a provider-authored part id cannot resolve to an inherited function. |+| `threejsRig.js` | `summarizeThreejsArticulation(spec)` → `{ articulationReady, jointCount, socketCount, attachmentCount, anchoredAttachmentCount, unanchoredAttachmentCount, jointsByPartId }` — client mirror of the readiness rule in `server/lib/threejsModelRig.js`, used by the Three.js Models preview, which is handed a bare spec rather than the record's stored report (and gets none at all for a model generated before rig readiness shipped). A spec with no `articulation` key reads as a static assembly; a graph is ready only when it carries more than a lone root, every child joint names a pivot socket, and every declared attachment names what it hangs from (the anchored `attachments` list and the older anchor-less `attachmentPartIds` are merged into one count). `jointsByPartId` is null-prototype so a provider-authored part id cannot resolve to an inherited function. || `threejsSculpt.js` | Three.js construction helpers for the validated procedural sculpt spec (`server/lib/threejsModel.js`) used by the Three.js Models preview. `createSculptBufferGeometry(definition)` builds the schema forms r3f has no direct element for — `custom` (indexed BufferGeometry), `extrude` (closed 2D outline + holes swept to `depth`, optional bevel) and `tube` (CatmullRom path swept at `radius`) — returning null for primitives, which stay declarative; callers own disposal. `needsSculptBufferGeometry(definition)` is the matching predicate. `sculptMaterialProps(definition, envMapIntensity)` maps a material definition to its Three.js props, forwarding the physical-only channels (`clearcoat`, `ior`, `transmission`, `thickness`, `sheen`, `iridescence`, `anisotropy`) only for `type: physical`, and the spec-level `environment.intensity` as `envMapIntensity` on every lit material (`basic` is unlit and takes none). Mirrors the `createGeometry`/`createMaterial` bodies `buildThreejsFactorySource()` emits, so the preview and the exported standalone factory render the same scene. || `universeBuilderShared.js` | Shared constants + pure category/trunk/composite helpers for the Universe Builder page and its extracted tab/editor components (#2374): `TRUNK_TABS`/`TRUNK_BY_ID`/`TRUNK_BY_KIND`, `TAB_*` + `BUCKET_CANON`, `CATEGORY_LABELS`, `DEFAULT_RENDER_OPTS`, `COMPOSITE_BOARD_KINDS`; and helpers `groupBucketsByKind`, `normalizeCategoryKey`, `humanizeCategory`, `ensureDraftCategories`, `getCategoryKeys`, `compositeKindLabel`. No React state — safe to import from the page or any tab component without a cycle. || `universeBuilderCounts.js` | Pure prompt-count helpers for the Universe Builder render buttons (#2374), mirroring the server's compile/skip rules so inline counts match what `/render` will enqueue: `totalVariationCount`, `canonEntryHasContent`, `countCanonWithContent`, `renderPromptCount`, `scopedPromptCount`. The server `compilePrompts`/`synthesizeCanonPrompt` copy is authoritative — keep in sync. |diff --git a/client/src/lib/threejsRig.js b/client/src/lib/threejsRig.jsindex 71506da8ee..d3f359d1e0 100644--- a/client/src/lib/threejsRig.js+++ b/client/src/lib/threejsRig.js@@ -13,26 +13,62 @@const MIN_USEFUL_JOINTS = 2;+/**+ * Client mirror of `resolveThreejsAttachments` in `server/lib/threejsModel.js`.+ *+ * A spec declares carried parts in two forms — the original anchor-less+ * `attachmentPartIds` and the anchored `attachments` — and both mean the same+ * thing, so the counts are derived from one merged list. An anchored entry wins+ * over a bare id for the same part.+ *+ * @param {object|null} articulation a spec's `articulation` object, or null+ * @returns {Array<{partId: string, anchored: boolean}>}+ */+function resolveAttachments(articulation) {+ const entries = new Map();+ const bareIds = Array.isArray(articulation?.attachmentPartIds) ? articulation.attachmentPartIds : [];+ for (const partId of bareIds) {+ if (typeof partId !== 'string' || entries.has(partId)) continue;+ entries.set(partId, { partId, anchored: false });+ }+ const anchored = Array.isArray(articulation?.attachments) ? articulation.attachments : [];+ for (const attachment of anchored) {+ if (typeof attachment?.partId !== 'string') continue;+ entries.set(attachment.partId, {+ partId: attachment.partId,+ anchored: Boolean(attachment.anchorPartId) || Boolean(attachment.anchorSocket),+ });+ }+ return [...entries.values()];+}+/*** @param {object|null} spec a validated sculpt spec, or null* @returns {{articulationReady: boolean, jointCount: number, socketCount: number,- * attachmentCount: number, jointsByPartId: object}}+ * attachmentCount: number, anchoredAttachmentCount: number,+ * unanchoredAttachmentCount: number, jointsByPartId: object}}*/export function summarizeThreejsArticulation(spec) {const joints = Array.isArray(spec?.articulation?.joints) ? spec.articulation.joints : [];- const attachments = Array.isArray(spec?.articulation?.attachmentPartIds)- ? spec.articulation.attachmentPartIds- : [];+ const attachments = resolveAttachments(spec?.articulation);+ const unanchoredAttachmentCount = attachments.filter((attachment) => !attachment.anchored).length;// Null-prototype: part ids are provider-authored and the id schema accepts// `toString`, so a bare lookup on a plain object can hand back a function.const jointsByPartId = Object.create(null);for (const joint of joints) jointsByPartId[joint.partId] = joint;const unpivoted = joints.filter((joint) => joint.parentJointId && !joint.pivotSocket);return {- articulationReady: joints.length >= MIN_USEFUL_JOINTS && unpivoted.length === 0,+ // An attachment that names nothing to hang from is a declaration with no+ // relationship in it, so — same rule the server applies — it keeps the graph+ // out of "ready" rather than being credited toward it.+ articulationReady: joints.length >= MIN_USEFUL_JOINTS+ && unpivoted.length === 0+ && unanchoredAttachmentCount === 0,jointCount: joints.length,socketCount: new Set(joints.map((joint) => joint.pivotSocket).filter(Boolean)).size,attachmentCount: attachments.length,+ anchoredAttachmentCount: attachments.length - unanchoredAttachmentCount,+ unanchoredAttachmentCount,jointsByPartId,};}diff --git a/client/src/lib/threejsRig.test.js b/client/src/lib/threejsRig.test.jsindex d615cbef9f..f32a624f9b 100644--- a/client/src/lib/threejsRig.test.js+++ b/client/src/lib/threejsRig.test.js@@ -7,7 +7,8 @@ const spec = () => ({{ id: 'rootJoint', partId: 'torso', parentJointId: null, pivotSocket: null },{ id: 'armJoint', partId: 'arm', parentJointId: 'rootJoint', pivotSocket: 'shoulder' },],- attachmentPartIds: ['pack'],+ attachmentPartIds: [],+ attachments: [{ partId: 'pack', anchorPartId: 'torso', anchorSocket: null, maxOffset: 0.25 }],},});@@ -18,6 +19,8 @@ describe('summarizeThreejsArticulation', () => {expect(summary.jointCount).toBe(2);expect(summary.socketCount).toBe(1);expect(summary.attachmentCount).toBe(1);+ expect(summary.anchoredAttachmentCount).toBe(1);+ expect(summary.unanchoredAttachmentCount).toBe(0);expect(summary.jointsByPartId.arm.id).toBe('armJoint');});@@ -43,6 +46,28 @@ describe('summarizeThreejsArticulation', () => {expect(summarizeThreejsArticulation(unpivoted).articulationReady).toBe(false);});+ // Same rule as the server: an attachment naming nothing to hang from is a+ // declaration with no relationship in it, so it keeps the graph out of ready.+ it('matches the server rule: a declared attachment with no anchor is not ready', () => {+ const unanchored = spec();+ unanchored.articulation.attachments = [];+ unanchored.articulation.attachmentPartIds = ['pack'];+ const summary = summarizeThreejsArticulation(unanchored);+ expect(summary.articulationReady).toBe(false);+ expect(summary.attachmentCount).toBe(1);+ expect(summary.anchoredAttachmentCount).toBe(0);+ expect(summary.unanchoredAttachmentCount).toBe(1);+ });++ // The two forms name the same part, so it is one attachment.+ it('merges a part declared in both attachment forms into one anchored entry', () => {+ const both = spec();+ both.articulation.attachmentPartIds = ['pack'];+ const summary = summarizeThreejsArticulation(both);+ expect(summary.attachmentCount).toBe(1);+ expect(summary.unanchoredAttachmentCount).toBe(0);+ });+// Part ids are provider-authored; a plain object would resolve `toString` to// an inherited function and the preview would label a part that has no joint.it('keeps the joint index null-prototype', () => {diff --git a/client/src/pages/ThreejsModelDetail.jsx b/client/src/pages/ThreejsModelDetail.jsxindex 1e4313a2e0..e1f809a66f 100644--- a/client/src/pages/ThreejsModelDetail.jsx+++ b/client/src/pages/ThreejsModelDetail.jsx@@ -159,6 +159,10 @@ function RigReadinessPanel({ rig, spec }) {const jointCount = count('jointCount');const socketCount = count('socketCount');const attachmentCount = count('attachmentCount');+ // A report written before anchors shipped carries no split, and inferring one+ // from the total would credit every legacy attachment as anchored — the exact+ // overstatement the split exists to remove. Fall back to the spec instead.+ const unanchoredAttachmentCount = count('unanchoredAttachmentCount');const reasons = Array.isArray(rig?.reasons) ? rig.reasons : [];return (<section className="rounded-xl border border-port-border bg-port-card p-4">@@ -174,6 +178,7 @@ function RigReadinessPanel({ rig, spec }) {<p className="text-xs text-gray-400">{jointCount} joint{jointCount === 1 ? '' : 's'} · {socketCount} pivot socket{socketCount === 1 ? '' : 's'}{' · '}{attachmentCount} declared attachment{attachmentCount === 1 ? '' : 's'}+ {attachmentCount > 0 && ` (${attachmentCount - unanchoredAttachmentCount} anchored, ${unanchoredAttachmentCount} unanchored)`}</p>{!rig && (<p className="mt-2 rounded-lg border border-port-border bg-port-bg/50 px-3 py-2 text-xs leading-relaxed text-gray-400">@@ -407,8 +412,21 @@ export default function ThreejsModelDetail() {const flatnessFindings = Array.isArray(record.flatness?.findings) ? record.flatness.findings : null;const flatnessHasWarnings = flatnessFindings?.some((finding) => finding.severity === 'warning');const penetrationFindings = Array.isArray(record.penetration?.findings) ? record.penetration.findings : null;+ // An attachment whose anchor could not be measured was not checked, so it is+ // rendered as a note rather than left to the panel's clean label — "no+ // findings" and "never verified" must not read the same on screen.+ const unmeasuredAttachments = Array.isArray(record.physicalAudit?.unmeasuredAttachments)+ ? record.physicalAudit.unmeasuredAttachments+ : [];const physicalAuditFindings = Array.isArray(record.physicalAudit?.findings)- ? record.physicalAudit.findings+ ? [+ ...record.physicalAudit.findings,+ ...unmeasuredAttachments.map((entry) => ({+ code: 'unmeasured-attachment',+ severity: 'note',+ message: `Attachment "${entry.partId}" could not be checked against ${entry.anchorSocket ? `socket "${entry.anchorSocket}"` : `"${entry.anchorPartId}"`} because ${entry.reason}.`,+ })),+ ]: null;const materialFindings = Array.isArray(record.materialPlausibility?.findings)? record.materialPlausibility.findings@@ -638,7 +656,7 @@ export default function ThreejsModelDetail() {title="Physical audit"findings={physicalAuditFindings}cleanLabel="Assembly satisfies physical attachment, exposure, and coplanarity rules"- footer={`This check inspects the model across resting and animation poses to detect floating parts, swallowed geometry, z-fighting coplanar surfaces, unprovenanced appearing geometry, and non-uniform parent scales that distort nested parts.${+ footer={`This check inspects the model across resting and animation poses to detect floating parts, swallowed geometry, z-fighting coplanar surfaces, unprovenanced appearing geometry, non-uniform parent scales that distort nested parts, and attachments that name nothing to hang from or sit further from their declared anchor than the spec allows.${physicalAuditDefects.error + physicalAuditDefects.warning > 0? ' Refining without your own feedback will also target physical conformance defects.': ''diff --git a/client/src/pages/ThreejsModelDetail.test.jsx b/client/src/pages/ThreejsModelDetail.test.jsxindex 408c4524cd..8aa7047100 100644--- a/client/src/pages/ThreejsModelDetail.test.jsx+++ b/client/src/pages/ThreejsModelDetail.test.jsx@@ -477,6 +477,8 @@ describe('ThreejsModelDetail rig readiness', () => {jointCount: 6,socketCount: 5,attachmentCount: 1,+ anchoredAttachmentCount: 1,+ unanchoredAttachmentCount: 0,rootJointId: 'rootJoint',subjectType: 'character',},@@ -485,7 +487,7 @@ describe('ThreejsModelDetail rig readiness', () => {await waitFor(() => expect(screen.getByText('Rig readiness')).toBeInTheDocument());expect(screen.getByText('Articulation-ready')).toBeInTheDocument();- expect(screen.getByText('6 joints · 5 pivot sockets · 1 declared attachment')).toBeInTheDocument();+ expect(screen.getByText('6 joints · 5 pivot sockets · 1 declared attachment (1 anchored, 0 unanchored)')).toBeInTheDocument();// The claim has to stay bounded: readiness is not a rigged mesh.expect(screen.getByText(/never a skeleton/)).toBeInTheDocument();});@@ -532,6 +534,32 @@ describe('ThreejsModelDetail rig readiness', () => {});});+// An attachment whose anchor could not be measured was never checked, and the+// panel's clean label would otherwise assert that it passed.+describe('ThreejsModelDetail unmeasured attachments', () => {+ beforeEach(resetMocks);++ it('renders an unmeasured attachment as a note rather than letting the panel read clean', async () => {+ getThreejsModel.mockResolvedValue({+ ...baseRecord,+ physicalAudit: {+ findings: [],+ errorCount: 0,+ warningCount: 0,+ noteCount: 0,+ unmeasuredAttachments: [+ { partId: 'hat', anchorPartId: 'head', anchorSocket: null, reason: 'the anchor part has no visible geometry to measure' },+ ],+ },+ });+ renderDetail();++ await waitFor(() => expect(screen.getByText('Physical audit')).toBeInTheDocument());+ expect(screen.getByText(/Attachment "hat" could not be checked against "head"/)).toBeInTheDocument();+ expect(screen.queryByText('Assembly satisfies physical attachment, exposure, and coplanarity rules')).not.toBeInTheDocument();+ });+});+describe('ThreejsModelDetail rig readiness fallbacks', () => {beforeEach(resetMocks);@@ -547,7 +575,8 @@ describe('ThreejsModelDetail rig readiness fallbacks', () => {{ id: 'rootJoint', partId: 'torso', parentJointId: null, pivotSocket: null },{ id: 'armJoint', partId: 'arm', parentJointId: 'rootJoint', pivotSocket: 'shoulder' },],- attachmentPartIds: ['pack'],+ attachmentPartIds: [],+ attachments: [{ partId: 'pack', anchorPartId: 'torso', anchorSocket: null, maxOffset: 0.25 }],},},rig: { articulationReady: true, reasons: [] },@@ -555,9 +584,34 @@ describe('ThreejsModelDetail rig readiness fallbacks', () => {renderDetail();await waitFor(() => expect(screen.getByText('Rig readiness')).toBeInTheDocument());- expect(screen.getByText('2 joints · 1 pivot socket · 1 declared attachment')).toBeInTheDocument();+ expect(screen.getByText('2 joints · 1 pivot socket · 1 declared attachment (1 anchored, 0 unanchored)')).toBeInTheDocument();expect(screen.queryByText(/undefined/)).not.toBeInTheDocument();});++ // A report written before anchors shipped carries a total and no split.+ // Inferring the split from the total would credit a legacy attachment as+ // anchored — the exact overstatement the split exists to remove — so the+ // panel reads the spec instead.+ it('reads the anchored/unanchored split off the spec when the stored report predates it', async () => {+ getThreejsModel.mockResolvedValue({+ ...baseRecord,+ spec: {+ ...baseRecord.spec,+ articulation: {+ joints: [+ { id: 'rootJoint', partId: 'torso', parentJointId: null, pivotSocket: null },+ { id: 'armJoint', partId: 'arm', parentJointId: 'rootJoint', pivotSocket: 'shoulder' },+ ],+ attachmentPartIds: ['pack'],+ },+ },+ rig: { articulationReady: false, reasons: [], jointCount: 2, socketCount: 1, attachmentCount: 1 },+ });+ renderDetail();++ await waitFor(() => expect(screen.getByText('Rig readiness')).toBeInTheDocument());+ expect(screen.getByText('2 joints · 1 pivot socket · 1 declared attachment (0 anchored, 1 unanchored)')).toBeInTheDocument();+ });});describe('ThreejsModelDetail clip inventory', () => {diff --git a/server/lib/README.md b/server/lib/README.mdindex 40dc1e1663..f033caca42 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -180,15 +180,15 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. || `localImageFilename.js` | `localImageFilename(urlOrPath)` resolves a stored image reference to the bare gallery-image filename under `data/images/` (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (`headshotImageFilename`/`portraitImageFilename`/`coverImageFilename`/`startingImageFilename` are thin wrappers). Also exports `assetBasename(pathOrName)`, the shared strip-querystring→basename primitive (reused by moodBoard's `imageUrlToAppAsset`). || `localMemory.js` | Shared best-effort local-model unload + available-memory report (`prepareLocalMemory`) for GPU-heavy local work; only loopback Ollama / LM Studio backends are evicted. |-| `threejsModel.js` | Validated declarative procedural-model schema plus deterministic standalone Three.js factory export for the Three.js Models workspace. Also the cross-section gate: `evaluateThreejsFlatness(spec)` counts distinct vertex planes per axis — relative to the mesh's own size, with a rotation-invariant zero-volume check behind it — and treats an `extrude` with no bevel thickness as the two-plane slab it is to report when the majority of identity-priority features are built only from flat parts — a model that reads right head-on and like cardboard when orbited. `buildThreejsFlatnessFeedback(flatness)` turns that into default refinement feedback; `listSpecNames(names)` is the shared capped name-list formatter both gates use in finding messages. Also the material-plausibility gate: `evaluateThreejsMaterialPlausibility(spec)` keys a bounded per-family prior table (metal, wood, plastic, glass, fabric, ceramic, rubber, stone, leather, paper) off tokens in each material's id and reports channels whose values the named substance does not support — metalness 0.9 oak, transmission 1.0 steel — skipping any id that names no family or two, and any channel the material's `type` never forwards to Three.js. Advisory only: it never clamps, because a stylized model may legitimately break every prior. `buildThreejsMaterialFeedback(plausibility)` turns that into default refinement feedback. The same pass emits a `reflective-material-without-environment` note when a spec authors reflective channels (metalness above 0.6, or any transmission/clearcoat/iridescence) while `environment.preset` is `none` — those channels read off an environment, so in that scene their values cannot be judged at all. The spec carries an optional `environment` block (see `threejsModelEnvironment.js`), and `buildThreejsFactorySource()` stamps its render profile onto `root.userData.sculptRuntime.render` and exports it as `renderProfile`, so a consumer wiring their own `WebGLRenderer` reproduces the model instead of a differently tone-mapped approximation. |+| `threejsModel.js` | Validated declarative procedural-model schema plus deterministic standalone Three.js factory export for the Three.js Models workspace. Also the cross-section gate: `evaluateThreejsFlatness(spec)` counts distinct vertex planes per axis — relative to the mesh's own size, with a rotation-invariant zero-volume check behind it — and treats an `extrude` with no bevel thickness as the two-plane slab it is to report when the majority of identity-priority features are built only from flat parts — a model that reads right head-on and like cardboard when orbited. `buildThreejsFlatnessFeedback(flatness)` turns that into default refinement feedback; `listSpecNames(names)` is the shared capped name-list formatter both gates use in finding messages. Also the material-plausibility gate: `evaluateThreejsMaterialPlausibility(spec)` keys a bounded per-family prior table (metal, wood, plastic, glass, fabric, ceramic, rubber, stone, leather, paper) off tokens in each material's id and reports channels whose values the named substance does not support — metalness 0.9 oak, transmission 1.0 steel — skipping any id that names no family or two, and any channel the material's `type` never forwards to Three.js. Advisory only: it never clamps, because a stylized model may legitimately break every prior. `buildThreejsMaterialFeedback(plausibility)` turns that into default refinement feedback. The same pass emits a `reflective-material-without-environment` note when a spec authors reflective channels (metalness above 0.6, or any transmission/clearcoat/iridescence) while `environment.preset` is `none` — those channels read off an environment, so in that scene their values cannot be judged at all. Attachments are declared in two forms — the original anchor-less `attachmentPartIds` and the anchored `attachments: [{ partId, anchorPartId | anchorSocket, maxOffset }]` — and `resolveThreejsAttachments(articulation)` merges them into one canonical list (an anchored entry wins over a bare id) so every gate reads the same set; `isThreejsAttachmentAnchored(attachment)` is the shared anchored/unanchored predicate and `DEFAULT_ATTACHMENT_MAX_OFFSET` the default tolerance. The spec-level refinement rejects an anchor that does not resolve, one that is the attachment itself, an anchor chain that cycles, and the model root (the sole top-level part) — which carries no relationship to any body part. The spec carries an optional `environment` block (see `threejsModelEnvironment.js`), and `buildThreejsFactorySource()` stamps its render profile onto `root.userData.sculptRuntime.render` and exports it as `renderProfile`, so a consumer wiring their own `WebGLRenderer` reproduces the model instead of a differently tone-mapped approximation. || `threejsModelAnimation.js` | `summarizeThreejsAnimation(spec)` — clip inventory *and* playback gate over an already-validated Three.js spec: `{ animated, clipCount, cueCount, sequenceCount, movingPartCount, longestClipSeconds, findings, warningCount, clips }`. The schema proves a declared `animation` block is well *formed* (sequences on real parts, inside their clip, never two on one channel at once, never a cue without motion); this reports what the model *declared* — one entry per clip with its role, duration, sequence and distinct-cue counts — plus the ways a well-formed clip still plays badly: a clip authored against a pose the assembly does not build (`clip-start-pose-mismatch`), a handover between sequences that do not meet (`clip-sequence-jump`), a `loop: true` clip that does not return to where it began, a one-shot `idle`, an unfired cue, a long dead tail, and an articulation graph with no clip at all. Advisory warnings only — a static assembly is a complete answer. `buildThreejsAnimationFeedback(animation)` turns those findings into default refinement feedback. A spec with no `animation` key summarizes as not animated — never as evaluated-and-empty. || `threejsModelCoverage.js` | `evaluateThreejsPartCoverage(spec, { family })` — structural assembly gate over an already-validated Three.js spec: flags promised features fused onto the same part set, geometry claimed by no detail, and details nothing was built for (folded minor relief stays a `note`). With a subject family it also warns on a required component the spec never mentions at all — the one check that can fault a spec for what it failed to *promise*. `buildThreejsCoverageFeedback(coverage)` turns the error findings (plus any family gap) into default refinement feedback. || `threejsModelEnvironment.js` | The image-based-lighting and render-profile half of the procedural sculpt contract, kept **dependency-free** so the client suite can import it to assert parity with `client/src/lib/threejsEnvironment.js` (`threejsModel.js` pulls in zod, which the client CI job does not install). `THREEJS_ENVIRONMENT_PRESETS` (`none`/`neutral`/`studio`) is the bounded preset list the spec schema builds its enum from; `resolveThreejsEnvironment(spec)` normalizes a spec's `{ preset, intensity }` block, reading an absent, partial, or unrecognized one as `DEFAULT_THREEJS_ENVIRONMENT` per field — a record stored before the block shipped has no key and was rendered with no environment, so `none` is the honest reading of it. `THREEJS_RENDER_PROFILE` is the output-colour-space / tone-mapping / exposure contract `buildThreejsFactorySource()` stamps onto every export. || `threejsModelFamilies.js` | Curated subject-family checklists for Three.js generation. `THREEJS_MODEL_FAMILY_OPTIONS` / `THREEJS_MODEL_FAMILY_IDS` drive the picker and route validation; `buildThreejsFamilyChecklist(id)` returns the prompt block spliced into generation (`''` for the default `general`, so an un-narrowed subject keeps the unchanged general-purpose prompt); `findMissingFamilyComponents(spec, id)` reports which required components the spec never mentions. || `threejsModelPenetration.js` | `evaluateThreejsPenetration(spec)` — cross-part penetration gate over an already-validated Three.js spec, the one check that compares two parts to each other. Rebuilds each part's world placement (the same `THREE.Euler` 'XYZ' composition the preview applies), derives an analytic solid per geometry type, and samples one part's interior against another's to flag a part entirely buried inside an unrelated one (`error`) or unrelated parts occupying substantially the same space (`warning`). Parts in the same subtree and declared `attachmentPartIds` are exempt — embedding is what those relationships are *for* — and a shallow or transparent-container overlap is reported as an undecided `note`, never as a defect. `buildThreejsPenetrationFeedback(penetration)` turns the errors and warnings (never the undecided notes) into default refinement feedback. |-| `threejsModelPhysicalAudit.js` | `evaluateThreejsPhysicalAudit(spec)` — pure bounds and pose audit gate over an already-validated Three.js spec: inspects static resting poses and animated clip poses to detect floating parts (`floating-part`), swallowed geometry (`buried-geometry`), z-fighting coplanar surfaces (`coplanar-surface`), unprovenanced appearing geometry (`unprovenanced-transition`), and non-uniform parent scale cascading into descendants (`nonuniform-parent-scale`). `buildThreejsPhysicalAuditFeedback(physicalAudit)` turns actionable findings into default refinement feedback. |+| `threejsModelPhysicalAudit.js` | `evaluateThreejsPhysicalAudit(spec)` — pure bounds and pose audit gate over an already-validated Three.js spec: inspects static resting poses and animated clip poses to detect floating parts (`floating-part`), swallowed geometry (`buried-geometry`), z-fighting coplanar surfaces (`coplanar-surface`), unprovenanced appearing geometry (`unprovenanced-transition`), non-uniform parent scale cascading into descendants (`nonuniform-parent-scale`), attachments declared with nothing to hang from (`unanchored-attachment`, warning), and attachments measured further from their declared anchor than `maxOffset` allows (`attachment-far-from-anchor`, error — the spec asserted the relationship itself), across the resting pose and the sampled clip poses so a clip that carries an attachment away from its anchor is caught too. An attachment whose anchor geometry could not be measured is listed in `unmeasuredAttachments` rather than counted as passing. `buildThreejsPhysicalAuditFeedback(physicalAudit)` turns actionable findings into default refinement feedback. || `threejsModelPlayerSource.js` | `THREEJS_PLAYER_SOURCE` — the fixed clip-player source `buildThreejsFactorySource` emits into every exported Three.js module, giving a standalone consumer `createSculptAnimationPlayer(root, { onCue })` (plus `evaluateSculptClipPose` / `collectSculptCues`) over the node map and validated `animation` block the factory already carries. A STRING constant, not generated text: nothing provider-authored is interpolated into it, so the export stays data-plus-PortOS-code. It takes `update(deltaSeconds)` from the host render loop rather than owning one, scrubs silently and fires cues only on playback (mirroring the preview), and clones a shared material before driving `opacity`. Semantics mirror `client/src/lib/threejsAnimation.js` — change one and change the other. |-| `threejsModelRig.js` | `evaluateThreejsRigReadiness(spec)` — honest rig-readiness report over an already-validated Three.js spec: `{ articulationReady, reasons, jointCount, socketCount, attachmentCount, rootJointId, subjectType }`. The schema proves the optional `articulation` graph is well *formed* (one root, no cycles or forward refs, joints and pivots pointed at real parts/sockets); this reports whether it is *useful* (more than a lone root, every child joint carrying a pivot axis) and names the reason when it is not. It reports rather than rejects, and never claims skinning: PortOS generates static assemblies and declared articulation intent, not skeletons or bind poses. |+| `threejsModelRig.js` | `evaluateThreejsRigReadiness(spec)` — honest rig-readiness report over an already-validated Three.js spec: `{ articulationReady, reasons, jointCount, socketCount, attachmentCount, anchoredAttachmentCount, unanchoredAttachmentCount, rootJointId, subjectType }`. The schema proves the optional `articulation` graph is well *formed* (one root, no cycles or forward refs, joints and pivots pointed at real parts/sockets); this reports whether it is *useful* (more than a lone root, every child joint carrying a pivot axis, every declared attachment naming what it hangs from) and names the reason when it is not. It reports rather than rejects, and never claims skinning: PortOS generates static assemblies and declared articulation intent, not skeletons or bind poses. || `pgFileFacade.js` | Shared PG/file store-backend backbone for the six storage dispatchers (pipeline series/issues, story builder, universe builder, catalog user-types, writers room). `isFileBackend()` (dev/test escape-hatch predicate) · `resolvePgBackend({ requirement, migrate?, loadDb, makePg })` (health-check → `ensureSchema` → one-time migration → import `db.js` → build the PG backend) · `createPgFileFacade({ makeFile, makePg })` (promise-memoized lazy selection so concurrent first calls don't run the migration twice; returns `{ getBackend, getBackendName, reset }`). Each store keeps its own `makeFile`/`makePg` factories + public surface. `createRecordStoreBackendSelector({ label, loadFileBackend, loadDbBackend, requireDbMessage?, isTestMode?, onDbReady? })` wraps the same backbone for the stores whose backends are whole MODULES rather than built objects (Creative Director, Music Video, Sprites) → `{ selectBackend, getBackendName }` where the name is `'file'`/`'postgres'`; `isTestMode` lets a store use the stronger `isTestRunner()` signal (Sprites). || `multipart.js` | Streaming multipart/form-data parser. || `safetensors.js` | `readSafetensorsHeader(path)` reads only the JSON header of a `.safetensors` file (never the tensor payload). `detectFlux2VariantFromHeader(header)` / `detectFlux2Variant(path)` classify a LoRA as FLUX.2 Klein `'4b'` (hidden dim 3072) vs `'9b'` (4096) by transformer-block tensor shapes, so the LoRA picker can hide off-variant weights that would silently fail to load. `classifyLoraKeyLayoutFromHeader(header)` / `classifyLoraKeyLayout(path)` classify the key layout as `LORA_KEY_LAYOUTS` (`bare` / `comfyui` / `diffusers` / `kohya` / `not_a_lora`, `null` = unreadable), `isKnownLoraKeyLayout(layout)` validates a layout read back out of persisted state, and `videoLoraLayoutIssue(layout)` returns the user-facing reason a layout can't fuse into the LTX-2 video transformer (or `null` when it can). |diff --git a/server/lib/threejsModel.js b/server/lib/threejsModel.jsindex 1a6bd0928e..216d4296a7 100644--- a/server/lib/threejsModel.js+++ b/server/lib/threejsModel.js@@ -358,13 +358,55 @@ const jointSchema = z.object({const MAX_JOINTS = 64;+// How far an attachment's bounds may sit from its anchor's surface before the+// physical audit calls the relationship broken. A correctly worn hat overlaps+// the head it sits on, so the AABB gap is zero; a charm on a short chain is a+// fraction of a unit away. The default is deliberately tight — a provider that+// needs slack says so per attachment rather than the gate guessing generously,+// because the defects this catches (a hat at hip height, a charm below the+// ground plane) are off by whole model-heights, not by fractions.+export const DEFAULT_ATTACHMENT_MAX_OFFSET = 0.25;+const MAX_ATTACHMENT_OFFSET = 10;+const MAX_ATTACHMENTS = 40;++// An attachment is only meaningful relative to the thing it hangs from, so this+// entry carries that relationship: the part being carried, and EXACTLY ONE of+// the part or the socket it is carried by. Declaring an attachment without an+// anchor is still accepted through the older `attachmentPartIds` list, which is+// what every spec authored before this field existed uses — those read forward+// as anchor-less entries and the gates report them as unanchored rather than+// rejecting a stored record.+const attachmentSchema = z.object({+ partId: idSchema,+ anchorPartId: idSchema.nullable().default(null),+ anchorSocket: idSchema.nullable().default(null),+ maxOffset: z.number().finite().min(0).max(MAX_ATTACHMENT_OFFSET).default(DEFAULT_ATTACHMENT_MAX_OFFSET),+}).superRefine((attachment, ctx) => {+ const anchors = [attachment.anchorPartId, attachment.anchorSocket].filter((value) => value !== null);+ if (anchors.length !== 1) {+ ctx.addIssue({+ code: 'custom',+ message: `attachment ${attachment.partId} needs exactly one of anchorPartId or anchorSocket, found ${anchors.length}`,+ path: ['anchorPartId'],+ });+ }+});+const articulationSchema = z.object({joints: z.array(jointSchema).min(1).max(MAX_JOINTS),// Parts explicitly declared as carried attachments — a pack, a weapon, a hat.// They ride an articulated part rather than articulating, and saying so is the// point: without the declaration "not a joint" and "nobody classified it" are// the same silence.- attachmentPartIds: z.array(idSchema).max(40).default([]),+ //+ // Kept unchanged and still accepted: this is the anchor-less form. `attachments`+ // below is additive, not a replacement, so a stored spec stays valid.+ attachmentPartIds: z.array(idSchema).max(MAX_ATTACHMENTS).default([]),+ // The same declaration plus the one thing the list above cannot say: what each+ // attachment is carried BY. Without it "declared as an attachment" and+ // "parented at the model root and related to nothing" are indistinguishable,+ // and every downstream gate credits the second as though it were the first.+ attachments: z.array(attachmentSchema).max(MAX_ATTACHMENTS).default([]),});const detailSchema = z.object({@@ -655,6 +697,82 @@ const makeSpecSchema = (scaleSchema) => z.object({ctx.addIssue({ code: 'custom', message: `part ${partId} is declared as an attachment and also driven by a joint`, path });}}++ // The model root carries no relationship to any body part, so anchoring to+ // it is the literal defect this field exists to catch. PortOS has no scene+ // root PART — `parts` is an array — so the root is the sole top-level part+ // when there is exactly one: that part IS the whole assembly. A spec with+ // several top-level parts has no such container, and each of them is a real+ // component worth anchoring to.+ const rootPartId = spec.parts.length === 1 ? spec.parts[0].id : null;+ const socketParentByName = new Map(spec.sockets.map((socket) => [socket.name, socket.parentPartId]));+ const anchorPartByAttachment = new Map();+ const seenAttachmentPartIds = new Set();++ for (const [index, attachment] of spec.articulation.attachments.entries()) {+ const at = (key) => ['articulation', 'attachments', index, key];+ if (!partIds.has(attachment.partId)) {+ ctx.addIssue({ code: 'custom', message: `unknown attachment part: ${attachment.partId}`, path: at('partId') });+ } else if (jointPartIds.has(attachment.partId)) {+ ctx.addIssue({ code: 'custom', message: `part ${attachment.partId} is declared as an attachment and also driven by a joint`, path: at('partId') });+ }+ if (seenAttachmentPartIds.has(attachment.partId)) {+ ctx.addIssue({ code: 'custom', message: `duplicate attachment part: ${attachment.partId}`, path: at('partId') });+ }+ seenAttachmentPartIds.add(attachment.partId);++ // Resolve whichever anchor form was given down to the part it names, so+ // self-anchoring, root-anchoring, and cycles are one check apiece rather+ // than one per form.+ let anchorPartId = null;+ if (attachment.anchorPartId !== null) {+ if (!partIds.has(attachment.anchorPartId)) {+ ctx.addIssue({ code: 'custom', message: `unknown attachment anchor part: ${attachment.anchorPartId}`, path: at('anchorPartId') });+ } else {+ anchorPartId = attachment.anchorPartId;+ }+ } else if (attachment.anchorSocket !== null) {+ if (!socketNames.has(attachment.anchorSocket)) {+ ctx.addIssue({ code: 'custom', message: `unknown attachment anchor socket: ${attachment.anchorSocket}`, path: at('anchorSocket') });+ } else {+ anchorPartId = socketParentByName.get(attachment.anchorSocket) ?? null;+ }+ }++ if (anchorPartId !== null) {+ const anchorPath = attachment.anchorPartId !== null ? at('anchorPartId') : at('anchorSocket');+ if (anchorPartId === attachment.partId) {+ ctx.addIssue({ code: 'custom', message: `attachment ${attachment.partId} is anchored to itself`, path: anchorPath });+ } else if (anchorPartId === rootPartId) {+ ctx.addIssue({+ code: 'custom',+ message: `attachment ${attachment.partId} is anchored to the model root ${anchorPartId}, which names no body part to hang from`,+ path: anchorPath,+ });+ } else {+ anchorPartByAttachment.set(attachment.partId, { anchorPartId, path: anchorPath });+ }+ }+ }++ // An anchor chain that closes on itself describes no position: a pack on a+ // strap on the pack. Walk each chain to its end; every hop is an attachment+ // that was itself anchored, so the walk is bounded by the entry count.+ for (const [partId, entry] of anchorPartByAttachment) {+ const visited = new Set([partId]);+ let cursor = entry.anchorPartId;+ while (cursor && anchorPartByAttachment.has(cursor) && !visited.has(cursor)) {+ visited.add(cursor);+ cursor = anchorPartByAttachment.get(cursor).anchorPartId;+ }+ if (cursor && visited.has(cursor)) {+ ctx.addIssue({+ code: 'custom',+ message: `attachment ${partId} sits on an anchor chain that cycles back through ${cursor}`,+ path: entry.path,+ });+ }+ }}if (spec.animation) {@@ -702,6 +820,47 @@ export const threejsSculptSpecSchema = makeSpecSchema(scale3Schema);*/export const storedThreejsSculptSpecSchema = makeSpecSchema(vec3Schema);+/**+ * One canonical attachment list from the two forms a spec may declare.+ *+ * `attachmentPartIds` (the original, anchor-less form) and `attachments` (the+ * anchored one) both mean "this part is carried", so every gate that reasons+ * about attachments reads them through here rather than each picking a form and+ * disagreeing with the next. An anchored entry wins over a bare id for the same+ * part — the richer declaration is the one the author meant.+ *+ * @param {object|null} articulation a spec's `articulation` object, or null+ * @returns {Array<{partId: string, anchorPartId: string|null, anchorSocket: string|null, maxOffset: number}>}+ */+export function resolveThreejsAttachments(articulation) {+ const entries = new Map();+ const bareIds = Array.isArray(articulation?.attachmentPartIds) ? articulation.attachmentPartIds : [];+ for (const partId of bareIds) {+ if (typeof partId !== 'string' || entries.has(partId)) continue;+ entries.set(partId, { partId, anchorPartId: null, anchorSocket: null, maxOffset: DEFAULT_ATTACHMENT_MAX_OFFSET });+ }+ const anchored = Array.isArray(articulation?.attachments) ? articulation.attachments : [];+ for (const attachment of anchored) {+ if (typeof attachment?.partId !== 'string') continue;+ entries.set(attachment.partId, {+ partId: attachment.partId,+ anchorPartId: attachment.anchorPartId ?? null,+ anchorSocket: attachment.anchorSocket ?? null,+ maxOffset: Number.isFinite(attachment.maxOffset) ? attachment.maxOffset : DEFAULT_ATTACHMENT_MAX_OFFSET,+ });+ }+ return [...entries.values()];+}++/**+ * Whether a resolved attachment names something to hang from at all.+ * @param {{anchorPartId: string|null, anchorSocket: string|null}} attachment+ * @returns {boolean}+ */+export const isThreejsAttachmentAnchored = (attachment) => (+ Boolean(attachment?.anchorPartId) || Boolean(attachment?.anchorSocket)+);+const MAX_NAMES_IN_MESSAGE = 8;/**diff --git a/server/lib/threejsModel.test.js b/server/lib/threejsModel.test.jsindex fccd458be1..d29bebd815 100644--- a/server/lib/threejsModel.test.js+++ b/server/lib/threejsModel.test.js@@ -3,8 +3,11 @@ import {buildThreejsFactorySource,buildThreejsFlatnessFeedback,buildThreejsMaterialFeedback,+ DEFAULT_ATTACHMENT_MAX_OFFSET,evaluateThreejsFlatness,evaluateThreejsMaterialPlausibility,+ isThreejsAttachmentAnchored,+ resolveThreejsAttachments,storedThreejsSculptSpecSchema,threejsGeometrySchema,threejsSculptSpecSchema,@@ -725,6 +728,47 @@ const articulationIssues = (mutate) => {return result.error.issues.map((issue) => issue.message);};+// The same graph plus a carried part and the plate it hangs from, both nested+// under the single top-level part so the model root stays unambiguous.+const anchoredSpec = () => {+ const spec = articulatedSpec();+ const body = spec.parts[0];+ body.children.push({+ id: 'backPlate',+ name: 'Back plate',+ geometry: { type: 'box', width: 1.6, height: 1, depth: 0.06 },+ material: 'body',+ position: [0, 0, -0.63],+ rotationDegrees: [0, 0, 0],+ scale: [1, 1, 1],+ children: [],+ });+ body.children.push({+ id: 'pack',+ name: 'Pack',+ geometry: { type: 'box', width: 0.8, height: 0.6, depth: 0.3 },+ material: 'body',+ position: [0, 0, -0.8],+ rotationDegrees: [0, 0, 0],+ scale: [1, 1, 1],+ children: [],+ });+ spec.sockets = [+ ...spec.sockets,+ { name: 'packSocket', parentPartId: 'backPlate', position: [0, 0, -0.03], rotationDegrees: [0, 0, 0] },+ ];+ spec.articulation.attachments = [{ partId: 'pack', anchorPartId: 'backPlate' }];+ return spec;+};++const anchorIssues = (mutate) => {+ const spec = anchoredSpec();+ mutate(spec);+ const result = threejsSculptSpecSchema.safeParse(spec);+ expect(result.success).toBe(false);+ return result.error.issues.map((issue) => issue.message);+};+describe('threejsSculptSpecSchema articulation', () => {it('accepts a well-formed graph and fills the optional joint fields', () => {const parsed = threejsSculptSpecSchema.parse(articulatedSpec());@@ -798,8 +842,144 @@ describe('threejsSculptSpecSchema articulation', () => {'part frontTrim is declared as an attachment and also driven by a joint',]));});++ // Attachment anchors. `attachmentPartIds` says a part is CARRIED; only an+ // anchor says what carries it, which is the difference between a hat on a head+ // and a hat at hip height that every other gate reads as fine.+ it('accepts an anchored attachment and defaults its offset tolerance', () => {+ const parsed = threejsSculptSpecSchema.parse(anchoredSpec());+ expect(parsed.articulation.attachments).toEqual([+ { partId: 'pack', anchorPartId: 'backPlate', anchorSocket: null, maxOffset: DEFAULT_ATTACHMENT_MAX_OFFSET },+ ]);+ });++ // Additive, not a replacement: a spec written before anchors shipped keeps+ // parsing and simply carries an empty anchored list.+ it('leaves a legacy attachmentPartIds spec valid, on both the authoring and stored schemas', () => {+ const legacy = anchoredSpec();+ legacy.articulation.attachmentPartIds = ['pack'];+ delete legacy.articulation.attachments;+ for (const schema of [threejsSculptSpecSchema, storedThreejsSculptSpecSchema]) {+ const parsed = schema.parse(legacy);+ expect(parsed.articulation.attachmentPartIds).toEqual(['pack']);+ expect(parsed.articulation.attachments).toEqual([]);+ }+ });++ it('requires exactly one anchor field per attachment', () => {+ expect(anchorIssues((spec) => {+ spec.articulation.attachments[0].anchorPartId = null;+ })).toEqual(expect.arrayContaining([+ 'attachment pack needs exactly one of anchorPartId or anchorSocket, found 0',+ ]));+ expect(anchorIssues((spec) => {+ spec.articulation.attachments[0].anchorSocket = 'packSocket';+ })).toEqual(expect.arrayContaining([+ 'attachment pack needs exactly one of anchorPartId or anchorSocket, found 2',+ ]));+ });++ it('rejects an anchor that names no declared part or socket', () => {+ expect(anchorIssues((spec) => {+ spec.articulation.attachments[0].anchorPartId = 'notARealPart';+ })).toEqual(expect.arrayContaining(['unknown attachment anchor part: notARealPart']));+ expect(anchorIssues((spec) => {+ spec.articulation.attachments[0].anchorPartId = null;+ spec.articulation.attachments[0].anchorSocket = 'notARealSocket';+ })).toEqual(expect.arrayContaining(['unknown attachment anchor socket: notARealSocket']));+ });++ it('rejects an attachment anchored to itself', () => {+ expect(anchorIssues((spec) => {+ spec.articulation.attachments[0].anchorPartId = 'pack';+ })).toEqual(expect.arrayContaining(['attachment pack is anchored to itself']));+ });++ // The literal defect this field exists for: the root carries no relationship+ // to any body part, so "anchored to the root" is the same silence as no anchor.+ it('rejects an anchor on the model root, named through a part or through a socket', () => {+ expect(anchorIssues((spec) => {+ spec.articulation.attachments[0].anchorPartId = 'crateBody';+ })).toEqual(expect.arrayContaining([+ 'attachment pack is anchored to the model root crateBody, which names no body part to hang from',+ ]));+ expect(anchorIssues((spec) => {+ spec.articulation.attachments[0].anchorPartId = null;+ spec.articulation.attachments[0].anchorSocket = 'lidPivot';+ })).toEqual(expect.arrayContaining([+ 'attachment pack is anchored to the model root crateBody, which names no body part to hang from',+ ]));+ });++ // A model with several top-level parts has no single container, so each of+ // them is a real component worth anchoring to.+ it('allows a top-level anchor when the spec has more than one top-level part', () => {+ const spec = anchoredSpec();+ spec.parts.push({+ id: 'standAlone',+ name: 'Stand',+ geometry: { type: 'box', width: 1, height: 0.2, depth: 1 },+ material: 'body',+ position: [0, 0.1, 0],+ rotationDegrees: [0, 0, 0],+ scale: [1, 1, 1],+ children: [],+ });+ spec.articulation.attachments[0].anchorPartId = 'crateBody';+ expect(threejsSculptSpecSchema.safeParse(spec).success).toBe(true);+ });++ it('rejects an anchor chain that cycles', () => {+ expect(anchorIssues((spec) => {+ spec.articulation.attachments = [+ { partId: 'pack', anchorPartId: 'backPlate' },+ { partId: 'backPlate', anchorPartId: 'pack' },+ ];+ })).toEqual(expect.arrayContaining([+ expect.stringContaining('sits on an anchor chain that cycles back through'),+ ]));+ });++ it('rejects a duplicate attachment entry and one that is also driven by a joint', () => {+ expect(anchorIssues((spec) => {+ spec.articulation.attachments.push({ partId: 'pack', anchorPartId: 'backPlate' });+ })).toEqual(expect.arrayContaining(['duplicate attachment part: pack']));+ expect(anchorIssues((spec) => {+ spec.articulation.attachments[0].partId = 'frontTrim';+ })).toEqual(expect.arrayContaining([+ 'part frontTrim is declared as an attachment and also driven by a joint',+ ]));+ });+});++describe('resolveThreejsAttachments', () => {+ it('reads the legacy list forward as anchor-less entries', () => {+ expect(resolveThreejsAttachments({ attachmentPartIds: ['pack'] })).toEqual([+ { partId: 'pack', anchorPartId: null, anchorSocket: null, maxOffset: DEFAULT_ATTACHMENT_MAX_OFFSET },+ ]);+ });++ // The richer declaration is the one the author meant, so it wins rather than+ // the part being counted twice with contradictory anchors.+ it('lets an anchored entry win over a bare id for the same part', () => {+ const resolved = resolveThreejsAttachments({+ attachmentPartIds: ['pack'],+ attachments: [{ partId: 'pack', anchorPartId: 'backPlate', anchorSocket: null, maxOffset: 1 }],+ });+ expect(resolved).toEqual([+ { partId: 'pack', anchorPartId: 'backPlate', anchorSocket: null, maxOffset: 1 },+ ]);+ expect(resolved.every(isThreejsAttachmentAnchored)).toBe(true);+ });++ it('reads a missing or malformed articulation as no attachments at all', () => {+ for (const value of [null, undefined, {}, { attachmentPartIds: 'nope', attachments: 7 }]) {+ expect(resolveThreejsAttachments(value)).toEqual([]);+ }+ });});+describe('buildThreejsFactorySource articulation', () => {it('carries a validated graph into the exported runtime metadata', () => {const source = buildThreejsFactorySource(articulatedSpec());diff --git a/server/lib/threejsModelPenetration.js b/server/lib/threejsModelPenetration.jsindex 3ab3065814..e2a06934a5 100644--- a/server/lib/threejsModelPenetration.js+++ b/server/lib/threejsModelPenetration.js@@ -34,7 +34,7 @@* reference being followed, not a mistake.*/-import { listSpecNames } from './threejsModel.js';+import { listSpecNames, resolveThreejsAttachments } from './threejsModel.js';// Sampling resolution over a part's local bounding box. 8³ is enough to// estimate a containment fraction to a couple of percent, which is all the@@ -492,7 +492,7 @@ export function evaluateThreejsPenetration(spec) {const materials = spec?.materials && typeof spec.materials === 'object' ? spec.materials : {};// A declared attachment says outright that this part rides another one, so a// pack sunk into the back it is strapped to is the spec working as declared.- const attachments = new Set(spec?.articulation?.attachmentPartIds || []);+ const attachments = new Set(resolveThreejsAttachments(spec?.articulation).map((attachment) => attachment.partId));const buried = [];const overlapping = [];diff --git a/server/lib/threejsModelPhysicalAudit.js b/server/lib/threejsModelPhysicalAudit.jsindex b46d6c22b7..7a33d33682 100644--- a/server/lib/threejsModelPhysicalAudit.js+++ b/server/lib/threejsModelPhysicalAudit.js@@ -7,9 +7,19 @@* 3. `coplanar-surface`: Sibling or unrelated part pairs sharing a near-coplanar surface (z-fighting).* 4. `unprovenanced-transition`: Animated parts that pop into existence in open space without emerging from a parent or ground level.* 5. `nonuniform-parent-scale`: A non-relief child inherits a parent's anisotropic scale and may be distorted.+ * 6. `unanchored-attachment`: A part declared as carried that names nothing it is carried by.+ * 7. `attachment-far-from-anchor`: A declared attachment measured away from the anchor the spec says it hangs from.+ *+ * Checks 6 and 7 exist because `floating-part` and `buried-geometry` both miss+ * the same defect: a hat that belongs behind the shoulders but is authored at+ * hip height touches its neighbours, so nothing calls it floating, and it is not+ * contained by anything, so nothing calls it buried. Only the declared+ * relationship to its anchor makes the position wrong — which is why an+ * attachment whose anchor geometry cannot be measured is reported as unmeasured+ * rather than allowed to read as clean.*/-import { listSpecNames } from './threejsModel.js';+import { isThreejsAttachmentAnchored, listSpecNames, resolveThreejsAttachments } from './threejsModel.js';const EPSILON = 1e-4;const COPLANAR_TOLERANCE = 1e-3;@@ -274,6 +284,9 @@ function getPoseStateResolver(clip, timeSeconds) {function collectPoseVolumes(spec, getPartState) {const volumes = [];+ // Every part, not only the ones that carry geometry: a socket hangs off its+ // parent part's world transform, and that parent is routinely a bare group.+ const transformsByPartId = new Map();const walk = (part, parentTransform, ancestorIds) => {const state = getPartState ? getPartState(part) : {position: part.position,@@ -284,6 +297,7 @@ function collectPoseVolumes(spec, getPartState) {};const transform = composeTransform(parentTransform, state.position, state.rotationDegrees, state.scale);+ transformsByPartId.set(part.id, transform);const localBounds = getLocalBounds(part.geometry);if (localBounds) {@@ -310,7 +324,7 @@ function collectPoseVolumes(spec, getPartState) {walk(part, IDENTITY_TRANSFORM, []);}- return volumes;+ return { volumes, transformsByPartId };}const flattenParts = (parts) => {@@ -396,6 +410,123 @@ const buildNonuniformParentScaleFinding = (part, scaleSamples, context = {}) =>};};+const unionBounds = (a, b) => {+ if (!a) return b;+ if (!b) return a;+ return [0, 1, 2].map((axis) => [Math.min(a[axis][0], b[axis][0]), Math.max(a[axis][1], b[axis][1])]);+};++/**+ * World bounds for each part INCLUDING its descendants.+ *+ * An anchor is routinely a bare group whose surface is entirely in its children+ * — "head" holding a skull and a jaw — so measuring only the part's own geometry+ * would report a hat as unmeasurable against the head it plainly sits on.+ */+const buildSubtreeBounds = (volumes) => {+ const bounds = new Map();+ for (const volume of volumes) {+ for (const id of [volume.id, ...volume.ancestorIds]) {+ bounds.set(id, unionBounds(bounds.get(id), volume.worldBounds));+ }+ }+ return bounds;+};++// A socket is a point, and `aabbDistance` already measures box-to-box, so the+// point rides in as a degenerate box rather than earning a second routine.+const pointBounds = ([x, y, z]) => [[x, x], [y, y], [z, z]];++const formatOffset = (value) => Number(value.toFixed(3));++/**+ * Measure every anchored attachment against the thing it says it hangs from, in+ * one pose.+ *+ * @returns {{findings: Array, unmeasured: Array<{partId: string, anchorPartId: string|null,+ * anchorSocket: string|null, reason: string}>}}+ */+function measureAttachmentAnchors({+ attachments,+ volumes,+ transformsByPartId,+ socketsByName,+ namesByPartId,+ context = {},+}) {+ const findings = [];+ const unmeasured = [];+ if (attachments.length === 0) return { findings, unmeasured };++ const measurable = volumes.filter((volume) => volume.visible && volume.opacity > 0);+ const subtreeBounds = buildSubtreeBounds(measurable);+ const label = (partId) => `"${namesByPartId.get(partId) || partId}"`;+ const { clipName, ...metadata } = context;++ for (const attachment of attachments) {+ const attachmentBounds = subtreeBounds.get(attachment.partId);+ if (!attachmentBounds) {+ unmeasured.push({+ partId: attachment.partId,+ anchorPartId: attachment.anchorPartId,+ anchorSocket: attachment.anchorSocket,+ reason: 'the attachment has no visible geometry to measure',+ });+ continue;+ }++ let anchorBounds = null;+ let anchorDescription = '';+ if (attachment.anchorSocket) {+ const socket = socketsByName.get(attachment.anchorSocket);+ const transform = socket ? transformsByPartId.get(socket.parentPartId) : null;+ if (transform) {+ anchorBounds = pointBounds(applyTransform(transform, socket.position || [0, 0, 0]));+ anchorDescription = `socket "${attachment.anchorSocket}" on ${label(socket.parentPartId)}`;+ }+ } else if (attachment.anchorPartId) {+ anchorBounds = subtreeBounds.get(attachment.anchorPartId) || null;+ anchorDescription = label(attachment.anchorPartId);+ }++ if (!anchorBounds) {+ unmeasured.push({+ partId: attachment.partId,+ anchorPartId: attachment.anchorPartId,+ anchorSocket: attachment.anchorSocket,+ reason: attachment.anchorSocket+ ? 'the anchor socket could not be located in this pose'+ : 'the anchor part has no visible geometry to measure',+ });+ continue;+ }++ const distance = aabbDistance(attachmentBounds, anchorBounds);+ if (distance <= attachment.maxOffset) continue;++ const scope = clipName+ ? `In clip "${clipName}", part ${label(attachment.partId)}`+ : `Part ${label(attachment.partId)}`;+ findings.push({+ code: 'attachment-far-from-anchor',+ // The spec asserted this relationship itself, so a part measured away from+ // its own declared anchor is a stated fact the model does not build.+ severity: 'error',+ ...metadata,+ partIds: attachment.anchorPartId+ ? [attachment.partId, attachment.anchorPartId]+ : [attachment.partId],+ anchorPartId: attachment.anchorPartId,+ anchorSocket: attachment.anchorSocket,+ distance: formatOffset(distance),+ maxOffset: attachment.maxOffset,+ message: `${scope} is declared as an attachment carried by ${anchorDescription}, but it sits ${formatOffset(distance)} units away from it (allowed ${attachment.maxOffset}). Move it onto ${anchorDescription} or re-anchor it to the part it is actually carried by.`,+ });+ }++ return { findings, unmeasured };+}+const collectAnimatedScaleSamples = (part, sequences) => sequences.filter((sequence) => sequence.partId === part.id && sequence.channels?.scale).flatMap((sequence) => [@@ -417,16 +548,21 @@ export function evaluateThreejsPhysicalAudit(spec) {noteCount: 0,evaluatedPartCount: 0,evaluatedPoseCount: 0,+ unmeasuredAttachments: [],};}const materials = spec.materials && typeof spec.materials === 'object' ? spec.materials : {};- const attachments = new Set(spec.articulation?.attachmentPartIds || []);+ const declaredAttachments = resolveThreejsAttachments(spec.articulation);+ const anchoredAttachments = declaredAttachments.filter(isThreejsAttachmentAnchored);+ const attachments = new Set(declaredAttachments.map((attachment) => attachment.partId));const jointPartIds = new Set((spec.articulation?.joints || []).map((j) => j.partId).filter(Boolean));+ const socketsByName = new Map((spec.sockets || []).map((socket) => [socket.name, socket]));const findings = [];const seenKeys = new Set();const parts = flattenParts(spec.parts);+ const namesByPartId = new Map(parts.map((part) => [part.id, part.name || part.id]));const staticScaleFindings = new Map();const strongestAnimatedScaleFindings = new Map();@@ -438,10 +574,36 @@ export function evaluateThreejsPhysicalAudit(spec) {};// 1. Static Resting Pose Evaluation- const staticVolumes = collectPoseVolumes(spec, null);+ const { volumes: staticVolumes, transformsByPartId } = collectPoseVolumes(spec, null);const evaluatedPartCount = staticVolumes.length;let evaluatedPoseCount = 1;+ // A declaration with no anchor in it cannot be measured at all, so it is+ // reported before any geometry is looked at.+ for (const attachment of declaredAttachments) {+ if (isThreejsAttachmentAnchored(attachment)) continue;+ addFinding({+ code: 'unanchored-attachment',+ severity: 'warning',+ partIds: [attachment.partId],+ message: `Part "${namesByPartId.get(attachment.partId) || attachment.partId}" is declared as a carried attachment but names nothing it is carried by, so nothing ties it to the part it hangs from. Declare it in "attachments" with an "anchorPartId" or "anchorSocket".`,+ });+ }++ const staticAnchorReport = measureAttachmentAnchors({+ attachments: anchoredAttachments,+ volumes: staticVolumes,+ transformsByPartId,+ socketsByName,+ namesByPartId,+ });+ const unmeasuredAttachments = staticAnchorReport.unmeasured;+ const staticAnchorFailures = new Set();+ for (const finding of staticAnchorReport.findings) {+ staticAnchorFailures.add(finding.partIds[0]);+ addFinding(finding);+ }+for (const part of parts) {const finding = buildNonuniformParentScaleFinding(part, [{ scale: part.scale }]);if (finding) {@@ -581,6 +743,34 @@ export function evaluateThreejsPhysicalAudit(spec) {remainingBudget -= timesToTest.length;evaluatedPoseCount += timesToTest.length;+ // A clip can carry an attachment away from its anchor without ever breaking+ // the resting pose, so the same measurement runs over the sampled poses —+ // reporting the WORST one per attachment rather than the first, so the+ // refinement feedback names the moment the relationship is most broken.+ if (anchoredAttachments.length > 0) {+ const worstByPartId = new Map();+ for (const timeSeconds of timesToTest) {+ const pose = collectPoseVolumes(spec, getPoseStateResolver(clip, timeSeconds));+ const report = measureAttachmentAnchors({+ attachments: anchoredAttachments,+ volumes: pose.volumes,+ transformsByPartId: pose.transformsByPartId,+ socketsByName,+ namesByPartId,+ context: { clipId: clip.id, clipName: clip.name || clip.id, timeSeconds },+ });+ for (const finding of report.findings) {+ const partId = finding.partIds[0];+ // The resting pose already reported this attachment; repeating it per+ // clip would bury the clip-only breaks the pose walk exists to find.+ if (staticAnchorFailures.has(partId)) continue;+ const current = worstByPartId.get(partId);+ if (!current || finding.distance > current.distance) worstByPartId.set(partId, finding);+ }+ }+ for (const finding of worstByPartId.values()) addFinding(finding);+ }+// Check unprovenanced transitions for sequences that toggle visibility/opacityfor (const seq of sequences) {const visCh = seq.channels?.visible;@@ -590,7 +780,7 @@ export function evaluateThreejsPhysicalAudit(spec) {if (appears && seq.startSeconds > 0) {const getPoseState = getPoseStateResolver(clip, seq.startSeconds);- const poseVolumes = collectPoseVolumes(spec, getPoseState);+ const { volumes: poseVolumes } = collectPoseVolumes(spec, getPoseState);const partVolume = poseVolumes.find((v) => v.id === seq.partId);if (partVolume) {@@ -631,6 +821,10 @@ export function evaluateThreejsPhysicalAudit(spec) {noteCount: countBy('note'),evaluatedPartCount,evaluatedPoseCount,+ // Never folded into the clean count: an attachment whose anchor could not be+ // measured was not checked, and reporting it as passing is the failure this+ // gate exists to avoid.+ unmeasuredAttachments,};}@@ -643,14 +837,28 @@ export function evaluateThreejsPhysicalAudit(spec) {*/export function buildThreejsPhysicalAuditFeedback(physicalAudit) {const actionable = (physicalAudit?.findings || []).filter((f) => f.severity === 'error' || f.severity === 'warning');- if (actionable.length === 0) return '';+ const unmeasured = Array.isArray(physicalAudit?.unmeasuredAttachments) ? physicalAudit.unmeasuredAttachments : [];+ if (actionable.length === 0 && unmeasured.length === 0) return '';const hasNonuniformParentScale = actionable.some((finding) => finding.code === 'nonuniform-parent-scale');+ const attachmentFindings = actionable.filter((finding) => (+ finding.code === 'unanchored-attachment' || finding.code === 'attachment-far-from-anchor'+ ));+ // Name the anchor rather than the defect: the next pass needs somewhere to put+ // the part, and "this is floating" without a destination is what produced the+ // hat at hip height in the first place.+ const anchorNames = [...new Set(attachmentFindings+ .map((finding) => finding.anchorSocket || finding.anchorPartId)+ .filter(Boolean))];return ['The previous pass failed physical conformance audits:',...actionable.map((finding, index) => `${index + 1}. ${finding.message}`),+ ...unmeasured.map((entry) => `Attachment "${entry.partId}" could not be checked against ${entry.anchorSocket ? `socket "${entry.anchorSocket}"` : `"${entry.anchorPartId}"`} because ${entry.reason} — give both the attachment and its anchor real geometry so the relationship can be verified.`),...(hasNonuniformParentScale ? ['For non-uniform parent scale findings, size each part through its own geometry dimensions (for example, box width/height/depth or sphere radius) and keep containers near-uniform instead of squashing a parent that owns other components.',] : []),+ ...(attachmentFindings.length > 0 ? [+ `For attachment findings, every entry in "articulation.attachments" must name the part or socket it hangs from and be positioned against it${anchorNames.length > 0 ? ` (the anchors named above: ${listSpecNames(anchorNames.map((name) => `"${name}"`))})` : ''}. Anchoring to the model root is not acceptable — name the body part that actually carries the piece.`,+ ] : []),'Ensure every part is physically attached to a parent, sibling, or ground plane, keep geometry exposed rather than buried inside unrelated parts, avoid exact coplanar surfaces that cause flickering, and make animated parts emerge cleanly from parents or hidden containers.',].join('\n');}diff --git a/server/lib/threejsModelPhysicalAudit.test.js b/server/lib/threejsModelPhysicalAudit.test.jsindex 708b7f29c7..85488777ee 100644--- a/server/lib/threejsModelPhysicalAudit.test.js+++ b/server/lib/threejsModelPhysicalAudit.test.js@@ -14,6 +14,7 @@ describe('threejsModelPhysicalAudit', () => {noteCount: 0,evaluatedPartCount: 0,evaluatedPoseCount: 0,+ unmeasuredAttachments: [],});});@@ -682,3 +683,166 @@ describe('threejsModelPhysicalAudit', () => {expect(finding.timeSeconds).toBe(1);});});++// Attachment anchors. The upstream defects these mirror — a conical hat rendered+// at hip height, a charm detached from the staff it hangs off — pass every other+// check in this file: the hat touches the torso so it does not float, and nothing+// contains it so it is not buried. Only its declared anchor makes it wrong.+describe('threejsModelPhysicalAudit attachment anchors', () => {+ const box = (id, name, position, size = 0.4) => ({+ id,+ name,+ geometry: { type: 'box', width: size, height: size, depth: size },+ material: 'skin',+ position,+ rotationDegrees: [0, 0, 0],+ scale: [1, 1, 1],+ children: [],+ });++ const wornSpec = (attachments, hatPosition = [0, 1.9, 0]) => ({+ name: 'Figure',+ materials: { skin: { type: 'standard', color: '#ffffff' } },+ parts: [+ box('torso', 'Torso', [0, 1, 0], 1.2),+ box('head', 'Head', [0, 1.8, 0], 0.5),+ { ...box('hat', 'Hat', hatPosition, 0.55) },+ ],+ sockets: [{ name: 'crown', parentPartId: 'head', position: [0, 0.25, 0], rotationDegrees: [0, 0, 0] }],+ articulation: {+ joints: [+ { id: 'rootJoint', partId: 'torso', parentJointId: null, pivotSocket: null },+ { id: 'headJoint', partId: 'head', parentJointId: 'rootJoint', pivotSocket: 'crown' },+ ],+ attachmentPartIds: [],+ attachments,+ },+ });++ const findingsOf = (spec, code) => evaluateThreejsPhysicalAudit(spec).findings.filter((f) => f.code === code);++ it('passes an attachment sitting on the part it is anchored to', () => {+ const spec = wornSpec([{ partId: 'hat', anchorPartId: 'head', anchorSocket: null, maxOffset: 0.25 }]);+ expect(findingsOf(spec, 'attachment-far-from-anchor')).toEqual([]);+ expect(findingsOf(spec, 'unanchored-attachment')).toEqual([]);+ expect(evaluateThreejsPhysicalAudit(spec).unmeasuredAttachments).toEqual([]);+ });++ it('reports an attachment measured away from its declared anchor as an error', () => {+ const spec = wornSpec([{ partId: 'hat', anchorPartId: 'head', anchorSocket: null, maxOffset: 0.25 }], [0, 0.6, 0]);+ const [finding] = findingsOf(spec, 'attachment-far-from-anchor');+ expect(finding).toBeDefined();+ expect(finding.severity).toBe('error');+ expect(finding.partIds).toEqual(['hat', 'head']);+ expect(finding.anchorPartId).toBe('head');+ expect(finding.distance).toBeGreaterThan(0.25);+ expect(finding.message).toContain('"Head"');+ // The same spec is clean for every pre-existing check: the hat touches the+ // torso, so nothing else in this gate has anything to say about it.+ expect(findingsOf(spec, 'floating-part')).toEqual([]);+ expect(findingsOf(spec, 'buried-geometry')).toEqual([]);+ });++ it('measures a socket anchor as the point it is, not as its parent part', () => {+ const anchored = [{ partId: 'hat', anchorPartId: null, anchorSocket: 'crown', maxOffset: 0.05 }];+ expect(findingsOf(wornSpec(anchored), 'attachment-far-from-anchor')).toEqual([]);+ const [finding] = findingsOf(wornSpec(anchored, [0, 0.6, 0]), 'attachment-far-from-anchor');+ expect(finding).toBeDefined();+ expect(finding.anchorSocket).toBe('crown');+ expect(finding.partIds).toEqual(['hat']);+ expect(finding.message).toContain('socket "crown"');+ });++ it('warns on a legacy attachment that names nothing to hang from', () => {+ const spec = wornSpec([]);+ spec.articulation.attachmentPartIds = ['hat'];+ const [finding] = findingsOf(spec, 'unanchored-attachment');+ expect(finding).toBeDefined();+ expect(finding.severity).toBe('warning');+ expect(finding.partIds).toEqual(['hat']);+ expect(finding.message).toContain('"Hat"');+ });++ // An anchor whose surface cannot be measured was not checked, and a gate that+ // reports "not checked" as "clean" is the failure mode this list prevents.+ it('reports an attachment whose anchor has no measurable geometry as unmeasured, never as passing', () => {+ const spec = wornSpec([{ partId: 'hat', anchorPartId: 'group', anchorSocket: null, maxOffset: 0.25 }]);+ spec.parts.push({+ id: 'group',+ name: 'Group',+ position: [0, 0, 0],+ rotationDegrees: [0, 0, 0],+ scale: [1, 1, 1],+ children: [],+ });+ const res = evaluateThreejsPhysicalAudit(spec);+ expect(res.findings.filter((f) => f.code === 'attachment-far-from-anchor')).toEqual([]);+ expect(res.unmeasuredAttachments).toEqual([+ { partId: 'hat', anchorPartId: 'group', anchorSocket: null, reason: 'the anchor part has no visible geometry to measure' },+ ]);+ });++ // An anchor that is a bare group is still measurable through its children —+ // "head" holding a skull and a jaw is the normal way to author one.+ it('measures an anchor group through the geometry of its descendants', () => {+ const spec = wornSpec([{ partId: 'hat', anchorPartId: 'headGroup', anchorSocket: null, maxOffset: 0.25 }]);+ spec.parts[1] = {+ id: 'headGroup',+ name: 'Head group',+ position: [0, 1.8, 0],+ rotationDegrees: [0, 0, 0],+ scale: [1, 1, 1],+ children: [box('skull', 'Skull', [0, 0, 0], 0.5)],+ };+ spec.sockets = [];+ spec.articulation.joints = [{ id: 'rootJoint', partId: 'torso', parentJointId: null, pivotSocket: null }];+ const res = evaluateThreejsPhysicalAudit(spec);+ expect(res.unmeasuredAttachments).toEqual([]);+ expect(res.findings.filter((f) => f.code === 'attachment-far-from-anchor')).toEqual([]);+ });++ it('catches a clip that carries an attachment away from its anchor mid-clip', () => {+ const spec = wornSpec([{ partId: 'hat', anchorPartId: 'head', anchorSocket: null, maxOffset: 0.25 }]);+ spec.animation = {+ clips: [{+ id: 'toss',+ name: 'Toss',+ durationSeconds: 2,+ sequences: [{+ id: 'lift',+ name: 'Lift',+ partId: 'hat',+ startSeconds: 0,+ endSeconds: 2,+ channels: { position: { from: [0, 1.9, 0], to: [0, 5, 0] } },+ }],+ }],+ };+ const [finding] = findingsOf(spec, 'attachment-far-from-anchor');+ expect(finding).toBeDefined();+ expect(finding.clipId).toBe('toss');+ expect(finding.timeSeconds).toBe(2);+ expect(finding.message).toContain('In clip "Toss"');+ });++ it('names the anchor in the refinement feedback, so the next pass has somewhere to move the part', () => {+ const spec = wornSpec([{ partId: 'hat', anchorPartId: 'head', anchorSocket: null, maxOffset: 0.25 }], [0, 0.6, 0]);+ const feedback = buildThreejsPhysicalAuditFeedback(evaluateThreejsPhysicalAudit(spec));+ expect(feedback).toContain('"head"');+ expect(feedback).toContain('Anchoring to the model root is not acceptable');+ });++ // Unmeasured is actionable on its own: nothing else in the report would tell+ // the next pass that the relationship was never verified.+ it('feeds an unmeasured attachment back even when no finding fired', () => {+ const spec = wornSpec([{ partId: 'hat', anchorPartId: 'group', anchorSocket: null, maxOffset: 0.25 }]);+ spec.parts.push({+ id: 'group', name: 'Group', position: [0, 0, 0], rotationDegrees: [0, 0, 0], scale: [1, 1, 1], children: [],+ });+ const res = evaluateThreejsPhysicalAudit(spec);+ expect(res.errorCount).toBe(0);+ expect(res.warningCount).toBe(0);+ const feedback = buildThreejsPhysicalAuditFeedback(res);+ expect(feedback).toContain('could not be checked against "group"');+ });+});diff --git a/server/lib/threejsModelRig.js b/server/lib/threejsModelRig.jsindex 89d32f6654..ca822b4d64 100644--- a/server/lib/threejsModelRig.js+++ b/server/lib/threejsModelRig.js@@ -14,7 +14,7 @@* that falls short is still a good model, it is just a static one.*/-import { listSpecNames } from './threejsModel.js';+import { isThreejsAttachmentAnchored, listSpecNames, resolveThreejsAttachments } from './threejsModel.js';// One joint is a root and nothing else — a graph with nothing to rotate against// it describes a static assembly with extra words.@@ -25,16 +25,21 @@ const jointLabel = (joint) => joint.id;/*** @param {object|null} spec a spec that has already passed a sculpt-spec schema* @returns {{articulationReady: boolean, reasons: string[], jointCount: number,- * socketCount: number, attachmentCount: number, rootJointId: string|null,+ * socketCount: number, attachmentCount: number, anchoredAttachmentCount: number,+ * unanchoredAttachmentCount: number, rootJointId: string|null,* subjectType: string|null}}*/export function evaluateThreejsRigReadiness(spec) {const subjectType = spec?.subjectType || null;const articulation = spec?.articulation || null;const joints = Array.isArray(articulation?.joints) ? articulation.joints : [];- const attachmentCount = Array.isArray(articulation?.attachmentPartIds)- ? articulation.attachmentPartIds.length- : 0;+ // An attachment that names nothing to hang from is a declaration with no+ // relationship in it, so it is counted separately rather than credited toward+ // a rig a later export path could actually attach to.+ const attachments = resolveThreejsAttachments(articulation);+ const anchored = attachments.filter(isThreejsAttachmentAnchored);+ const unanchored = attachments.filter((attachment) => !isThreejsAttachmentAnchored(attachment));+ const attachmentCount = attachments.length;const rootJoint = joints.find((joint) => !joint.parentJointId) || null;// Distinct sockets, not joint count: two joints naming the same pivot is one// usable axis, and reporting two would overstate what the model can be rigged@@ -56,6 +61,9 @@ export function evaluateThreejsRigReadiness(spec) {if (unpivoted.length > 0) {reasons.push(`${unpivoted.length} of ${joints.length} joints name no pivot socket, so they have no axis to rotate about (${listSpecNames(unpivoted.map(jointLabel))}).`);}+ if (unanchored.length > 0) {+ reasons.push(`${unanchored.length} of ${attachmentCount} declared attachments name nothing to hang from, so nothing ties them to the part they are carried by (${listSpecNames(unanchored.map((attachment) => attachment.partId))}).`);+ }}return {@@ -64,6 +72,8 @@ export function evaluateThreejsRigReadiness(spec) {jointCount: joints.length,socketCount,attachmentCount,+ anchoredAttachmentCount: anchored.length,+ unanchoredAttachmentCount: unanchored.length,rootJointId: rootJoint?.id || null,subjectType,};diff --git a/server/lib/threejsModelRig.test.js b/server/lib/threejsModelRig.test.jsindex 5decc3c7e7..436c279398 100644--- a/server/lib/threejsModelRig.test.js+++ b/server/lib/threejsModelRig.test.js@@ -8,7 +8,8 @@ const spec = (overrides = {}) => ({{ id: 'rootJoint', partId: 'torso', parentJointId: null, pivotSocket: null },{ id: 'armJoint', partId: 'arm', parentJointId: 'rootJoint', pivotSocket: 'shoulder' },],- attachmentPartIds: ['pack'],+ attachmentPartIds: [],+ attachments: [{ partId: 'pack', anchorPartId: 'torso', anchorSocket: null, maxOffset: 0.25 }],},...overrides,});@@ -21,6 +22,8 @@ describe('evaluateThreejsRigReadiness', () => {jointCount: 2,socketCount: 1,attachmentCount: 1,+ anchoredAttachmentCount: 1,+ unanchoredAttachmentCount: 0,rootJointId: 'rootJoint',subjectType: 'character',});@@ -71,6 +74,40 @@ describe('evaluateThreejsRigReadiness', () => {expect(report.socketCount).toBe(1);});+ // The declaration this whole field exists for: a part named as carried, with+ // nothing naming what carries it, is a relationship the graph does not hold.+ it('reports a declared attachment that names nothing to hang from', () => {+ const unanchored = spec();+ unanchored.articulation.attachments = [];+ unanchored.articulation.attachmentPartIds = ['pack'];+ const report = evaluateThreejsRigReadiness(unanchored);+ expect(report.articulationReady).toBe(false);+ expect(report.attachmentCount).toBe(1);+ expect(report.anchoredAttachmentCount).toBe(0);+ expect(report.unanchoredAttachmentCount).toBe(1);+ expect(report.reasons[0]).toContain('name nothing to hang from');+ expect(report.reasons[0]).toContain('pack');+ });++ it('accepts a socket anchor as an anchor, so a part on a named pivot still counts', () => {+ const socketAnchored = spec();+ socketAnchored.articulation.attachments = [{ partId: 'pack', anchorPartId: null, anchorSocket: 'shoulder', maxOffset: 0.25 }];+ const report = evaluateThreejsRigReadiness(socketAnchored);+ expect(report.articulationReady).toBe(true);+ expect(report.anchoredAttachmentCount).toBe(1);+ });++ // The two forms name the same part, so it is one attachment — and the anchored+ // entry is the one the author meant.+ it('merges a part declared in both attachment forms into one anchored entry', () => {+ const both = spec();+ both.articulation.attachmentPartIds = ['pack'];+ const report = evaluateThreejsRigReadiness(both);+ expect(report.attachmentCount).toBe(1);+ expect(report.anchoredAttachmentCount).toBe(1);+ expect(report.unanchoredAttachmentCount).toBe(0);+ });+it('degrades to a not-ready static report for a missing spec instead of throwing', () => {const report = evaluateThreejsRigReadiness(null);expect(report.articulationReady).toBe(false);diff --git a/server/services/threejsModels/prompt.js b/server/services/threejsModels/prompt.jsindex 6abd4cc7fb..2ed9bf2a95 100644--- a/server/services/threejsModels/prompt.js+++ b/server/services/threejsModels/prompt.js@@ -145,7 +145,7 @@ and omit it for a character whose reference does not support a defensible joint"articulation": {"joints": [{"id":"stableJointId","partId":"partId","parentJointId":null,"pivotSocket":"socketName"}],- "attachmentPartIds": ["partId"]+ "attachments": [{"partId":"partId","anchorPartId":"partId","maxOffset":0.25}]}Rules, all enforced — a spec that breaks one is rejected outright:@@ -155,8 +155,19 @@ Rules, all enforced — a spec that breaks one is rejected outright:- Every "partId" names a real part, and no part is driven by two joints.- "pivotSocket" names a real entry in "sockets" — the point the part rotates about. Add thatsocket. The root may use null; every other joint needs one to be considered rig-ready.-- "attachmentPartIds" lists parts that are CARRIED rather than articulated (packs, weapons,- hats, held props). A part may be an attachment or be driven by a joint, never both.+- "attachments" lists parts that are CARRIED rather than articulated (packs, weapons, hats,+ held props). A part may be an attachment or be driven by a joint, never both.+- EVERY attachment must name what it hangs from: exactly one of "anchorPartId" (a real part)+ or "anchorSocket" (a real entry in "sockets"). An attachment is only meaningful relative to+ its anchor, and one that names nothing is reported as unanchored rather than accepted.+- The anchor must be the body part or socket that actually carries the piece — a hat is+ anchored to the head, a charm to the staff it hangs from. The MODEL ROOT is not an+ acceptable anchor: it carries no relationship to any body part, which is exactly how a hat+ ends up rendered at hip height. An anchor may not be the attachment itself, and anchor+ chains may not cycle.+- Position each attachment ON its anchor. "maxOffset" (default 0.25, world units) is how far+ the attachment's bounds may sit from the anchor's surface before the physical audit calls+ the relationship broken; raise it only for a piece that genuinely hangs at a distance.This is an intent declaration, not a skeleton: do not invent skinning weights, a bind pose, orbones for parts the reference does not clearly show. A short, defensible graph beats a longdiff --git a/server/services/threejsModels/prompt.test.js b/server/services/threejsModels/prompt.test.jsindex 1597dc7107..b10304fd62 100644--- a/server/services/threejsModels/prompt.test.js+++ b/server/services/threejsModels/prompt.test.js@@ -117,7 +117,12 @@ describe('buildThreejsGenerationPrompt articulation', () => {const prompt = build({ family });expect(prompt).toContain('ARTICULATION (character and hybrid subjects only)');expect(prompt).toContain('"parentJointId":null');- expect(prompt).toContain('"attachmentPartIds"');+ expect(prompt).toContain('"attachments"');+ // An attachment with no anchor is the defect the field exists to remove,+ // so the contract has to ask for one — and rule out the root by name.+ expect(prompt).toContain('"anchorPartId"');+ expect(prompt).toContain('"anchorSocket"');+ expect(prompt).toContain('MODEL ROOT is not an');// The contract has to say what it is NOT, or the model invents weights.expect(prompt).toContain('not a skeleton');}