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 Three.js specs whose identity parts are all flat slabs (#3482)
[._.]/ Adam Eivy8f5a7ff5f4d8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex c5474f8784..c398274525 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -92,6 +92,8 @@- **[issue-3483] Take a generated model apart and click any piece to find out what it is.** The preview used to render a finished model as one inert lump — the only way to check it was actually built from parts, rather than fused into a single shape, was to export the source and read it. An Explode slider now separates the assembly, and clicking any surface names the part it belongs to and lights up that whole component. Separation scales the layout outward from the model's centre instead of shoving every piece the same distance, so parts that were touching genuinely come apart, pieces sitting at the centre still clear their neighbours, and the camera re-frames to whatever the disassembly actually grew to. Surface detail — serrations, stria, trim, port floors — rides the part it belongs to instead of shattering into loose slivers, and clicking it selects that part; models are now generated with that distinction marked, and exported models carry it too.+- **[issue-3482] A model that looks perfect head-on and like cardboard the moment you orbit it now says so before you find out yourself.** Since the spec gained extruded outlines, a generation can score a near-perfect match against its reference — right silhouette, right colour zones, right part count — while every load-bearing piece is a flat slab standing on its own depth plane, because a head-on comparison actively rewards that flatness. A new cross-section check reads the finished geometry instead of the picture: it counts how many distinct planes each mesh actually occupies on its thinnest axis (a fan of four hundred triangles sharing one Z value has no profile at all) and treats an unbevelled extrusion as the two-plane slab it is by construction. It reports at the level of the whole model rather than per part, because a flat extrusion is the *right* answer for a badge, a sign, or a panel — the finding fires only when the majority of the subject's identity-defining features have nothing but flat parts behind them, and it names the parts responsible. The result sits beside the assembly-coverage findings on the model's page, and a Refine you didn't steer now asks for real depth as well as for the promises the last pass didn't build. The generation prompt was closing the loop from the other end too: it sold extrude for silhouettes without ever saying when extrude is the wrong answer, so it now states that a body with a real cross-section — a torso, a housing, a grip, a shell that varies in thickness — must not be an unbevelled extrusion, and gates on a subject that isn't genuinely plate-like not having every identity part flat along one axis.+## Internal- **[issue-3497] The Chief of Staff no longer re-reads and re-parses its task lists on every scheduler tick** — an unchanged list is served from memory instead, which matters most on installs whose task history has grown large. Edits made outside PortOS (a text editor, a restore, a sync peer) are still picked up immediately.diff --git a/client/src/pages/ThreejsModelDetail.jsx b/client/src/pages/ThreejsModelDetail.jsxindex d917c71a22..3f1ac6ad7c 100644--- a/client/src/pages/ThreejsModelDetail.jsx+++ b/client/src/pages/ThreejsModelDetail.jsx@@ -28,6 +28,56 @@ const SEVERITY_STYLE = {note: 'border-port-border bg-port-bg/50 text-gray-400',};+// Counted from the findings actually rendered rather than read off the stored+// tallies, so a header can never disagree with the list below it — or print+// "undefined error" for a record whose gate result arrived without its counts.+// An unrecognized severity counts as a note rather than being dropped: the list+// still renders it (styled as a note), and a tally that omitted it would read+// "0 note" above a visible finding.+const countSeverities = (findings) => findings.reduce((counts, finding) => {+ const bucket = counts[finding.severity] === undefined ? 'note' : finding.severity;+ counts[bucket] += 1;+ return counts;+}, { error: 0, warning: 0, note: 0 });++/**+ * One quality-gate result (assembly coverage, cross-section) rendered as a+ * severity-styled finding list. Shared so a second gate cannot drift into a+ * different look for the same data.+ */+function GatePanel({ title, findings, cleanLabel, footer }) {+ const counts = countSeverities(findings);+ return (+ <section className="rounded-xl border border-port-border bg-port-card p-4">+ <div className="mb-2 flex flex-wrap items-center justify-between gap-2">+ <h2 className="text-xs font-medium uppercase tracking-wide text-gray-400">{title}</h2>+ <span className="text-xs text-gray-600">+ {findings.length === 0+ ? cleanLabel+ : `${counts.error} error · ${counts.warning} warning · ${counts.note} note`}+ </span>+ </div>+ {findings.length > 0 && (+ <ul className="space-y-2">+ {findings.map((finding, index) => (+ <li+ key={`${finding.code}-${index}`}+ className={`rounded-lg border px-3 py-2 text-xs leading-relaxed ${SEVERITY_STYLE[finding.severity] || SEVERITY_STYLE.note}`}+ >+ <span className="mr-2 text-[9px] uppercase tracking-wide opacity-80">{finding.severity}</span>+ {finding.message}+ </li>+ ))}+ </ul>+ )}+ <p className="mt-3 flex items-start gap-1.5 text-[11px] leading-relaxed text-gray-500">+ <Info className="mt-0.5 h-3 w-3 shrink-0" />+ <span>{footer}</span>+ </p>+ </section>+ );+}+export default function ThreejsModelDetail() {const { id } = useParams();const navigate = useNavigate();@@ -162,18 +212,11 @@ export default function ThreejsModelDetail() {const generating = record.status === 'generating' || starting;const latestRun = Array.isArray(record.runs) ? record.runs[record.runs.length - 1] : null;+ // A record generated before a gate shipped has no result at all, which is not+ // the same as passing it — the panel is omitted rather than shown clean.const coverageFindings = Array.isArray(record.coverage?.findings) ? record.coverage.findings : null;- // Counted from the findings actually rendered rather than read off the stored- // tallies, so the header can never disagree with the list below it — or print- // "undefined error" for a record whose coverage arrived without its counts.- // An unrecognized severity counts as a note rather than being dropped — the- // list below still renders it (styled as a note), and a tally that omitted it- // would read "0 note" above a visible finding.- const coverageCounts = (coverageFindings || []).reduce((counts, finding) => {- const bucket = counts[finding.severity] === undefined ? 'note' : finding.severity;- counts[bucket] += 1;- return counts;- }, { error: 0, warning: 0, note: 0 });+ const flatnessFindings = Array.isArray(record.flatness?.findings) ? record.flatness.findings : null;+ const coverageErrors = countSeverities(coverageFindings || []).error;return (<div className="mx-auto max-w-7xl space-y-4">@@ -318,37 +361,25 @@ export default function ThreejsModelDetail() {</section>{coverageFindings && (- <section className="rounded-xl border border-port-border bg-port-card p-4">- <div className="mb-2 flex flex-wrap items-center justify-between gap-2">- <h2 className="text-xs font-medium uppercase tracking-wide text-gray-400">Assembly coverage</h2>- <span className="text-xs text-gray-600">- {coverageFindings.length === 0- ? 'Nothing promised was left unbuilt'- : `${coverageCounts.error} error · ${coverageCounts.warning} warning · ${coverageCounts.note} note`}- </span>- </div>- {coverageFindings.length > 0 && (- <ul className="space-y-2">- {coverageFindings.map((finding, index) => (- <li- key={`${finding.code}-${index}`}- className={`rounded-lg border px-3 py-2 text-xs leading-relaxed ${SEVERITY_STYLE[finding.severity] || SEVERITY_STYLE.note}`}- >- <span className="mr-2 text-[9px] uppercase tracking-wide opacity-80">{finding.severity}</span>- {finding.message}- </li>- ))}- </ul>- )}- <p className="mt-3 flex items-start gap-1.5 text-[11px] leading-relaxed text-gray-500">- <Info className="mt-0.5 h-3 w-3 shrink-0" />- <span>- This check proves the model built what its own spec promised — never that the spec promised enough.- {coverageCounts.error > 0- && ' Refining without your own feedback will target the errors above.'}- </span>- </p>- </section>+ <GatePanel+ title="Assembly coverage"+ findings={coverageFindings}+ cleanLabel="Nothing promised was left unbuilt"+ footer={`This check proves the model built what its own spec promised — never that the spec promised enough.${+ coverageErrors > 0 ? ' Refining without your own feedback will target the errors above.' : ''+ }`}+ />+ )}++ {flatnessFindings && (+ <GatePanel+ title="Cross-section"+ findings={flatnessFindings}+ cleanLabel="Identity parts carry real depth"+ footer={`A model can match its reference head-on and still be a stack of cardboard cut-outs, so this check counts how many identity-defining features are built only from flat parts.${+ flatnessFindings.length > 0 ? ' Refining without your own feedback will also ask for real depth.' : ''+ }`}+ />)}{record.spec?.detailInventory?.length > 0 && (diff --git a/client/src/pages/ThreejsModelDetail.test.jsx b/client/src/pages/ThreejsModelDetail.test.jsxindex 1cf0cdfbae..601aa41401 100644--- a/client/src/pages/ThreejsModelDetail.test.jsx+++ b/client/src/pages/ThreejsModelDetail.test.jsx@@ -117,3 +117,50 @@ describe('ThreejsModelDetail assembly coverage', () => {expect(screen.queryByText('Assembly coverage')).not.toBeInTheDocument();});});++describe('ThreejsModelDetail cross-section gate', () => {+ beforeEach(() => vi.clearAllMocks());++ it('lists the flatness finding and says an unsteered refinement will ask for depth', async () => {+ getThreejsModel.mockResolvedValue({+ ...baseRecord,+ flatness: {+ errorCount: 0,+ warningCount: 1,+ noteCount: 0,+ identityDetailCount: 3,+ flatIdentityDetailCount: 3,+ flatRatio: 1,+ slabPartIds: ['front', 'back', 'fin'],+ findings: [{+ code: 'flat-identity-parts',+ severity: 'warning',+ message: '3 of 3 identity-defining features are built only from flat parts (Front, Back, Fin).',+ }],+ },+ });+ renderDetail();++ await waitFor(() => expect(screen.getByText('Cross-section')).toBeInTheDocument());+ expect(screen.getByText('3 of 3 identity-defining features are built only from flat parts (Front, Back, Fin).')).toBeInTheDocument();+ expect(screen.getByText('0 error · 1 warning · 0 note')).toBeInTheDocument();+ expect(screen.getByText(/will also ask for real depth/)).toBeInTheDocument();+ });++ it('reports real depth on a clean pass and stays quiet about refinement', async () => {+ getThreejsModel.mockResolvedValue({ ...baseRecord, flatness: { warningCount: 0, findings: [] } });+ renderDetail();++ await waitFor(() => expect(screen.getByText('Cross-section')).toBeInTheDocument());+ expect(screen.getByText('Identity parts carry real depth')).toBeInTheDocument();+ expect(screen.queryByText(/will also ask for real depth/)).not.toBeInTheDocument();+ });++ it('hides the section for a record generated before the gate existed', async () => {+ getThreejsModel.mockResolvedValue({ ...baseRecord, flatness: null });+ renderDetail();++ await waitFor(() => expect(screen.getByText('Example Beacon')).toBeInTheDocument());+ expect(screen.queryByText('Cross-section')).not.toBeInTheDocument();+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex dbdc68a650..f3af4dc704 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -148,7 +148,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `imageClean.js` | `cleanImageBuffer(buf, { metadata, denoise })` (composable opt-in pipeline: lossless metadata/C2PA strip + optional median/sharpen denoise) · `stripPngMetadataChunks` / `stripPngC2PAChunk` (lossless PNG-chunk removers) · `compositeIgnoreZone(base, original, mask, { feather })` (preserve-region compositing: restore original pixels into a feathered mask over a diffused result) · `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer` and appends a CPU light diffusion pass (`applyLightRegen` from `services/imageGen/regen.js`) for the `diffusion=light` SynthID-disruption step. || `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. || `localImageFilename.js` | `localImageFilename(urlOrPath)` resolves a stored image reference to the bare gallery-image filename under `data/images/` (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (`headshotImageFilename`/`portraitImageFilename`/`coverImageFilename`/`startingImageFilename` are thin wrappers). Also exports `assetBasename(pathOrName)`, the shared strip-querystring→basename primitive (reused by moodBoard's `imageUrlToAppAsset`). |-| `threejsModel.js` | Validated declarative procedural-model schema plus deterministic standalone Three.js factory export for the Three.js Models workspace. |+| `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 (and treats an unbevelled `extrude` as a two-plane slab) 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)` — structural assembly gate over an already-validated Three.js spec: flags promised features fused onto one mesh, geometry claimed by no detail, and details nothing was built for (folded minor relief stays a `note`). `buildThreejsCoverageFeedback(coverage)` turns the error findings into default refinement feedback. || `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/threejsModel.js b/server/lib/threejsModel.jsindex ced9b1a2b8..933b35f377 100644--- a/server/lib/threejsModel.js+++ b/server/lib/threejsModel.js@@ -419,6 +419,150 @@ export const threejsSculptSpecSchema = makeSpecSchema(makePartSchema(scale3Schem*/export const storedThreejsSculptSpecSchema = makeSpecSchema(makePartSchema(vec3Schema));+const MAX_NAMES_IN_MESSAGE = 8;++/**+ * Render a capped, comma-joined list of spec-level names (parts or features) for+ * a finding message. Shared with `threejsModelCoverage.js` so both gates cap the+ * same way — a finding that prints forty part names is one nobody reads.+ */+export const listSpecNames = (names) => (names.length > MAX_NAMES_IN_MESSAGE+ ? `${names.slice(0, MAX_NAMES_IN_MESSAGE).join(', ')} (+${names.length - MAX_NAMES_IN_MESSAGE} more)`+ : names.join(', '));++// Cross-section gate. A spec can match its reference head-on — silhouette,+// colour zones, part count — and still be a diorama of cardboard cut-outs:+// every load-bearing part a planar extrusion on its own depth plane, correct+// from the generated camera and hollow the moment the user orbits. Neither the+// schema nor the assembly-coverage gate sees it, because a slab is well-formed+// geometry that implements exactly the detail it claims.+//+// Evidence of form is PLANE count, not triangle count: a fan of four hundred+// triangles sharing one Z value has no profile at all. So a `custom` mesh is+// slab-like when its thinnest axis carries fewer distinct coordinates than a+// curved surface needs to read as curved, and an unbevelled `extrude` is one by+// construction — its sweep has exactly two depth planes no matter how many+// `steps` subdivide the side walls.+//+// Honest limit: a genuinely three-dimensional but very coarse custom mesh (an+// eight-vertex box) also lands under the plane threshold. That shape is already+// against the prompt's guidance — `box` exists — so the false positive only+// fires on geometry that should not have been custom triangles in the first+// place.+const SLAB_PLANE_THRESHOLD = 11;+const PLANE_QUANTUM = 1e-3;++// Aggregate, never per-part: `extrude` is the RIGHT answer for a plate, a badge,+// or a sign, so a flat part is only evidence when the model's identity rides on+// it. The finding is "the load-bearing parts are predominantly flat", reported+// once the majority of buildable identity features are backed by nothing else.+const FLAT_IDENTITY_RATIO_THRESHOLD = 0.6;++const countAxisPlanes = (vertices) => {+ const axes = [new Set(), new Set(), new Set()];+ vertices.forEach((value, index) => axes[index % 3].add(Math.round(value / PLANE_QUANTUM)));+ return axes.map((axis) => axis.size);+};++const isSlabGeometry = (geometry) => {+ if (!geometry) return false;+ // `bevelEnabled` defaults to false in the schema, so a parsed spec always+ // carries it; `!== true` also reads an older stored spec that predates it.+ if (geometry.type === 'extrude') return geometry.bevelEnabled !== true;+ if (geometry.type !== 'custom') return false;+ const vertices = Array.isArray(geometry.vertices) ? geometry.vertices : [];+ if (vertices.length < 9) return false;+ return Math.min(...countAxisPlanes(vertices)) < SLAB_PLANE_THRESHOLD;+};++const collectMeshes = (part, out = []) => {+ if (part.geometry) out.push(part);+ for (const child of part.children || []) collectMeshes(child, out);+ return out;+};++/**+ * @param {object} spec a spec that has already passed `threejsSculptSpecSchema`+ * @returns {{findings: Array, errorCount: number, warningCount: number, noteCount: number,+ * identityDetailCount: number, flatIdentityDetailCount: number, flatRatio: number|null,+ * slabPartIds: string[]}}+ */+export function evaluateThreejsFlatness(spec) {+ const byId = new Map();+ const indexPart = (part) => {+ byId.set(part.id, part);+ for (const child of part.children || []) indexPart(child);+ };+ for (const part of spec?.parts || []) indexPart(part);++ const details = Array.isArray(spec?.detailInventory) ? spec.detailInventory : [];+ const slabPartIds = new Set();+ const flatFeatures = [];+ let evaluated = 0;++ for (const detail of details) {+ if (detail.priority !== 'identity') continue;+ const meshes = new Map();+ for (const id of new Set(detail.implementationPartIds || [])) {+ const part = byId.get(id);+ if (!part) continue;+ // A detail may point at a group whose children carry the geometry, and two+ // of its ids may nest, so meshes are collected by id rather than counted.+ for (const mesh of collectMeshes(part)) meshes.set(mesh.id, mesh);+ }+ // Nothing was built for this feature anywhere — that is the assembly-coverage+ // gate's `unbuilt-detail`, and counting it here would let a spec that built+ // almost nothing read as a flat one.+ if (meshes.size === 0) continue;+ evaluated += 1;+ const implementing = [...meshes.values()];+ if (!implementing.every((mesh) => isSlabGeometry(mesh.geometry))) continue;+ flatFeatures.push(detail.feature);+ for (const mesh of implementing) slabPartIds.add(mesh.id);+ }++ // `null`, not 0: a spec with no buildable identity feature was not measured+ // flat, it was not measured at all, and a 0 would read as a clean result.+ const flatRatio = evaluated === 0 ? null : flatFeatures.length / evaluated;+ const findings = [];+ if (flatRatio !== null && flatRatio > FLAT_IDENTITY_RATIO_THRESHOLD) {+ const offenders = [...slabPartIds];+ findings.push({+ code: 'flat-identity-parts',+ severity: 'warning',+ partIds: offenders,+ features: flatFeatures,+ message: `${flatFeatures.length} of ${evaluated} identity-defining features are built only from flat parts (${listSpecNames(offenders.map((id) => byId.get(id)?.name || id))}). The model will read as a projection the moment it is orbited — give the parts the subject's identity rides on a real cross-section instead of stacking unbevelled extrusions and planar triangle fans.`,+ });+ }++ return {+ findings,+ errorCount: 0,+ warningCount: findings.length,+ noteCount: 0,+ identityDetailCount: evaluated,+ flatIdentityDetailCount: flatFeatures.length,+ flatRatio,+ slabPartIds: [...slabPartIds],+ };+}++/**+ * Default refinement feedback derived from a stored flatness result. Returns ''+ * when the model has a cross-section, so the caller falls through to whatever+ * other feedback it has.+ */+export function buildThreejsFlatnessFeedback(flatness) {+ const warnings = (flatness?.findings || []).filter((finding) => finding.severity === 'warning');+ if (warnings.length === 0) return '';+ return [+ 'The previous pass failed the cross-section check — it reads as a flat projection rather than a solid:',+ ...warnings.map((finding, index) => `${index + 1}. ${finding.message}`),+ 'Rebuild those parts with genuine depth: compose them from primitives, or give an extrude a bevel, so the model holds up from any orbit angle.',+ ].join('\n');+}+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 bc8205993e..af6fead1a9 100644--- a/server/lib/threejsModel.test.js+++ b/server/lib/threejsModel.test.js@@ -1,6 +1,8 @@import { describe, expect, it } from 'vitest';import {buildThreejsFactorySource,+ buildThreejsFlatnessFeedback,+ evaluateThreejsFlatness,storedThreejsSculptSpecSchema,threejsGeometrySchema,threejsSculptSpecSchema,@@ -384,3 +386,178 @@ describe('buildThreejsFactorySource', () => {expect(thrown?.code).toBe('VALIDATION_ERROR');});});++// A wide, finely-sampled outline that is nonetheless ONE plane in Z: the shape+// the gate exists to catch, and the one a head-on similarity score rewards.+const flatFanGeometry = () => {+ const points = 24;+ const vertices = [];+ const indices = [];+ for (let index = 0; index < points; index += 1) {+ const angle = (index / points) * Math.PI * 2;+ vertices.push(Number(Math.cos(angle).toFixed(3)), Number(Math.sin(angle).toFixed(3)), 0);+ }+ vertices.push(0, 0, 0);+ for (let index = 0; index < points; index += 1) indices.push(points, index, (index + 1) % points);+ return { type: 'custom', vertices, indices };+};++// A lat/long sphere shell — every axis carries far more than the plane+// threshold, which is what having a cross-section looks like numerically.+const solidShellGeometry = () => {+ const rings = 12;+ const segments = 12;+ const vertices = [];+ const indices = [];+ for (let ring = 0; ring <= rings; ring += 1) {+ const phi = (ring / rings) * Math.PI;+ for (let segment = 0; segment < segments; segment += 1) {+ const theta = (segment / segments) * Math.PI * 2;+ vertices.push(+ Number((Math.sin(phi) * Math.cos(theta)).toFixed(3)),+ Number(Math.cos(phi).toFixed(3)),+ Number((Math.sin(phi) * Math.sin(theta)).toFixed(3)),+ );+ }+ }+ for (let index = 0; index + 2 < vertices.length / 3; index += 3) indices.push(index, index + 1, index + 2);+ return { type: 'custom', vertices, indices };+};++const geometryPart = (id, geometry) => ({+ id,+ name: `${id} part`,+ geometry,+ material: 'body',+ position: [0, 0, 0],+ rotationDegrees: [0, 0, 0],+ scale: [1, 1, 1],+ children: [],+});++// Every part gets its own identity-priority detail, so the aggregate ratio is+// exactly the fraction of parts that are slabs.+const flatnessSpec = (parts, priority = 'identity') => ({+ ...validSpec(),+ parts,+ sockets: [],+ detailInventory: parts.map((part) => ({+ feature: `${part.name} silhouette`,+ evidence: 'Visible in the reference image.',+ implementationPartIds: [part.id],+ priority,+ })),+});++describe('evaluateThreejsFlatness', () => {+ it('keeps the fixtures inside the authoring contract', () => {+ const spec = flatnessSpec([geometryPart('fan', flatFanGeometry()), geometryPart('shell', solidShellGeometry())]);+ expect(threejsSculptSpecSchema.safeParse(spec).success).toBe(true);+ });++ it('flags a spec whose identity parts are all slab custom meshes', () => {+ const flatness = evaluateThreejsFlatness(flatnessSpec([+ geometryPart('front', flatFanGeometry()),+ geometryPart('back', flatFanGeometry()),+ ]));+ expect(flatness.findings).toHaveLength(1);+ expect(flatness.findings[0]).toMatchObject({+ code: 'flat-identity-parts',+ severity: 'warning',+ partIds: ['front', 'back'],+ });+ expect(flatness).toMatchObject({+ errorCount: 0,+ warningCount: 1,+ identityDetailCount: 2,+ flatIdentityDetailCount: 2,+ flatRatio: 1,+ });+ });++ it('accepts a custom mesh with a real cross-section on every axis', () => {+ const flatness = evaluateThreejsFlatness(flatnessSpec([+ geometryPart('shellA', solidShellGeometry()),+ geometryPart('shellB', solidShellGeometry()),+ ]));+ expect(flatness.findings).toEqual([]);+ expect(flatness).toMatchObject({ flatIdentityDetailCount: 0, flatRatio: 0, slabPartIds: [] });+ });++ it('reads an unbevelled extrude as a slab and a bevelled one as solid', () => {+ const unbevelled = { ...validExtrude(), bevelEnabled: false };+ const bevelled = { ...validExtrude(), bevelEnabled: true, bevelThickness: 0.15, bevelSize: 0.1 };++ const flat = evaluateThreejsFlatness(flatnessSpec([geometryPart('plate', unbevelled)]));+ expect(flat.findings.map((finding) => finding.code)).toEqual(['flat-identity-parts']);+ expect(flat.flatRatio).toBe(1);++ const solid = evaluateThreejsFlatness(flatnessSpec([geometryPart('plate', bevelled)]));+ expect(solid.findings).toEqual([]);+ expect(solid.flatRatio).toBe(0);+ });++ it('stays quiet while flat parts are the minority — extrude is right for a plate', () => {+ const flatness = evaluateThreejsFlatness(flatnessSpec([+ geometryPart('badge', { ...validExtrude(), bevelEnabled: false }),+ geometryPart('shellA', solidShellGeometry()),+ geometryPart('shellB', solidShellGeometry()),+ ]));+ expect(flatness.findings).toEqual([]);+ // Still recorded, so the UI can show which part the one flat feature used.+ expect(flatness).toMatchObject({ flatIdentityDetailCount: 1, slabPartIds: ['badge'] });+ expect(flatness.flatRatio).toBeCloseTo(1 / 3);+ });++ it('ignores flat parts that carry no identity-priority feature', () => {+ const flatness = evaluateThreejsFlatness(flatnessSpec([+ geometryPart('vent', flatFanGeometry()),+ geometryPart('grille', flatFanGeometry()),+ ], 'minor'));+ expect(flatness.findings).toEqual([]);+ expect(flatness).toMatchObject({ identityDetailCount: 0, flatIdentityDetailCount: 0, flatRatio: null });+ });++ it('measures the meshes beneath a group rather than the group itself', () => {+ const group = {+ ...geometryPart('housing', undefined),+ children: [geometryPart('housingShell', solidShellGeometry())],+ };+ delete group.geometry;+ delete group.material;+ const flatness = evaluateThreejsFlatness(flatnessSpec([group]));+ expect(flatness).toMatchObject({ identityDetailCount: 1, flatIdentityDetailCount: 0 });+ });++ it('leaves a detail nothing was built for to the assembly-coverage gate', () => {+ const locator = { ...geometryPart('anchor', undefined), children: [] };+ delete locator.geometry;+ delete locator.material;+ const flatness = evaluateThreejsFlatness(flatnessSpec([locator]));+ // `null`, not 0 — nothing was measured, which is not the same as passing.+ expect(flatness).toMatchObject({ identityDetailCount: 0, flatRatio: null, findings: [] });+ });++ it('returns a clean result for a missing spec', () => {+ expect(evaluateThreejsFlatness(null)).toMatchObject({ findings: [], flatRatio: null });+ });+});++describe('buildThreejsFlatnessFeedback', () => {+ it('returns empty for a missing or clean flatness result', () => {+ expect(buildThreejsFlatnessFeedback(null)).toBe('');+ expect(buildThreejsFlatnessFeedback({ findings: [] })).toBe('');+ });++ it('turns the warning into a numbered instruction naming the offending parts', () => {+ const flatness = evaluateThreejsFlatness(flatnessSpec([+ geometryPart('front', flatFanGeometry()),+ geometryPart('back', flatFanGeometry()),+ ]));+ const feedback = buildThreejsFlatnessFeedback(flatness);+ expect(feedback).toContain('cross-section check');+ expect(feedback).toContain('1. ');+ expect(feedback).toContain('front part');+ expect(feedback).toContain('genuine depth');+ });+});diff --git a/server/lib/threejsModelCoverage.js b/server/lib/threejsModelCoverage.jsindex 5172f9af04..05228cbd6b 100644--- a/server/lib/threejsModelCoverage.js+++ b/server/lib/threejsModelCoverage.js@@ -12,13 +12,14 @@* promised, never that the spec promised enough.*/+import { listSpecNames } from './threejsModel.js';+// Severity of a promised-but-unbuilt feature scales with how much of the// subject's identity rides on it. A missing identity feature is a defect; a// missing minor one is a note, because folding fine relief into a parent mesh// is a legitimate modeling choice rather than an omission.const UNBUILT_SEVERITY = { identity: 'error', major: 'warning', minor: 'note' };const RANKED_PRIORITIES = new Set(['identity', 'major']);-const MAX_NAMES_IN_MESSAGE = 8;/*** Depth-first flatten that carries, per part, the ancestor chain and whether the@@ -43,10 +44,6 @@ function flattenParts(parts) {return flat;}-const listNames = (names) => (names.length > MAX_NAMES_IN_MESSAGE- ? `${names.slice(0, MAX_NAMES_IN_MESSAGE).join(', ')} (+${names.length - MAX_NAMES_IN_MESSAGE} more)`- : names.join(', '));-/*** @param {object} spec a spec that has already passed `threejsSculptSpecSchema`* @returns {{findings: Array, errorCount: number, warningCount: number, noteCount: number}}@@ -110,7 +107,7 @@ export function evaluateThreejsPartCoverage(spec) {severity: 'error',partIds: [partId],features,- message: `${features.length} promised features collapsed onto the single part "${label(partId)}" (${listNames(features)}). ${remedy}`,+ message: `${features.length} promised features collapsed onto the single part "${label(partId)}" (${listSpecNames(features)}). ${remedy}`,});continue;}@@ -121,7 +118,7 @@ export function evaluateThreejsPartCoverage(spec) {severity: 'note',partIds: [partId],features: group.map((detail) => detail.feature),- message: `${group.length} details share the single part "${label(partId)}" (${listNames(group.map((detail) => detail.feature))}). Folding minor relief into the piece it rides on is expected.`,+ message: `${group.length} details share the single part "${label(partId)}" (${listSpecNames(group.map((detail) => detail.feature))}). Folding minor relief into the piece it rides on is expected.`,});}@@ -138,7 +135,7 @@ export function evaluateThreejsPartCoverage(spec) {severity: 'warning',count: orphans.length,partIds: orphans.map((part) => part.id),- message: `${orphans.length} geometry part(s) are claimed by no detailInventory entry (${listNames(orphans.map((part) => part.name))}). Unattributed geometry cannot be reviewed or refined.`,+ message: `${orphans.length} geometry part(s) are claimed by no detailInventory entry (${listSpecNames(orphans.map((part) => part.name))}). Unattributed geometry cannot be reviewed or refined.`,});}@@ -178,7 +175,7 @@ export function evaluateThreejsPartCoverage(spec) {severity: UNBUILT_SEVERITY[detail.priority] || 'warning',partIds: resolved.map((part) => part.id),features: [detail.feature],- message: `"${detail.feature}" (${detail.priority}) points only at parts with no geometry (${listNames(resolved.map((part) => part.name))}), so nothing was built for it.`,+ message: `"${detail.feature}" (${detail.priority}) points only at parts with no geometry (${listSpecNames(resolved.map((part) => part.name))}), so nothing was built for it.`,});}diff --git a/server/services/threejsModels/db.js b/server/services/threejsModels/db.jsindex adcca2b84c..71b67dff73 100644--- a/server/services/threejsModels/db.js+++ b/server/services/threejsModels/db.js@@ -73,6 +73,11 @@ export async function createModel(input) {// `evaluateThreejsPartCoverage`. Records written before this field existed// read back as undefined; every consumer treats that as "not evaluated".coverage: null,+ // Cross-section findings for `spec`, written alongside it by+ // `evaluateThreejsFlatness`. Same additive-field contract as `coverage`:+ // an older record reads back undefined, which every consumer treats as+ // "not evaluated" rather than "passed".+ flatness: null,error: null,generationOperationId: null,runs: [],diff --git a/server/services/threejsModels/index.js b/server/services/threejsModels/index.jsindex fc9ba52e8e..486f1857b3 100644--- a/server/services/threejsModels/index.js+++ b/server/services/threejsModels/index.js@@ -8,7 +8,12 @@ import { ServerError } from '../../lib/errorHandler.js';import { PATHS, resolveGalleryImage } from '../../lib/fileUtils.js';import { runPromptThroughProvider } from '../../lib/promptRunner.js';import { extractJson } from '../../lib/jsonExtract.js';-import { buildThreejsFactorySource, threejsSculptSpecSchema } from '../../lib/threejsModel.js';+import {+ buildThreejsFactorySource,+ buildThreejsFlatnessFeedback,+ evaluateThreejsFlatness,+ threejsSculptSpecSchema,+} from '../../lib/threejsModel.js';import { buildThreejsCoverageFeedback, evaluateThreejsPartCoverage } from '../../lib/threejsModelCoverage.js';import { resolveCliEffort } from '../../lib/providerModels.js';import { getProviderById } from '../providers.js';@@ -97,6 +102,10 @@ async function executeGeneration({// it builds is still a usable generation, so the gate is recorded on the// record and surfaced as refinement feedback rather than thrown away.const coverage = evaluateThreejsPartCoverage(spec);+ // Likewise for a spec that builds everything it promised out of slabs: it+ // 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);const completedAt = new Date().toISOString();const effectiveProvider = result.provider?.id || result.fallbackProvider?.id || provider.id;const effectiveModel = result.model || requestedModel || provider.defaultModel || null;@@ -110,6 +119,7 @@ async function executeGeneration({status: 'ready',spec,coverage,+ flatness,error: null,generationOperationId: null,generatedAt: completedAt,@@ -126,6 +136,9 @@ async function executeGeneration({if (coverage.errorCount > 0) {console.warn(`⚠️ Three.js model ${id} assembly coverage: ${coverage.errorCount} error, ${coverage.warningCount} warning finding(s)`);}+ if (flatness.warningCount > 0) {+ console.warn(`⚠️ Three.js model ${id} cross-section: ${flatness.flatIdentityDetailCount}/${flatness.identityDetailCount} identity feature(s) built only from flat parts`);+ }} catch (error) {console.error(`❌ Three.js model generation failed for ${id}: ${cleanError(error)}`);await failGeneration(id, operationId, error);@@ -176,10 +189,14 @@ export async function startGeneration(id, {const operationId = randomUUID();const startedAt = new Date().toISOString();const effectivePrompt = prompt ?? current.prompt ?? '';- // A refinement the user did not steer aims at the last pass's assembly-coverage- // errors — the promises the model measurably did not build — instead of a- // generic "improve it".- const effectiveFeedback = (feedback || '').trim() || buildThreejsCoverageFeedback(current.coverage);+ // 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.+ const effectiveFeedback = (feedback || '').trim() || [+ buildThreejsCoverageFeedback(current.coverage),+ buildThreejsFlatnessFeedback(current.flatness),+ ].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.const requestedEffort = effort === undefined ? (current.effort || null) : (effort || null);diff --git a/server/services/threejsModels/index.test.js b/server/services/threejsModels/index.test.jsindex c65c66679f..508cdd9a77 100644--- a/server/services/threejsModels/index.test.js+++ b/server/services/threejsModels/index.test.js@@ -198,6 +198,74 @@ describe('Three.js model generation orchestration', () => {})));});+ it('records the cross-section gate and folds it into an unsteered refinement', async () => {+ // Both identity features are unbevelled extrudes: a spec that renders+ // correctly from its own camera and like cardboard from anywhere else.+ const slabSpec = {+ ...spec,+ parts: [+ {+ id: 'body',+ name: 'Body',+ geometry: { type: 'extrude', outline: [[-1, -1], [1, -1], [1, 1], [-1, 1]], depth: 0.4 },+ material: 'body',+ },+ {+ id: 'lens',+ name: 'Lens',+ geometry: { type: 'extrude', outline: [[-0.4, -0.4], [0.4, -0.4], [0.4, 0.4]], depth: 0.2 },+ material: 'lens',+ },+ ],+ detailInventory: [+ { ...spec.detailInventory[0], implementationPartIds: ['lens'] },+ {+ feature: 'Beacon housing',+ evidence: 'A tapered housing carries the lens in the reference.',+ implementationPartIds: ['body'],+ priority: 'identity',+ },+ ],+ };+ let current = {+ id: 'threejs-flat',+ name: 'Example Beacon',+ sourceImage: { filename: 'example.png' },+ providerId: 'vision-api',+ model: null,+ prompt: '',+ status: 'draft',+ spec: null,+ coverage: null,+ flatness: 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(slabSpec),+ runId: 'run-flat',+ provider: { id: 'vision-api' },+ model: null,+ });++ await startGeneration(current.id, { providerId: 'vision-api' });+ await vi.waitFor(() => expect(current.status).toBe('ready'));+ expect(current.flatness).toMatchObject({+ warningCount: 1,+ identityDetailCount: 2,+ flatIdentityDetailCount: 2,+ });+ expect(current.flatness.findings[0]).toMatchObject({ code: 'flat-identity-parts' });++ await startGeneration(current.id, { providerId: 'vision-api' });+ expect(current.runs.at(-1).feedback).toContain('cross-section check');+ });+it('gives CLI agents a gallery path without passing an API attachment', async () => {getProviderById.mockResolvedValue({id: 'local-agent',diff --git a/server/services/threejsModels/prompt.js b/server/services/threejsModels/prompt.jsindex f5026e5a44..6fed14c763 100644--- a/server/services/threejsModels/prompt.js+++ b/server/services/threejsModels/prompt.js@@ -23,6 +23,15 @@ Choosing between them:- tube — anything sweeping a constant round section along a path: cables, hoses, wires, handles, pipes, straps, springs, antennae, bent rods, rope, rims.- lathe — profiles that are rotationally symmetric about the Y axis.- custom triangles — a last resort, only after none of the above can express the silhouette.++When extrude is the WRONG answer: an unbevelled extrude has exactly two depth planes, so it is+a slab. A body with a real cross-section — a torso, a limb, a head, a housing, a grip, a shell+that swells or tapers through its thickness — must not be one. Build it from primitives, a+lathe, or a tube, or compose several. When only an extrude can express the silhouette of a part+that is not genuinely plate-like, set "bevelEnabled":true with a real bevelThickness/bevelSize,+or add primitives on top of it that give it depth. The same applies to custom triangles: a fan+of points sharing one Z value is a cut-out no matter how many triangles it carries — a custom+mesh standing in for a solid must have depth on every axis.`;const outputContract = `@@ -119,6 +128,7 @@ QUALITY GATE:- Major visible attachments may not float or be omitted.- Identity-priority details must be represented by actual geometry/material choices.- Do not spend custom triangles on a shape extrude, tube, or lathe already expresses.+- A subject that is not genuinely plate-like must not have every identity part flat along one axis: the model has to hold up when it is orbited, not only from the camera you choose.- Include useful ambient/hemisphere fill plus at least one directional/key light.- Keep the full hierarchy at 160 parts or fewer.diff --git a/server/services/threejsModels/prompt.test.js b/server/services/threejsModels/prompt.test.jsindex b513dc0072..90f6da3f59 100644--- a/server/services/threejsModels/prompt.test.js+++ b/server/services/threejsModels/prompt.test.js@@ -23,6 +23,15 @@ describe('buildThreejsGenerationPrompt', () => {expect(build()).toContain('The model must come apart into readable components');});+ it('says when extrude is the WRONG answer and gates on cross-section', () => {+ const prompt = build();+ // Selling extrude for silhouettes without naming its failure mode is how a+ // whole model ends up as a stack of unbevelled slabs.+ expect(prompt).toContain('When extrude is the WRONG answer');+ expect(prompt).toContain('"bevelEnabled":true');+ expect(prompt).toContain('must not have every identity part flat along one axis');+ });+it('carries the reference path, name, and direction into the prompt', () => {const prompt = build({ prompt: 'Match the brass finish.' });expect(prompt).toContain('/tmp/reference.png');