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: flag cross-part penetration in generated Three.js specs (#3803)
[._.]/ Adam Eivy5ab7c12fcbdb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 1436aa4821..4bab99dc08 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -93,3 +93,4 @@- **A local video render now tells you how long it has left, once your machine has rendered something comparable.** Local renders run 15–40+ minutes and the only progress the UI could show was a step counter — "20%" on a job that might finish in four minutes or forty, with no way to tell which. Each completed render now records its wall-clock time alongside the shape it rendered (model, resolution, frames, steps), and a new job estimates itself from that history: a run of the same shape uses the median of your own measured runs outright, a different shape is placed on a least-squares fit of cost against pixels × frames × steps, and the fit's intercept — the fixed per-render cost of loading weights and decoding — is what lets a chained multi-chunk render be estimated as N renders rather than one long one. The estimate rides the render's started/progress events through to the client, where the progress bar reads "20% · ~18m 30s left". An install that has never measured a comparable render reports no estimate at all rather than a fabricated one, and the progress bar simply shows the percentage as before.- **A video LoRA in the wrong key layout is now refused with the reason instead of quietly rendering an un-LoRA'd clip.** Downloaded LoRAs ship in several incompatible safetensors key conventions, and the LTX-2 loader fuses exactly one of them: `lora_A`/`lora_B` rank pairs, optionally under a `diffusion_model.` prefix. A kohya/LyCORIS file (`lora_down`/`lora_up` + `alpha`) or a diffusers/PEFT-prefixed file matches nothing in the transformer — so the render burned its full GPU time and came back looking like the LoRA had never been selected, with no error anywhere to explain it. Confusingly, kohya files are commonly published *with* the ComfyUI `diffusion_model.` prefix, so the prefix alone was never a reliable signal. PortOS now classifies the layout from the safetensors header (`bare` / `comfyui` / `diffusers` / `kohya` / `not_a_lora`) at install time, records it in the LoRA's sidecar, and backfills it on the next listing for LoRAs installed earlier. A render that selects an un-fusable one fails up front with a 400 naming the layout and what to use instead. A file whose header can't be read stays "undetermined" and is still allowed through — unreadable is not the same as unusable.- **A resumed arc verification no longer forgets why its last rewrite was rejected.** When Series Autopilot restored a safe checkpoint after a regressive rewrite, it persisted both the standing blockers and the rejected candidate's new blockers — but a fresh Resume discarded the latter before calling the resolver. That made the new run liable to repeat the same bad trade from the same checkpoint. A resumed arc gate now carries the bounded discarded set into every normal, corrective, and isolated resolve attempt as explicit avoid evidence, while non-arc and non-regression pauses start clean as before.+- **A generated Three.js model is now checked for parts modelled inside each other.** Every existing gate reads one part at a time — the schema proves each geometry is well formed, the coverage gate proves the assembly backs the inventory, and the cross-section gate proves the identity parts have real depth — so nothing ever compared two parts to each other, and the whole class of defect where sibling parts occupy the *same* space was invisible: a greeble modelled at the wrong scale and swallowed whole by the hull it was meant to sit on, a limb rooted a full radius inside a torso, an eye socket punched clean through the back of a skull. All of those render perfectly from the hero camera the model generated for itself and only read as broken once you orbit or explode the assembly. A new cross-part penetration gate reconstructs each part's world placement (the same rotation/scale composition the preview applies), derives an analytic solid per geometry type — a torus is measured as a ring rather than a filled disc, a hollow lathe as hollow, an extrude's hole as empty space — and samples one part's interior against another's, flagging a part that is entirely inside an unrelated one as an error and a pair that shares most of the smaller part's volume as a warning. It reports rather than rejects, and it is deliberately quiet where it cannot be sure: parts parented together or declared as attachments are exempt (embedding is what those relationships are *for*), and a shallow seated joint or anything inside a transparent part comes back as an undecided note that a refinement pass is never told to "fix". Findings land on the record, show up in a new panel on the model detail page, and an unsteered refinement now asks for each part to get its own volume alongside the existing coverage and depth feedback.diff --git a/client/src/pages/ThreejsModelDetail.jsx b/client/src/pages/ThreejsModelDetail.jsxindex 466425a1a4..e1a114b4a8 100644--- a/client/src/pages/ThreejsModelDetail.jsx+++ b/client/src/pages/ThreejsModelDetail.jsx@@ -352,6 +352,11 @@ export default function ThreejsModelDetail() {// the same as passing it — the panel is omitted rather than shown clean.const coverageFindings = Array.isArray(record.coverage?.findings) ? record.coverage.findings : null;const flatnessFindings = Array.isArray(record.flatness?.findings) ? record.flatness.findings : null;+ const penetrationFindings = Array.isArray(record.penetration?.findings) ? record.penetration.findings : null;+ // Undecided contact is a note the reader is meant to judge, never something a+ // refinement is told to fix — so the footer only promises a refinement when+ // there is an actual defect above it.+ const penetrationDefects = countSeverities(penetrationFindings || []);const coverageErrors = countSeverities(coverageFindings || []).error;// Only present when the generation ran with a family — a record generated// under `general` (or before families shipped) has no checklist to render.@@ -545,6 +550,19 @@ export default function ThreejsModelDetail() {/>)}+ {penetrationFindings && (+ <GatePanel+ title="Cross-part penetration"+ findings={penetrationFindings}+ cleanLabel="No unrelated parts share the same space"+ footer={`Parts modelled inside each other look correct from the hero angle and fall apart the moment the model is orbited, so this check compares every unrelated pair by volume. Parts parented together or declared as attachments are exempt — embedding is what those relationships are for.${+ penetrationDefects.error + penetrationDefects.warning > 0+ ? ' Refining without your own feedback will also ask for each part to get its own volume.'+ : ''+ }`}+ />+ )}+{record.spec && (<RigReadinessPanelrig={record.rig && typeof record.rig === 'object' ? record.rig : null}diff --git a/client/src/pages/ThreejsModelDetail.test.jsx b/client/src/pages/ThreejsModelDetail.test.jsxindex 2a3f078add..19b4ac4090 100644--- a/client/src/pages/ThreejsModelDetail.test.jsx+++ b/client/src/pages/ThreejsModelDetail.test.jsx@@ -176,6 +176,65 @@ describe('ThreejsModelDetail cross-section gate', () => {});});+describe('ThreejsModelDetail cross-part penetration gate', () => {+ beforeEach(resetMocks);++ it('lists the buried-part finding and says an unsteered refinement will target it', async () => {+ getThreejsModel.mockResolvedValue({+ ...baseRecord,+ penetration: {+ errorCount: 1,+ warningCount: 0,+ noteCount: 0,+ evaluatedPartCount: 4,+ comparedPairCount: 3,+ undecidedPairCount: 0,+ findings: [{+ code: 'buried-part',+ severity: 'error',+ partIds: ['lens', 'body'],+ message: '1 part(s) are entirely inside another part they are not attached to or parented under ("Lens" inside "Body").',+ }],+ },+ });+ renderDetail();++ await waitFor(() => expect(screen.getByText('Cross-part penetration')).toBeInTheDocument());+ expect(screen.getByText('1 part(s) are entirely inside another part they are not attached to or parented under ("Lens" inside "Body").')).toBeInTheDocument();+ expect(screen.getByText('1 error · 0 warning · 0 note')).toBeInTheDocument();+ expect(screen.getByText(/each part to get its own volume/)).toBeInTheDocument();+ });++ it('does not promise a refinement for an undecided note alone', async () => {+ getThreejsModel.mockResolvedValue({+ ...baseRecord,+ penetration: {+ errorCount: 0,+ warningCount: 0,+ noteCount: 1,+ findings: [{+ code: 'undecided-contact',+ severity: 'note',+ partIds: ['peg', 'body'],+ message: '1 unrelated part pair(s) overlap partially ("Peg" and "Body" (22%)).',+ }],+ },+ });+ renderDetail();++ await waitFor(() => expect(screen.getByText('Cross-part penetration')).toBeInTheDocument());+ expect(screen.queryByText(/each part to get its own volume/)).not.toBeInTheDocument();+ });++ it('hides the section for a record generated before the gate existed', async () => {+ getThreejsModel.mockResolvedValue({ ...baseRecord, penetration: null });+ renderDetail();++ await waitFor(() => expect(screen.getByText('Example Beacon')).toBeInTheDocument());+ expect(screen.queryByText('Cross-part penetration')).not.toBeInTheDocument();+ });+});+describe('ThreejsModelDetail subject family', () => {beforeEach(resetMocks);diff --git a/server/lib/README.md b/server/lib/README.mdindex d38c391a07..987da170f5 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -161,6 +161,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. |+| `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. || `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. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 250e9f757b..edb219afb5 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 './threejsModelPenetration.js';export * from './threejsModelRig.js';// === Story & narrative ===diff --git a/server/lib/threejsModelPenetration.js b/server/lib/threejsModelPenetration.jsnew file mode 100644index 0000000000..52373f953d--- /dev/null+++ b/server/lib/threejsModelPenetration.js@@ -0,0 +1,606 @@+/**+ * Cross-part penetration gate for an already-validated Three.js scene spec.+ *+ * Every other gate reads one part at a time. `threejsSculptSpecSchema` proves+ * each geometry is well formed (a hole inside its outline, a tube that does not+ * retrace itself), the coverage gate proves the assembly backs the inventory,+ * and the flatness gate proves the identity parts have a cross-section. None of+ * them ever compares two parts to each other, so the whole class of defect where+ * sibling parts occupy the SAME space is invisible: an eye socket punched+ * through the back of a skull, a limb rooted a whole radius inside a torso, a+ * greeble modelled at the wrong scale and swallowed entirely by the hull it was+ * meant to sit on. Each of those renders perfectly from the generated hero+ * camera and only reads as broken once the model is orbited or taken apart.+ *+ * This module reconstructs each part's world placement (the same+ * position/rotation/scale composition the preview and the exported factory+ * apply), derives an analytic solid for its geometry, and samples one part's+ * interior against another's to estimate how much of it is swallowed.+ *+ * Its honest limits, all of which push toward reporting LESS:+ * - The solids are analytic approximations. A bevel is ignored, a tube is+ * measured against its control polyline rather than the interpolated curve,+ * and a `custom` triangle soup has no interior test at all — it contributes+ * its own vertices as occupancy samples and can only ever be found buried IN+ * something, never found to have buried something.+ * - Parts in the same subtree are never compared. Relief riding its parent, a+ * pupil inside an eyeball, a bolt sunk into the plate it fastens — those are+ * modelled as parent/child precisely because they are meant to interpenetrate.+ * Declared `attachmentPartIds` are exempt for the same reason.+ * - A merely-joined pair (a peg in its socket, a limb seated in a shoulder)+ * overlaps by construction, so a small overlap fraction is reported as+ * UNDECIDED contact rather than as a defect, and a transparent container can+ * only ever produce an undecided note — a part inside a glass dome is the+ * reference being followed, not a mistake.+ */++import { listSpecNames } 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+// thresholds below need; a shape too thin to catch any cell centre gets ONE+// retry at double the resolution before it is written off as unmeasurable.+const SAMPLE_GRID = 8;+const RETRY_GRID = 16;++// Pairwise work is quadratic in part count (the schema caps a spec at 160+// parts), so the interior sample set each part carries into the pair loop is+// strided down to a bound that keeps the whole gate well under a second.+const MAX_PAIR_SAMPLES = 96;++// A part whose every interior sample lands inside another part is not partly+// sunk into it, it is GONE — nothing of it can ever be seen. The threshold is+// just short of 1 because the sample set is a grid, not the solid itself.+const CONTAINED_FRACTION = 0.98;++// Half of a part's volume inside an unrelated sibling is well past any joint,+// seam, or seat: at that point the two parts are modelling the same space.+const HEAVY_OVERLAP_FRACTION = 0.5;++// Below this, an overlap is ordinary assembly — a tenon in its mortise, a limb+// seated in its socket — and reporting it would drown the real findings.+const CONTACT_FRACTION = 0.15;++const EPSILON = 1e-9;++const degreesToRadians = (degrees) => (degrees * Math.PI) / 180;++/** Row-major 3×3 linear part plus a translation — an affine transform. */+const IDENTITY_TRANSFORM = { linear: [1, 0, 0, 0, 1, 0, 0, 0, 1], translation: [0, 0, 0] };++const multiplyLinear = (a, b) => {+ const out = new Array(9);+ for (let row = 0; row < 3; row += 1) {+ for (let column = 0; column < 3; column += 1) {+ out[(row * 3) + column] = (a[row * 3] * b[column])+ + (a[(row * 3) + 1] * b[3 + column])+ + (a[(row * 3) + 2] * b[6 + column]);+ }+ }+ return out;+};++const applyLinear = (linear, [x, y, z]) => [+ (linear[0] * x) + (linear[1] * y) + (linear[2] * z),+ (linear[3] * x) + (linear[4] * y) + (linear[5] * z),+ (linear[6] * x) + (linear[7] * y) + (linear[8] * z),+];++const applyTransform = (transform, point) => {+ const rotated = applyLinear(transform.linear, point);+ return [+ rotated[0] + transform.translation[0],+ rotated[1] + transform.translation[1],+ rotated[2] + transform.translation[2],+ ];+};++// Matches `THREE.Euler` order 'XYZ', which is what the preview and the exported+// factory both apply — a different composition here would measure a part that+// is not the one on screen.+const rotationMatrix = ([xDegrees, yDegrees, zDegrees]) => {+ const [c1, s1] = [Math.cos(degreesToRadians(xDegrees)), Math.sin(degreesToRadians(xDegrees))];+ const [c2, s2] = [Math.cos(degreesToRadians(yDegrees)), Math.sin(degreesToRadians(yDegrees))];+ const [c3, s3] = [Math.cos(degreesToRadians(zDegrees)), Math.sin(degreesToRadians(zDegrees))];+ return [+ c2 * c3, -c2 * s3, s2,+ (c1 * s3) + (s1 * c3 * s2), (c1 * c3) - (s1 * s3 * s2), -s1 * c2,+ (s1 * s3) - (c1 * c3 * s2), (s1 * c3) + (c1 * s3 * s2), c1 * c2,+ ];+};++const composeTransform = (parent, part) => {+ const rotation = rotationMatrix(part.rotationDegrees || [0, 0, 0]);+ const [sx, sy, sz] = part.scale || [1, 1, 1];+ // R · S with S diagonal — scaling columns is the whole multiplication.+ const local = [+ rotation[0] * sx, rotation[1] * sy, rotation[2] * sz,+ rotation[3] * sx, rotation[4] * sy, rotation[5] * sz,+ rotation[6] * sx, rotation[7] * sy, rotation[8] * sz,+ ];+ const position = part.position || [0, 0, 0];+ const offset = applyLinear(parent.linear, position);+ return {+ linear: multiplyLinear(parent.linear, local),+ translation: [+ offset[0] + parent.translation[0],+ offset[1] + parent.translation[1],+ offset[2] + parent.translation[2],+ ],+ };+};++/**+ * Affine inverse, or `null` when the linear part is singular. A stored spec+ * predates the positive-scale bound, so a zero or mirrored component is+ * reachable here — `null` makes it an unmeasurable part rather than a NaN that+ * would quietly read as "no overlap".+ */+const invertTransform = ({ linear, translation }) => {+ const [a, b, c, d, e, f, g, h, i] = linear;+ const determinant = (a * ((e * i) - (f * h))) - (b * ((d * i) - (f * g))) + (c * ((d * h) - (e * g)));+ if (!Number.isFinite(determinant) || Math.abs(determinant) < EPSILON) return null;+ const inverseLinear = [+ ((e * i) - (f * h)) / determinant, ((c * h) - (b * i)) / determinant, ((b * f) - (c * e)) / determinant,+ ((f * g) - (d * i)) / determinant, ((a * i) - (c * g)) / determinant, ((c * d) - (a * f)) / determinant,+ ((d * h) - (e * g)) / determinant, ((b * g) - (a * h)) / determinant, ((a * e) - (b * d)) / determinant,+ ];+ const shifted = applyLinear(inverseLinear, translation);+ return {+ linear: inverseLinear,+ translation: [-shifted[0], -shifted[1], -shifted[2]],+ };+};++const ringMinMax = (points, axis) => points.reduce(+ ([min, max], point) => [Math.min(min, point[axis]), Math.max(max, point[axis])],+ [Infinity, -Infinity],+);++// Even-odd ray cast in the profile plane. Shared shape with the extrude-hole+// check in `threejsModel.js`, but this one answers "is this sample inside the+// swept solid", so it is kept local rather than exported across modules.+const pointInPolygon = (ring, px, py) => {+ let inside = false;+ for (let index = 0, previous = ring.length - 1; index < ring.length; previous = index, index += 1) {+ const [xi, yi] = ring[index];+ const [xj, yj] = ring[previous];+ const straddles = (yi > py) !== (yj > py);+ if (straddles && px < (((xj - xi) * (py - yi)) / (yj - yi)) + xi) inside = !inside;+ }+ return inside;+};++/**+ * One tube segment with its direction and a bounding box already padded by the+ * tube radius. Both are precomputed per segment rather than per sample: a+ * 96-point path is tested against every interior sample of every part it might+ * touch, and the padded box rejects almost all of those segments on six+ * comparisons instead of a projection.+ */+const prepareSegment = ([ax, ay, az], [bx, by, bz], radius) => {+ const [dx, dy, dz] = [bx - ax, by - ay, bz - az];+ return {+ ax,+ ay,+ az,+ dx,+ dy,+ dz,+ lengthSquared: (dx * dx) + (dy * dy) + (dz * dz),+ min: [Math.min(ax, bx) - radius, Math.min(ay, by) - radius, Math.min(az, bz) - radius],+ max: [Math.max(ax, bx) + radius, Math.max(ay, by) + radius, Math.max(az, bz) + radius],+ };+};++const withinSegment = (segment, [px, py, pz], radiusSquared) => {+ if (px < segment.min[0] || px > segment.max[0]) return false;+ if (py < segment.min[1] || py > segment.max[1]) return false;+ if (pz < segment.min[2] || pz > segment.max[2]) return false;+ const t = segment.lengthSquared < EPSILON+ ? 0+ : Math.max(0, Math.min(1, (((px - segment.ax) * segment.dx)+ + ((py - segment.ay) * segment.dy)+ + ((pz - segment.az) * segment.dz)) / segment.lengthSquared));+ const qx = px - (segment.ax + (segment.dx * t));+ const qy = py - (segment.ay + (segment.dy * t));+ const qz = pz - (segment.az + (segment.dz * t));+ return (qx * qx) + (qy * qy) + (qz * qz) <= radiusSquared;+};++/**+ * The local-space solid for one geometry: an axis-aligned bounding box plus an+ * interior predicate. `contains: null` marks a geometry PortOS cannot test from+ * the inside (`custom` triangle soup), which the caller degrades rather than+ * guesses at.+ */+function describeSolid(geometry) {+ switch (geometry.type) {+ case 'box': {+ const [x, y, z] = [geometry.width / 2, geometry.height / 2, geometry.depth / 2];+ return {+ bounds: [[-x, -y, -z], [x, y, z]],+ contains: ([px, py, pz]) => Math.abs(px) <= x && Math.abs(py) <= y && Math.abs(pz) <= z,+ };+ }+ case 'sphere': {+ const r = geometry.radius;+ return {+ bounds: [[-r, -r, -r], [r, r, r]],+ contains: ([px, py, pz]) => (px * px) + (py * py) + (pz * pz) <= r * r,+ };+ }+ case 'cylinder':+ case 'cone': {+ const top = geometry.type === 'cone' ? 0 : geometry.radiusTop;+ const bottom = geometry.type === 'cone' ? geometry.radius : geometry.radiusBottom;+ const half = geometry.height / 2;+ const widest = Math.max(top, bottom);+ return {+ bounds: [[-widest, -half, -widest], [widest, half, widest]],+ contains: ([px, py, pz]) => {+ if (Math.abs(py) > half) return false;+ // Three.js interpolates the radius linearly from bottom to top.+ const radius = bottom + ((top - bottom) * ((py + half) / geometry.height));+ return (px * px) + (pz * pz) <= radius * radius;+ },+ };+ }+ case 'capsule': {+ const { radius } = geometry;+ const half = geometry.length / 2;+ return {+ bounds: [[-radius, -(half + radius), -radius], [radius, half + radius, radius]],+ contains: ([px, py, pz]) => {+ const radial = (px * px) + (pz * pz);+ if (Math.abs(py) <= half) return radial <= radius * radius;+ const capOffset = Math.abs(py) - half;+ return radial + (capOffset * capOffset) <= radius * radius;+ },+ };+ }+ case 'torus': {+ const { radius, tube } = geometry;+ const outer = radius + tube;+ // The arc is deliberately absent from the bounds: over-reporting the+ // extent of a partial ring only ever costs an extra pair comparison,+ // while under-reporting it would silently drop real overlaps.+ const arc = degreesToRadians(geometry.arcDegrees ?? 360);+ return {+ bounds: [[-outer, -outer, -tube], [outer, outer, tube]],+ contains: ([px, py, pz]) => {+ const planar = Math.hypot(px, py) - radius;+ if ((planar * planar) + (pz * pz) > tube * tube) return false;+ if (arc >= (2 * Math.PI) - EPSILON) return true;+ const angle = Math.atan2(py, px);+ return (angle < 0 ? angle + (2 * Math.PI) : angle) <= arc;+ },+ };+ }+ case 'lathe': {+ // The profile is revolved about Y, so a sample is inside when its+ // (radius, height) lands in the profile polygon. Three.js sweeps an open+ // polyline; closing it back to the first point is the only solid that+ // polyline can bound.+ const profile = geometry.points;+ const [minRadius, maxRadius] = ringMinMax(profile, 0);+ const [minHeight, maxHeight] = ringMinMax(profile, 1);+ const widest = Math.max(Math.abs(minRadius), Math.abs(maxRadius));+ return {+ bounds: [[-widest, minHeight, -widest], [widest, maxHeight, widest]],+ contains: ([px, py, pz]) => pointInPolygon(profile, Math.hypot(px, pz), py),+ };+ }+ case 'extrude': {+ // ExtrudeGeometry sweeps the shape from z=0 to z=depth. The bevel is+ // ignored, which only ever shrinks the real solid near its caps.+ const [minX, maxX] = ringMinMax(geometry.outline, 0);+ const [minY, maxY] = ringMinMax(geometry.outline, 1);+ const holes = geometry.holes || [];+ return {+ bounds: [[minX, minY, 0], [maxX, maxY, geometry.depth]],+ contains: ([px, py, pz]) => {+ if (pz < 0 || pz > geometry.depth) return false;+ if (!pointInPolygon(geometry.outline, px, py)) return false;+ return !holes.some((hole) => pointInPolygon(hole, px, py));+ },+ };+ }+ case 'tube': {+ // Measured against the control polyline rather than the interpolated+ // Catmull-Rom curve: the curve bulges outside the polyline between+ // control points, so this reads slightly thin, never fat.+ const { path, radius } = geometry;+ const axisBounds = [0, 1, 2].map((axis) => ringMinMax(path, axis));+ const segmentCount = geometry.closed ? path.length : path.length - 1;+ const segments = [];+ for (let index = 0; index < segmentCount; index += 1) {+ segments.push(prepareSegment(path[index], path[(index + 1) % path.length], radius));+ }+ const radiusSquared = radius * radius;+ return {+ bounds: [+ axisBounds.map(([min]) => min - radius),+ axisBounds.map(([, max]) => max + radius),+ ],+ contains: (point) => segments.some((segment) => withinSegment(segment, point, radiusSquared)),+ };+ }+ case 'custom': {+ const { vertices } = geometry;+ const bounds = [[Infinity, Infinity, Infinity], [-Infinity, -Infinity, -Infinity]];+ for (let index = 0; index < vertices.length; index += 1) {+ const axis = index % 3;+ bounds[0][axis] = Math.min(bounds[0][axis], vertices[index]);+ bounds[1][axis] = Math.max(bounds[1][axis], vertices[index]);+ }+ return { bounds, contains: null };+ }+ default:+ return null;+ }+}++/** Cell centres of a uniform grid over `bounds`, kept when `contains` accepts. */+function sampleSolid(bounds, contains, divisions) {+ const [min, max] = bounds;+ const step = [0, 1, 2].map((axis) => (max[axis] - min[axis]) / divisions);+ const kept = [];+ let total = 0;+ for (let i = 0; i < divisions; i += 1) {+ const x = min[0] + (step[0] * (i + 0.5));+ for (let j = 0; j < divisions; j += 1) {+ const y = min[1] + (step[1] * (j + 0.5));+ for (let k = 0; k < divisions; k += 1) {+ total += 1;+ const point = [x, y, min[2] + (step[2] * (k + 0.5))];+ if (contains(point)) kept.push(point);+ }+ }+ }+ return { kept, total };+}++/** Deterministic stride down to at most `limit` entries, endpoints included. */+const strideDown = (values, limit) => {+ if (values.length <= limit) return values;+ const step = values.length / limit;+ const out = [];+ for (let index = 0; index < limit; index += 1) out.push(values[Math.floor(index * step)]);+ return out;+};++const customVertexPoints = (geometry) => {+ const points = [];+ for (let index = 0; index + 2 < geometry.vertices.length; index += 3) {+ points.push([geometry.vertices[index], geometry.vertices[index + 1], geometry.vertices[index + 2]]);+ }+ return points;+};++/**+ * Flatten the part tree into world-placed volumes. Parts with no geometry are+ * groups: they carry their transform down to their children and are never+ * compared themselves.+ */+function collectVolumes(spec) {+ const volumes = [];+ const walk = (part, parentTransform, ancestorIds) => {+ const transform = composeTransform(parentTransform, part);+ if (part.geometry) {+ const solid = describeSolid(part.geometry);+ const inverse = solid ? invertTransform(transform) : null;+ if (solid && inverse) {+ const sampled = solid.contains+ ? sampleSolid(solid.bounds, solid.contains, SAMPLE_GRID)+ : { kept: customVertexPoints(part.geometry), total: 0 };+ // A shape too thin to catch a cell centre gets one finer pass before it+ // is written off — a narrow torus or a shallow extrude is a real solid,+ // not an unmeasurable one.+ const refined = solid.contains && sampled.kept.length === 0+ ? sampleSolid(solid.bounds, solid.contains, RETRY_GRID)+ : sampled;+ if (refined.kept.length > 0) {+ const worldSamples = strideDown(refined.kept, MAX_PAIR_SAMPLES)+ .map((point) => applyTransform(transform, point));+ const corners = [];+ for (const x of [solid.bounds[0][0], solid.bounds[1][0]]) {+ for (const y of [solid.bounds[0][1], solid.bounds[1][1]]) {+ for (const z of [solid.bounds[0][2], solid.bounds[1][2]]) {+ corners.push(applyTransform(transform, [x, y, z]));+ }+ }+ }+ volumes.push({+ id: part.id,+ name: part.name || part.id,+ ancestorIds,+ materialId: part.material || null,+ samples: worldSamples,+ // `null` for a `custom` mesh: it can be found buried inside another+ // part, but nothing can be tested against ITS interior.+ contains: solid.contains+ ? (worldPoint) => solid.contains(applyTransform(inverse, worldPoint))+ : null,+ worldBounds: [0, 1, 2].map((axis) => [+ Math.min(...corners.map((corner) => corner[axis])),+ Math.max(...corners.map((corner) => corner[axis])),+ ]),+ });+ }+ }+ }+ for (const child of part.children || []) walk(child, transform, [...ancestorIds, part.id]);+ };+ for (const part of spec?.parts || []) walk(part, IDENTITY_TRANSFORM, []);+ return volumes;+}++const boundsDisjoint = (a, b) => [0, 1, 2].some((axis) => (+ a.worldBounds[axis][0] > b.worldBounds[axis][1] || b.worldBounds[axis][0] > a.worldBounds[axis][1]+));++/**+ * The share of `subject`'s interior samples that land inside `container`, or+ * `null` when the container has no interior test.+ *+ * Bails as soon as every remaining sample landing inside could no longer reach+ * `CONTACT_FRACTION` — the caller drops anything under that floor, and the+ * abandoned tally is by construction below it too, so the early exit cannot+ * change a verdict. It is what keeps the common case (parts that merely brush+ * each other's bounding boxes) from paying for a full sample sweep.+ */+const containedFraction = (subject, container) => {+ if (!container.contains) return null;+ const total = subject.samples.length;+ let inside = 0;+ for (let index = 0; index < total; index += 1) {+ if (container.contains(subject.samples[index])) inside += 1;+ else if ((inside + (total - index - 1)) / total < CONTACT_FRACTION) return inside / total;+ }+ return inside / total;+};++const isTransparent = (material) => Boolean(material)+ && ((material.transparent === true && (material.opacity ?? 1) < 1) || (material.transmission ?? 0) > 0);++const describePair = (a, b) => `"${a.name}" and "${b.name}"`;++/**+ * @param {object|null} spec a spec that has already passed a sculpt-spec schema+ * @returns {{findings: Array, errorCount: number, warningCount: number, noteCount: number,+ * evaluatedPartCount: number, comparedPairCount: number, undecidedPairCount: number}}+ */+export function evaluateThreejsPenetration(spec) {+ const volumes = collectVolumes(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 buried = [];+ const overlapping = [];+ const undecided = [];+ let comparedPairCount = 0;++ for (let i = 0; i < volumes.length; i += 1) {+ for (let j = i + 1; j < volumes.length; j += 1) {+ const [a, b] = [volumes[i], volumes[j]];+ // Same subtree: interpenetration is what a parent/child relationship is+ // FOR, so the pair carries no information.+ if (a.ancestorIds.includes(b.id) || b.ancestorIds.includes(a.id)) continue;+ if (attachments.has(a.id) || attachments.has(b.id)) continue;+ if (boundsDisjoint(a, b)) continue;+ comparedPairCount += 1;++ const aInB = containedFraction(a, b);+ const bInA = containedFraction(b, a);+ if (aInB === null && bInA === null) continue;+ // Whichever direction is measurable and deeper: a small part swallowed by+ // a large one reports ~1 in its own direction and a sliver in the other.+ const [subject, container, fraction] = (aInB ?? -1) >= (bInA ?? -1)+ ? [a, b, aInB]+ : [b, a, bInA];+ if (fraction < CONTACT_FRACTION) continue;++ // A part inside glass is the reference being followed, not a mistake, so+ // a transparent container can only ever raise an undecided note.+ const seeThrough = isTransparent(materials[container.materialId]);+ const entry = { subject, container, fraction };+ if (fraction >= CONTAINED_FRACTION && !seeThrough) buried.push(entry);+ else if (fraction >= HEAVY_OVERLAP_FRACTION && !seeThrough) overlapping.push(entry);+ else undecided.push({ ...entry, seeThrough });+ }+ }++ const deepestFirst = (entries) => [...entries]+ .sort((left, right) => (right.fraction - left.fraction)+ || left.subject.id.localeCompare(right.subject.id)+ || left.container.id.localeCompare(right.container.id));+ const partIdsOf = (entries) => [...new Set(entries.flatMap(({ subject, container }) => [subject.id, container.id]))];+ const findings = [];++ if (buried.length > 0) {+ const ranked = deepestFirst(buried);+ // `listSpecNames` caps the printed list and appends "(+N more)" — a spec+ // that buried forty parts produces one readable instruction, and `pairs`+ // below still carries every one of them for the UI.+ const names = ranked.map(({ subject, container }) => `"${subject.name}" inside "${container.name}"`);+ findings.push({+ code: 'buried-part',+ severity: 'error',+ partIds: partIdsOf(ranked),+ pairs: ranked.map(({ subject, container, fraction }) => ({+ partId: subject.id,+ containerPartId: container.id,+ fraction: Number(fraction.toFixed(3)),+ })),+ message: `${ranked.length} part(s) are entirely inside another part they are not attached to or parented under (${listSpecNames(names)}). Nothing of them can ever be seen from any angle — move each one out to the surface it belongs on, scale it to the part it sits against, or delete it and drop the detail it claims.`,+ });+ }++ if (overlapping.length > 0) {+ const ranked = deepestFirst(overlapping);+ const names = ranked.map(({ subject, container, fraction }) => `${describePair(subject, container)} (${Math.round(fraction * 100)}%)`);+ findings.push({+ code: 'part-interpenetration',+ severity: 'warning',+ partIds: partIdsOf(ranked),+ pairs: ranked.map(({ subject, container, fraction }) => ({+ partId: subject.id,+ containerPartId: container.id,+ fraction: Number(fraction.toFixed(3)),+ })),+ message: `${ranked.length} unrelated part pair(s) occupy substantially the same space (${listSpecNames(names)}, by volume of the smaller part). That is far past a seated joint or a seam — reposition or resize them so each part reads as its own piece when the model is orbited or taken apart.`,+ });+ }++ if (undecided.length > 0) {+ const ranked = deepestFirst(undecided);+ const names = ranked.map(({ subject, container, fraction }) => `${describePair(subject, container)} (${Math.round(fraction * 100)}%)`);+ findings.push({+ code: 'undecided-contact',+ severity: 'note',+ partIds: partIdsOf(ranked),+ pairs: ranked.map(({ subject, container, fraction }) => ({+ partId: subject.id,+ containerPartId: container.id,+ fraction: Number(fraction.toFixed(3)),+ })),+ message: `${ranked.length} unrelated part pair(s) overlap partially (${listSpecNames(names)}). This gate cannot tell a seated joint from a modelling error at this depth, so it is reported undecided rather than as a defect — check these against the reference if the assembly looks wrong when orbited.`,+ });+ }++ const countBy = (severity) => findings.filter((finding) => finding.severity === severity).length;+ return {+ findings,+ errorCount: countBy('error'),+ warningCount: countBy('warning'),+ noteCount: countBy('note'),+ // How many parts had a measurable solid at all — a spec built entirely from+ // `custom` triangle soup is not a clean result, it is an unmeasured one.+ evaluatedPartCount: volumes.length,+ comparedPairCount,+ undecidedPairCount: undecided.length,+ };+}++/**+ * Default refinement feedback derived from a stored penetration result. Only+ * errors and warnings are worth another provider run — the undecided notes exist+ * for a human reading the record, and asking a model to "fix" a contact this+ * gate could not classify would break assemblies that were correct. Returns ''+ * when nothing is interpenetrating, so the caller falls through to whatever+ * other feedback it has.+ */+export function buildThreejsPenetrationFeedback(penetration) {+ const actionable = (penetration?.findings || []).filter((finding) => (+ finding.severity === 'error' || finding.severity === 'warning'+ ));+ if (actionable.length === 0) return '';+ return [+ 'The previous pass failed the cross-part penetration check — unrelated parts are modelled in the same space:',+ ...actionable.map((finding, index) => `${index + 1}. ${finding.message}`),+ 'Give every part its own volume: place each one against the surface it belongs on rather than inside it, and parent anything that is genuinely meant to be embedded to the part it rides.',+ ].join('\n');+}diff --git a/server/lib/threejsModelPenetration.test.js b/server/lib/threejsModelPenetration.test.jsnew file mode 100644index 0000000000..08c7bb03b7--- /dev/null+++ b/server/lib/threejsModelPenetration.test.js@@ -0,0 +1,295 @@+import { describe, expect, it } from 'vitest';+import { threejsSculptSpecSchema } from './threejsModel.js';+import { buildThreejsPenetrationFeedback, evaluateThreejsPenetration } from './threejsModelPenetration.js';++const box = (size = 1) => ({ type: 'box', width: size, height: size, depth: size });++const part = (id, geometry, overrides = {}) => ({+ id,+ name: `${id} part`,+ geometry,+ material: 'shell',+ ...overrides,+});++// Every fixture goes through the real schema first: the evaluator's contract is+// "already validated", so a test that skipped parsing would exercise a shape the+// evaluator never sees (missing `position`/`scale`/`children` defaults).+const makeSpec = ({ parts, materials, articulation }) => threejsSculptSpecSchema.parse({+ schemaVersion: 1,+ name: 'Example Assembly',+ summary: 'Placeholder spec used to exercise the cross-part penetration gate.',+ subjectType: 'object',+ camera: { position: [3, 2, 4] },+ materials: materials || { shell: { color: '#334455' } },+ lights: [{ type: 'directional', intensity: 2 }],+ parts,+ articulation,+ detailInventory: [{+ feature: 'Overall silhouette',+ evidence: 'Visible in the reference image.',+ implementationPartIds: [parts[0].id],+ priority: 'identity',+ }],+});++const codes = (penetration) => penetration.findings.map((finding) => finding.code);+const finding = (penetration, code) => penetration.findings.find((entry) => entry.code === code);++describe('evaluateThreejsPenetration', () => {+ it('reports nothing when unrelated parts sit apart', () => {+ const penetration = evaluateThreejsPenetration(makeSpec({+ parts: [+ part('hull', box(4)),+ part('fin', box(1), { position: [4, 0, 0] }),+ ],+ }));+ expect(penetration.findings).toEqual([]);+ expect(penetration).toMatchObject({ errorCount: 0, warningCount: 0, noteCount: 0, evaluatedPartCount: 2 });+ });++ it('never compares a pair whose bounding boxes are disjoint', () => {+ const penetration = evaluateThreejsPenetration(makeSpec({+ parts: [part('hull', box(2)), part('fin', box(2), { position: [10, 0, 0] })],+ }));+ expect(penetration.comparedPairCount).toBe(0);+ });++ it('flags a small part swallowed whole by an unrelated sibling', () => {+ const penetration = evaluateThreejsPenetration(makeSpec({+ parts: [part('hull', box(6)), part('core', box(1))],+ }));+ expect(codes(penetration)).toContain('buried-part');+ const buried = finding(penetration, 'buried-part');+ expect(buried).toMatchObject({ severity: 'error', partIds: ['core', 'hull'] });+ expect(buried.pairs[0]).toMatchObject({ partId: 'core', containerPartId: 'hull', fraction: 1 });+ expect(penetration.errorCount).toBe(1);+ });++ it('leaves a buried part alone when it is parented under its container', () => {+ const penetration = evaluateThreejsPenetration(makeSpec({+ parts: [part('hull', box(6), { children: [part('core', box(1))] })],+ }));+ expect(penetration.findings).toEqual([]);+ });++ it('leaves a buried part alone when it is a declared attachment', () => {+ const penetration = evaluateThreejsPenetration(makeSpec({+ parts: [part('hull', box(6)), part('pack', box(1))],+ articulation: {+ joints: [{ id: 'root', partId: 'hull' }],+ attachmentPartIds: ['pack'],+ },+ }));+ expect(penetration.findings).toEqual([]);+ });++ it('downgrades containment inside a transparent part to an undecided note', () => {+ const penetration = evaluateThreejsPenetration(makeSpec({+ parts: [part('dome', box(6), { material: 'glass' }), part('core', box(1))],+ materials: {+ shell: { color: '#334455' },+ glass: { color: '#88ccff', transparent: true, opacity: 0.4 },+ },+ }));+ expect(codes(penetration)).toEqual(['undecided-contact']);+ expect(penetration).toMatchObject({ errorCount: 0, noteCount: 1, undecidedPairCount: 1 });+ });++ it('warns when unrelated parts share most of the smaller part volume', () => {+ // The 1³ box straddles the 4³ hull's wall three quarters of the way in —+ // past a seam, short of buried.+ const penetration = evaluateThreejsPenetration(makeSpec({+ parts: [part('hull', box(4)), part('boss', box(1), { position: [1.75, 0, 0] })],+ }));+ expect(codes(penetration)).toEqual(['part-interpenetration']);+ const overlap = finding(penetration, 'part-interpenetration');+ expect(overlap.severity).toBe('warning');+ expect(overlap.pairs[0].fraction).toBeGreaterThan(0.5);+ expect(overlap.pairs[0].fraction).toBeLessThan(0.98);+ });++ it('treats a shallow seated joint as ordinary assembly', () => {+ const penetration = evaluateThreejsPenetration(makeSpec({+ parts: [part('hull', box(4)), part('peg', box(1), { position: [2.45, 0, 0] })],+ }));+ expect(penetration.findings).toEqual([]);+ });++ it('reports a mid-depth overlap as undecided rather than as a defect', () => {+ const penetration = evaluateThreejsPenetration(makeSpec({+ parts: [part('hull', box(4)), part('peg', box(1), { position: [2.2, 0, 0] })],+ }));+ expect(codes(penetration)).toEqual(['undecided-contact']);+ expect(penetration).toMatchObject({ errorCount: 0, warningCount: 0, noteCount: 1 });+ expect(finding(penetration, 'undecided-contact').message).toMatch(/undecided/);+ });++ it('applies the parent transform chain when placing a child part', () => {+ // The child sits at the group origin, and only the GROUP's offset carries it+ // clear of the hull — a gate that ignored the ancestor transform would read+ // it as buried.+ const spec = makeSpec({+ parts: [+ part('hull', box(4)),+ {+ id: 'arm',+ name: 'arm group',+ position: [6, 0, 0],+ children: [part('hand', box(1))],+ },+ ],+ });+ expect(evaluateThreejsPenetration(spec).findings).toEqual([]);+ });++ it('applies part rotation when measuring overlap', () => {+ // Two thin slabs crossing at right angles intersect in a small cube: well+ // under the contact floor, and only if the rotation is actually applied.+ const slab = { type: 'box', width: 6, height: 0.4, depth: 0.4 };+ const penetration = evaluateThreejsPenetration(makeSpec({+ parts: [+ part('beamA', slab),+ part('beamB', slab, { rotationDegrees: [0, 90, 0] }),+ ],+ }));+ expect(penetration.comparedPairCount).toBe(1);+ expect(penetration.findings).toEqual([]);+ });++ it('measures a sphere as a solid ball rather than as its bounding box', () => {+ // A 1³ box parked at the corner of the sphere's bounding box is outside the+ // ball entirely — a box-only gate would call it buried.+ const penetration = evaluateThreejsPenetration(makeSpec({+ parts: [+ part('ball', { type: 'sphere', radius: 3 }),+ part('cube', box(1), { position: [2.6, 2.6, 2.6] }),+ ],+ }));+ expect(penetration.findings).toEqual([]);+ });++ it('finds a custom mesh buried inside a primitive', () => {+ const vertices = [];+ for (const x of [-0.4, 0.4]) {+ for (const y of [-0.4, 0.4]) {+ for (const z of [-0.4, 0.4]) vertices.push(x, y, z);+ }+ }+ const penetration = evaluateThreejsPenetration(makeSpec({+ parts: [+ part('hull', box(6)),+ part('greeble', { type: 'custom', vertices, indices: [0, 1, 2, 3, 4, 5] }),+ ],+ }));+ expect(codes(penetration)).toContain('buried-part');+ expect(finding(penetration, 'buried-part').pairs[0]).toMatchObject({ partId: 'greeble', containerPartId: 'hull' });+ });++ it('skips a pair whose only measurable side is a custom mesh', () => {+ const vertices = [-1, -1, -1, 1, -1, -1, 1, 1, -1, -1, 1, 1];+ const mesh = { type: 'custom', vertices, indices: [0, 1, 2] };+ const penetration = evaluateThreejsPenetration(makeSpec({+ parts: [part('meshA', mesh), part('meshB', mesh)],+ }));+ expect(penetration.comparedPairCount).toBe(1);+ expect(penetration.findings).toEqual([]);+ });++ it('reads a hollow lathe shell as hollow', () => {+ // A thin-walled cup: a part sitting in the cavity is inside the bounding+ // box and outside the material.+ const wall = [[1, -1], [1.2, -1], [1.2, 1], [1, 1]];+ const penetration = evaluateThreejsPenetration(makeSpec({+ parts: [+ part('cup', { type: 'lathe', points: wall }),+ part('pip', box(0.5)),+ ],+ }));+ expect(penetration.findings).toEqual([]);+ });++ it('measures a torus as a ring rather than as a filled disc', () => {+ const penetration = evaluateThreejsPenetration(makeSpec({+ parts: [+ part('ring', { type: 'torus', radius: 3, tube: 0.4 }),+ part('hubMesh', box(1)),+ ],+ }));+ expect(penetration.comparedPairCount).toBe(1);+ expect(penetration.findings).toEqual([]);+ });++ it('reads an extrude hole as empty space', () => {+ const outline = [[-2, -2], [2, -2], [2, 2], [-2, 2]];+ const hole = [[-0.8, -0.8], [-0.8, 0.8], [0.8, 0.8], [0.8, -0.8]];+ const penetration = evaluateThreejsPenetration(makeSpec({+ parts: [+ part('plate', { type: 'extrude', outline, holes: [hole], depth: 2 }),+ part('pin', { type: 'cylinder', radiusTop: 0.5, radiusBottom: 0.5, height: 4 }, {+ position: [0, 0, 1],+ rotationDegrees: [90, 0, 0],+ }),+ ],+ }));+ expect(penetration.comparedPairCount).toBe(1);+ expect(penetration.findings).toEqual([]);+ });++ it('caps the pairs it names while still counting them all', () => {+ const parts = [part('hull', box(20))];+ for (let index = 0; index < 9; index += 1) {+ parts.push(part(`greeble${index}`, box(0.5), { position: [index - 4, 0, 0] }));+ }+ const buried = finding(evaluateThreejsPenetration(makeSpec({ parts })), 'buried-part');+ // Nine swallowed greebles, plus the hull, all listed in `partIds`, but the+ // message names only the capped head of the list.+ expect(buried.pairs).toHaveLength(9);+ expect(buried.partIds).toHaveLength(10);+ expect(buried.message).toMatch(/\(\+\d+ more\)/);+ });++ it('returns an empty result for a spec with no parts at all', () => {+ expect(evaluateThreejsPenetration(null)).toMatchObject({+ findings: [],+ evaluatedPartCount: 0,+ comparedPairCount: 0,+ });+ });++ it('ignores a part whose stored scale collapses it to nothing', () => {+ // The authoring schema rejects a zero scale, but a stored spec predates that+ // bound — the transform is singular, so the part is unmeasurable, not buried.+ const spec = makeSpec({ parts: [part('hull', box(6)), part('ghost', box(1))] });+ spec.parts[1].scale = [0, 1, 1];+ const penetration = evaluateThreejsPenetration(spec);+ expect(penetration.evaluatedPartCount).toBe(1);+ expect(penetration.findings).toEqual([]);+ });+});++describe('buildThreejsPenetrationFeedback', () => {+ it('says nothing when there is nothing to fix', () => {+ expect(buildThreejsPenetrationFeedback(null)).toBe('');+ expect(buildThreejsPenetrationFeedback({ findings: [] })).toBe('');+ });++ it('ignores undecided contact, which a refinement pass must not be told to fix', () => {+ expect(buildThreejsPenetrationFeedback({+ findings: [{ code: 'undecided-contact', severity: 'note', message: 'partial overlap' }],+ })).toBe('');+ });++ it('turns errors and warnings into numbered refinement instructions', () => {+ const feedback = buildThreejsPenetrationFeedback({+ findings: [+ { code: 'buried-part', severity: 'error', message: 'core is inside hull' },+ { code: 'part-interpenetration', severity: 'warning', message: 'boss overlaps hull' },+ { code: 'undecided-contact', severity: 'note', message: 'peg meets hull' },+ ],+ });+ expect(feedback).toContain('1. core is inside hull');+ expect(feedback).toContain('2. boss overlaps hull');+ expect(feedback).not.toContain('peg meets hull');+ });+});diff --git a/server/services/threejsModels/db.js b/server/services/threejsModels/db.jsindex 89648a0583..52cf484bf5 100644--- a/server/services/threejsModels/db.js+++ b/server/services/threejsModels/db.js@@ -84,6 +84,11 @@ export async function createModel(input) {// an older record reads back undefined, which every consumer treats as// "not evaluated" rather than "passed".flatness: null,+ // Cross-part penetration findings for `spec`, written alongside it by+ // `evaluateThreejsPenetration`. Same additive-field contract as `coverage`+ // and `flatness`: an older record reads back undefined, which every consumer+ // treats as "not evaluated" rather than "no parts interpenetrate".+ penetration: 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,diff --git a/server/services/threejsModels/index.js b/server/services/threejsModels/index.jsindex a1f7880789..afcef43aad 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 { buildThreejsPenetrationFeedback, evaluateThreejsPenetration } from '../../lib/threejsModelPenetration.js';import { evaluateThreejsRigReadiness } from '../../lib/threejsModelRig.js';import { GENERAL_FAMILY_ID } from '../../lib/threejsModelFamilies.js';import { resolveCliEffort } from '../../lib/providerModels.js';@@ -109,6 +110,10 @@ 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);+ // And likewise for a spec whose parts are modelled inside each other: it+ // still renders, and from the hero angle it still looks right, so the+ // finding is recorded and fed back rather than thrown away.+ const penetration = evaluateThreejsPenetration(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@@ -128,6 +133,7 @@ async function executeGeneration({spec,coverage,flatness,+ penetration,rig,error: null,generationOperationId: null,@@ -148,6 +154,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 (penetration.errorCount > 0 || penetration.warningCount > 0) {+ console.warn(`⚠️ Three.js model ${id} cross-part penetration: ${penetration.errorCount} error, ${penetration.warningCount} warning finding(s) over ${penetration.comparedPairCount} compared pair(s)`);+ }if (rig.articulationReady) {console.log(`🦴 Three.js model ${id} declares an articulation graph: ${rig.jointCount} joint(s), ${rig.socketCount} pivot socket(s)`);}@@ -204,12 +213,14 @@ export async function startGeneration(id, {const startedAt = new Date().toISOString();const effectivePrompt = prompt ?? current.prompt ?? '';// A refinement the user did not steer aims at what the last pass measurably- // got wrong — the promises it did not build, and the identity parts it built- // without a cross-section — instead of a generic "improve it". Both are sent- // when both fired: they are independent defects with independent remedies.+ // got wrong — the promises it did not build, the identity parts it built+ // without a cross-section, and the parts it modelled inside each other —+ // instead of a generic "improve it". All are sent when all fired: they are+ // independent defects with independent remedies.const effectiveFeedback = (feedback || '').trim() || [buildThreejsCoverageFeedback(current.coverage),buildThreejsFlatnessFeedback(current.flatness),+ buildThreejsPenetrationFeedback(current.penetration),].filter(Boolean).join('\n\n');// Absent (`undefined`) keeps whatever the record already had; an explicit// `null` — what the picker's "Default effort" choice sends — clears it.diff --git a/server/services/threejsModels/index.test.js b/server/services/threejsModels/index.test.jsindex 0ef2ee0fe7..100c9ba111 100644--- a/server/services/threejsModels/index.test.js+++ b/server/services/threejsModels/index.test.js@@ -323,6 +323,64 @@ describe('Three.js model generation orchestration', () => {expect(current.runs.at(-1).feedback).toContain('cross-section check');});+ it('records the cross-part penetration gate and folds it into an unsteered refinement', async () => {+ // The lens is a SIBLING of the body here rather than its child, and it sits+ // entirely inside it — nothing of it can ever be seen.+ const buriedSpec = {+ ...spec,+ parts: [+ {+ id: 'body',+ name: 'Body',+ geometry: { type: 'box', width: 3, height: 3, depth: 3 },+ material: 'body',+ },+ {+ id: 'lens',+ name: 'Lens',+ geometry: { type: 'sphere', radius: 0.35 },+ material: 'lens',+ },+ ],+ };+ let current = {+ id: 'threejs-buried',+ name: 'Example Beacon',+ sourceImage: { filename: 'example.png' },+ providerId: 'vision-api',+ model: null,+ prompt: '',+ status: 'draft',+ spec: null,+ penetration: null,+ runs: [],+ };+ store.getModel.mockImplementation(async () => current);+ store.mutateModel.mockImplementation(async (_id, mutate) => {+ const next = mutate(current);+ if (next) current = next;+ return current;+ });+ runPromptThroughProvider.mockResolvedValue({+ text: JSON.stringify(buriedSpec),+ runId: 'run-buried',+ provider: { id: 'vision-api' },+ model: null,+ });++ await startGeneration(current.id, { providerId: 'vision-api' });+ await vi.waitFor(() => expect(current.status).toBe('ready'));+ expect(current.penetration).toMatchObject({ errorCount: 1, evaluatedPartCount: 2, comparedPairCount: 1 });+ expect(current.penetration.findings[0]).toMatchObject({+ code: 'buried-part',+ severity: 'error',+ partIds: ['lens', 'body'],+ });++ await startGeneration(current.id, { providerId: 'vision-api' });+ expect(current.runs.at(-1).feedback).toContain('cross-part penetration check');+ });+it('gives CLI agents a gallery path without passing an API attachment', async () => {getProviderById.mockResolvedValue({id: 'local-agent',