Skip to content

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

flag fused and unbuilt parts in a generated Three.js scene spec ([issue-3481])

[._.]/ Adam Eivy1349edc359e1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 005272a1b0..7ef50ed0cc 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -80,4 +80,6 @@
## Three.js Models
+- **[issue-3481] A generated model now tells you which of its own promises it did not actually build.** The spec check only ever proved that every feature the model listed pointed at a real part — so a spec could name eight defining features, aim all eight at the same box, and still validate clean: one fused mesh wearing a photograph. Each finished generation is now measured against its own inventory and the result is shown on the model's page: features collapsed onto a single shared part, geometry no feature claims, and features nothing was built for at all. Severity follows how much of the subject rides on the miss — a missing defining feature is an error, fine relief folded into the piece it sits on is called out as the correct modeling choice rather than a defect. When you hit Refine without typing your own notes, the refinement pass is now aimed at exactly those errors instead of a generic "improve it." The page states the check's honest limit alongside the findings: it proves the model built what its spec promised, never that the spec promised enough.
+
- **[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.
diff --git a/client/src/pages/ThreejsModelDetail.jsx b/client/src/pages/ThreejsModelDetail.jsx
index 668f83158a..ceccd52c56 100644
--- a/client/src/pages/ThreejsModelDetail.jsx
+++ b/client/src/pages/ThreejsModelDetail.jsx
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from 'react';
-import { ArrowLeft, Box, Code2, Download, LoaderCircle, RefreshCw, Trash2 } from 'lucide-react';
+import { ArrowLeft, Box, Code2, Download, Info, LoaderCircle, RefreshCw, Trash2 } from 'lucide-react';
import { Link, useNavigate, useParams } from 'react-router';
import MediaImage from '../components/MediaImage';
import ProviderModelSelector from '../components/ProviderModelSelector';
@@ -21,6 +21,12 @@ import { timeAgo } from '../utils/formatters';
const providerFilter = (provider) =>
provider.enabled !== false && ['api', 'cli', 'tui'].includes(provider.type);
+const SEVERITY_STYLE = {
+ error: 'border-port-error/40 bg-port-error/10 text-port-error',
+ warning: 'border-port-warning/40 bg-port-warning/10 text-port-warning',
+ note: 'border-port-border bg-port-bg/50 text-gray-400',
+};
+
export default function ThreejsModelDetail() {
const { id } = useParams();
const navigate = useNavigate();
@@ -139,6 +145,7 @@ export default function ThreejsModelDetail() {
const generating = record.status === 'generating' || starting;
const latestRun = Array.isArray(record.runs) ? record.runs[record.runs.length - 1] : null;
+ const coverageFindings = Array.isArray(record.coverage?.findings) ? record.coverage.findings : null;
return (
<div className="mx-auto max-w-7xl space-y-4">
@@ -280,6 +287,40 @@ export default function ThreejsModelDetail() {
</button>
</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
+ ? 'Every promised feature has its own geometry'
+ : `${record.coverage.errorCount} error · ${record.coverage.warningCount} warning · ${record.coverage.noteCount} 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.
+ {record.coverage.errorCount > 0
+ && ' Refining without your own feedback will target the errors above.'}
+ </span>
+ </p>
+ </section>
+ )}
+
{record.spec?.detailInventory?.length > 0 && (
<section className="rounded-xl border border-port-border bg-port-card p-4">
<div className="mb-2 flex items-center justify-between">
diff --git a/server/lib/README.md b/server/lib/README.md
index 4360015c58..4853f15ee9 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -149,6 +149,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. |
| `localImageFilename.js` | `localImageFilename(urlOrPath)` resolves a stored image reference to the bare gallery-image filename under `data/images/` (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (`headshotImageFilename`/`portraitImageFilename`/`coverImageFilename`/`startingImageFilename` are thin wrappers). Also exports `assetBasename(pathOrName)`, the shared strip-querystring→basename primitive (reused by moodBoard's `imageUrlToAppAsset`). |
| `threejsModel.js` | Validated declarative procedural-model schema plus deterministic standalone Three.js factory export for the Three.js Models workspace. |
+| `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. |
| `safetensors.js` | `readSafetensorsHeader(path)` reads only the JSON header of a `.safetensors` file (never the tensor payload). `detectFlux2VariantFromHeader(header)` / `detectFlux2Variant(path)` classify a LoRA as FLUX.2 Klein `'4b'` (hidden dim 3072) vs `'9b'` (4096) by transformer-block tensor shapes, so the LoRA picker can hide off-variant weights that would silently fail to load. |
diff --git a/server/lib/index.js b/server/lib/index.js
index 4a43142229..f0cc44b4e8 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -43,6 +43,7 @@ export * as storyBuilderValidation from './storyBuilderValidation.js';
export * as telegramValidation from './telegramValidation.js';
export * from './validation.js';
export * from './threejsModel.js';
+export * from './threejsModelCoverage.js';
// === Story & narrative ===
export * from './bibleExtractor.js';
diff --git a/server/lib/threejsModelCoverage.js b/server/lib/threejsModelCoverage.js
new file mode 100644
index 0000000000..1225f10c06
--- /dev/null
+++ b/server/lib/threejsModelCoverage.js
@@ -0,0 +1,171 @@
+/**
+ * Assembly-coverage gate for an already-validated Three.js scene spec.
+ *
+ * `threejsSculptSpecSchema` proves that every `detailInventory[].implementationPartIds`
+ * entry names a real part. It never checks the inverse direction, so a spec can
+ * declare eight identity-priority details, point all eight at the same box, or
+ * promise a component it never builds, and still validate cleanly — one fused
+ * mesh wearing a photograph.
+ *
+ * This module reads the parsed spec and reports where the assembly does not back
+ * the inventory. Its honest limit: it proves the model built what the spec
+ * promised, never that the spec promised enough.
+ */
+
+// 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
+ * part's own subtree contains any geometry at all.
+ */
+function flattenParts(parts) {
+ const flat = [];
+ const walk = (part, ancestorIds) => {
+ const children = (part.children || []).map((child) => walk(child, [...ancestorIds, part.id]));
+ const hasGeometry = Boolean(part.geometry);
+ const node = {
+ id: part.id,
+ name: part.name || part.id,
+ ancestorIds,
+ hasGeometry,
+ subtreeHasGeometry: hasGeometry || children.some((child) => child.subtreeHasGeometry),
+ };
+ flat.push(node);
+ return node;
+ };
+ for (const part of parts || []) walk(part, []);
+ 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}}
+ */
+export function evaluateThreejsPartCoverage(spec) {
+ const parts = flattenParts(spec?.parts);
+ const byId = new Map(parts.map((part) => [part.id, part]));
+ const details = Array.isArray(spec?.detailInventory) ? spec.detailInventory : [];
+ const implementedIds = new Set(details.flatMap((detail) => detail.implementationPartIds || []));
+ const label = (id) => byId.get(id)?.name || id;
+ const findings = [];
+
+ // 1. Fusion — details whose ONLY implementing part is the same single part.
+ const soleImplementers = new Map();
+ for (const detail of details) {
+ const ids = detail.implementationPartIds || [];
+ if (ids.length !== 1) continue;
+ const group = soleImplementers.get(ids[0]) || [];
+ group.push(detail);
+ soleImplementers.set(ids[0], group);
+ }
+
+ // Details already accounted for by a shared-part finding, so the folded-relief
+ // pass below cannot report the same detail a second time.
+ const groupedDetails = new Set();
+ for (const [partId, group] of soleImplementers) {
+ if (group.length < 2) continue;
+ for (const detail of group) groupedDetails.add(detail);
+ const ranked = group.filter((detail) => RANKED_PRIORITIES.has(detail.priority));
+ if (ranked.length >= 2) {
+ const features = ranked.map((detail) => detail.feature);
+ findings.push({
+ code: 'fused-parts',
+ severity: 'error',
+ partIds: [partId],
+ features,
+ message: `${features.length} promised features collapsed onto the single part "${label(partId)}" (${listNames(features)}). Build each as its own part instead of one fused mesh.`,
+ });
+ continue;
+ }
+ // At most one ranked feature owns the part and the rest are minor: relief
+ // folded into the piece it rides on. A right answer is not a defect.
+ findings.push({
+ code: 'folded-detail',
+ 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.`,
+ });
+ }
+
+ // 2. Orphan geometry — built but claimed by nobody. An ancestor only launders
+ // attribution downward when it is itself a claimed *mesh*: letting a bare
+ // group count would let one detail on the root claim the entire tree, which is
+ // the fused-model failure this gate exists to catch.
+ const orphans = parts.filter((part) => part.hasGeometry
+ && !implementedIds.has(part.id)
+ && !part.ancestorIds.some((id) => implementedIds.has(id) && byId.get(id)?.hasGeometry));
+ if (orphans.length > 0) {
+ findings.push({
+ code: 'orphan-geometry',
+ 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.`,
+ });
+ }
+
+ // 3. Unbuilt details — a promised feature whose parts contain no geometry
+ // anywhere in their subtrees, so nothing was ever built for it.
+ for (const detail of details) {
+ const resolved = (detail.implementationPartIds || []).map((id) => byId.get(id)).filter(Boolean);
+ if (resolved.length === 0 || resolved.some((part) => part.subtreeHasGeometry)) continue;
+ findings.push({
+ code: 'unbuilt-detail',
+ 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.`,
+ });
+ }
+
+ // 4. Minor detail folded into an implemented mesh above it — reported so the
+ // reviewer sees the modeling decision, never as a defect.
+ for (const detail of details) {
+ if (detail.priority !== 'minor' || groupedDetails.has(detail)) continue;
+ const ids = detail.implementationPartIds || [];
+ if (ids.length !== 1) continue;
+ const part = byId.get(ids[0]);
+ const parentId = part?.ancestorIds.findLast((id) => implementedIds.has(id) && byId.get(id)?.hasGeometry);
+ if (!parentId) continue;
+ findings.push({
+ code: 'folded-detail',
+ severity: 'note',
+ partIds: [part.id],
+ features: [detail.feature],
+ message: `"${detail.feature}" is minor relief on "${label(parentId)}". Folding it into its parent is the correct modeling choice.`,
+ });
+ }
+
+ const countBy = (severity) => findings.filter((finding) => finding.severity === severity).length;
+ return {
+ findings,
+ errorCount: countBy('error'),
+ warningCount: countBy('warning'),
+ noteCount: countBy('note'),
+ };
+}
+
+/**
+ * Default refinement feedback derived from a stored coverage result. Only
+ * error-severity findings are worth spending another provider run on; a spec
+ * with none returns '' so the caller falls back to its own generic wording.
+ */
+export function buildThreejsCoverageFeedback(coverage) {
+ const errors = (coverage?.findings || []).filter((finding) => finding.severity === 'error');
+ if (errors.length === 0) return '';
+ return [
+ 'The previous pass failed the assembly-coverage check. Fix these before anything else:',
+ ...errors.map((finding, index) => `${index + 1}. ${finding.message}`),
+ ].join('\n');
+}
diff --git a/server/lib/threejsModelCoverage.test.js b/server/lib/threejsModelCoverage.test.js
new file mode 100644
index 0000000000..84d8bf3124
--- /dev/null
+++ b/server/lib/threejsModelCoverage.test.js
@@ -0,0 +1,196 @@
+import { describe, expect, it } from 'vitest';
+import { threejsSculptSpecSchema } from './threejsModel.js';
+import { buildThreejsCoverageFeedback, evaluateThreejsPartCoverage } from './threejsModelCoverage.js';
+
+const box = (size = 1) => ({ type: 'box', width: size, height: size, depth: size });
+
+// 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 `children` defaults, unnormalized priorities).
+const makeSpec = ({ parts, detailInventory }) => threejsSculptSpecSchema.parse({
+ schemaVersion: 1,
+ name: 'Example Rig',
+ summary: 'Placeholder spec used to exercise the assembly-coverage gate.',
+ subjectType: 'object',
+ camera: { position: [3, 2, 4] },
+ materials: { shell: { color: '#334455' } },
+ lights: [{ type: 'directional', intensity: 2 }],
+ parts,
+ detailInventory,
+});
+
+const detail = (feature, implementationPartIds, priority) => ({
+ feature,
+ evidence: `${feature} is visible in the reference image.`,
+ implementationPartIds,
+ priority,
+});
+
+const codes = (coverage) => coverage.findings.map((finding) => finding.code);
+
+describe('evaluateThreejsPartCoverage', () => {
+ it('reports nothing when every promised feature has its own geometry', () => {
+ const coverage = evaluateThreejsPartCoverage(makeSpec({
+ parts: [
+ { id: 'hull', name: 'Hull', geometry: box(2), material: 'shell' },
+ { id: 'lens', name: 'Lens', geometry: box(0.4), material: 'shell' },
+ ],
+ detailInventory: [
+ detail('Boxy hull', ['hull'], 'identity'),
+ detail('Recessed lens', ['lens'], 'identity'),
+ ],
+ }));
+
+ expect(coverage.findings).toEqual([]);
+ expect(coverage).toMatchObject({ errorCount: 0, warningCount: 0, noteCount: 0 });
+ });
+
+ it('errors when two identity features collapse onto the same single part', () => {
+ const coverage = evaluateThreejsPartCoverage(makeSpec({
+ parts: [{ id: 'hull', name: 'Hull', geometry: box(2), material: 'shell' }],
+ detailInventory: [
+ detail('Boxy hull', ['hull'], 'identity'),
+ detail('Recessed lens', ['hull'], 'identity'),
+ ],
+ }));
+
+ expect(codes(coverage)).toEqual(['fused-parts']);
+ expect(coverage.errorCount).toBe(1);
+ expect(coverage.findings[0]).toMatchObject({
+ severity: 'error',
+ partIds: ['hull'],
+ features: ['Boxy hull', 'Recessed lens'],
+ });
+ expect(coverage.findings[0].message).toContain('Hull');
+ });
+
+ it('warns about geometry no detail entry claims', () => {
+ const coverage = evaluateThreejsPartCoverage(makeSpec({
+ parts: [
+ { id: 'hull', name: 'Hull', geometry: box(2), material: 'shell' },
+ { id: 'antenna', name: 'Antenna', geometry: box(0.2), material: 'shell' },
+ ],
+ detailInventory: [detail('Boxy hull', ['hull'], 'identity')],
+ }));
+
+ expect(codes(coverage)).toEqual(['orphan-geometry']);
+ expect(coverage.findings[0]).toMatchObject({
+ severity: 'warning',
+ count: 1,
+ partIds: ['antenna'],
+ });
+ expect(coverage.errorCount).toBe(0);
+ });
+
+ it('does not let one detail on a bare group launder the whole tree', () => {
+ const coverage = evaluateThreejsPartCoverage(makeSpec({
+ parts: [{
+ id: 'robot',
+ name: 'Robot',
+ children: [
+ { id: 'head', name: 'Head', geometry: box(0.8), material: 'shell' },
+ { id: 'torso', name: 'Torso', geometry: box(1.4), material: 'shell' },
+ ],
+ }],
+ detailInventory: [detail('Overall robot form', ['robot'], 'identity')],
+ }));
+
+ expect(codes(coverage)).toEqual(['orphan-geometry']);
+ expect(coverage.findings[0].partIds).toEqual(['head', 'torso']);
+ });
+
+ it('treats minor relief folded into its implemented parent as a note, not an error', () => {
+ const coverage = evaluateThreejsPartCoverage(makeSpec({
+ parts: [{
+ id: 'hull',
+ name: 'Hull',
+ geometry: box(2),
+ material: 'shell',
+ children: [{
+ id: 'stria',
+ name: 'Stria',
+ geometry: box(0.05),
+ material: 'shell',
+ explodeWithParent: true,
+ }],
+ }],
+ detailInventory: [
+ detail('Boxy hull', ['hull'], 'identity'),
+ detail('Fine surface stria', ['stria'], 'minor'),
+ ],
+ }));
+
+ expect(codes(coverage)).toEqual(['folded-detail']);
+ expect(coverage).toMatchObject({ errorCount: 0, warningCount: 0, noteCount: 1 });
+ expect(coverage.findings[0].message).toContain('Hull');
+ });
+
+ it('treats a minor detail sharing an identity feature\'s part as a note', () => {
+ const coverage = evaluateThreejsPartCoverage(makeSpec({
+ parts: [{ id: 'hull', name: 'Hull', geometry: box(2), material: 'shell' }],
+ detailInventory: [
+ detail('Boxy hull', ['hull'], 'identity'),
+ detail('Faint scuffing', ['hull'], 'minor'),
+ ],
+ }));
+
+ expect(codes(coverage)).toEqual(['folded-detail']);
+ expect(coverage.errorCount).toBe(0);
+ });
+
+ it('errors on an identity feature whose parts contain no geometry at all', () => {
+ const coverage = evaluateThreejsPartCoverage(makeSpec({
+ parts: [
+ { id: 'hull', name: 'Hull', geometry: box(2), material: 'shell' },
+ { id: 'mast', name: 'Radio mast', children: [{ id: 'mastTip', name: 'Mast tip' }] },
+ ],
+ detailInventory: [
+ detail('Boxy hull', ['hull'], 'identity'),
+ detail('Tall radio mast', ['mast'], 'identity'),
+ ],
+ }));
+
+ expect(codes(coverage)).toEqual(['unbuilt-detail']);
+ expect(coverage.findings[0]).toMatchObject({ severity: 'error', partIds: ['mast'] });
+ });
+
+ it('tiers an unbuilt feature by how much identity rides on it', () => {
+ const build = (priority) => evaluateThreejsPartCoverage(makeSpec({
+ parts: [
+ { id: 'hull', name: 'Hull', geometry: box(2), material: 'shell' },
+ { id: 'mast', name: 'Radio mast' },
+ ],
+ detailInventory: [
+ detail('Boxy hull', ['hull'], 'identity'),
+ detail('Tall radio mast', ['mast'], priority),
+ ],
+ }));
+
+ expect(build('major').findings[0]).toMatchObject({ severity: 'warning' });
+ expect(build('minor').findings[0]).toMatchObject({ severity: 'note' });
+ });
+});
+
+describe('buildThreejsCoverageFeedback', () => {
+ it('returns empty for a missing, clean, or warning-only coverage result', () => {
+ expect(buildThreejsCoverageFeedback(null)).toBe('');
+ expect(buildThreejsCoverageFeedback({ findings: [] })).toBe('');
+ expect(buildThreejsCoverageFeedback({
+ findings: [{ severity: 'warning', message: 'unattributed geometry' }],
+ })).toBe('');
+ });
+
+ it('lists only the error findings for the next refinement pass', () => {
+ const feedback = buildThreejsCoverageFeedback({
+ findings: [
+ { severity: 'error', message: 'two features collapsed onto "Hull"' },
+ { severity: 'warning', message: 'unattributed geometry' },
+ { severity: 'error', message: 'nothing was built for "Radio mast"' },
+ ],
+ });
+
+ expect(feedback).toContain('1. two features collapsed onto "Hull"');
+ expect(feedback).toContain('2. nothing was built for "Radio mast"');
+ expect(feedback).not.toContain('unattributed geometry');
+ });
+});
diff --git a/server/services/threejsModels/db.js b/server/services/threejsModels/db.js
index a331dfe244..9dd4531fdb 100644
--- a/server/services/threejsModels/db.js
+++ b/server/services/threejsModels/db.js
@@ -65,6 +65,10 @@ export async function createModel(input) {
model: input.model || null,
status: 'draft',
spec: null,
+ // Assembly-coverage findings for `spec`, written alongside it by
+ // `evaluateThreejsPartCoverage`. Records written before this field existed
+ // read back as undefined; every consumer treats that as "not evaluated".
+ coverage: null,
error: null,
generationOperationId: null,
runs: [],
diff --git a/server/services/threejsModels/index.js b/server/services/threejsModels/index.js
index aa8bed7f9f..43c05df369 100644
--- a/server/services/threejsModels/index.js
+++ b/server/services/threejsModels/index.js
@@ -9,6 +9,7 @@ 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 { buildThreejsCoverageFeedback, evaluateThreejsPartCoverage } from '../../lib/threejsModelCoverage.js';
import { getProviderById } from '../providers.js';
import { buildThreejsGenerationPrompt } from './prompt.js';
import * as store from './db.js';
@@ -87,6 +88,10 @@ async function executeGeneration({
shapePredicate: (value) => threejsSculptSpecSchema.safeParse(value).success,
});
const spec = threejsSculptSpecSchema.parse(extracted.value);
+ // A structural miss is not a parse failure — a spec that promises more than
+ // 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);
const completedAt = new Date().toISOString();
const effectiveProvider = result.provider?.id || result.fallbackProvider?.id || provider.id;
const effectiveModel = result.model || requestedModel || provider.defaultModel || null;
@@ -99,6 +104,7 @@ async function executeGeneration({
model: effectiveModel,
status: 'ready',
spec,
+ coverage,
error: null,
generationOperationId: null,
generatedAt: completedAt,
@@ -112,6 +118,9 @@ async function executeGeneration({
};
});
console.log(`🧊 Three.js model ready: ${id} (${effectiveProvider}/${effectiveModel || 'default'})`);
+ if (coverage.errorCount > 0) {
+ console.warn(`⚠️ Three.js model ${id} assembly coverage: ${coverage.errorCount} error, ${coverage.warningCount} warning finding(s)`);
+ }
} catch (error) {
console.error(`❌ Three.js model generation failed for ${id}: ${cleanError(error)}`);
await failGeneration(id, operationId, error);
@@ -160,12 +169,16 @@ 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);
const generationPrompt = buildThreejsGenerationPrompt({
sourcePath,
name: current.name,
prompt: effectivePrompt,
currentSpec: current.spec,
- feedback,
+ feedback: effectiveFeedback,
});
const next = await store.mutateModel(id, (fresh) => {
if (fresh.status === 'generating') {
@@ -186,7 +199,7 @@ export async function startGeneration(id, {
status: 'running',
providerId: provider.id,
model: model || provider.defaultModel || null,
- feedback: feedback || null,
+ feedback: effectiveFeedback || null,
startedAt,
completedAt: null,
runId: null,
diff --git a/server/services/threejsModels/index.test.js b/server/services/threejsModels/index.test.js
index 200fcfeba9..83edef17a2 100644
--- a/server/services/threejsModels/index.test.js
+++ b/server/services/threejsModels/index.test.js
@@ -137,6 +137,10 @@ describe('Three.js model generation orchestration', () => {
source: 'threejs-model-generation',
}));
expect(current.spec.name).toBe('Example Beacon');
+ // The body mesh is claimed by no detail entry, so the assembly gate records
+ // it alongside the spec instead of failing an otherwise usable generation.
+ expect(current.coverage).toMatchObject({ errorCount: 0, warningCount: 1 });
+ expect(current.coverage.findings[0]).toMatchObject({ code: 'orphan-geometry', partIds: ['body'] });
expect(current.runs.at(-1)).toMatchObject({
status: 'completed',
runId: 'run-example',
@@ -145,6 +149,55 @@ describe('Three.js model generation orchestration', () => {
});
});
+ it('aims an unsteered refinement at the previous pass coverage errors', async () => {
+ const fusedSpec = {
+ ...spec,
+ detailInventory: [
+ { ...spec.detailInventory[0], implementationPartIds: ['body'] },
+ {
+ feature: 'Ribbed collar',
+ evidence: 'A ribbed collar wraps the reference object.',
+ implementationPartIds: ['body'],
+ priority: 'identity',
+ },
+ ],
+ };
+ let current = {
+ id: 'threejs-fused',
+ name: 'Example Beacon',
+ sourceImage: { filename: 'example.png' },
+ providerId: 'vision-api',
+ model: null,
+ prompt: '',
+ status: 'draft',
+ spec: null,
+ coverage: 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(fusedSpec),
+ runId: 'run-fused',
+ provider: { id: 'vision-api' },
+ model: null,
+ });
+
+ await startGeneration(current.id, { providerId: 'vision-api' });
+ await vi.waitFor(() => expect(current.status).toBe('ready'));
+ expect(current.coverage.errorCount).toBe(1);
+
+ await startGeneration(current.id, { providerId: 'vision-api' });
+ expect(current.runs.at(-1).feedback).toContain('assembly-coverage check');
+ await vi.waitFor(() => expect(runPromptThroughProvider).toHaveBeenLastCalledWith(expect.objectContaining({
+ prompt: expect.stringContaining('collapsed onto the single part'),
+ })));
+ });
+
it('gives CLI agents a gallery path without passing an API attachment', async () => {
getProviderById.mockResolvedValue({
id: 'local-agent',