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: report a declared-curved part built from a sweep that never bends (#5453)
[._.]/ Adam Eivycd5bd716719a
diff --git a/server/lib/threejsModel.js b/server/lib/threejsModel.jsindex 216d4296a7..72756809e5 100644--- a/server/lib/threejsModel.js+++ b/server/lib/threejsModel.js@@ -1309,12 +1309,13 @@ const REFLECTIVE_CHANNELS_BY_TYPE = {const reflectiveChannelFloor = (channel) => (channel === 'metalness' ? REFLECTIVE_METALNESS_FLOOR : 0);/**- * Split a material id into lowercase word tokens, breaking on separators AND on- * camelCase boundaries so `oakTrim` and `oak_trim` tokenize the same. A trailing+ * Split a spec identifier — a material id, a part name, a feature phrase — into+ * lowercase word tokens, breaking on separators AND on camelCase boundaries so+ * `oakTrim` and `oak_trim` tokenize the same. A trailing* plural is folded in as an extra candidate token rather than replacing the* original, so `planks` matches `plank` without `abs` losing its own keyword.*/-const tokenizeMaterialId = (id) => {+const tokenizeSpecIdentifier = (id) => {const words = String(id || '').replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase()@@ -1335,7 +1336,7 @@ const tokenizeMaterialId = (id) => {*/const matchMaterialFamily = (id) => {const matched = new Set();- for (const token of tokenizeMaterialId(id)) {+ for (const token of tokenizeSpecIdentifier(id)) {const prior = MATERIAL_KEYWORD_FAMILIES.get(token);if (prior) matched.add(prior);}@@ -1444,6 +1445,418 @@ export function buildThreejsMaterialFeedback(plausibility) {return [...substance, ...unlit.map((finding) => finding.message)].join('\n');}+// Swept-arc curvature gate. A generated spec routinely DECLARES a curved feature+// — a horn, a tail, a hook, a bent conduit — and then implements it with a+// straight run of control points. Every bounds-based check is blind to that: the+// bounding box of a straight tube is a perfectly reasonable box, nothing+// penetrates anything, the part touches its parent, and the silhouette from the+// generated camera can even be right. Only the SHAPE of the swept path says the+// horn does not curve.+//+// Two different measurements, because the two sweep geometries carry their+// curvature in different places:+//+// * `tube` sweeps a circle along an explicit list of control points, so the+// curvature lives in that polyline. The points are fitted to their best-fit+// plane and then to a circle within it, and the path counts as curved when it+// rides that circle — a fit its points really lie on, spanning a minimum+// angle, with the centre a bounded distance from the path — or, for a bend+// that rides no single circle at all, when its excursion from its own+// best-fit line is large enough to see. Each bound below rejects a different+// degenerate fit.+// * `extrude` sweeps a closed outline along a STRAIGHT axis, so there is no+// sweep path to fit an arc to — and a closed ring is useless as one, since it+// has no endpoints and always turns a full 360°. Its curvature is in the+// outline's silhouette instead: a curved form (crescent, hook, claw) has a+// concave side, while a straight tapered spike is convex however finely it is+// subdivided. So the outline is measured by how much of its turning is+// concave.+//+// Both gates fire only on a part the spec itself declares curved — by name, or+// through a `detailInventory` feature that names it. `tube` and `extrude` are+// the right answer for plenty of straight parts (a rail, a plate, a strut), so a+// straight sweep is evidence of nothing until something says it was meant to+// bend.++// How far a path has to turn to read as a curve rather than as authoring slack.+// The travel is accumulated as an ABSOLUTE sum per segment rather than as the+// signed range about the fitted centre: an S-curved tail sweeps one way and then+// back, and a signed range would cancel those halves and report a genuinely+// curved path as straight.+export const SWEPT_ARC_MIN_SPAN_DEGREES = 25;++// Absolute accumulation means authoring noise ADDS UP instead of cancelling, so+// a jittered straight run reaches the span threshold without ever bending. A+// span is therefore only credited when the points actually LIE on the circle+// that was fitted to them, measured as RMS radial error against its radius.+const SWEPT_ARC_MAX_RADIAL_ERROR_RATIO = 0.05;++// And the fitted circle has to sit alongside the path rather than out at+// infinity: an arc riding one circle puts its centre about a radius away, which+// at 25° of span is 2.25 times the path's own extent. For a clean fit this+// agrees with the span bound by construction — it is the bound that still holds+// when the fit is only approximate, and the span it produced cannot be trusted+// on its own.+const SWEPT_ARC_MAX_CENTER_DISTANCE_RATIO = 3;++// An arc fit answers "does this ride ONE circle", which an S-curved tail and a+// sharply kinked hook both fail while being obviously not straight. So bending+// is also measured directly, as the path's largest excursion from its own+// best-fit line relative to its extent — the one measure that survives a path+// with no single centre at all.+const SWEPT_PATH_MIN_SAGITTA_RATIO = 0.05;++// A crescent's concave (inner) boundary turns back through about the same angle+// its outer boundary sweeps, so the outline threshold is the arc threshold.+export const CURVED_OUTLINE_MIN_CONCAVE_TURN_DEGREES = 25;++// Tokens that declare a form which has to bend to read as itself. Deliberately+// narrow: a token earns a place here only when a STRAIGHT version of the part+// would be wrong, which is why "pipe", "rod", and "trunk" are absent — those are+// straight far more often than not, and only qualify through a "bent"/"curved"+// modifier that is itself on the list. Bare "arc" and "hoop" are absent for the+// opposite reason: an "arcReactor" is a disc, and a hoop authored as an extruded+// ring has a convex outline with the curve in its HOLE, so both would report a+// correct build as the defect.+const CURVED_FORM_TOKENS = new Set([+ 'horn', 'antler', 'tusk', 'fang', 'claw', 'talon', 'pincer', 'mandible',+ 'tail', 'tentacle', 'whisker', 'hook', 'crook', 'barb',+ 'curve', 'curved', 'curving', 'curl', 'curled', 'coil', 'coiled', 'spiral',+ 'bend', 'bent', 'arced', 'arch', 'arched', 'bow', 'bowed',+ 'crescent', 'scythe', 'sickle', 'elbow',+]);++/**+ * True when an identifier names a form that has to bend. Reuses the material+ * tokenizer so `hornLeft`, `horn_left`, and `Horns` all match.+ */+const namesCurvedForm = (identifier) => tokenizeSpecIdentifier(identifier)+ .some((token) => CURVED_FORM_TOKENS.has(token));++const crossProduct = (a, b) => [+ (a[1] * b[2]) - (a[2] * b[1]),+ (a[2] * b[0]) - (a[0] * b[2]),+ (a[0] * b[1]) - (a[1] * b[0]),+];++/**+ * The eigenvector of the smallest eigenvalue of a symmetric 3x3 covariance —+ * the best-fit plane's normal. Closed-form rather than iterative: a path carries+ * at most 96 points and the audit runs on every refinement pass.+ *+ * @param {number[]} covariance `[xx, yy, zz, xy, xz, yz]`+ */+const smallestEigenvector = ([xx, yy, zz, xy, xz, yz]) => {+ const offDiagonal = (xy * xy) + (xz * xz) + (yz * yz);+ const mean = (xx + yy + zz) / 3;+ let smallest;+ if (offDiagonal <= 0) {+ smallest = Math.min(xx, yy, zz);+ } else {+ const spread = ((xx - mean) ** 2) + ((yy - mean) ** 2) + ((zz - mean) ** 2) + (2 * offDiagonal);+ const scale = Math.sqrt(spread / 6);+ const b = [+ (xx - mean) / scale, xy / scale, xz / scale,+ xy / scale, (yy - mean) / scale, yz / scale,+ xz / scale, yz / scale, (zz - mean) / scale,+ ];+ const determinant = (b[0] * ((b[4] * b[8]) - (b[5] * b[7])))+ - (b[1] * ((b[3] * b[8]) - (b[5] * b[6])))+ + (b[2] * ((b[3] * b[7]) - (b[4] * b[6])));+ const phi = Math.acos(Math.min(1, Math.max(-1, determinant / 2))) / 3;+ const first = mean + (2 * scale * Math.cos(phi));+ const third = mean + (2 * scale * Math.cos(phi + ((2 * Math.PI) / 3)));+ smallest = Math.min(first, third, (3 * mean) - first - third);+ }+ // The null space of (covariance - smallest * I): every pair of its rows spans+ // the plane, so their cross product is the normal. The longest one is taken+ // because a near-degenerate pair produces numerical dust.+ const rows = [+ [xx - smallest, xy, xz],+ [xy, yy - smallest, yz],+ [xz, yz, zz - smallest],+ ];+ let normal = null;+ let longest = 0;+ for (let i = 0; i < 3; i += 1) {+ for (let j = i + 1; j < 3; j += 1) {+ const candidate = crossProduct(rows[i], rows[j]);+ const length = vectorLength(candidate);+ if (length > longest) {+ longest = length;+ normal = candidate;+ }+ }+ }+ return longest > 0 ? normal.map((value) => value / longest) : [0, 0, 1];+};++/**+ * Least-squares circle through 2D points (Kasa). Returns `null` when the points+ * are collinear, where the normal equations are singular and any "circle"+ * through them is an artifact of float noise.+ */+const fitCircle2D = (points) => {+ const count = points.length;+ const meanX = points.reduce((total, [x]) => total + x, 0) / count;+ const meanY = points.reduce((total, [, y]) => total + y, 0) / count;+ let suu = 0; let svv = 0; let suv = 0; let suuu = 0; let svvv = 0; let suvv = 0; let svuu = 0;+ for (const [x, y] of points) {+ const u = x - meanX;+ const v = y - meanY;+ suu += u * u; svv += v * v; suv += u * v;+ suuu += u * u * u; svvv += v * v * v;+ suvv += u * v * v; svuu += v * u * u;+ }+ const determinant = (suu * svv) - (suv * suv);+ // Relative, not absolute: the same collinear path authored in millimetres and+ // in metres must both read as collinear.+ if (Math.abs(determinant) <= ((suu + svv) ** 2) * 1e-12) return null;+ const rhsU = (suuu + suvv) / 2;+ const rhsV = (svvv + svuu) / 2;+ const centerU = ((rhsU * svv) - (rhsV * suv)) / determinant;+ const centerV = ((rhsV * suu) - (rhsU * suv)) / determinant;+ return {+ center: [meanX + centerU, meanY + centerV],+ radius: Math.sqrt((centerU * centerU) + (centerV * centerV) + ((suu + svv) / count)),+ centroid: [meanX, meanY],+ };+};++/**+ * The largest perpendicular excursion of 2D points from their own best-fit+ * line. Straightness measured directly, so a path that bends without riding any+ * single circle still reads as bent.+ */+const maxDeviationFromBestFitLine = (points) => {+ const meanX = points.reduce((total, [x]) => total + x, 0) / points.length;+ const meanY = points.reduce((total, [, y]) => total + y, 0) / points.length;+ let sxx = 0; let syy = 0; let sxy = 0;+ for (const [x, y] of points) {+ sxx += (x - meanX) ** 2;+ syy += (y - meanY) ** 2;+ sxy += (x - meanX) * (y - meanY);+ }+ // The principal direction of a symmetric 2x2 scatter, in closed form.+ const angle = Math.atan2(2 * sxy, sxx - syy) / 2;+ const normal = [-Math.sin(angle), Math.cos(angle)];+ return points.reduce((widest, [x, y]) => Math.max(+ widest,+ Math.abs(((x - meanX) * normal[0]) + ((y - meanY) * normal[1])),+ ), 0);+};++/**+ * Measure how far a swept path actually bends.+ *+ * The points are projected onto their own best-fit plane and fitted to a circle+ * there. The path is credited as curved when it rides that circle — a fit its+ * points really lie on, spanning a minimum angle, with the centre a bounded+ * distance from the path — OR, for a bend that rides no single circle, when its+ * excursion from its own best-fit line is large enough to see.+ *+ * @param {Array<number[]>} points ordered `[x, y, z]` control points+ * @returns {{straight: boolean, collinear: boolean, arcSpanDegrees: number,+ * radius: number|null, centerDistanceRatio: number|null,+ * radialErrorRatio: number|null, sagittaRatio: number, extent: number}}+ */+export function evaluateSweptArcCurvature(points) {+ const usable = (Array.isArray(points) ? points : [])+ .filter((point) => Array.isArray(point) && point.length === 3 && point.every(Number.isFinite));+ const straightResult = (extent) => ({+ straight: true,+ collinear: true,+ arcSpanDegrees: 0,+ radius: null,+ centerDistanceRatio: null,+ radialErrorRatio: null,+ sagittaRatio: 0,+ extent,+ });+ const separation = (a, b) => vectorLength(b.map((value, axis) => value - a[axis]));+ // Two points ARE a straight segment, and an exactly collinear run of any+ // length sweeps one too — no fit is needed, and none would be meaningful.+ if (usable.length < 3) return straightResult(usable.length === 2 ? separation(usable[0], usable[1]) : 0);+ if (isCollinearPath(usable)) return straightResult(separation(usable[0], usable[usable.length - 1]));++ const centroid = [0, 1, 2].map((axis) => usable.reduce((total, point) => total + point[axis], 0) / usable.length);+ const offsets = usable.map((point) => point.map((value, axis) => value - centroid[axis]));+ const covariance = [0, 0, 0, 0, 0, 0];+ for (const [x, y, z] of offsets) {+ covariance[0] += (x * x) / offsets.length;+ covariance[1] += (y * y) / offsets.length;+ covariance[2] += (z * z) / offsets.length;+ covariance[3] += (x * y) / offsets.length;+ covariance[4] += (x * z) / offsets.length;+ covariance[5] += (y * z) / offsets.length;+ }+ const normal = smallestEigenvector(covariance);+ // Any seed not parallel to the normal spans the plane with it; the axis with+ // the smallest component is the one guaranteed not to be.+ const seed = Math.abs(normal[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0];+ const uAxis = crossProduct(normal, seed);+ const uLength = vectorLength(uAxis);+ const u = uLength > 0 ? uAxis.map((value) => value / uLength) : [1, 0, 0];+ const v = crossProduct(normal, u);+ const projected = offsets.map((offset) => [+ (offset[0] * u[0]) + (offset[1] * u[1]) + (offset[2] * u[2]),+ (offset[0] * v[0]) + (offset[1] * v[1]) + (offset[2] * v[2]),+ ]);++ let extent = 0;+ for (let i = 0; i < projected.length; i += 1) {+ for (let j = i + 1; j < projected.length; j += 1) {+ extent = Math.max(extent, Math.hypot(projected[i][0] - projected[j][0], projected[i][1] - projected[j][1]));+ }+ }+ if (!(extent > 0)) return straightResult(extent);+ const sagittaRatio = maxDeviationFromBestFitLine(projected) / extent;++ const circle = fitCircle2D(projected);+ if (!circle) {+ return {+ straight: sagittaRatio < SWEPT_PATH_MIN_SAGITTA_RATIO,+ collinear: false,+ arcSpanDegrees: 0,+ radius: null,+ centerDistanceRatio: null,+ radialErrorRatio: null,+ sagittaRatio,+ extent,+ };+ }++ // Per-segment and absolute, so an S-curve accumulates its two opposing bends+ // instead of cancelling them. Safe to sum unsigned only because the radial+ // error below refuses to credit a span the points did not trace.+ let arcSpanRadians = 0;+ for (let index = 1; index < projected.length; index += 1) {+ const previous = Math.atan2(projected[index - 1][1] - circle.center[1], projected[index - 1][0] - circle.center[0]);+ const current = Math.atan2(projected[index][1] - circle.center[1], projected[index][0] - circle.center[0]);+ let step = current - previous;+ while (step > Math.PI) step -= 2 * Math.PI;+ while (step < -Math.PI) step += 2 * Math.PI;+ arcSpanRadians += Math.abs(step);+ }+ const arcSpanDegrees = (arcSpanRadians * 180) / Math.PI;+ const squaredRadialError = projected.reduce((total, [x, y]) => {+ const deviation = Math.hypot(x - circle.center[0], y - circle.center[1]) - circle.radius;+ return total + ((deviation * deviation) / projected.length);+ }, 0);+ const radialErrorRatio = Math.sqrt(squaredRadialError) / circle.radius;+ const centerDistanceRatio = Math.hypot(+ circle.center[0] - circle.centroid[0],+ circle.center[1] - circle.centroid[1],+ ) / extent;++ const ridesArc = radialErrorRatio <= SWEPT_ARC_MAX_RADIAL_ERROR_RATIO+ && arcSpanDegrees >= SWEPT_ARC_MIN_SPAN_DEGREES+ && centerDistanceRatio <= SWEPT_ARC_MAX_CENTER_DISTANCE_RATIO;++ return {+ straight: !ridesArc && sagittaRatio < SWEPT_PATH_MIN_SAGITTA_RATIO,+ collinear: false,+ arcSpanDegrees,+ radius: circle.radius,+ centerDistanceRatio,+ radialErrorRatio,+ sagittaRatio,+ extent,+ };+}++/**+ * How much of a closed outline's turning is concave, in degrees. A convex ring+ * returns 0; a crescent returns roughly the arc its inner boundary sweeps.+ *+ * @param {Array<number[]>} ring ordered `[x, y]` outline points+ */+export function measureOutlineConcaveTurn(ring) {+ const points = (Array.isArray(ring) ? ring : [])+ .filter((point) => Array.isArray(point) && point.length === 2 && point.every(Number.isFinite));+ if (points.length < 3) return 0;+ const turns = points.map((current, index) => {+ const previous = points[(index - 1 + points.length) % points.length];+ const next = points[(index + 1) % points.length];+ const incoming = [current[0] - previous[0], current[1] - previous[1]];+ const outgoing = [next[0] - current[0], next[1] - current[1]];+ return Math.atan2(+ (incoming[0] * outgoing[1]) - (incoming[1] * outgoing[0]),+ (incoming[0] * outgoing[0]) + (incoming[1] * outgoing[1]),+ );+ });+ // A simple ring turns through a full circle exactly once, so the sign of the+ // total is its winding — measured from the turns themselves rather than from a+ // signed area, so the two can never disagree about which side is concave.+ const winding = turns.reduce((total, turn) => total + turn, 0) >= 0 ? 1 : -1;+ const concave = turns.reduce((total, turn) => total + Math.max(0, -turn * winding), 0);+ return (concave * 180) / Math.PI;+}++/**+ * The sweep geometries whose curvature this gate can measure, and the reason a+ * given part is treated as declared-curved. Returns `null` for anything else, so+ * a straight `box` rail named "elbowBracket" is never reported — this gate only+ * speaks about sweeps.+ */+export function evaluateSweptGeometryCurvature(geometry) {+ if (geometry?.type === 'tube') {+ // A closed tube is a loop: the schema already refuses a collinear one, and a+ // loop has no endpoints for an arc span to mean anything between.+ if (geometry.closed === true) return null;+ const curvature = evaluateSweptArcCurvature(geometry.path);+ return { kind: 'tube', straight: curvature.straight, arcSpanDegrees: curvature.arcSpanDegrees };+ }+ if (geometry?.type === 'extrude') {+ const concaveTurnDegrees = measureOutlineConcaveTurn(geometry.outline);+ return {+ kind: 'extrude',+ straight: concaveTurnDegrees < CURVED_OUTLINE_MIN_CONCAVE_TURN_DEGREES,+ concaveTurnDegrees,+ };+ }+ return null;+}++/**+ * Parts the spec declares as curved forms, keyed by part id, with the name or+ * feature phrase that declared it. A `detailInventory` feature counts as a+ * declaration, which is how a part called `part_17` still gets measured when the+ * feature it builds is "curved brass horn".+ *+ * Only declarations that name ONE sweep are returned. A curved form built from+ * several parts — a tail of five tapered segments, a horn split into a base and+ * a tip — curves by ARRANGEMENT, and every piece of it is legitimately straight,+ * so measuring the pieces would report the correct build as the defect. That is+ * why a segment nested under an already-declared part is skipped, and why a+ * feature implementing itself with more than one sweep is skipped too.+ */+export function collectDeclaredCurvedParts(spec) {+ const declared = new Map();+ const byId = new Map();+ const declare = (partId, declaredBy) => {+ if (!declared.has(partId)) declared.set(partId, declaredBy);+ };+ const walk = (parts, ancestorDeclared) => {+ for (const part of parts || []) {+ byId.set(part.id, part);+ const name = part.name || part.id;+ const isDeclared = namesCurvedForm(name);+ if (isDeclared && !ancestorDeclared) declare(part.id, name);+ walk(part.children, ancestorDeclared || isDeclared);+ }+ };+ walk(spec?.parts, false);+ for (const detail of spec?.detailInventory || []) {+ if (!namesCurvedForm(detail.feature)) continue;+ const sweeps = (detail.implementationPartIds || [])+ .filter((partId) => evaluateSweptGeometryCurvature(byId.get(partId)?.geometry));+ if (sweeps.length !== 1) continue;+ declare(sweeps[0], detail.feature);+ }+ return declared;+}+const toIdentifier = (name) => {const words = String(name || 'Procedural').replace(/[^A-Za-z0-9]+/g, ' ').trim().split(/\s+/).filter(Boolean);const joined = words.map((word) => word[0].toUpperCase() + word.slice(1)).join('') || 'Procedural';diff --git a/server/lib/threejsModel.test.js b/server/lib/threejsModel.test.jsindex d29bebd815..c570c50d3c 100644--- a/server/lib/threejsModel.test.js+++ b/server/lib/threejsModel.test.js@@ -3,10 +3,14 @@ import {buildThreejsFactorySource,buildThreejsFlatnessFeedback,buildThreejsMaterialFeedback,+ collectDeclaredCurvedParts,DEFAULT_ATTACHMENT_MAX_OFFSET,+ evaluateSweptArcCurvature,+ evaluateSweptGeometryCurvature,evaluateThreejsFlatness,evaluateThreejsMaterialPlausibility,isThreejsAttachmentAnchored,+ measureOutlineConcaveTurn,resolveThreejsAttachments,storedThreejsSculptSpecSchema,threejsGeometrySchema,@@ -1417,3 +1421,160 @@ describe('buildThreejsFactorySource animation', () => {expect(source).not.toContain('"sequences"');});});++// A generated horn that never bends passes every bounds check in the audit — its+// box is a reasonable box — so the input matrix here is the whole gate. Each+// case names a different way a path can fail to be an arc.+describe('evaluateSweptArcCurvature', () => {+ const arcPath = (spanDegrees, { count = 8, radius = 1 } = {}) => Array.from({ length: count }, (_, index) => {+ const angle = (index / (count - 1)) * spanDegrees * (Math.PI / 180);+ return [radius * Math.cos(angle), radius * Math.sin(angle), 0];+ });++ it('reports a collinear path as straight without fitting anything', () => {+ const curvature = evaluateSweptArcCurvature([[0, 0, 0], [1, 0, 0], [2, 0, 0], [3, 0, 0]]);+ expect(curvature.collinear).toBe(true);+ expect(curvature.straight).toBe(true);+ expect(curvature.radius).toBeNull();+ });++ it('reports a two-point path as straight', () => {+ expect(evaluateSweptArcCurvature([[0, 0, 0], [0, 2, 0]]).straight).toBe(true);+ });++ it('measures the span of a genuine arc and passes it', () => {+ const curvature = evaluateSweptArcCurvature(arcPath(90));+ expect(curvature.straight).toBe(false);+ expect(curvature.arcSpanDegrees).toBeCloseTo(90, 4);+ expect(curvature.radius).toBeCloseTo(1, 4);+ });++ // The measurement has to be a property of the shape, not of the axes it was+ // authored against, or a horn tilted off the world planes reads as straight.+ it('fits the path plane rather than a world plane', () => {+ const tilted = arcPath(90).map(([x, y]) => [x, y * Math.SQRT1_2, y * Math.SQRT1_2]);+ const curvature = evaluateSweptArcCurvature(tilted);+ expect(curvature.straight).toBe(false);+ expect(curvature.arcSpanDegrees).toBeCloseTo(90, 3);+ });++ it('reports a shallow arc below the span threshold as straight', () => {+ const curvature = evaluateSweptArcCurvature(arcPath(15));+ expect(curvature.arcSpanDegrees).toBeCloseTo(15, 4);+ expect(curvature.straight).toBe(true);+ });++ // Angular travel is accumulated unsigned, so alternating authoring noise adds+ // up to a span the path never swept. Only the radial fit error says the points+ // are nowhere near the circle that produced it.+ it('does not credit a jittered straight run with the span its noise accumulates', () => {+ const jittered = Array.from({ length: 12 }, (_, index) => [index * 0.2, (index % 2 ? 1 : -1) * 0.002, 0]);+ const curvature = evaluateSweptArcCurvature(jittered);+ expect(curvature.arcSpanDegrees).toBeGreaterThan(25);+ expect(curvature.radialErrorRatio).toBeGreaterThan(0.05);+ expect(curvature.straight).toBe(true);+ });++ // The other side of that trade: an S-curve rides no single circle either, and+ // rejecting it on fit alone would report a bent tail as a straight one.+ it('accepts an S-curve that rides no single circle', () => {+ const sCurve = Array.from({ length: 16 }, (_, index) => {+ const t = (index / 15) * 2 * Math.PI;+ return [t * 0.3, Math.sin(t) * 0.4, 0];+ });+ const curvature = evaluateSweptArcCurvature(sCurve);+ expect(curvature.radialErrorRatio).toBeGreaterThan(0.05);+ expect(curvature.straight).toBe(false);+ });++ it('ignores non-finite and malformed points', () => {+ expect(evaluateSweptArcCurvature([[0, 0, 0], [1, Number.NaN, 0], [2, 0]]).straight).toBe(true);+ expect(evaluateSweptArcCurvature(null).straight).toBe(true);+ });+});++describe('measureOutlineConcaveTurn', () => {+ const crescent = () => {+ const outer = Array.from({ length: 14 }, (_, index) => {+ const angle = (index / 13) * Math.PI * 0.75;+ return [Math.cos(angle), Math.sin(angle)];+ });+ const inner = Array.from({ length: 14 }, (_, index) => {+ const angle = (Math.PI * 0.75) - ((index / 13) * Math.PI * 0.75);+ return [0.8 * Math.cos(angle), 0.8 * Math.sin(angle)];+ });+ return [...outer, ...inner];+ };++ it('reports no concave turning for a convex outline', () => {+ expect(measureOutlineConcaveTurn([[0, 0], [1, 0], [1, 1], [0, 1]])).toBeCloseTo(0, 6);+ });++ it('reports the inner sweep of a crescent', () => {+ expect(measureOutlineConcaveTurn(crescent())).toBeGreaterThan(100);+ });++ // Winding is read off the turning itself, so an outline authored clockwise is+ // not reported as concave along its whole boundary.+ it('measures the same crescent whichever way it winds', () => {+ expect(measureOutlineConcaveTurn([...crescent()].reverse()))+ .toBeCloseTo(measureOutlineConcaveTurn(crescent()), 6);+ });+});++describe('evaluateSweptGeometryCurvature', () => {+ it('measures a tube path and an extrude outline, and nothing else', () => {+ expect(evaluateSweptGeometryCurvature({ type: 'tube', path: [[0, 0, 0], [0, 1, 0], [0, 2, 0]] }))+ .toMatchObject({ kind: 'tube', straight: true });+ expect(evaluateSweptGeometryCurvature({ type: 'extrude', outline: [[0, 0], [1, 0], [1, 1], [0, 1]] }))+ .toMatchObject({ kind: 'extrude', straight: true });+ expect(evaluateSweptGeometryCurvature({ type: 'box', width: 1, height: 1, depth: 1 })).toBeNull();+ expect(evaluateSweptGeometryCurvature(null)).toBeNull();+ });++ // A closed tube is a loop with no endpoints, and the schema already refuses a+ // collinear one, so there is no arc span for this gate to mean anything about.+ it('declines to measure a closed tube', () => {+ expect(evaluateSweptGeometryCurvature({+ type: 'tube',+ closed: true,+ path: [[0, 0, 0], [1, 0, 0], [1, 1, 0]],+ })).toBeNull();+ });+});++describe('collectDeclaredCurvedParts', () => {+ const tube = { type: 'tube', path: [[0, 0, 0], [0, 1, 0], [0, 2, 0]] };++ it('declares a part by its own name and by a detail feature that names it', () => {+ const declared = collectDeclaredCurvedParts({+ parts: [+ { id: 'horn', name: 'Left Horn', geometry: tube },+ { id: 'part_17', name: 'part_17', geometry: tube },+ { id: 'rail', name: 'Support Rail', geometry: tube },+ ],+ detailInventory: [{ feature: 'curved brass conduit', implementationPartIds: ['part_17'] }],+ });+ expect([...declared.entries()]).toEqual([['horn', 'Left Horn'], ['part_17', 'curved brass conduit']]);+ });++ // A tail of five straight segments arranged along an arc is the CORRECT build,+ // and every segment of it is straight — so an assembly is never measured piece+ // by piece, from either declaration source.+ it('skips an assembly that can curve by arrangement', () => {+ const declared = collectDeclaredCurvedParts({+ parts: [+ {+ id: 'tail',+ name: 'Tail',+ children: [+ { id: 'tail-a', name: 'Tail Segment A', geometry: tube },+ { id: 'tail-b', name: 'Tail Segment B', geometry: tube },+ ],+ },+ ],+ detailInventory: [{ feature: 'curved tail', implementationPartIds: ['tail-a', 'tail-b'] }],+ });+ expect([...declared.keys()]).toEqual(['tail']);+ });+});diff --git a/server/lib/threejsModelPhysicalAudit.js b/server/lib/threejsModelPhysicalAudit.jsindex 1d7534ad96..d5113822d4 100644--- a/server/lib/threejsModelPhysicalAudit.js+++ b/server/lib/threejsModelPhysicalAudit.js@@ -12,6 +12,7 @@* 8. `bilateral-mirror-scale`: One half of a named left/right pair mirrored by negating a scale component.* 9. `bilateral-pair-same-side`: A named left/right pair that never crosses the lateral plane.* 10. `bilateral-chirality`: A named left/right pair mirrored by a 180-degree yaw instead of a lateral reflection.+ * 11. `straight-swept-path`: A part declared as a curved form built from a sweep that never bends.** Checks 6 and 7 exist because `floating-part` and `buried-geometry` both miss* the same defect: a hat that belongs behind the shoulders but is authored at@@ -24,10 +25,22 @@* handedness: a hand spun around the vertical axis, or scaled by -1 in X,* occupies exactly the same box as a correctly reflected one. Only the* transform that placed it says which way round the limb is built.+ * Check 11 covers the same blind spot in one more dimension: a horn swept along+ * a straight run of control points has a perfectly reasonable bounding box,+ * penetrates nothing, and touches its parent, so every check above passes it.+ * Only the shape of the swept path itself says it never curves.*/-import { isThreejsAttachmentAnchored, listSpecNames, resolveThreejsAttachments } from './threejsModel.js';+import {+ CURVED_OUTLINE_MIN_CONCAVE_TURN_DEGREES,+ SWEPT_ARC_MIN_SPAN_DEGREES,+ collectDeclaredCurvedParts,+ evaluateSweptGeometryCurvature,+ isThreejsAttachmentAnchored,+ listSpecNames,+ resolveThreejsAttachments,+} from './threejsModel.js';const EPSILON = 1e-4;const COPLANAR_TOLERANCE = 1e-3;@@ -799,6 +812,40 @@ function buildBilateralChiralityFindings({ pairs, chains, volumes }) {* @returns {{findings: Array, errorCount: number, warningCount: number, noteCount: number,* evaluatedPartCount: number, evaluatedPoseCount: number}}*/+const formatDegrees = (value) => `${Math.round(value)}°`;++/**+ * Report a part the spec declares as a curved form whose sweep never bends.+ *+ * Named or feature-declared curvature is the whole trigger: `tube` and `extrude`+ * are the right answer for plenty of straight parts — a rail, a plate, a strut —+ * so a straight sweep is evidence of nothing until the spec says it was meant to+ * turn.+ */+const buildSweptPathCurvatureFindings = (spec, parts) => {+ const partsById = new Map(parts.map((part) => [part.id, part]));+ const findings = [];+ for (const [partId, declaredBy] of collectDeclaredCurvedParts(spec)) {+ const part = partsById.get(partId);+ const curvature = evaluateSweptGeometryCurvature(part?.geometry);+ if (!curvature || !curvature.straight) continue;+ const name = part.name || part.id;+ // Only when the declaration came from somewhere else — repeating the part's+ // own name back at it reads as a stutter.+ const declaration = declaredBy === name ? '' : ` (declared by the feature "${declaredBy}")`;+ const message = curvature.kind === 'tube'+ ? `Part "${name}"${declaration} is a curved form built from a tube whose path ${curvature.arcSpanDegrees > 0 ? `only turns through ${formatDegrees(curvature.arcSpanDegrees)}` : 'runs through collinear control points'}, so it sweeps straight. Sample the intended curve into "path" so consecutive points step around a centre — a horn, tail, hook, or bent conduit needs at least ${formatDegrees(SWEPT_ARC_MIN_SPAN_DEGREES)} of turn — instead of listing points along one line.`+ : `Part "${name}"${declaration} is a curved form built from an extrude whose outline never turns back on itself (${formatDegrees(curvature.concaveTurnDegrees)} of concave turning). An extrude sweeps its outline along a STRAIGHT axis, so the curve has to be in the outline's own silhouette: give it a concave side of at least ${formatDegrees(CURVED_OUTLINE_MIN_CONCAVE_TURN_DEGREES)}, or build the part as a "tube" whose path follows the curve.`;+ findings.push({+ code: 'straight-swept-path',+ severity: 'warning',+ partIds: [partId],+ message,+ });+ }+ return findings;+};+export function evaluateThreejsPhysicalAudit(spec) {if (!spec || !Array.isArray(spec.parts)) {return {@@ -887,6 +934,10 @@ export function evaluateThreejsPhysicalAudit(spec) {addFinding(finding);}+ for (const finding of buildSweptPathCurvatureFindings(spec, parts)) {+ addFinding(finding);+ }+// Floating check & Buried & Coplanar on resting posefor (let i = 0; i < visibleStaticVolumes.length; i += 1) {const subject = visibleStaticVolumes[i];@@ -1125,6 +1176,7 @@ export function buildThreejsPhysicalAuditFeedback(physicalAudit) {|| finding.code === 'bilateral-mirror-scale'|| finding.code === 'bilateral-pair-same-side'));+ const hasStraightSweptPath = actionable.some((finding) => finding.code === 'straight-swept-path');const attachmentFindings = actionable.filter((finding) => (finding.code === 'unanchored-attachment' || finding.code === 'attachment-far-from-anchor'));@@ -1141,6 +1193,9 @@ export function buildThreejsPhysicalAuditFeedback(physicalAudit) {...(hasNonuniformParentScale ? ['For non-uniform parent scale findings, size each part through its own geometry dimensions (for example, box width/height/depth or sphere radius) and keep containers near-uniform instead of squashing a parent that owns other components.',] : []),+ ...(hasStraightSweptPath ? [+ 'For straight swept-path findings, put the curve in the geometry rather than in the part name: a "tube" needs enough control points, stepped around a centre, that its path visibly turns, and an "extrude" only curves when its outline itself has a concave side. Rotating or repositioning a straight sweep does not make it a curved one.',+ ] : []),...(hasBilateralChirality ? ['For bilateral pair findings, mirror a paired limb across the lateral plane rather than turning it around: give the counterpart position [-x, y, z] and rotation [rx, -ry, -rz] with every scale component positive. A 180° yaw about the vertical axis or a negative scale factor leaves the bounding box correct while pointing thumbs backward and putting big toes on the outer edge.',] : []),diff --git a/server/lib/threejsModelPhysicalAudit.test.js b/server/lib/threejsModelPhysicalAudit.test.jsindex 9fd3b663a2..6eaa7c626c 100644--- a/server/lib/threejsModelPhysicalAudit.test.js+++ b/server/lib/threejsModelPhysicalAudit.test.js@@ -1054,3 +1054,112 @@ describe('threejsModelPhysicalAudit attachment anchors', () => {});});});++// A straight horn is invisible to every check above — its bounding box is a+// perfectly reasonable box, it penetrates nothing, and it touches its parent.+// Only what the spec CALLS the part makes the straight sweep a defect.+describe('swept-path curvature', () => {+ const arcPath = (spanDegrees, count = 8) => Array.from({ length: count }, (_, index) => {+ const angle = (index / (count - 1)) * spanDegrees * (Math.PI / 180);+ return [Math.cos(angle) - 1, Math.sin(angle), 0];+ });+ const hornSpec = (horn, detailInventory) => ({+ name: 'Horned Figure',+ parts: [+ {+ id: 'skull',+ name: 'Skull',+ geometry: { type: 'box', width: 1, height: 1, depth: 1 },+ position: [0, 0.5, 0],+ children: [{ id: 'horn', name: 'Horn', position: [0, 0.5, 0], ...horn }],+ },+ ],+ ...(detailInventory ? { detailInventory } : {}),+ });+ const sweptFindings = (spec) => evaluateThreejsPhysicalAudit(spec).findings+ .filter((finding) => finding.code === 'straight-swept-path');++ it('flags a horn swept along collinear control points', () => {+ const findings = sweptFindings(hornSpec({+ geometry: { type: 'tube', path: [[0, 0, 0], [0, 0.5, 0], [0, 1, 0]], radius: 0.1 },+ }));+ expect(findings).toHaveLength(1);+ expect(findings[0].severity).toBe('warning');+ expect(findings[0].partIds).toEqual(['horn']);+ expect(findings[0].message).toContain('collinear control points');+ });++ it('reports the measured span for a horn that bends too little', () => {+ const findings = sweptFindings(hornSpec({+ geometry: { type: 'tube', path: arcPath(12), radius: 0.1 },+ }));+ expect(findings).toHaveLength(1);+ expect(findings[0].message).toContain('only turns through 12°');+ });++ it('accepts a horn that actually curves', () => {+ expect(sweptFindings(hornSpec({+ geometry: { type: 'tube', path: arcPath(80), radius: 0.1 },+ }))).toEqual([]);+ });++ // `tube` is the right answer for plenty of straight parts, so a straight+ // sweep is evidence of nothing until the spec says the part was meant to bend.+ it('leaves an undeclared straight tube alone', () => {+ const spec = hornSpec({+ geometry: { type: 'tube', path: [[0, 0, 0], [0, 0.5, 0], [0, 1, 0]], radius: 0.1 },+ });+ spec.parts[0].children[0].name = 'Antenna Mast';+ expect(sweptFindings(spec)).toEqual([]);+ });++ it('names the detail feature when the part name does not declare the curve', () => {+ const spec = hornSpec(+ { geometry: { type: 'tube', path: [[0, 0, 0], [0, 0.5, 0], [0, 1, 0]], radius: 0.1 } },+ [{ feature: 'coiled brass conduit', evidence: 'reference photo', implementationPartIds: ['horn'], priority: 'identity' }],+ );+ spec.parts[0].children[0].name = 'Conduit';+ const findings = sweptFindings(spec);+ expect(findings).toHaveLength(1);+ expect(findings[0].message).toContain('declared by the feature "coiled brass conduit"');+ });++ // An extrude sweeps along a straight axis, so its outline is the only place+ // a curve can live — and a convex outline has no curve in it at all.+ it('flags a curved feature built from a convex extrude outline', () => {+ const findings = sweptFindings(hornSpec({+ geometry: {+ type: 'extrude',+ outline: [[0, 0], [0.2, 0], [0.1, 1]],+ depth: 0.2,+ bevelEnabled: true,+ bevelThickness: 0.05,+ },+ }));+ expect(findings).toHaveLength(1);+ expect(findings[0].message).toContain('0° of concave turning');+ });++ it('accepts a crescent extrude outline', () => {+ const outer = Array.from({ length: 12 }, (_, index) => {+ const angle = (index / 11) * Math.PI * 0.8;+ return [Math.cos(angle), Math.sin(angle)];+ });+ const inner = Array.from({ length: 12 }, (_, index) => {+ const angle = (Math.PI * 0.8) - ((index / 11) * Math.PI * 0.8);+ return [0.75 * Math.cos(angle), 0.75 * Math.sin(angle)];+ });+ expect(sweptFindings(hornSpec({+ geometry: { type: 'extrude', outline: [...outer, ...inner], depth: 0.2 },+ }))).toEqual([]);+ });++ it('feeds the finding back with the recipe for putting the curve in the geometry', () => {+ const feedback = buildThreejsPhysicalAuditFeedback(evaluateThreejsPhysicalAudit(hornSpec({+ geometry: { type: 'tube', path: [[0, 0, 0], [0, 0.5, 0], [0, 1, 0]], radius: 0.1 },+ })));+ expect(feedback).toContain('For straight swept-path findings');+ expect(feedback).toContain('outline itself has a concave side');+ });+});+