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: declare and report Three.js character rig readiness instead of claiming every model is animation-ready (#3697)
[._.]/ Adam Eivycb51ce739327
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 594f956dc6..72f209e2f9 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **Three.js Models now tells you the truth about rigging.** Every generated model was described as "animation-ready", including characters — but the spec holds a parts hierarchy and sockets, never a skeleton, a bind pose, or a deformation contract, and PortOS does no skinning at all. A character spec can now declare a bounded, optional **articulation graph**: stable joint ids, exactly one root, each joint naming a parent declared before it (so a cycle or a dangling parent is unrepresentable rather than merely unlikely), a named pivot socket per joint, and an explicit list of parts that are *carried* rather than articulated. An impossible graph is rejected outright at generation — two roots, a duplicate joint id, a joint pointed at a part or socket that does not exist, one part driven by two joints, or a part declared as both an attachment and a joint — and only a graph that passed reaches the exported factory's runtime metadata. Alongside it the record now stores a rig-readiness report, and it is honest in both directions: a model with no graph reads **static assembly** with the reason attached rather than a silent pass, and a graph that validates but rigs into nothing (a lone root, or child joints with no pivot axis) is reported the same way. The detail page shows the verdict, the joint/pivot/attachment counts and the reasons; the preview badges static versus articulation-ready and names the joint driving whichever part you click. The generation prompt asks for the contract only when the subject could be a character — a vehicle, weapon, architecture or device family, or a refinement of a spec already classified as an object, leaves the prompt exactly as it was. Models generated before this shipped have no graph and no report; they read as static and unevaluated, never as rigged. Deliberately out of scope: automatic skinning, external rigging models, and generated GLB assets.+- Series Pipeline **Autonomous mode** gains an **"Unlock everything this series owns first"** option. A locked arc, volume, issue stage, or canon entry makes the corresponding fix path throw or silently skip, so a run would surface an editorial finding and then pause on a problem it was never allowed to resolve — leaving you to hunt down every lock toggle by hand before re-running. With the option on, the run's first step clears the arc freeze, the per-field arc locks, every volume lock and every issue stage lock, then reports exactly what it cleared and what it deliberately left frozen. Two boundaries are hard. **Shared records stay locked:** the universe's canon and world fields are only unlocked when this is the universe's *only* series — a stamp saying this series introduced a character records provenance, not exclusive use, and once a sibling series shares the universe that character may be one the sibling is built on. **Nothing is ever deleted:** the pass clears lock bits only, so characters, objects and volumes can be rewritten in full but stay in the Universe and the Catalog. Because unlocking the volume locks also removes the only thing that used to stop a regenerated arc from *dropping* a volume, all three arc-rewriting paths (arc generation, arc auto-resolve, and the foundation gate's structure fix) now re-insert any volume the rewrite omitted, and existing volumes win the per-series volume cap so a large regeneration can't push them out of the list. Consent is per run and per series: it is never saved as a default, the box clears itself once you launch, and it resets when you switch series — so a scheduled, repeat, or other-series run can't inherit lock-clearing. The dry-run plan names the step, with a count of the locks it would clear, before you commit.- Series Pipeline **Autonomous mode gains an observing orchestrator** — the continuous, self-dispatching sibling of *Improve the pipeline itself*. With the new *Observing orchestrator* toggle on, the run watches its own telemetry step by step: when a step's fresh signals say the automation misbehaved (a retried or escalated child runner, a skipped step, an editorial check that threw, a filed gap), it spends one bounded diagnosis call asking what in PortOS should change — a missing or misordered step, an ineffective verify→resolve loop, a broken check or stage prompt, a misconfigured gate, even a missing autopilot option — and **dispatches the fix immediately** as an auto-approved CoS task that works in a worktree, opens a PR, and merges through the review loop with no human gate, so a defect noticed at step 4 is being fixed while steps 5–16 still run. Enabling the toggle is the explicit consent for those unattended changes; the guards are structural: execute-mode only, every pass billed against and gated on the daily cos budget, at most three mid-run passes plus one terminal pass per run, a higher confidence bar than the approval-gated post-mortem (which it supersedes at the run's end), and repeat diagnoses collapsing onto one open task. Live progress frames show each observation and dispatch, and the run's status banner lists everything that was filed. Off by default; scheduled runs inherit whatever you saved.diff --git a/client/src/components/threejsModels/ThreejsModelPreview.jsx b/client/src/components/threejsModels/ThreejsModelPreview.jsxindex c64c373c77..983b80f28e 100644--- a/client/src/components/threejsModels/ThreejsModelPreview.jsx+++ b/client/src/components/threejsModels/ThreejsModelPreview.jsx@@ -5,6 +5,7 @@ import { Bounds, OrbitControls, useBounds } from '@react-three/drei';import * as THREE from 'three';import { createSculptBufferGeometry, needsSculptBufferGeometry, sculptMaterialProps } from '../../lib/threejsSculpt';import { buildPartSelectionIndex, computeExplodeLayout, isReliefPart } from '../../lib/threejsExplode';+import { summarizeThreejsArticulation } from '../../lib/threejsRig';const radians = (degrees = 0) => THREE.MathUtils.degToRad(degrees);const rotation = (degrees = [0, 0, 0]) => degrees.map(radians);@@ -218,6 +219,7 @@ export default function ThreejsModelPreview({ spec, className = '' }) {}, [authoredBackground]);const parts = spec?.parts;+ const articulation = useMemo(() => summarizeThreejsArticulation(spec), [spec]);const selection = useMemo(() => buildPartSelectionIndex(parts || []), [parts]);const layout = useMemo(() => computeExplodeLayout(parts || [], explode), [parts, explode]);@@ -328,6 +330,16 @@ export default function ThreejsModelPreview({ spec, className = '' }) {<div className="always-dark absolute right-2 top-2 flex max-w-[calc(100%-1rem)] items-center gap-2 rounded-lg bg-black/70 px-2 py-1.5 text-[10px] text-gray-200 backdrop-blur-sm"><span className="truncate font-medium text-white">{selection.names[selectedId] || selectedId}</span><code className="truncate text-gray-400">{selectedId}</code>+ {/* Which declared joint (if any) drives the picked part — the diagnostic+ that turns "it says articulation-ready" into something checkable. */}+ {articulation.jointsByPartId[selectedId] && (+ <span className="truncate text-port-accent">+ joint {articulation.jointsByPartId[selectedId].id}+ {articulation.jointsByPartId[selectedId].pivotSocket+ ? ` · pivot ${articulation.jointsByPartId[selectedId].pivotSocket}`+ : ' · no pivot'}+ </span>+ )}<buttontype="button"aria-label="Clear part selection"@@ -338,8 +350,22 @@ export default function ThreejsModelPreview({ spec, className = '' }) {</button></div>)}- <div className="always-dark pointer-events-none absolute bottom-2 left-2 rounded bg-black/60 px-2 py-1 text-[10px] text-gray-300">- Drag to orbit · scroll to zoom · click a part to identify it+ <div className="always-dark pointer-events-none absolute bottom-2 left-2 flex max-w-[calc(100%-1rem)] flex-wrap items-center gap-1.5 text-[10px]">+ <span className="rounded bg-black/60 px-2 py-1 text-gray-300">+ Drag to orbit · scroll to zoom · click a part to identify it+ </span>+ {/* Never "animation-ready": nothing here is skinned. The badge says only+ whether the spec declared a usable articulation graph, and a model+ that predates the contract has none and reads as a static assembly. */}+ <span+ className={articulation.articulationReady+ ? 'rounded bg-port-success/20 px-2 py-1 text-port-success'+ : 'rounded bg-black/60 px-2 py-1 text-gray-400'}+ >+ {articulation.articulationReady+ ? `Articulation-ready · ${articulation.jointCount} joints · ${articulation.socketCount} pivot${articulation.socketCount === 1 ? '' : 's'}`+ : `Static assembly${articulation.jointCount > 0 ? ` · ${articulation.jointCount} joints declared` : ''}`}+ </span></div></div>);diff --git a/client/src/components/threejsModels/ThreejsModelPreview.test.jsx b/client/src/components/threejsModels/ThreejsModelPreview.test.jsxindex 97c1d337d6..2783d68bc1 100644--- a/client/src/components/threejsModels/ThreejsModelPreview.test.jsx+++ b/client/src/components/threejsModels/ThreejsModelPreview.test.jsx@@ -300,3 +300,56 @@ describe('ThreejsModelPreview disassembly', () => {expect(container.querySelectorAll('meshStandardMaterial[emissive="#38bdf8"]')).toHaveLength(0);});});++// The knife again, this time with a declared articulation graph: the handle is+// the root and the blade pivots about a named socket.+const articulatedKnifeSpec = () => ({+ ...knifeSpec(),+ sockets: [{ name: 'bladePivot', parentPartId: 'handle', position: [0, 0, 0], rotationDegrees: [0, 0, 0] }],+ articulation: {+ joints: [+ { id: 'rootJoint', partId: 'handle', parentJointId: null, pivotSocket: null },+ { id: 'bladeJoint', partId: 'blade', parentJointId: 'rootJoint', pivotSocket: 'bladePivot' },+ ],+ attachmentPartIds: [],+ },+});++describe('ThreejsModelPreview articulation status', () => {+ it('calls a spec with no articulation a static assembly, never animation-ready', () => {+ renderPreview(<ThreejsModelPreview spec={knifeSpec()} />);+ expect(screen.getByText('Static assembly')).toBeInTheDocument();+ expect(screen.queryByText(/Articulation-ready/)).not.toBeInTheDocument();+ });++ it('reports a usable graph with its joint and pivot counts', () => {+ renderPreview(<ThreejsModelPreview spec={articulatedKnifeSpec()} />);+ expect(screen.getByText('Articulation-ready · 2 joints · 1 pivot')).toBeInTheDocument();+ });++ // Schema-valid but rig-useless: the child joint has no axis, so the badge must+ // agree with the server's report instead of claiming a rig off mere presence.+ it('stays static when a child joint names no pivot socket, and says how many joints it saw', () => {+ const spec = articulatedKnifeSpec();+ spec.articulation.joints[1].pivotSocket = null;+ renderPreview(<ThreejsModelPreview spec={spec} />);+ expect(screen.getByText('Static assembly · 2 joints declared')).toBeInTheDocument();+ });++ it('names the joint driving a picked part, and the fact when it has no pivot', () => {+ const { container } = renderPreview(<ThreejsModelPreview spec={articulatedKnifeSpec()} />);++ fireEvent.click(container.querySelector('group[name="Blade"] mesh'));+ expect(screen.getByText('joint bladeJoint · pivot bladePivot')).toBeInTheDocument();++ fireEvent.click(container.querySelector('group[name="Handle"] mesh'));+ expect(screen.getByText('joint rootJoint · no pivot')).toBeInTheDocument();+ });++ it('renders a legacy spec with no articulation key without crashing the picker', () => {+ const { container } = renderPreview(<ThreejsModelPreview spec={knifeSpec()} />);+ fireEvent.click(container.querySelector('group[name="Handle"] mesh'));+ expect(screen.getByText('Handle')).toBeInTheDocument();+ expect(screen.queryByText(/^joint /)).not.toBeInTheDocument();+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 95d5dcc436..5cced3e638 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -168,6 +168,7 @@ grep -i "what you want to do" client/src/lib/README.md| `tabNotation.js` | Guitar-tab / chord-sheet / ChordPro text parser for SongBook (`/songbook`). `parseTabSheet(text)` → `{ lines, meta, errors }` classifying each line (`section`/`chords`/`lyric`/`tabstaff`/`chordlyric`/`blank`/`text`) with chord names + column offsets, plus ChordPro meta (`{title:}`/`{artist:}`/`{key:}`/`{capo:}`); `detectFormat(text)` → `'chordpro' \| 'tab' \| 'plain'`; `normalizePastedTab(text)` cleans HTML remnants/entities, CRLF, tabs→spaces, blank-line runs; `transposeChordName(name, n)` / `transposeText(text, n)` transpose chord symbols (slash chords, sensible sharp/flat spelling, column-preserving on chord lines); `TAB_ARTICULATIONS` documents tab-staff technique characters for the viewer legend; `CHORD_TOKEN_RE` exported for reuse, plus `NOTE_TO_PC` / `spellPitchClass` exported minimally so `chordShapes.js` derives voicings from the same pitch-class tables. Forgiving — never throws, unknown lines classify as `text`. NOT the lead-sheet parser (`scoreNotation.js`). || `terminalTheme.js` | Pure xterm.js palette builder for the Shell terminal. `buildTerminalTheme({ bg, fg, accent, card, error, success, warning }, mode)` assembles the xterm `theme` object — base ANSI colors from the active theme's CSS vars, the rest from mode-tuned literals (`ANSI_NIGHT` bright/pastel for dark backgrounds, `ANSI_DAY` darkened/saturated so colored CLI output stays legible on daytime themes). `parseCssColorToHex(raw, fallback)` normalizes both the `15 15 15` triple form and the `rgb(7 7 7 / 0.86)` function form (used by `--port-terminal-*` tokens) to `#rrggbb`, dropping alpha. No DOM reads — `Shell.jsx` resolves CSS vars and re-applies on theme switch. || `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. || `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)` 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`. 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/index.js b/client/src/lib/index.jsindex 647c29ea58..dec15f00e4 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -135,6 +135,7 @@ export * from './syncCounts.js';export * from './tabNotation.js';export * from './terminalTheme.js';export * from './threejsExplode.js';+export * from './threejsRig.js';export * from './threejsSculpt.js';export * from './tribe.js';export * from './quotaBurnPatch.js';diff --git a/client/src/lib/threejsRig.js b/client/src/lib/threejsRig.jsnew file mode 100644index 0000000000..71506da8ee--- /dev/null+++ b/client/src/lib/threejsRig.js@@ -0,0 +1,38 @@+/**+ * Client mirror of `server/lib/threejsModelRig.js`'s readiness rule, plus the+ * joint lookup the preview needs to label a picked part.+ *+ * The server writes an authoritative report onto the record at generation time.+ * The preview is handed a bare `spec` (and a record generated before the report+ * shipped has none at all), so it derives the same verdict from the spec rather+ * than inventing a second, looser one — a preview that says "articulation-ready"+ * while the detail panel says "static" is worse than either answer alone.+ *+ * Keep the thresholds here and in the server module in step.+ */++const MIN_USEFUL_JOINTS = 2;++/**+ * @param {object|null} spec a validated sculpt spec, or null+ * @returns {{articulationReady: boolean, jointCount: number, socketCount: number,+ * attachmentCount: 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+ : [];+ // 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,+ jointCount: joints.length,+ socketCount: new Set(joints.map((joint) => joint.pivotSocket).filter(Boolean)).size,+ attachmentCount: attachments.length,+ jointsByPartId,+ };+}diff --git a/client/src/lib/threejsRig.test.js b/client/src/lib/threejsRig.test.jsnew file mode 100644index 0000000000..1d3df3e8b9--- /dev/null+++ b/client/src/lib/threejsRig.test.js@@ -0,0 +1,53 @@+import { describe, expect, it } from 'vitest';+import { summarizeThreejsArticulation } from './threejsRig';++const spec = () => ({+ articulation: {+ joints: [+ { id: 'rootJoint', partId: 'torso', parentJointId: null, pivotSocket: null },+ { id: 'armJoint', partId: 'arm', parentJointId: 'rootJoint', pivotSocket: 'shoulder' },+ ],+ attachmentPartIds: ['pack'],+ },+});++describe('summarizeThreejsArticulation', () => {+ it('summarizes a usable graph and indexes the joints by the part they drive', () => {+ const summary = summarizeThreejsArticulation(spec());+ expect(summary.articulationReady).toBe(true);+ expect(summary.jointCount).toBe(2);+ expect(summary.socketCount).toBe(1);+ expect(summary.attachmentCount).toBe(1);+ expect(summary.jointsByPartId.arm.id).toBe('armJoint');+ });++ // Legacy records and static subjects both arrive with no key at all — that is+ // a static assembly, not a crash and not a pass.+ it('reads a spec with no articulation, and a missing spec, as static', () => {+ for (const value of [null, undefined, {}, { articulation: null }]) {+ const summary = summarizeThreejsArticulation(value);+ expect(summary.articulationReady).toBe(false);+ expect(summary.jointCount).toBe(0);+ expect(summary.socketCount).toBe(0);+ expect(summary.attachmentCount).toBe(0);+ }+ });++ it('matches the server rule: a lone root, or a child joint with no pivot, is not ready', () => {+ const lonely = spec();+ lonely.articulation.joints = [lonely.articulation.joints[0]];+ expect(summarizeThreejsArticulation(lonely).articulationReady).toBe(false);++ const unpivoted = spec();+ unpivoted.articulation.joints[1].pivotSocket = null;+ expect(summarizeThreejsArticulation(unpivoted).articulationReady).toBe(false);+ });++ // 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', () => {+ const summary = summarizeThreejsArticulation(spec());+ expect(summary.jointsByPartId.toString).toBeUndefined();+ expect(Object.getPrototypeOf(summary.jointsByPartId)).toBeNull();+ });+});diff --git a/client/src/pages/ThreejsModelDetail.jsx b/client/src/pages/ThreejsModelDetail.jsxindex 217275927e..be854044da 100644--- a/client/src/pages/ThreejsModelDetail.jsx+++ b/client/src/pages/ThreejsModelDetail.jsx@@ -18,6 +18,7 @@ import {} from '../services/api';import toast from '../components/ui/Toast';import { copyToClipboard } from '../lib/clipboard';+import { summarizeThreejsArticulation } from '../lib/threejsRig';import { timeAgo } from '../utils/formatters';import { seedModelEffort } from '../utils/providers';@@ -141,6 +142,61 @@ function FamilyChecklistPanel({ family }) {);}+/**+ * Static-versus-articulation-ready status for the generated spec, plus the+ * joint/pivot diagnostics behind it. Prefers the report the server wrote at+ * generation time; a record from before that shipped has none, and degrades to+ * an honest "static, and never evaluated" rather than borrowing a pass.+ */+function RigReadinessPanel({ rig, spec }) {+ const derived = summarizeThreejsArticulation(spec);+ const ready = rig ? rig.articulationReady === true : false;+ const jointCount = rig ? rig.jointCount : derived.jointCount;+ const socketCount = rig ? rig.socketCount : derived.socketCount;+ const attachmentCount = rig ? rig.attachmentCount : derived.attachmentCount;+ const reasons = Array.isArray(rig?.reasons) ? rig.reasons : [];+ return (+ <section className="rounded-xl border border-port-border bg-port-card p-4">+ <div className="mb-2 flex flex-wrap items-center justify-between gap-2">+ <h2 className="text-xs font-medium uppercase tracking-wide text-gray-400">Rig readiness</h2>+ <span className={ready+ ? 'rounded bg-port-success/15 px-2 py-0.5 text-[10px] uppercase text-port-success'+ : 'rounded bg-port-border px-2 py-0.5 text-[10px] uppercase text-gray-400'}+ >+ {ready ? 'Articulation-ready' : 'Static assembly'}+ </span>+ </div>+ <p className="text-xs text-gray-400">+ {jointCount} joint{jointCount === 1 ? '' : 's'} · {socketCount} pivot socket{socketCount === 1 ? '' : 's'}+ {' · '}{attachmentCount} declared attachment{attachmentCount === 1 ? '' : 's'}+ </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">+ This model was generated before rig readiness was reported, so it was never evaluated —+ regenerate it to get a verdict.+ </p>+ )}+ {reasons.length > 0 && (+ <ul className="mt-2 space-y-2">+ {reasons.map((reason) => (+ <li key={reason} className="rounded-lg border border-port-border bg-port-bg/50 px-3 py-2 text-xs leading-relaxed text-gray-400">+ {reason}+ </li>+ ))}+ </ul>+ )}+ <p className="mt-3 flex items-start gap-1.5 text-[11px] leading-relaxed text-gray-500">+ <Info className="mt-0.5 h-3 w-3 shrink-0" />+ <span>+ PortOS builds static assemblies. Articulation is a declaration of what is meant to move —+ stable joint ids, one root, and a named pivot socket per joint — never a skeleton: nothing+ here is skinned, bound to a bind pose, or exported as a rigged mesh.+ </span>+ </p>+ </section>+ );+}+export default function ThreejsModelDetail() {const { id } = useParams();const navigate = useNavigate();@@ -485,6 +541,13 @@ export default function ThreejsModelDetail() {/>)}+ {record.spec && (+ <RigReadinessPanel+ rig={record.rig && typeof record.rig === 'object' ? record.rig : null}+ spec={record.spec}+ />+ )}+{record.spec?.detailInventory?.length > 0 && (<section className="rounded-xl border border-port-border bg-port-card p-4"><div className="mb-2 flex items-center justify-between">diff --git a/client/src/pages/ThreejsModelDetail.test.jsx b/client/src/pages/ThreejsModelDetail.test.jsxindex 450c742698..638e9c8114 100644--- a/client/src/pages/ThreejsModelDetail.test.jsx+++ b/client/src/pages/ThreejsModelDetail.test.jsx@@ -273,3 +273,70 @@ describe('ThreejsModelDetail subject family', () => {));});});++describe('ThreejsModelDetail rig readiness', () => {+ beforeEach(resetMocks);++ it('reports an articulation-ready character with its joint and pivot counts', async () => {+ getThreejsModel.mockResolvedValue({+ ...baseRecord,+ rig: {+ articulationReady: true,+ reasons: [],+ jointCount: 6,+ socketCount: 5,+ attachmentCount: 1,+ rootJointId: 'rootJoint',+ subjectType: 'character',+ },+ });+ renderDetail();++ 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();+ // The claim has to stay bounded: readiness is not a rigged mesh.+ expect(screen.getByText(/never a skeleton/)).toBeInTheDocument();+ });++ it('reports a static assembly with the reasons rather than a silent pass', async () => {+ getThreejsModel.mockResolvedValue({+ ...baseRecord,+ rig: {+ articulationReady: false,+ reasons: ['The spec declares no articulation graph, so this character is a static assembly.'],+ jointCount: 0,+ socketCount: 0,+ attachmentCount: 0,+ rootJointId: null,+ subjectType: 'character',+ },+ });+ renderDetail();++ await waitFor(() => expect(screen.getByText('Rig readiness')).toBeInTheDocument());+ expect(screen.getByText('Static assembly')).toBeInTheDocument();+ expect(screen.getByText('0 joints · 0 pivot sockets · 0 declared attachments')).toBeInTheDocument();+ expect(screen.getByText(/declares no articulation graph/)).toBeInTheDocument();+ expect(screen.queryByText('Articulation-ready')).not.toBeInTheDocument();+ });++ // A record from before the report shipped was never evaluated, which is not+ // the same as having passed — it degrades to static and says so.+ it('degrades a record with no report to an unevaluated static assembly', async () => {+ getThreejsModel.mockResolvedValue({ ...baseRecord, rig: undefined });+ renderDetail();++ await waitFor(() => expect(screen.getByText('Rig readiness')).toBeInTheDocument());+ expect(screen.getByText('Static assembly')).toBeInTheDocument();+ expect(screen.getByText(/generated before rig readiness was reported/)).toBeInTheDocument();+ });++ it('omits the panel entirely until there is a generated scene', async () => {+ getThreejsModel.mockResolvedValue({ ...baseRecord, spec: null, rig: undefined });+ renderDetail();++ await waitFor(() => expect(screen.getByText('Example Beacon')).toBeInTheDocument());+ expect(screen.queryByText('Rig readiness')).not.toBeInTheDocument();+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex a05459a483..b2f80fe466 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -157,6 +157,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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. || `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. || `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. |+| `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. || `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. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 04913b1316..585e00ecb8 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -45,6 +45,7 @@ export * from './validation.js';export * from './threejsModel.js';export * from './threejsModelCoverage.js';export * from './threejsModelFamilies.js';+export * from './threejsModelRig.js';// === Story & narrative ===export * from './bibleExtractor.js';diff --git a/server/lib/threejsModel.js b/server/lib/threejsModel.jsindex 4a4f02b5ef..063d7a019e 100644--- a/server/lib/threejsModel.js+++ b/server/lib/threejsModel.js@@ -322,6 +322,36 @@ const socketSchema = z.object({rotationDegrees: vec3Schema.default([0, 0, 0]),});+// Articulation is a DECLARATION of intent, not a skeleton: PortOS does not skin,+// bind, or deform anything, and nothing downstream of this schema pretends it+// does. A joint names a part that is meant to rotate and the socket it rotates+// about, so a later rig/export path has something stable to attach to and the UI+// can say "articulation-ready" only when the graph is actually well formed.+const jointSchema = z.object({+ id: idSchema,+ // The part this joint drives. One part backs at most one joint — two joints on+ // the same part is a graph that cannot be built, not a redundancy.+ partId: idSchema,+ // `null` marks the single root. Every other joint names a joint declared+ // EARLIER in the array, which is what makes a cycle unrepresentable.+ parentJointId: idSchema.nullable().default(null),+ // The named socket this joint pivots about. Optional on the root (whose pivot+ // is the model origin); a child joint without one has no defined axis, which+ // the rig-readiness report treats as not-ready rather than silently rigged.+ pivotSocket: idSchema.nullable().default(null),+});++const MAX_JOINTS = 64;++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([]),+});+const detailSchema = z.object({feature: z.string().trim().min(1).max(240),evidence: z.string().trim().min(1).max(500),@@ -347,6 +377,9 @@ const makeSpecSchema = (partSchema) => z.object({lights: z.array(lightSchema).min(1).max(8),parts: z.array(partSchema).min(1).max(40),sockets: z.array(socketSchema).max(40).default([]),+ // Optional and additive: a spec written before articulation shipped simply has+ // no key, which every consumer reads as "static assembly", never as "rigged".+ articulation: articulationSchema.optional(),detailInventory: z.array(detailSchema).min(1).max(80),}).superRefine((spec, ctx) => {const materialIds = new Set(Object.keys(spec.materials));@@ -388,6 +421,57 @@ const makeSpecSchema = (partSchema) => z.object({ctx.addIssue({ code: 'custom', message: `unknown socket parent: ${socket.parentPartId}`, path: ['sockets', index, 'parentPartId'] });}}+ if (spec.articulation) {+ const socketNames = new Set(spec.sockets.map((socket) => socket.name));+ const jointIds = new Set();+ const jointPartIds = new Set();+ let rootCount = 0;+ for (const [index, joint] of spec.articulation.joints.entries()) {+ const at = (key) => ['articulation', 'joints', index, key];+ if (jointIds.has(joint.id)) {+ ctx.addIssue({ code: 'custom', message: `duplicate joint id: ${joint.id}`, path: at('id') });+ }+ if (!partIds.has(joint.partId)) {+ ctx.addIssue({ code: 'custom', message: `unknown joint part: ${joint.partId}`, path: at('partId') });+ } else if (jointPartIds.has(joint.partId)) {+ ctx.addIssue({ code: 'custom', message: `part ${joint.partId} is already driven by another joint`, path: at('partId') });+ }+ if (joint.parentJointId === null) {+ rootCount += 1;+ } else if (!jointIds.has(joint.parentJointId)) {+ // Earlier-only, so a dangling parent, a forward reference, and a cycle+ // are all the same rejection — there is no graph walk to get wrong.+ ctx.addIssue({+ code: 'custom',+ message: `joint ${joint.id} names parent ${joint.parentJointId}, which is not a joint declared before it`,+ path: at('parentJointId'),+ });+ }+ if (joint.pivotSocket !== null && !socketNames.has(joint.pivotSocket)) {+ ctx.addIssue({ code: 'custom', message: `unknown pivot socket: ${joint.pivotSocket}`, path: at('pivotSocket') });+ }+ jointIds.add(joint.id);+ jointPartIds.add(joint.partId);+ }+ if (rootCount !== 1) {+ ctx.addIssue({+ code: 'custom',+ message: `articulation needs exactly one root joint (a joint with parentJointId null), found ${rootCount}`,+ path: ['articulation', 'joints'],+ });+ }+ for (const [index, partId] of spec.articulation.attachmentPartIds.entries()) {+ const path = ['articulation', 'attachmentPartIds', index];+ if (!partIds.has(partId)) {+ ctx.addIssue({ code: 'custom', message: `unknown attachment part: ${partId}`, path });+ } else if (jointPartIds.has(partId)) {+ // A part cannot be both carried and articulated — that is the one+ // ambiguity this declaration exists to remove.+ ctx.addIssue({ code: 'custom', message: `part ${partId} is declared as an attachment and also driven by a joint`, path });+ }+ }+ }+for (const [index, detail] of spec.detailInventory.entries()) {for (const [partIndex, id] of detail.implementationPartIds.entries()) {if (!partIds.has(id)) {@@ -775,6 +859,11 @@ export function ${factoryName}() {subjectType: spec.subjectType,nodes,sockets: spec.sockets,+ // Declared articulation intent, or null when the spec has none — the parse+ // above is what makes this trustworthy, so a consumer reads a graph that is+ // known single-rooted, acyclic, and pointed at real parts and sockets. It is+ // NOT a skeleton: nothing here is skinned, bound, or deformed.+ articulation: spec.articulation || null,detailInventory: spec.detailInventory,limitations: spec.limitations,};diff --git a/server/lib/threejsModel.test.js b/server/lib/threejsModel.test.jsindex 8fd0f2aaa0..7ab349b7fb 100644--- a/server/lib/threejsModel.test.js+++ b/server/lib/threejsModel.test.js@@ -606,3 +606,135 @@ describe('buildThreejsFlatnessFeedback', () => {expect(feedback).toContain('genuine depth');});});++// A two-joint character graph over the shared fixture: the crate body is the+// root and its trim is a child that pivots about a declared socket.+const articulatedSpec = () => {+ const spec = validSpec();+ spec.subjectType = 'character';+ spec.sockets = [+ ...spec.sockets,+ { name: 'trimPivot', parentPartId: 'frontTrim', position: [0, 0, 0], rotationDegrees: [0, 0, 0] },+ ];+ spec.articulation = {+ joints: [+ { id: 'rootJoint', partId: 'crateBody', parentJointId: null, pivotSocket: null },+ { id: 'trimJoint', partId: 'frontTrim', parentJointId: 'rootJoint', pivotSocket: 'trimPivot' },+ ],+ attachmentPartIds: [],+ };+ return spec;+};++const articulationIssues = (mutate) => {+ const spec = articulatedSpec();+ 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());+ expect(parsed.articulation.joints[0].parentJointId).toBeNull();+ expect(parsed.articulation.joints[1].pivotSocket).toBe('trimPivot');+ expect(parsed.articulation.attachmentPartIds).toEqual([]);+ });++ // The whole point of the field being optional: a record written before it+ // existed has no key at all, and must not acquire one on read.+ it('leaves a spec that declares no articulation without the key', () => {+ const parsed = threejsSculptSpecSchema.parse(validSpec());+ expect(parsed.articulation).toBeUndefined();+ expect(storedThreejsSculptSpecSchema.parse(validSpec()).articulation).toBeUndefined();+ });++ it('rejects duplicate joint ids', () => {+ expect(articulationIssues((spec) => {+ spec.articulation.joints[1].id = 'rootJoint';+ })).toEqual(expect.arrayContaining(['duplicate joint id: rootJoint']));+ });++ it('rejects two roots and a graph with no root at all', () => {+ expect(articulationIssues((spec) => {+ spec.articulation.joints[1].parentJointId = null;+ })).toEqual(expect.arrayContaining([expect.stringContaining('exactly one root joint')]));+ expect(articulationIssues((spec) => {+ spec.articulation.joints[0].parentJointId = 'trimJoint';+ })).toEqual(expect.arrayContaining([expect.stringContaining('exactly one root joint')]));+ });++ it('rejects a dangling parent and a forward reference, which is what makes a cycle unrepresentable', () => {+ expect(articulationIssues((spec) => {+ spec.articulation.joints[1].parentJointId = 'noSuchJoint';+ })).toEqual(expect.arrayContaining([+ 'joint trimJoint names parent noSuchJoint, which is not a joint declared before it',+ ]));+ // A two-joint cycle can only be written as a forward reference, so the+ // earlier-only rule rejects it without walking the graph.+ expect(articulationIssues((spec) => {+ spec.articulation.joints[0].parentJointId = 'trimJoint';+ spec.articulation.joints[1].parentJointId = 'rootJoint';+ })).toEqual(expect.arrayContaining([+ 'joint rootJoint names parent trimJoint, which is not a joint declared before it',+ ]));+ });++ it('rejects joints pointed at parts and sockets that do not exist', () => {+ expect(articulationIssues((spec) => {+ spec.articulation.joints[1].partId = 'notARealPart';+ spec.articulation.joints[1].pivotSocket = 'notARealSocket';+ })).toEqual(expect.arrayContaining([+ 'unknown joint part: notARealPart',+ 'unknown pivot socket: notARealSocket',+ ]));+ });++ it('rejects one part driven by two joints', () => {+ expect(articulationIssues((spec) => {+ spec.articulation.joints[1].partId = 'crateBody';+ })).toEqual(expect.arrayContaining(['part crateBody is already driven by another joint']));+ });++ it('rejects an attachment that is unknown or also articulated', () => {+ expect(articulationIssues((spec) => {+ spec.articulation.attachmentPartIds = ['notARealPart'];+ })).toEqual(expect.arrayContaining(['unknown attachment part: notARealPart']));+ expect(articulationIssues((spec) => {+ spec.articulation.attachmentPartIds = ['frontTrim'];+ })).toEqual(expect.arrayContaining([+ 'part frontTrim is declared as an attachment and also driven by a joint',+ ]));+ });+});++describe('buildThreejsFactorySource articulation', () => {+ it('carries a validated graph into the exported runtime metadata', () => {+ const source = buildThreejsFactorySource(articulatedSpec());+ expect(source).toContain('articulation: spec.articulation || null,');+ expect(source.replace(/\s+/g, '')).toContain('"pivotSocket":"trimPivot"');+ });++ it('exports null articulation for a spec that declares none, and never invents one', () => {+ const source = buildThreejsFactorySource(validSpec());+ expect(source).toContain('articulation: spec.articulation || null,');+ expect(source).not.toContain('"joints"');+ });++ // Only VALIDATED metadata reaches the factory: an impossible graph fails the+ // export the same way a bad material reference does, rather than being+ // serialized into a file a downstream tool would trust.+ it('refuses to export an impossible graph', () => {+ const broken = articulatedSpec();+ broken.articulation.joints[1].parentJointId = 'noSuchJoint';+ let thrown = null;+ try {+ buildThreejsFactorySource(broken);+ } catch (error) {+ thrown = error;+ }+ expect(thrown?.status).toBe(400);+ expect(thrown?.message).toMatch(/not a joint declared before it/);+ });+});diff --git a/server/lib/threejsModelRig.js b/server/lib/threejsModelRig.jsnew file mode 100644index 0000000000..89d32f6654--- /dev/null+++ b/server/lib/threejsModelRig.js@@ -0,0 +1,70 @@+/**+ * Rig-readiness report for an already-validated Three.js scene spec.+ *+ * PortOS generates static assemblies. It does not skin a mesh, bind a bind pose,+ * or export a skeleton, and the honest thing to publish is therefore not "this+ * model is animation-ready" but "this model declares an articulation graph a+ * later rig/export path could attach to — or it does not, and here is why".+ *+ * `threejsSculptSpecSchema` already proves the graph is well FORMED: one root,+ * no cycles or forward references, joints pointed at real parts, pivots pointed+ * at real sockets. What it cannot say is whether the graph is USEFUL — a single+ * root joint, or child joints with no pivot axis, validate cleanly and rig into+ * nothing. That judgement lives here, and it reports rather than rejects: a spec+ * that falls short is still a good model, it is just a static one.+ */++import { listSpecNames } 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.+const MIN_USEFUL_JOINTS = 2;++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,+ * 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;+ 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+ // against.+ const socketCount = new Set(joints.map((joint) => joint.pivotSocket).filter(Boolean)).size;+ const reasons = [];++ if (!articulation) {+ reasons.push(subjectType === 'character' || subjectType === 'hybrid'+ ? 'The spec declares no articulation graph, so this character is a static assembly — its parts have a hierarchy but no joints, pivots, or bind pose.'+ : 'This subject was generated as a static assembly and declares no articulation graph.');+ } else {+ if (joints.length < MIN_USEFUL_JOINTS) {+ reasons.push(`Only ${joints.length} joint is declared, which is a root and nothing to move against it.`);+ }+ // A root's pivot is the model origin; a child joint without one has no axis+ // to rotate about, so the graph names moving parts it cannot actually move.+ const unpivoted = joints.filter((joint) => joint.parentJointId && !joint.pivotSocket);+ 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))}).`);+ }+ }++ return {+ articulationReady: reasons.length === 0,+ reasons,+ jointCount: joints.length,+ socketCount,+ attachmentCount,+ rootJointId: rootJoint?.id || null,+ subjectType,+ };+}diff --git a/server/lib/threejsModelRig.test.js b/server/lib/threejsModelRig.test.jsnew file mode 100644index 0000000000..5decc3c7e7--- /dev/null+++ b/server/lib/threejsModelRig.test.js@@ -0,0 +1,80 @@+import { describe, expect, it } from 'vitest';+import { evaluateThreejsRigReadiness } from './threejsModelRig.js';++const spec = (overrides = {}) => ({+ subjectType: 'character',+ articulation: {+ joints: [+ { id: 'rootJoint', partId: 'torso', parentJointId: null, pivotSocket: null },+ { id: 'armJoint', partId: 'arm', parentJointId: 'rootJoint', pivotSocket: 'shoulder' },+ ],+ attachmentPartIds: ['pack'],+ },+ ...overrides,+});++describe('evaluateThreejsRigReadiness', () => {+ it('reports a usable graph as ready with its joint, pivot, and attachment counts', () => {+ expect(evaluateThreejsRigReadiness(spec())).toEqual({+ articulationReady: true,+ reasons: [],+ jointCount: 2,+ socketCount: 1,+ attachmentCount: 1,+ rootJointId: 'rootJoint',+ subjectType: 'character',+ });+ });++ // The honest half of the contract: silence is not a pass. A character with no+ // graph is static and says so, with the reason attached.+ it('reports a character with no articulation as not ready and names why', () => {+ const report = evaluateThreejsRigReadiness(spec({ articulation: undefined }));+ expect(report.articulationReady).toBe(false);+ expect(report.jointCount).toBe(0);+ expect(report.socketCount).toBe(0);+ expect(report.rootJointId).toBeNull();+ expect(report.reasons[0]).toContain('static assembly');+ });++ it('describes an object subject as a static assembly rather than a failed character', () => {+ const report = evaluateThreejsRigReadiness({ subjectType: 'object' });+ expect(report.articulationReady).toBe(false);+ expect(report.reasons).toEqual(['This subject was generated as a static assembly and declares no articulation graph.']);+ });++ it('rejects a lone root as an articulation graph', () => {+ const lonely = spec();+ lonely.articulation.joints = [lonely.articulation.joints[0]];+ const report = evaluateThreejsRigReadiness(lonely);+ expect(report.articulationReady).toBe(false);+ expect(report.reasons[0]).toContain('root and nothing to move against it');+ });++ // A child joint with no socket has no axis, so the graph names moving parts it+ // cannot move — schema-valid, and not rig-ready.+ it('reports child joints with no pivot socket, naming them', () => {+ const unpivoted = spec();+ unpivoted.articulation.joints[1].pivotSocket = null;+ const report = evaluateThreejsRigReadiness(unpivoted);+ expect(report.articulationReady).toBe(false);+ expect(report.socketCount).toBe(0);+ expect(report.reasons[0]).toContain('1 of 2 joints name no pivot socket');+ expect(report.reasons[0]).toContain('armJoint');+ });++ it('counts distinct pivot sockets rather than joints, so a shared axis is not double-counted', () => {+ const shared = spec();+ shared.articulation.joints.push({ id: 'armJoint2', partId: 'arm2', parentJointId: 'rootJoint', pivotSocket: 'shoulder' });+ const report = evaluateThreejsRigReadiness(shared);+ expect(report.jointCount).toBe(3);+ expect(report.socketCount).toBe(1);+ });++ it('degrades to a not-ready static report for a missing spec instead of throwing', () => {+ const report = evaluateThreejsRigReadiness(null);+ expect(report.articulationReady).toBe(false);+ expect(report.subjectType).toBeNull();+ expect(report.jointCount).toBe(0);+ });+});diff --git a/server/services/threejsModels/db.js b/server/services/threejsModels/db.jsindex c77d83dbfe..89648a0583 100644--- a/server/services/threejsModels/db.js+++ b/server/services/threejsModels/db.js@@ -84,6 +84,12 @@ export async function createModel(input) {// an older record reads back undefined, which every consumer treats as// "not evaluated" rather than "passed".flatness: null,+ // Rig-readiness report for `spec`, written alongside it by+ // `evaluateThreejsRigReadiness`. Same additive-field contract as `coverage`+ // and `flatness`: a record written before this shipped reads back undefined,+ // which every consumer renders as an unevaluated STATIC assembly — never as+ // "articulation-ready".+ rig: null,error: null,generationOperationId: null,runs: [],diff --git a/server/services/threejsModels/index.js b/server/services/threejsModels/index.jsindex e9d182303f..a1f7880789 100644--- a/server/services/threejsModels/index.js+++ b/server/services/threejsModels/index.js@@ -15,6 +15,7 @@ import {threejsSculptSpecSchema,} from '../../lib/threejsModel.js';import { buildThreejsCoverageFeedback, evaluateThreejsPartCoverage } from '../../lib/threejsModelCoverage.js';+import { evaluateThreejsRigReadiness } from '../../lib/threejsModelRig.js';import { GENERAL_FAMILY_ID } from '../../lib/threejsModelFamilies.js';import { resolveCliEffort } from '../../lib/providerModels.js';import { getProviderById } from '../providers.js';@@ -108,6 +109,11 @@ async function executeGeneration({// renders correctly from the generated camera, so it is recorded rather than// rejected — the user sees it and an unsteered refinement asks for depth.const flatness = evaluateThreejsFlatness(spec);+ // Nothing PortOS generates is skinned, so what gets recorded is whether the+ // spec declared an articulation graph a later rig path could attach to — and+ // when it did not, the reason. A model with no graph reports not-ready with+ // reasons rather than passing silently.+ const rig = evaluateThreejsRigReadiness(spec);const completedAt = new Date().toISOString();const effectiveProvider = result.provider?.id || result.fallbackProvider?.id || provider.id;const effectiveModel = result.model || requestedModel || provider.defaultModel || null;@@ -122,6 +128,7 @@ async function executeGeneration({spec,coverage,flatness,+ rig,error: null,generationOperationId: null,generatedAt: completedAt,@@ -141,6 +148,9 @@ async function executeGeneration({if (flatness.warningCount > 0) {console.warn(`⚠️ Three.js model ${id} cross-section: ${flatness.flatIdentityDetailCount}/${flatness.identityDetailCount} identity feature(s) built only from flat parts`);}+ if (rig.articulationReady) {+ console.log(`🦴 Three.js model ${id} declares an articulation graph: ${rig.jointCount} joint(s), ${rig.socketCount} pivot socket(s)`);+ }} catch (error) {console.error(`❌ Three.js model generation failed for ${id}: ${cleanError(error)}`);await failGeneration(id, operationId, error);diff --git a/server/services/threejsModels/index.test.js b/server/services/threejsModels/index.test.jsindex 7071e7139e..0ef2ee0fe7 100644--- a/server/services/threejsModels/index.test.js+++ b/server/services/threejsModels/index.test.js@@ -141,6 +141,10 @@ describe('Three.js model generation orchestration', () => {// it alongside the spec instead of failing an otherwise usable generation.expect(current.coverage).toMatchObject({ errorCount: 0, warningCount: 1 });expect(current.coverage.findings[0]).toMatchObject({ code: 'orphan-geometry', partIds: ['body'] });+ // Nothing is skinned, so a spec that declared no articulation is recorded as+ // not-ready WITH a reason rather than passing silently.+ expect(current.rig).toMatchObject({ articulationReady: false, jointCount: 0, socketCount: 0 });+ expect(current.rig.reasons).toHaveLength(1);expect(current.runs.at(-1)).toMatchObject({status: 'completed',runId: 'run-example',@@ -149,6 +153,59 @@ describe('Three.js model generation orchestration', () => {});});+ it('persists an articulation-ready report when the character declares a usable graph', async () => {+ const characterSpec = {+ ...spec,+ subjectType: 'character',+ sockets: [{ name: 'lensPivot', parentPartId: 'body' }],+ articulation: {+ joints: [+ { id: 'rootJoint', partId: 'body', parentJointId: null },+ { id: 'lensJoint', partId: 'lens', parentJointId: 'rootJoint', pivotSocket: 'lensPivot' },+ ],+ attachmentPartIds: [],+ },+ };+ let current = {+ id: 'threejs-rigged',+ name: 'Example Beacon',+ sourceImage: { filename: 'example.png' },+ providerId: 'vision-api',+ model: null,+ prompt: '',+ status: 'draft',+ spec: null,+ runs: [],+ };+ store.getModel.mockResolvedValue(current);+ store.mutateModel.mockImplementation(async (_id, mutate) => {+ const next = mutate(current);+ if (next) current = next;+ return current;+ });+ runPromptThroughProvider.mockResolvedValue({+ text: JSON.stringify(characterSpec),+ runId: 'run-rigged',+ provider: { id: 'vision-api' },+ model: null,+ });++ await startGeneration(current.id, { providerId: 'vision-api' });+ await vi.waitFor(() => expect(current.status).toBe('ready'));++ expect(current.rig).toMatchObject({+ articulationReady: true,+ reasons: [],+ jointCount: 2,+ socketCount: 1,+ rootJointId: 'rootJoint',+ subjectType: 'character',+ });+ // The graph survives the parse onto the record, so the export and the+ // preview read the same joints the report counted.+ expect(current.spec.articulation.joints).toHaveLength(2);+ });+it('aims an unsteered refinement at the previous pass coverage errors', async () => {const fusedSpec = {...spec,diff --git a/server/services/threejsModels/prompt.js b/server/services/threejsModels/prompt.jsindex 3dcb57df61..5e2ef78fbf 100644--- a/server/services/threejsModels/prompt.js+++ b/server/services/threejsModels/prompt.js@@ -5,7 +5,11 @@* approach, while targeting PortOS's bounded JSON scene schema.*/-import { buildThreejsFamilyChecklist } from '../../lib/threejsModelFamilies.js';+import {+ buildThreejsFamilyChecklist,+ GENERAL_FAMILY_ID,+ THREEJS_MODEL_FAMILY_IDS,+} from '../../lib/threejsModelFamilies.js';const geometryContract = `Allowed geometry definitions:@@ -87,6 +91,50 @@ a mirrored counterpart as its own part with its own position and rotationDegreessimply omit a part you do not want rendered.`;+const CHARACTER_FAMILY_ID = 'character';++// Requested ONLY when the subject could be a character. A chosen vehicle,+// weapon, architecture, or device family is positive evidence that it is not,+// and a refinement pass over a spec the model already classified as an `object`+// is the same evidence — those prompts stay exactly as they were. An unknown+// family id resolves to `general` the way the checklist builder resolves it, so+// a stale stored family cannot silently change which contract is requested.+const wantsArticulation = (family, currentSpec) => {+ if (currentSpec?.subjectType) return currentSpec.subjectType !== 'object';+ const resolved = THREEJS_MODEL_FAMILY_IDS.includes(family) ? family : GENERAL_FAMILY_ID;+ return resolved === CHARACTER_FAMILY_ID || resolved === GENERAL_FAMILY_ID;+};++// PortOS does not skin, bind, or deform anything — this asks for a DECLARATION+// of what is meant to move, so a later rig/export path has stable ids to attach+// to and the workspace can report rig readiness truthfully instead of calling+// every parts hierarchy animation-ready.+const articulationContract = `+ARTICULATION (character and hybrid subjects only):+If — and only if — you classify the subject as "character" or "hybrid", also return an+"articulation" object alongside "sockets". Omit the key entirely for an "object" subject,+and omit it for a character whose reference does not support a defensible joint layout.++"articulation": {+ "joints": [{"id":"stableJointId","partId":"partId","parentJointId":null,"pivotSocket":"socketName"}],+ "attachmentPartIds": ["partId"]+}++Rules, all enforced — a spec that breaks one is rejected outright:+- Exactly ONE joint has "parentJointId": null. That is the root.+- Every other joint's "parentJointId" names a joint declared EARLIER in the array, so the+ graph reads root-first and cannot contain a cycle or a forward reference.+- 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 that+ socket. 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.++This is an intent declaration, not a skeleton: do not invent skinning weights, a bind pose, or+bones for parts the reference does not clearly show. A short, defensible graph beats a long+speculative one, and omitting the key is better than guessing.+`;+export function buildThreejsGenerationPrompt({sourcePath,name,@@ -109,7 +157,13 @@ ${feedback || 'Improve likeness, proportions, construction, and visible detail.'`: '';- return `You are a senior procedural 3D artist reconstructing one reference image as an animation-ready Three.js model.+ // PortOS ships no skinning or skeletal-export path, so the brief no longer+ // calls the result "animation-ready" — what it asks for is a model that comes+ // apart cleanly, plus (for characters) an explicit declaration of what is+ // meant to move.+ const articulation = wantsArticulation(family, currentSpec) ? articulationContract : '';++ return `You are a senior procedural 3D artist reconstructing one reference image as a cleanly decomposed Three.js model.REFERENCE IMAGE:- A multimodal API provider receives the image as an attached image.@@ -143,5 +197,5 @@ QUALITY GATE:under-observed the reference.` : ''}${geometryContract}-${outputContract}`;+${outputContract}${articulation}`;}diff --git a/server/services/threejsModels/prompt.test.js b/server/services/threejsModels/prompt.test.jsindex 9c08c352cd..3645bbb09e 100644--- a/server/services/threejsModels/prompt.test.js+++ b/server/services/threejsModels/prompt.test.js@@ -80,3 +80,40 @@ describe('buildThreejsGenerationPrompt', () => {});});});++describe('buildThreejsGenerationPrompt articulation', () => {+ it('never calls the result animation-ready, because nothing PortOS generates is skinned', () => {+ const prompt = build();+ expect(prompt).not.toContain('animation-ready');+ expect(prompt).toContain('cleanly decomposed Three.js model');+ });++ it('requests the articulation contract when the subject could be a character', () => {+ for (const family of [undefined, null, 'general', 'character', 'not-a-family']) {+ const prompt = build({ family });+ expect(prompt).toContain('ARTICULATION (character and hybrid subjects only)');+ expect(prompt).toContain('"parentJointId":null');+ expect(prompt).toContain('"attachmentPartIds"');+ // The contract has to say what it is NOT, or the model invents weights.+ expect(prompt).toContain('not a skeleton');+ }+ });++ it('leaves a prop, vehicle, or structure prompt without an articulation section', () => {+ for (const family of ['vehicle', 'weapon', 'architecture', 'device']) {+ expect(build({ family })).not.toContain('ARTICULATION');+ }+ });++ it('drops the section on a refinement of a spec already classified as an object', () => {+ const object = build({ currentSpec: { schemaVersion: 1, name: 'Example Model', subjectType: 'object' } });+ expect(object).not.toContain('ARTICULATION');+ // …and keeps it for a character refinement even under a non-character family,+ // because the spec's own classification is the stronger signal.+ const character = build({+ family: 'vehicle',+ currentSpec: { schemaVersion: 1, name: 'Example Model', subjectType: 'hybrid' },+ });+ expect(character).toContain('ARTICULATION (character and hybrid subjects only)');+ });+});