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

feat: narrow Three.js generation with opt-in subject-family checklists (#3485)

[._.]/ Adam Eivyab0ccdd7fd4e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ab9d6546f1..98b4deab6e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -154,3 +154,5 @@
- **[issue-3531] Deleting an autobiography life story no longer leaves it to be resurrected by your other machines.** Peer sync merged the stories add-only, so a story you deleted on one machine was put straight back by any machine that still had it, on the next sync cycle and every cycle after that — there was no way to permanently remove a story you had written. A delete now records a tombstone against the story, and those tombstones union in both directions, so the machine that still holds the story drops it too rather than the deleting machine merely defending itself while the peer keeps re-sending. The tombstone keys on the story's own id, which is safe here in a way it was not for identity documents: a story id is minted once when the story is written and travels with the record, so every machine knows the same story under the same id. A story that was edited after another machine deleted it is kept rather than reaped — that edit is the user's later word on it — and the now-obsolete tombstone is dropped so it cannot bounce back from a peer that has not seen the edit. A peer running an older build simply ignores the new field and keeps offering its copy; the upgraded machine still refuses it, so nothing is corrupted while the two versions differ. Two neighbouring bugs in the same merge went with it: the list of prompts you have already answered was only checked for having changed *length*, so a list that was merely in a different order than a peer's was never written back in the shared order — leaving two machines with the same prompts computing different checksums and re-syncing that file forever — and a story arriving from a peer without a usable id was filed under a blank key, where a second such story would overwrite it and neither could ever be deleted. Separately, a fresh install's first story read handed back the shared default record by reference, so anything written into it lingered in memory for the next reader; that record is now copied per read.
- **[issue-3507] Opening the Brain graph's search box no longer walks every record on disk.** The graph search index returns nothing but a name and a type per node, but it was building that list by loading the *full* body of every person, project, idea, admin item and memory entry — plus every Daily Log day — and then discarding the summaries, tags and status it had just parsed. Since Brain keeps one file per record, focusing a search input meant thousands of file reads for a dropdown of labels. The index now reads the same in-memory field projections unified search uses, so it costs a scan of memory rather than a walk of the disk, and a Daily Log entry contributes only "is this day non-empty?" instead of its whole text — the biggest body in the Brain never enters the cache at all. The two graph views that genuinely need bodies (the overview and a node's neighborhood) still load them; only the label list changed, and it derives its labels and its skip rules from the same helpers the full-record path uses so the two cannot drift. Nodes come back in the same order as before: the projections are read unranked, so the memory entries in the dropdown stay in store order rather than silently re-sorting themselves newest-first.
+
+- **[issue-3485] Three.js model generation can now be narrowed to a subject family, so the model is judged against a checklist it did not write itself.** The assembly-coverage gate has always carried an honest limit: it proves a spec built everything it promised, never that it promised enough — a component nobody noticed is never inventoried, never specified, and passes every check clean. Picking one of five coarse families (character, vehicle, weapon, building, device) on the create form or the workspace splices a curated checklist into the generation prompt — the components a reconstruction of that family is usually judged on, the material zones worth separating, the axes to judge the result on, and the orbit views that expose the usual failures — and lets the coverage gate warn on a required component the spec never mentions anywhere. That warning feeds the unsteered refinement pass, so "you never accounted for the trigger guard" becomes something the next run is actually told. The checklist is deliberately framed as a floor rather than a ceiling, in the prompt and in the panel: it names the limitations escape hatch for a component the reference genuinely does not show, and it says outright that a spec inventorying only the checklist has under-observed its reference — a thin taxonomy that teaches the model to stop early would be worse than none. Family is optional and defaults to General, which splices nothing at all: an existing model, and anyone who does not pick a family, gets the byte-identical prompt that shipped before this. The workspace renders the chosen family's checklist under the coverage panel with each component marked accounted-for or not, so the orbit views worth checking are next to the preview you would check them in. The field is additive on the record, so no migration is needed and a model generated before this reads back as General; a family id this install does not recognize — from a peer running a newer taxonomy — degrades to no checklist rather than failing the record.
diff --git a/client/src/components/threejsModels/SubjectFamilySelect.jsx b/client/src/components/threejsModels/SubjectFamilySelect.jsx
new file mode 100644
index 0000000000..2d3fc20050
--- /dev/null
+++ b/client/src/components/threejsModels/SubjectFamilySelect.jsx
@@ -0,0 +1,43 @@
+/**
+ * Subject-family picker, shared by the create form and the workspace so the two
+ * cannot drift on labelling or on what an empty taxonomy does. Renders nothing
+ * when the taxonomy could not be fetched — an empty select would look broken,
+ * and generation is perfectly usable without a family.
+ */
+export default function SubjectFamilySelect({
+ id,
+ families,
+ value,
+ onChange,
+ disabled = false,
+ optional = false,
+ showDescription = false,
+ className = '',
+}) {
+ // Returning null (rather than an empty wrapper) is why the spacing lives on
+ // this element: a caller's own margin div would leave a visible gap where the
+ // picker isn't.
+ if (families.length === 0) return null;
+ const description = families.find((option) => option.id === value)?.description;
+ return (
+ <div className={className}>
+ <label htmlFor={id} className="mb-1 block text-xs text-gray-400">
+ Subject family {optional && <span className="text-gray-600">(optional)</span>}
+ </label>
+ <select
+ id={id}
+ value={value}
+ onChange={(event) => onChange(event.target.value)}
+ disabled={disabled}
+ className="w-full rounded-lg border border-port-border bg-port-bg px-3 py-2 text-sm text-white focus:border-port-accent focus:outline-none disabled:opacity-50"
+ >
+ {families.map((option) => (
+ <option key={option.id} value={option.id}>{option.label}</option>
+ ))}
+ </select>
+ {showDescription && description && (
+ <p className="mt-1 text-xs text-gray-500">{description}</p>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 48cc20e2a0..f4f1cf84aa 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -162,6 +162,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useLocalModels` | Live installed Ollama/LM Studio model ids per backend + the server's editorial recommendation. | Model pickers that must show currently-installed local models (not just a provider's stale stored `models`). Fold in via `mergeModelLists` + `localBackendForProvider`. |
| `useVisionModelIds` | `{ idsByProvider, loaded }` — vision-capable model ids the server reports (Ollama `/api/show` + LM Studio `type:'vlm'`), keyed by the provider id that serves them (`{ ollama: Set, lmstudio: Set }`), `null` until fetched; `loaded` flips once the fetch settles. Drops `backend:'cli'` rows (a blanket per-provider claim, not a per-model fact) and never vouches for a provider the server didn't enumerate. | Any VISION model picker — pass `idsByProvider` to `visionLocalModelFilter` / `assignmentModelOptions` so a new multimodal family (`gemma4`) isn't hidden by the stale client id regex, and so an installed VLM shows even when the provider's stored `models` snapshot is stale; gate any "none installed" messaging on `loaded` and on the provider being a local backend. |
| `useTheme` | Dark/light theme + paired-theme switching. | Theme picker. |
+| `useThreejsModelFamilies` | Three.js subject-family checklist options served by `/api/threejs-models/families`; `[]` when the fetch fails, plus the exported `GENERAL_FAMILY_ID` default. | Any surface picking a subject family — the taxonomy is served, never mirrored client-side, so the picker and the generation prompt cannot drift. Hide the picker on an empty list rather than rendering an empty select. |
| `useSingToScore` | Capture a sung melody from the mic and transcribe it into lead-sheet notation. `start()` opens the mic, counts in on the shared metronome, then accumulates a pitch track relative to beat 1; `stop()` runs the `transcribePitchTrack` pipeline (segment → quantize at the song tempo → spell for the key) and returns the lead-sheet body. Exposes `{ phase, beat, result, error, start, stop, reset }`; tears down mic/analyser/tracker/metronome on stop and unmount. | The Song editor's Sing-to-score panel. |
| `useSingToVerify` | Captures a singer from a selected score bar after a one-bar count-in, aligns the pitch track to written-note windows, and exposes `{ phase, beat, rows, error, start, stop, reset, toggleAccept, acceptAll }` for explicit note-by-note correction. Tears down mic/analyser/tracker/metronome on stop and unmount. | The Song editor's Sing-to-verify panel. |
| `useRoundViewParams` | The Round editor's three URL-param views (`?mode=edit`, `?stack=1`, `?analyze=<refId>`) as one hook — every setter `replace`s so flipping surfaces doesn't pile up history. Returns `{ editing, setMode, stackOpen, setStack, analyzeId, setAnalyze }`. | `/rounds/:id`. Add a new Round view here rather than a fourth ad-hoc `useSearchParams` reader. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 786cbdf4cb..32259d12bb 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -64,6 +64,7 @@ export { default as useProviderModels } from './useProviderModels.js';
export { default as useReviewerModelOptions } from './useReviewerModelOptions.js';
export { default as useRowDraft } from './useRowDraft.js';
export { default as useTheme } from './useTheme.js';
+export { default as useThreejsModelFamilies } from './useThreejsModelFamilies.js';
export { default as useUniverse } from './useUniverse.js';
export { default as useUniverseAction } from './useUniverseAction.js';
export { default as useUniverseBucketActions } from './useUniverseBucketActions.js';
diff --git a/client/src/hooks/useThreejsModelFamilies.js b/client/src/hooks/useThreejsModelFamilies.js
new file mode 100644
index 0000000000..969d2a3990
--- /dev/null
+++ b/client/src/hooks/useThreejsModelFamilies.js
@@ -0,0 +1,26 @@
+import { useEffect, useState } from 'react';
+import { listThreejsModelFamilies } from '../services/api';
+
+/**
+ * The default "no checklist" subject family. Mirrors the server id so a form has
+ * a valid value before the taxonomy resolves; the option list itself is always
+ * served rather than mirrored, so the picker and the prompt cannot drift.
+ */
+export const GENERAL_FAMILY_ID = 'general';
+
+/**
+ * The Three.js subject-family options. A failed fetch yields an empty list, and
+ * callers hide the picker rather than rendering an empty select — generation
+ * still works and simply gets the general-purpose prompt.
+ */
+export default function useThreejsModelFamilies() {
+ const [families, setFamilies] = useState([]);
+
+ useEffect(() => {
+ listThreejsModelFamilies({ silent: true })
+ .then((options) => setFamilies(Array.isArray(options) ? options : []))
+ .catch(() => setFamilies([]));
+ }, []);
+
+ return families;
+}
diff --git a/client/src/pages/ThreejsModelDetail.jsx b/client/src/pages/ThreejsModelDetail.jsx
index 3f1ac6ad7c..b40e39e896 100644
--- a/client/src/pages/ThreejsModelDetail.jsx
+++ b/client/src/pages/ThreejsModelDetail.jsx
@@ -1,12 +1,14 @@
import { useEffect, useRef, useState } from 'react';
-import { ArrowLeft, Box, Code2, Download, Info, LoaderCircle, RefreshCw, Trash2 } from 'lucide-react';
+import { ArrowLeft, Box, Check, Code2, Download, Info, LoaderCircle, RefreshCw, Trash2, X } from 'lucide-react';
import { Link, useNavigate, useParams } from 'react-router';
import MediaImage from '../components/MediaImage';
import ProviderModelSelector from '../components/ProviderModelSelector';
+import SubjectFamilySelect from '../components/threejsModels/SubjectFamilySelect';
import ThreejsModelPreview from '../components/threejsModels/ThreejsModelPreview';
import PageSkeleton from '../components/ui/PageSkeleton';
import InlineConfirmRow from '../components/ui/InlineConfirmRow';
import useProviderModels from '../hooks/useProviderModels';
+import useThreejsModelFamilies, { GENERAL_FAMILY_ID } from '../hooks/useThreejsModelFamilies';
import {
deleteThreejsModel,
generateThreejsModel,
@@ -78,6 +80,67 @@ function GatePanel({ title, findings, cleanLabel, footer }) {
);
}
+/**
+ * The chosen subject family's checklist, with each required component marked
+ * resolved or unresolved by the coverage pass, plus the axes and orbit views
+ * worth checking against the live preview above. Snapshotted onto the record at
+ * generation time, so it always describes the spec on screen — not whatever the
+ * taxonomy happens to say today.
+ */
+function FamilyChecklistPanel({ family }) {
+ const missing = new Set(family.missing || []);
+ 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">
+ {family.label} checklist
+ </h2>
+ <span className="text-xs text-gray-600">
+ {missing.size === 0
+ ? 'Every expected component is accounted for'
+ : `${missing.size} of ${family.components.length} unaccounted for`}
+ </span>
+ </div>
+ <ul className="grid gap-1.5 sm:grid-cols-2">
+ {family.components.map((component) => {
+ const unresolved = missing.has(component);
+ return (
+ <li
+ key={component}
+ className={`flex items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs ${
+ unresolved ? SEVERITY_STYLE.warning : 'border-port-border bg-port-bg/50 text-gray-300'
+ }`}
+ >
+ {unresolved
+ ? <X className="mt-0.5 h-3 w-3 shrink-0" />
+ : <Check className="mt-0.5 h-3 w-3 shrink-0 text-port-success" />}
+ <span>{component}</span>
+ </li>
+ );
+ })}
+ </ul>
+ {family.reviewAxes?.length > 0 && (
+ <p className="mt-3 text-[11px] leading-relaxed text-gray-500">
+ <span className="text-gray-400">Judge it on:</span> {family.reviewAxes.join('; ')}.
+ </p>
+ )}
+ {family.orbitViews?.length > 0 && (
+ <p className="mt-1 text-[11px] leading-relaxed text-gray-500">
+ <span className="text-gray-400">Orbit the preview to:</span> {family.orbitViews.join(', ')}.
+ </p>
+ )}
+ <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 list is a floor, not a ceiling — it is what this subject family is usually judged on,
+ not the whole inventory. A component is marked accounted for when the spec names it
+ anywhere, including a limitation explaining the reference does not show it.
+ </span>
+ </p>
+ </section>
+ );
+}
+
export default function ThreejsModelDetail() {
const { id } = useParams();
const navigate = useNavigate();
@@ -87,6 +150,8 @@ export default function ThreejsModelDetail() {
const [feedback, setFeedback] = useState('');
const [starting, setStarting] = useState(false);
const [effort, setEffort] = useState('');
+ const families = useThreejsModelFamilies();
+ const [family, setFamily] = useState(GENERAL_FAMILY_ID);
const [confirmingDelete, setConfirmingDelete] = useState(false);
const providerSyncRef = useRef('');
const {
@@ -155,6 +220,15 @@ export default function ThreejsModelDetail() {
providerSyncRef.current = key;
}, [record, providers, setSelectedProviderId, setSelectedModel]);
+ // Kept out of the provider-sync effect above: the family belongs to the record,
+ // not to the provider, so a record whose provider is gone (or an install with
+ // none configured) must still read its stored family back into the picker.
+ // Re-seeds per record id only, so a user's in-form change survives the
+ // 2s poll while a generation is running.
+ useEffect(() => {
+ setFamily(record?.family || GENERAL_FAMILY_ID);
+ }, [record?.id]);
+
const handleGenerate = async () => {
if (!selectedProviderId || record?.status === 'generating') return;
setStarting(true);
@@ -164,6 +238,9 @@ export default function ThreejsModelDetail() {
// Always sent (as `''` when unset) so picking "Default effort" CLEARS the
// record's stored override instead of silently re-applying it.
effort,
+ // Always sent so switching back to General turns the checklist OFF for
+ // this pass instead of silently re-applying the record's stored family.
+ family,
prompt: record.prompt || '',
feedback: feedback.trim(),
}, { silent: true }).catch((error) => {
@@ -217,6 +294,16 @@ export default function ThreejsModelDetail() {
const coverageFindings = Array.isArray(record.coverage?.findings) ? record.coverage.findings : null;
const flatnessFindings = Array.isArray(record.flatness?.findings) ? record.flatness.findings : null;
const coverageErrors = countSeverities(coverageFindings || []).error;
+ // Only present when the generation ran with a family — a record generated
+ // under `general` (or before families shipped) has no checklist to render.
+ const coverageFamily = Array.isArray(record.coverage?.family?.components)
+ ? record.coverage.family
+ : null;
+ // The record's own family, not the coverage snapshot's — the header should
+ // read the current setting even before the next generation re-runs the gate.
+ const familyLabel = record.family && record.family !== GENERAL_FAMILY_ID
+ ? (families.find((option) => option.id === record.family)?.label || record.family)
+ : '';
return (
<div className="mx-auto max-w-7xl space-y-4">
@@ -237,7 +324,8 @@ export default function ThreejsModelDetail() {
</span>
</div>
<p className="mt-1 text-xs text-gray-500">
- {record.providerId}{record.model ? ` · ${record.model}` : ''}{record.effort ? ` · ${record.effort} effort` : ''} · updated {timeAgo(record.updatedAt)}
+ {record.providerId}{record.model ? ` · ${record.model}` : ''}{record.effort ? ` · ${record.effort} effort` : ''}
+ {familyLabel ? ` · ${familyLabel}` : ''} · updated {timeAgo(record.updatedAt)}
</p>
</div>
<div className="flex items-center gap-2">
@@ -333,6 +421,14 @@ export default function ThreejsModelDetail() {
layout="stacked"
/>
<div>
+ <SubjectFamilySelect
+ id="threejs-family"
+ families={families}
+ value={family}
+ onChange={setFamily}
+ disabled={generating}
+ className="mb-3"
+ />
<label htmlFor="threejs-feedback" className="mb-1 block text-xs text-gray-400">
{record.spec ? 'Refinement feedback' : 'Generation direction'}
</label>
@@ -365,12 +461,16 @@ export default function ThreejsModelDetail() {
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.${
+ footer={`${coverageFamily
+ ? 'This check proves the model built what its own spec promised; the subject-family checklist below is what holds the spec itself to a floor.'
+ : '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.' : ''
}`}
/>
)}
+ {coverageFamily && <FamilyChecklistPanel family={coverageFamily} />}
+
{flatnessFindings && (
<GatePanel
title="Cross-section"
diff --git a/client/src/pages/ThreejsModelDetail.test.jsx b/client/src/pages/ThreejsModelDetail.test.jsx
index 601aa41401..cf79dfab35 100644
--- a/client/src/pages/ThreejsModelDetail.test.jsx
+++ b/client/src/pages/ThreejsModelDetail.test.jsx
@@ -1,4 +1,4 @@
-import { render, screen, waitFor } from '@testing-library/react';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter, Route, Routes } from 'react-router';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import ThreejsModelDetail from './ThreejsModelDetail';
@@ -8,6 +8,7 @@ vi.mock('../services/api', () => ({
generateThreejsModel: vi.fn(),
getThreejsModel: vi.fn(),
getThreejsModelSource: vi.fn(),
+ listThreejsModelFamilies: vi.fn(),
threejsModelSourceUrl: (id) => `/api/threejs-models/${id}/source`,
}));
@@ -32,7 +33,7 @@ vi.mock('../components/threejsModels/ThreejsModelPreview', () => ({
default: () => <div>Model preview</div>,
}));
-import { getThreejsModel } from '../services/api';
+import { generateThreejsModel, getThreejsModel, listThreejsModelFamilies } from '../services/api';
const baseRecord = {
id: 'threejs-example',
@@ -47,6 +48,16 @@ const baseRecord = {
runs: [],
};
+const FAMILY_OPTIONS = [
+ { id: 'general', label: 'General (no checklist)', description: 'One general-purpose prompt.' },
+ { id: 'vehicle', label: 'Vehicle', description: 'Cars, ships, aircraft.' },
+];
+
+const resetMocks = () => {
+ vi.clearAllMocks();
+ listThreejsModelFamilies.mockResolvedValue(FAMILY_OPTIONS);
+};
+
const renderDetail = () => render(
<MemoryRouter initialEntries={['/media/threejs/threejs-example']}>
<Routes>
@@ -56,7 +67,7 @@ const renderDetail = () => render(
);
describe('ThreejsModelDetail assembly coverage', () => {
- beforeEach(() => vi.clearAllMocks());
+ beforeEach(resetMocks);
it('lists the findings, tallies them, and states the gate is not a completeness proof', async () => {
getThreejsModel.mockResolvedValue({
@@ -119,7 +130,7 @@ describe('ThreejsModelDetail assembly coverage', () => {
});
describe('ThreejsModelDetail cross-section gate', () => {
- beforeEach(() => vi.clearAllMocks());
+ beforeEach(resetMocks);
it('lists the flatness finding and says an unsteered refinement will ask for depth', async () => {
getThreejsModel.mockResolvedValue({
@@ -164,3 +175,79 @@ describe('ThreejsModelDetail cross-section gate', () => {
expect(screen.queryByText('Cross-section')).not.toBeInTheDocument();
});
});
+
+describe('ThreejsModelDetail subject family', () => {
+ beforeEach(resetMocks);
+
+ const withFamily = (family) => ({
+ ...baseRecord,
+ family: 'vehicle',
+ coverage: { errorCount: 0, warningCount: 0, noteCount: 0, findings: [], family },
+ });
+
+ it('marks each expected component resolved or not and names the orbit views to check', async () => {
+ getThreejsModel.mockResolvedValue(withFamily({
+ id: 'vehicle',
+ label: 'Vehicle',
+ components: ['Chassis or hull', 'Glazing', 'Lights'],
+ missing: ['Lights'],
+ reviewAxes: ['wheelbase and track proportion'],
+ orbitViews: ['side profile', 'top-down'],
+ }));
+ renderDetail();
+
+ await waitFor(() => expect(screen.getByText('Vehicle checklist')).toBeInTheDocument());
+ expect(screen.getByText('1 of 3 unaccounted for')).toBeInTheDocument();
+ expect(screen.getByText('Lights')).toBeInTheDocument();
+ expect(screen.getByText(/side profile, top-down/)).toBeInTheDocument();
+ expect(screen.getByText(/wheelbase and track proportion/)).toBeInTheDocument();
+ // The floor-not-ceiling framing has to reach the user too — otherwise the
+ // checklist reads as the whole job rather than the minimum.
+ expect(screen.getByText(/floor, not a ceiling/)).toBeInTheDocument();
+ });
+
+ it('reports a fully accounted-for checklist without claiming completeness', async () => {
+ getThreejsModel.mockResolvedValue(withFamily({
+ id: 'vehicle', label: 'Vehicle', components: ['Chassis or hull'], missing: [], reviewAxes: [], orbitViews: [],
+ }));
+ renderDetail();
+
+ await waitFor(() => expect(screen.getByText('Vehicle checklist')).toBeInTheDocument());
+ expect(screen.getByText('Every expected component is accounted for')).toBeInTheDocument();
+ });
+
+ it('hides the checklist for a record generated with no family', async () => {
+ getThreejsModel.mockResolvedValue({
+ ...baseRecord,
+ coverage: { errorCount: 0, warningCount: 0, noteCount: 0, findings: [], family: null },
+ });
+ renderDetail();
+
+ await waitFor(() => expect(screen.getByText('Assembly coverage')).toBeInTheDocument());
+ expect(screen.queryByText(/checklist$/)).not.toBeInTheDocument();
+ // With no family the coverage footer keeps its original honest caveat.
+ expect(screen.getByText(/never that the spec promised enough/)).toBeInTheDocument();
+ });
+
+ it('seeds the picker from the record and sends the family with a refinement', async () => {
+ getThreejsModel.mockResolvedValue({ ...baseRecord, family: 'vehicle' });
+ generateThreejsModel.mockResolvedValue({ ...baseRecord, family: 'general', status: 'generating' });
+ renderDetail();
+
+ // The picker renders as soon as the taxonomy lands and is seeded from the
+ // record a tick later, so the two fetches can resolve in either order.
+ const picker = await screen.findByLabelText('Subject family');
+ await waitFor(() => expect(picker).toHaveValue('vehicle'));
+
+ // Switching back to General must turn the checklist OFF for the next pass
+ // rather than silently re-applying the record's stored family.
+ fireEvent.change(picker, { target: { value: 'general' } });
+ fireEvent.click(screen.getByRole('button', { name: /Refine model/ }));
+
+ await waitFor(() => expect(generateThreejsModel).toHaveBeenCalledWith(
+ 'threejs-example',
+ expect.objectContaining({ family: 'general' }),
+ { silent: true },
+ ));
+ });
+});
diff --git a/client/src/pages/ThreejsModels.jsx b/client/src/pages/ThreejsModels.jsx
index bc6804c2c8..7a23bf6184 100644
--- a/client/src/pages/ThreejsModels.jsx
+++ b/client/src/pages/ThreejsModels.jsx
@@ -6,6 +6,8 @@ import PageSkeleton from '../components/ui/PageSkeleton';
import MediaImage from '../components/MediaImage';
import ProviderModelSelector from '../components/ProviderModelSelector';
import useProviderModels from '../hooks/useProviderModels';
+import SubjectFamilySelect from '../components/threejsModels/SubjectFamilySelect';
+import useThreejsModelFamilies, { GENERAL_FAMILY_ID } from '../hooks/useThreejsModelFamilies';
import { createThreejsModel, listThreejsModels } from '../services/api';
import toast from '../components/ui/Toast';
import { timeAgo, nameFromImageFilename } from '../utils/formatters';
@@ -36,6 +38,8 @@ export default function ThreejsModels() {
));
const [name, setName] = useState(() => nameFromFilename(imageFromRoute));
const [prompt, setPrompt] = useState('');
+ const families = useThreejsModelFamilies();
+ const [family, setFamily] = useState(GENERAL_FAMILY_ID);
const [creating, setCreating] = useState(false);
const {
providers,
@@ -88,6 +92,7 @@ export default function ThreejsModels() {
prompt: prompt.trim(),
providerId: selectedProviderId,
model: selectedModel || undefined,
+ family,
}, { silent: true }).catch((error) => {
toast.error(error.message || 'Failed to start model generation');
return null;
@@ -144,6 +149,15 @@ export default function ThreejsModels() {
className="w-full rounded-lg border border-port-border bg-port-bg px-3 py-2 text-sm text-white placeholder:text-gray-600 focus:border-port-accent focus:outline-none"
/>
</div>
+ <SubjectFamilySelect
+ id="threejs-model-family"
+ families={families}
+ value={family}
+ onChange={setFamily}
+ disabled={creating}
+ optional
+ showDescription
+ />
<div>
<label htmlFor="threejs-model-direction" className="mb-1 block text-xs text-gray-400">
Modeling direction <span className="text-gray-600">(optional)</span>
diff --git a/client/src/pages/ThreejsModels.test.jsx b/client/src/pages/ThreejsModels.test.jsx
index 0bd770f05b..bfff5b9e7b 100644
--- a/client/src/pages/ThreejsModels.test.jsx
+++ b/client/src/pages/ThreejsModels.test.jsx
@@ -5,6 +5,7 @@ import ThreejsModels from './ThreejsModels';
vi.mock('../services/api', () => ({
createThreejsModel: vi.fn(),
+ listThreejsModelFamilies: vi.fn(),
listThreejsModels: vi.fn(),
}));
@@ -35,16 +36,22 @@ vi.mock('../components/imageGen/GalleryImagePicker', () => ({
) : null,
}));
-import { createThreejsModel, listThreejsModels } from '../services/api';
+import { createThreejsModel, listThreejsModelFamilies, listThreejsModels } from '../services/api';
function LocationProbe() {
return <output aria-label="Current query">{useLocation().search}</output>;
}
+const FAMILY_OPTIONS = [
+ { id: 'general', label: 'General (no checklist)', description: 'One general-purpose prompt.' },
+ { id: 'vehicle', label: 'Vehicle', description: 'Cars, ships, aircraft.' },
+];
+
describe('ThreejsModels', () => {
beforeEach(() => {
vi.clearAllMocks();
listThreejsModels.mockResolvedValue([]);
+ listThreejsModelFamilies.mockResolvedValue(FAMILY_OPTIONS);
});
it('starts a model from a gallery deep link and navigates to its workspace', async () => {
@@ -70,10 +77,55 @@ describe('ThreejsModels', () => {
prompt: 'Keep the antenna articulated.',
providerId: 'vision-api',
model: 'vision-pro',
+ family: 'general',
}, { silent: true }));
expect(await screen.findByText('Model workspace opened')).toBeInTheDocument();
});
+ it('sends the chosen subject family and shows what it narrows to', async () => {
+ createThreejsModel.mockResolvedValue({ id: 'threejs-example', status: 'generating' });
+ render(
+ <MemoryRouter initialEntries={['/media/threejs?image=example-robot.png']}>
+ <Routes>
+ <Route path="/media/threejs" element={<ThreejsModels />} />
+ <Route path="/media/threejs/:id" element={<div>Model workspace opened</div>} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ const picker = await screen.findByLabelText(/Subject family/);
+ fireEvent.change(picker, { target: { value: 'vehicle' } });
+ expect(screen.getByText('Cars, ships, aircraft.')).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Generate model' }));
+
+ await waitFor(() => expect(createThreejsModel).toHaveBeenCalledWith(
+ expect.objectContaining({ family: 'vehicle' }),
+ { silent: true },
+ ));
+ });
+
+ it('hides the family picker rather than showing an empty select when the fetch fails', async () => {
+ // Creation must still work — it simply gets the general-purpose prompt.
+ listThreejsModelFamilies.mockRejectedValue(new Error('offline'));
+ createThreejsModel.mockResolvedValue({ id: 'threejs-example', status: 'generating' });
+ render(
+ <MemoryRouter initialEntries={['/media/threejs?image=example-robot.png']}>
+ <Routes>
+ <Route path="/media/threejs" element={<ThreejsModels />} />
+ <Route path="/media/threejs/:id" element={<div>Model workspace opened</div>} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ await waitFor(() => expect(listThreejsModelFamilies).toHaveBeenCalled());
+ expect(screen.queryByLabelText(/Subject family/)).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Generate model' }));
+ await waitFor(() => expect(createThreejsModel).toHaveBeenCalledWith(
+ expect.objectContaining({ family: 'general' }),
+ { silent: true },
+ ));
+ });
+
it('keeps a newly picked gallery image in the shareable URL', async () => {
render(
<MemoryRouter initialEntries={['/media/threejs?image=example-robot.png']}>
diff --git a/client/src/services/README.md b/client/src/services/README.md
index 5564f482c1..ebae8b76d3 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -101,7 +101,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiMusicVideo.js` | Music Video projects + scene board + audio analysis. |
| `apiSprites.js` | Sprite Manager records, asset library, production-set import (#2895), reference workflow: create/generate/lock (#2896), directional walk and per-track generation/approval, animation-type definition CRUD (#3153), trim/postprocess, and per-run source-frame listing for the Loop Trimmer's re-derive (#2980). |
| `apiShell.js` | Shell sessions over HTTP: hand a photo (plus a message) to the agent TUI running in a session. Keystrokes/output stay on the `shell:*` socket protocol. |
-| `apiThreejsModels.js` | Procedural Three.js model workspaces: gallery-image generation, refinement, source export, and deletion. |
+| `apiThreejsModels.js` | Procedural Three.js model workspaces: gallery-image generation, refinement, source export, deletion, and the subject-family checklist options. |
| `apiImageTo3d.js` | Image-to-3D (`/3d`): selectable targets (TRELLIS.2) with host availability/install status, and per-image model records — create/list/get/generate/delete + GLB asset URL. |
| `apiPipeline.js` | Pipeline (issues + stages + canon). |
| `apiUniverseBuilder.js` | Universe Builder (generate + edit + commit). |
diff --git a/client/src/services/apiThreejsModels.js b/client/src/services/apiThreejsModels.js
index 0690a2d61f..06bcc552fd 100644
--- a/client/src/services/apiThreejsModels.js
+++ b/client/src/services/apiThreejsModels.js
@@ -2,6 +2,8 @@ import { request } from './apiCore.js';
export const listThreejsModels = (options) => request('/threejs-models', options);
+export const listThreejsModelFamilies = (options) => request('/threejs-models/families', options);
+
export const getThreejsModel = (id, options) =>
request(`/threejs-models/${encodeURIComponent(id)}`, options);
diff --git a/server/lib/README.md b/server/lib/README.md
index cfa9f4a9d4..ea54e01ad6 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -150,7 +150,8 @@ 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. Also the cross-section gate: `evaluateThreejsFlatness(spec)` counts distinct vertex planes per axis — relative to the mesh's own size, with a rotation-invariant zero-volume check behind it — and treats an `extrude` with no bevel thickness as the two-plane slab it is to report when the majority of identity-priority features are built only from flat parts — a model that reads right head-on and like cardboard when orbited. `buildThreejsFlatnessFeedback(flatness)` turns that into default refinement feedback; `listSpecNames(names)` is the shared capped name-list formatter both gates use in finding messages. |
-| `threejsModelCoverage.js` | `evaluateThreejsPartCoverage(spec)` — structural assembly gate over an already-validated Three.js spec: flags promised features fused onto the same part set, geometry claimed by no detail, and details nothing was built for (folded minor relief stays a `note`). `buildThreejsCoverageFeedback(coverage)` turns the error findings into default refinement feedback. |
+| `threejsModelCoverage.js` | `evaluateThreejsPartCoverage(spec, { family })` — structural assembly gate over an already-validated Three.js spec: flags promised features fused onto the same part set, geometry claimed by no detail, and details nothing was built for (folded minor relief stays a `note`). With a subject family it also warns on a required component the spec never mentions at all — the one check that can fault a spec for what it failed to *promise*. `buildThreejsCoverageFeedback(coverage)` turns the error findings (plus any family gap) into default refinement feedback. |
+| `threejsModelFamilies.js` | Curated subject-family checklists for Three.js generation. `THREEJS_MODEL_FAMILY_OPTIONS` / `THREEJS_MODEL_FAMILY_IDS` drive the picker and route validation; `buildThreejsFamilyChecklist(id)` returns the prompt block spliced into generation (`''` for the default `general`, so an un-narrowed subject keeps the unchanged general-purpose prompt); `findMissingFamilyComponents(spec, id)` reports which required components the spec never mentions. |
| `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 38ba201e81..79b80e2c56 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -44,6 +44,7 @@ export * as telegramValidation from './telegramValidation.js';
export * from './validation.js';
export * from './threejsModel.js';
export * from './threejsModelCoverage.js';
+export * from './threejsModelFamilies.js';
// === Story & narrative ===
export * from './bibleExtractor.js';
diff --git a/server/lib/threejsModelCoverage.js b/server/lib/threejsModelCoverage.js
index f20d51b8d4..96c9ab956e 100644
--- a/server/lib/threejsModelCoverage.js
+++ b/server/lib/threejsModelCoverage.js
@@ -9,10 +9,18 @@
*
* 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.
+ * promised, never that the spec promised enough — a component nobody noticed is
+ * never promised and so never missed.
+ *
+ * A chosen subject family is the one lever against that limit: it supplies an
+ * external list of components the spec is expected to resolve, so the gate can
+ * fail a spec that never mentioned the trigger guard rather than only a build
+ * that skipped it. That check runs ONLY when the user picked a family; with none
+ * (the default) this module behaves exactly as it did before families existed.
*/
import { listSpecNames } from './threejsModel.js';
+import { findMissingFamilyComponents } from './threejsModelFamilies.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
@@ -46,9 +54,10 @@ function flattenParts(parts) {
/**
* @param {object} spec a spec that has already passed `threejsSculptSpecSchema`
- * @returns {{findings: Array, errorCount: number, warningCount: number, noteCount: number}}
+ * @param {{family?: string|null}} [options] the subject family the user chose, if any
+ * @returns {{findings: Array, errorCount: number, warningCount: number, noteCount: number, family: object|null}}
*/
-export function evaluateThreejsPartCoverage(spec) {
+export function evaluateThreejsPartCoverage(spec, { family = null } = {}) {
const parts = flattenParts(spec?.parts);
const byId = new Map(parts.map((part) => [part.id, part]));
const details = Array.isArray(spec?.detailInventory) ? spec.detailInventory : [];
@@ -197,25 +206,62 @@ export function evaluateThreejsPartCoverage(spec) {
findings.push(...foldedNotes);
+ // 5. Family gap — a component the chosen family says a faithful reconstruction
+ // has to resolve, which the spec never mentions anywhere: not in the inventory,
+ // not in a part name, not even in limitations as something the reference does
+ // not show. This is the one check that can fault a spec for what it failed to
+ // promise, and it is a `warning` rather than an `error` precisely because the
+ // evidence is a substring match — over-claiming here would make the whole gate
+ // less trustworthy than the gap it closes.
+ const familyResult = findMissingFamilyComponents(spec, family);
+ if (familyResult?.missing.length > 0) {
+ findings.push({
+ code: 'missing-family-component',
+ severity: 'warning',
+ components: familyResult.missing,
+ message: `${familyResult.missing.length} component(s) the ${familyResult.family.label.toLowerCase()} checklist expects are not mentioned anywhere in the spec (${listSpecNames(familyResult.missing)}). Build each one, or say in limitations why the reference does not show it.`,
+ });
+ }
+
const countBy = (severity) => findings.filter((finding) => finding.severity === severity).length;
return {
findings,
errorCount: countBy('error'),
warningCount: countBy('warning'),
noteCount: countBy('note'),
+ // Snapshotted onto the record so the detail page can render the checklist
+ // (and which items are unresolved) without re-deriving the taxonomy client
+ // side. `null` when no family applies — distinct from a family with nothing
+ // missing, which is `missing: []`.
+ family: familyResult
+ ? {
+ id: familyResult.family.id,
+ label: familyResult.family.label,
+ components: familyResult.family.components.map((component) => component.name),
+ missing: familyResult.missing,
+ reviewAxes: familyResult.family.reviewAxes,
+ orbitViews: familyResult.family.orbitViews,
+ }
+ : null,
};
}
/**
* 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.
+ * error-severity findings are worth spending another provider run on — plus the
+ * family gap, which is a `warning` only because its evidence is textual, not
+ * because it matters less: an unmentioned required component is exactly the
+ * defect a refinement pass should be told about, and nothing else in the loop
+ * will ever surface it. A spec with neither 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 '';
+ const actionable = (coverage?.findings || []).filter((finding) => (
+ finding.severity === 'error' || finding.code === 'missing-family-component'
+ ));
+ if (actionable.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}`),
+ ...actionable.map((finding, index) => `${index + 1}. ${finding.message}`),
].join('\n');
}
diff --git a/server/lib/threejsModelCoverage.test.js b/server/lib/threejsModelCoverage.test.js
index 947ffe3d64..30a5790525 100644
--- a/server/lib/threejsModelCoverage.test.js
+++ b/server/lib/threejsModelCoverage.test.js
@@ -434,6 +434,67 @@ describe('evaluateThreejsPartCoverage', () => {
});
});
+describe('subject-family coverage', () => {
+ // A clean, ordinary spec: one mesh, one detail pointing at it. Nothing here
+ // trips any of the structural checks, so a family finding stands alone.
+ const cleanSpec = () => makeSpec({
+ parts: [{ id: 'hull', name: 'Hull', geometry: box(2), material: 'shell' }],
+ detailInventory: [detail('Boxy hull', ['hull'], 'identity')],
+ });
+
+ it('adds nothing at all when no family is chosen', () => {
+ const coverage = evaluateThreejsPartCoverage(cleanSpec());
+ expect(codes(coverage)).not.toContain('missing-family-component');
+ // `null` rather than an empty snapshot, so the detail page can tell "no
+ // family" apart from "a family with nothing missing".
+ expect(coverage.family).toBeNull();
+ expect(evaluateThreejsPartCoverage(cleanSpec(), { family: 'general' }).family).toBeNull();
+ });
+
+ it('warns on components the spec never mentions and snapshots the checklist', () => {
+ const coverage = evaluateThreejsPartCoverage(cleanSpec(), { family: 'vehicle' });
+ const finding = coverage.findings.find((item) => item.code === 'missing-family-component');
+ // Warning, never error: the evidence is a substring match, and a gate that
+ // over-claims is worse than the gap it closes.
+ expect(finding.severity).toBe('warning');
+ expect(finding.components).toContain('Cockpit or cabin');
+ // "Chassis or hull" is satisfied by the part named "Hull", proving the
+ // haystack really does read part names and not just the inventory.
+ expect(finding.components).not.toContain('Chassis or hull');
+ expect(coverage.family).toMatchObject({ id: 'vehicle', label: 'Vehicle' });
+ expect(coverage.family.missing).toEqual(finding.components);
+ expect(coverage.family.orbitViews.length).toBeGreaterThan(0);
+ expect(coverage.warningCount).toBeGreaterThan(0);
+ });
+
+ it('records a family with nothing missing as an empty miss list, not as absent', () => {
+ const parts = [
+ { id: 'grip', name: 'Wrapped grip', geometry: box(1), material: 'shell' },
+ { id: 'blade', name: 'Blade', geometry: box(1), material: 'shell' },
+ { id: 'guard', name: 'Crossguard', geometry: box(1), material: 'shell' },
+ { id: 'pommel', name: 'Pommel', geometry: box(1), material: 'shell' },
+ { id: 'pins', name: 'Handle pins', geometry: box(1), material: 'shell' },
+ { id: 'latch', name: 'Release catch', geometry: box(1), material: 'shell' },
+ { id: 'sight', name: 'Alignment notch', geometry: box(1), material: 'shell' },
+ { id: 'ring', name: 'Lanyard ring', geometry: box(1), material: 'shell' },
+ ];
+ const coverage = evaluateThreejsPartCoverage(makeSpec({
+ parts,
+ detailInventory: parts.map((part) => detail(part.name, [part.id], 'major')),
+ }), { family: 'weapon' });
+
+ expect(codes(coverage)).not.toContain('missing-family-component');
+ expect(coverage.family).toMatchObject({ id: 'weapon', missing: [] });
+ });
+
+ it('degrades an unknown family id to no checklist instead of throwing', () => {
+ // A record synced from a peer running a newer taxonomy must still evaluate.
+ const coverage = evaluateThreejsPartCoverage(cleanSpec(), { family: 'kaiju-mecha-hybrid' });
+ expect(coverage.family).toBeNull();
+ expect(codes(coverage)).not.toContain('missing-family-component');
+ });
+});
+
describe('buildThreejsCoverageFeedback', () => {
it('returns empty for a missing, clean, or warning-only coverage result', () => {
expect(buildThreejsCoverageFeedback(null)).toBe('');
@@ -443,6 +504,19 @@ describe('buildThreejsCoverageFeedback', () => {
})).toBe('');
});
+ it('carries the family gap into refinement even though it is only a warning', () => {
+ // Nothing else in the loop will ever surface an under-observed component —
+ // if this warning does not reach the next pass, the checklist buys nothing.
+ const feedback = buildThreejsCoverageFeedback({
+ findings: [
+ { severity: 'warning', code: 'orphan-geometry', message: 'unattributed geometry' },
+ { severity: 'warning', code: 'missing-family-component', message: '3 component(s) are not mentioned' },
+ ],
+ });
+ expect(feedback).toContain('1. 3 component(s) are not mentioned');
+ expect(feedback).not.toContain('unattributed geometry');
+ });
+
it('lists only the error findings for the next refinement pass', () => {
const feedback = buildThreejsCoverageFeedback({
findings: [
diff --git a/server/lib/threejsModelFamilies.js b/server/lib/threejsModelFamilies.js
new file mode 100644
index 0000000000..25fc3126e2
--- /dev/null
+++ b/server/lib/threejsModelFamilies.js
@@ -0,0 +1,261 @@
+/**
+ * Subject-family checklists for Three.js model generation.
+ *
+ * `evaluateThreejsPartCoverage` proves a spec built what it promised, never that
+ * it promised enough — a component nobody noticed is never inventoried, never
+ * specified, and passes every structural gate. A family checklist closes that
+ * direction: for a coarse subject family, the components a faithful
+ * reconstruction has to account for, the material zones worth separating, the
+ * axes a reviewer should judge, and the orbit views that expose the usual
+ * failures.
+ *
+ * The cost of a taxonomy is that a THIN one is worse than none — it teaches the
+ * model to stop at the checklist. Two things hold that off:
+ *
+ * 1. `general` is the default and splices nothing, so a user who does not opt in
+ * gets exactly the general-purpose prompt that shipped before this existed.
+ * 2. Every spliced block says outright that the list is a floor, that the
+ * inventory must still carry everything else visible, and that a component
+ * genuinely absent from the reference belongs in `limitations` with a reason.
+ *
+ * Families are deliberately coarse and few. A component is matched textually
+ * against the spec's own words, so the resulting findings are `warning`, never
+ * `error` — the gate should not claim certainty a substring match cannot carry.
+ */
+
+/** The no-op family. Selecting it (or nothing) leaves generation unchanged. */
+export const GENERAL_FAMILY_ID = 'general';
+
+/**
+ * @typedef {object} ThreejsModelFamily
+ * @property {string} id stable id persisted on the record
+ * @property {string} label human label for the picker
+ * @property {string} description one line telling the user when to pick it
+ * @property {Array<{name: string, aliases: string[]}>} components required components; `aliases` are
+ * the lowercase substrings that count as evidence the component was accounted for
+ * @property {string[]} materialZones surfaces worth separating into their own material
+ * @property {string[]} reviewAxes what a reviewer should judge the result on
+ * @property {string[]} orbitViews the camera angles worth checking before accepting the model
+ */
+
+/** @type {ThreejsModelFamily[]} */
+const FAMILY_DEFINITIONS = [
+ {
+ id: 'character',
+ label: 'Character / creature',
+ description: 'Humanoids, animals, and creatures — anything with a body plan and articulation.',
+ components: [
+ { name: 'Head', aliases: ['head', 'skull', 'cranium', 'muzzle', 'snout'] },
+ { name: 'Eyes', aliases: ['eye', 'eyes', 'iris', 'pupil', 'eyeball', 'visor'] },
+ { name: 'Torso', aliases: ['torso', 'chest', 'body', 'trunk', 'abdomen', 'ribcage'] },
+ { name: 'Upper limbs', aliases: ['arm', 'arms', 'foreleg', 'forelimb', 'wing', 'shoulder', 'tentacle'] },
+ { name: 'Hands or paws', aliases: ['hand', 'hands', 'paw', 'claw', 'finger', 'gauntlet', 'talon'] },
+ { name: 'Lower limbs', aliases: ['leg', 'legs', 'hindleg', 'hindlimb', 'thigh', 'shin', 'haunch'] },
+ { name: 'Feet or hooves', aliases: ['foot', 'feet', 'hoof', 'boot', 'shoe', 'toe'] },
+ { name: 'Hair, fur, or headwear', aliases: ['hair', 'fur', 'mane', 'helmet', 'hat', 'hood', 'crest', 'horn'] },
+ { name: 'Clothing or surface covering', aliases: ['cloth', 'shirt', 'coat', 'armor', 'armour', 'scale', 'skin', 'hide', 'plate', 'garment', 'robe'] },
+ { name: 'Articulation joints', aliases: ['joint', 'elbow', 'knee', 'hip', 'wrist', 'ankle', 'neck', 'pivot', 'socket'] },
+ ],
+ materialZones: ['skin or hide', 'hair or fur', 'eyes', 'clothing or armor', 'metal fittings'],
+ reviewAxes: [
+ 'head-to-body proportion',
+ 'limb length and articulation direction',
+ 'facial landmark placement and spacing',
+ 'silhouette readability at a distance',
+ ],
+ orbitViews: ['front', 'three-quarter', 'strict profile', 'back'],
+ },
+ {
+ id: 'vehicle',
+ label: 'Vehicle',
+ description: 'Cars, ships, aircraft, mechs, and anything else built to carry and move.',
+ components: [
+ { name: 'Chassis or hull', aliases: ['chassis', 'hull', 'frame', 'fuselage', 'body', 'monocoque'] },
+ { name: 'Body panels', aliases: ['panel', 'fender', 'hood', 'bonnet', 'door', 'bumper', 'skirt', 'cowl'] },
+ { name: 'Ground contact or propulsion', aliases: ['wheel', 'tire', 'tyre', 'track', 'thruster', 'engine', 'propeller', 'rotor', 'rudder', 'leg'] },
+ { name: 'Cockpit or cabin', aliases: ['cockpit', 'cabin', 'seat', 'interior', 'dashboard', 'bridge'] },
+ { name: 'Glazing', aliases: ['window', 'windshield', 'windscreen', 'canopy', 'glass', 'porthole', 'viewport'] },
+ { name: 'Lights', aliases: ['light', 'headlamp', 'headlight', 'lamp', 'beacon', 'taillight'] },
+ { name: 'Intakes or exhaust', aliases: ['intake', 'exhaust', 'vent', 'grille', 'grill', 'nozzle', 'muffler'] },
+ { name: 'Protrusions and hardware', aliases: ['mirror', 'antenna', 'aerial', 'handle', 'rail', 'wing', 'spoiler', 'fin', 'mast'] },
+ { name: 'Suspension or landing gear', aliases: ['suspension', 'axle', 'strut', 'landing gear', 'skid', 'shock', 'spring'] },
+ ],
+ materialZones: ['painted bodywork', 'glazing', 'tire rubber or tread', 'bare or chromed metal', 'emissive lamps'],
+ reviewAxes: [
+ 'wheelbase and track proportion',
+ 'ground clearance and stance',
+ 'panel gap and seam continuity',
+ 'how deeply the glazing sits in its frame',
+ ],
+ orbitViews: ['front three-quarter', 'side profile', 'rear three-quarter', 'top-down'],
+ },
+ {
+ id: 'weapon',
+ label: 'Weapon / handheld tool',
+ description: 'Blades, firearms, staves, and hand tools — anything gripped and wielded.',
+ components: [
+ { name: 'Grip or handle', aliases: ['grip', 'handle', 'haft', 'hilt', 'shaft', 'stock', 'wrap'] },
+ { name: 'Working end', aliases: ['blade', 'edge', 'head', 'barrel', 'tip', 'point', 'bit', 'muzzle', 'prong'] },
+ { name: 'Guard or bolster', aliases: ['guard', 'bolster', 'crossguard', 'quillon', 'ferrule', 'collar', 'hand guard'] },
+ { name: 'Pommel or butt', aliases: ['pommel', 'butt', 'cap', 'counterweight', 'heel', 'end cap'] },
+ { name: 'Fasteners', aliases: ['pin', 'rivet', 'screw', 'bolt', 'peg', 'binding', 'lashing'] },
+ { name: 'Actuator or mechanism', aliases: ['trigger', 'lever', 'catch', 'latch', 'hammer', 'bolt', 'switch', 'release'] },
+ { name: 'Sights or alignment features', aliases: ['sight', 'scope', 'notch', 'bead', 'rail', 'aperture'] },
+ { name: 'Carry points', aliases: ['sling', 'lanyard', 'strap', 'loop', 'ring', 'swivel', 'sheath'] },
+ ],
+ materialZones: ['working metal', 'grip material', 'fittings and furniture', 'worn or polished edges'],
+ reviewAxes: [
+ 'grip length against the working end',
+ 'edge or bore geometry',
+ 'implied balance point',
+ 'clearance for a real hand on the grip',
+ ],
+ orbitViews: ['broad profile', 'edge-on', 'three-quarter', 'close orbit on the grip'],
+ },
+ {
+ id: 'architecture',
+ label: 'Building / structure',
+ description: 'Buildings, towers, bridges, and built environments.',
+ components: [
+ { name: 'Base or foundation', aliases: ['base', 'foundation', 'plinth', 'footing', 'podium', 'ground', 'slab'] },
+ { name: 'Walls', aliases: ['wall', 'facade', 'façade', 'cladding', 'siding', 'masonry', 'panel'] },
+ { name: 'Roof', aliases: ['roof', 'eave', 'gable', 'dome', 'parapet', 'shingle', 'ridge'] },
+ { name: 'Doors', aliases: ['door', 'doorway', 'entrance', 'gate', 'portal', 'threshold'] },
+ { name: 'Windows', aliases: ['window', 'glazing', 'pane', 'sill', 'shutter', 'mullion'] },
+ { name: 'Vertical supports', aliases: ['column', 'pillar', 'post', 'pier', 'buttress', 'beam', 'truss'] },
+ { name: 'Circulation', aliases: ['stair', 'step', 'ramp', 'ladder', 'balcony', 'walkway', 'porch'] },
+ { name: 'Railings and trim', aliases: ['rail', 'railing', 'balustrade', 'cornice', 'molding', 'moulding', 'trim', 'fascia'] },
+ { name: 'Roofline hardware', aliases: ['chimney', 'vent', 'duct', 'antenna', 'aerial', 'spire', 'gutter', 'downspout'] },
+ { name: 'Signage or markings', aliases: ['sign', 'signage', 'lettering', 'plaque', 'banner', 'number', 'awning'] },
+ ],
+ materialZones: ['wall cladding', 'roofing', 'glazing', 'trim and joinery', 'ground or paving'],
+ reviewAxes: [
+ 'floor-height against overall mass',
+ 'rhythm and alignment of openings',
+ 'roof pitch and overhang depth',
+ 'how deep the window and door reveals sit',
+ ],
+ orbitViews: ['front elevation', 'corner three-quarter', 'rear', 'top-down massing'],
+ },
+ {
+ id: 'device',
+ label: 'Device / machine',
+ description: 'Electronics, appliances, instruments, and mechanisms with controls and an enclosure.',
+ components: [
+ { name: 'Enclosure', aliases: ['housing', 'enclosure', 'case', 'casing', 'shell', 'chassis', 'body', 'cabinet'] },
+ { name: 'Seams and panel lines', aliases: ['seam', 'panel line', 'split line', 'joint', 'gap', 'parting', 'panel'] },
+ { name: 'Display or indicator', aliases: ['display', 'screen', 'lcd', 'led', 'indicator', 'dial', 'gauge', 'readout', 'lamp'] },
+ { name: 'Controls', aliases: ['button', 'knob', 'switch', 'dial', 'slider', 'lever', 'key', 'trigger', 'wheel'] },
+ { name: 'Ports or connectors', aliases: ['port', 'connector', 'jack', 'socket', 'plug', 'terminal', 'receptacle'] },
+ { name: 'Vents or cooling', aliases: ['vent', 'grille', 'grill', 'louver', 'fan', 'slot', 'mesh', 'heatsink'] },
+ { name: 'Cabling', aliases: ['cable', 'cord', 'wire', 'hose', 'lead', 'harness', 'strain relief'] },
+ { name: 'Fasteners', aliases: ['screw', 'bolt', 'rivet', 'clip', 'latch', 'fastener', 'hinge'] },
+ { name: 'Feet or mounting', aliases: ['foot', 'feet', 'stand', 'bracket', 'mount', 'pad', 'base', 'handle'] },
+ { name: 'Branding or labelling', aliases: ['label', 'badge', 'logo', 'plate', 'marking', 'lettering', 'decal', 'sticker'] },
+ ],
+ materialZones: ['housing shell', 'screen glass', 'control caps', 'metal trim', 'emissive indicators'],
+ reviewAxes: [
+ 'control spacing and reachability',
+ 'seam continuity around the enclosure',
+ 'port alignment along its face',
+ 'bezel thickness around the display',
+ ],
+ orbitViews: ['front', 'three-quarter', 'rear where the ports live', 'underside'],
+ },
+];
+
+/** Every family a record may store, `general` first. */
+export const THREEJS_MODEL_FAMILIES = FAMILY_DEFINITIONS;
+
+/**
+ * Picker options, including `general`. The general entry carries no checklist —
+ * it exists so "no narrowing" is an explicit, labelled choice rather than a
+ * blank in the form.
+ */
+export const THREEJS_MODEL_FAMILY_OPTIONS = [
+ {
+ id: GENERAL_FAMILY_ID,
+ label: 'General (no checklist)',
+ description: 'One general-purpose prompt. The inventory is bounded only by what the model notices.',
+ },
+ ...FAMILY_DEFINITIONS.map(({ id, label, description }) => ({ id, label, description })),
+];
+
+export const THREEJS_MODEL_FAMILY_IDS = [
+ GENERAL_FAMILY_ID,
+ ...FAMILY_DEFINITIONS.map((family) => family.id),
+];
+
+/**
+ * The family definition for an id, or `null` for `general`, an absent value, and
+ * an id this install no longer ships. A record written by a newer peer or an
+ * older taxonomy must degrade to "no checklist" rather than throwing — the
+ * stored spec is still perfectly renderable without one.
+ */
+export function getThreejsModelFamily(familyId) {
+ if (!familyId || familyId === GENERAL_FAMILY_ID) return null;
+ return FAMILY_DEFINITIONS.find((family) => family.id === familyId) || null;
+}
+
+/**
+ * The prompt block spliced into generation when a family is chosen. Returns ''
+ * for `general` so the caller emits nothing at all.
+ */
+export function buildThreejsFamilyChecklist(familyId) {
+ const family = getThreejsModelFamily(familyId);
+ if (!family) return '';
+ const components = family.components.map((component) => `- ${component.name}`).join('\n');
+ return `SUBJECT FAMILY — ${family.label}:
+The user classified this subject as a ${family.label.toLowerCase()}. The list below is a FLOOR, not a
+ceiling. It is the set of components a reconstruction of this family is usually judged on, so each one
+must be resolved before you finish — but it is not the inventory. Everything else visible in the
+reference still belongs in detailInventory exactly as it would without this list, and a subject with
+components this list does not name is the normal case, not an exception.
+
+Required components — for each, either build it as real geometry and name it in detailInventory, or
+state in "limitations" that the reference does not show it and why (occluded, cropped, genuinely absent):
+${components}
+
+Separate materials for these zones where the reference distinguishes them: ${family.materialZones.join(', ')}.
+Judge your own result on: ${family.reviewAxes.join('; ')}.
+Choose a camera that holds up when the model is orbited to: ${family.orbitViews.join(', ')}.
+`;
+}
+
+const normalize = (value) => String(value || '').toLowerCase();
+
+/**
+ * Which of a family's required components the spec never accounts for.
+ *
+ * Evidence is textual and deliberately generous: a component counts as accounted
+ * for when any alias appears in a detailInventory feature/evidence string, in a
+ * part name, or in the spec's own summary/limitations prose. A component the
+ * model consciously ruled out ("no visible antenna") is therefore NOT reported —
+ * the gate is looking for silence, not for a negative answer.
+ *
+ * @returns {{family: ThreejsModelFamily, missing: string[]}|null} null when no
+ * family applies, so callers can skip the whole check.
+ */
+export function findMissingFamilyComponents(spec, familyId) {
+ const family = getThreejsModelFamily(familyId);
+ if (!family) return null;
+ const haystack = [
+ ...(Array.isArray(spec?.detailInventory) ? spec.detailInventory : [])
+ .flatMap((detail) => [detail?.feature, detail?.evidence]),
+ ...collectPartNames(spec?.parts),
+ spec?.summary,
+ ...(Array.isArray(spec?.limitations) ? spec.limitations : []),
+ ].map(normalize).filter(Boolean).join(' | ');
+ const missing = family.components
+ .filter((component) => !component.aliases.some((alias) => haystack.includes(alias)))
+ .map((component) => component.name);
+ return { family, missing };
+}
+
+function collectPartNames(parts, names = []) {
+ for (const part of Array.isArray(parts) ? parts : []) {
+ names.push(part?.name, part?.id);
+ collectPartNames(part?.children, names);
+ }
+ return names;
+}
diff --git a/server/lib/threejsModelFamilies.test.js b/server/lib/threejsModelFamilies.test.js
new file mode 100644
index 0000000000..44716d45ab
--- /dev/null
+++ b/server/lib/threejsModelFamilies.test.js
@@ -0,0 +1,140 @@
+import { describe, expect, it } from 'vitest';
+import {
+ GENERAL_FAMILY_ID,
+ THREEJS_MODEL_FAMILIES,
+ THREEJS_MODEL_FAMILY_IDS,
+ THREEJS_MODEL_FAMILY_OPTIONS,
+ buildThreejsFamilyChecklist,
+ findMissingFamilyComponents,
+ getThreejsModelFamily,
+} from './threejsModelFamilies.js';
+
+describe('the taxonomy itself', () => {
+ it('keeps every family id unique and exposes general as an explicit option', () => {
+ expect(new Set(THREEJS_MODEL_FAMILY_IDS).size).toBe(THREEJS_MODEL_FAMILY_IDS.length);
+ expect(THREEJS_MODEL_FAMILY_IDS[0]).toBe(GENERAL_FAMILY_ID);
+ expect(THREEJS_MODEL_FAMILY_OPTIONS.map((option) => option.id)).toEqual(THREEJS_MODEL_FAMILY_IDS);
+ // Every option needs a label AND the one line telling the user when to pick
+ // it — a picker of bare ids is how a taxonomy stops getting used.
+ for (const option of THREEJS_MODEL_FAMILY_OPTIONS) {
+ expect(option.label.length).toBeGreaterThan(0);
+ expect(option.description.length).toBeGreaterThan(0);
+ }
+ });
+
+ it('gives every family real content in all four dimensions', () => {
+ // A family missing any one of these degrades to a worse-than-nothing
+ // checklist: components with no aliases match nothing, and a family with no
+ // orbit views cannot tell the user what to check.
+ for (const family of THREEJS_MODEL_FAMILIES) {
+ expect(family.components.length).toBeGreaterThanOrEqual(5);
+ expect(family.materialZones.length).toBeGreaterThan(0);
+ expect(family.reviewAxes.length).toBeGreaterThan(0);
+ expect(family.orbitViews.length).toBeGreaterThan(0);
+ for (const component of family.components) {
+ expect(component.aliases.length).toBeGreaterThan(0);
+ // Aliases are matched against lowercased spec text, so an uppercase
+ // alias would silently never match.
+ for (const alias of component.aliases) expect(alias).toBe(alias.toLowerCase());
+ }
+ }
+ });
+});
+
+describe('getThreejsModelFamily', () => {
+ it('resolves a known family', () => {
+ expect(getThreejsModelFamily('vehicle')?.label).toBe('Vehicle');
+ });
+
+ it('degrades an absent, general, or unknown id to no checklist', () => {
+ // A record synced from a peer running a newer taxonomy must still render;
+ // "no checklist" is always a safe answer, throwing is not.
+ expect(getThreejsModelFamily(undefined)).toBeNull();
+ expect(getThreejsModelFamily(GENERAL_FAMILY_ID)).toBeNull();
+ expect(getThreejsModelFamily('kaiju-mecha-hybrid')).toBeNull();
+ });
+});
+
+describe('buildThreejsFamilyChecklist', () => {
+ it('emits nothing for the default family so the shipped prompt is unchanged', () => {
+ expect(buildThreejsFamilyChecklist(GENERAL_FAMILY_ID)).toBe('');
+ expect(buildThreejsFamilyChecklist(undefined)).toBe('');
+ expect(buildThreejsFamilyChecklist('not-a-family')).toBe('');
+ });
+
+ it('names every required component, material zone, review axis, and orbit view', () => {
+ const family = getThreejsModelFamily('weapon');
+ const block = buildThreejsFamilyChecklist('weapon');
+ for (const component of family.components) expect(block).toContain(component.name);
+ for (const zone of family.materialZones) expect(block).toContain(zone);
+ for (const axis of family.reviewAxes) expect(block).toContain(axis);
+ for (const view of family.orbitViews) expect(block).toContain(view);
+ });
+
+ it('states the floor-not-ceiling framing and the limitations escape hatch', () => {
+ // Without both, the checklist becomes a ceiling — the model inventories the
+ // listed components, stops looking, and silently drops what it cannot find.
+ const block = buildThreejsFamilyChecklist('character');
+ expect(block).toContain('FLOOR, not a');
+ expect(block).toContain('ceiling');
+ expect(block).toContain('limitations');
+ });
+});
+
+describe('findMissingFamilyComponents', () => {
+ const specWith = (overrides = {}) => ({
+ summary: '',
+ limitations: [],
+ parts: [],
+ detailInventory: [],
+ ...overrides,
+ });
+
+ it('returns null when no family applies, so callers can skip the check entirely', () => {
+ expect(findMissingFamilyComponents(specWith(), GENERAL_FAMILY_ID)).toBeNull();
+ expect(findMissingFamilyComponents(specWith(), undefined)).toBeNull();
+ });
+
+ it('reports every required component when the spec says nothing at all', () => {
+ const result = findMissingFamilyComponents(specWith(), 'device');
+ expect(result.family.id).toBe('device');
+ expect(result.missing).toEqual(getThreejsModelFamily('device').components.map((c) => c.name));
+ });
+
+ it('accepts evidence from a detail feature, a part name, or a nested child part', () => {
+ const result = findMissingFamilyComponents(specWith({
+ detailInventory: [{ feature: 'Recessed display bezel', evidence: 'Front face' }],
+ parts: [{ name: 'Outer housing', children: [{ name: 'Cooling vent bank' }] }],
+ }), 'device');
+ expect(result.missing).not.toContain('Display or indicator');
+ expect(result.missing).not.toContain('Enclosure');
+ // Nested children count — a component modelled two levels down is still
+ // modelled, and reporting it missing would send refinement after geometry
+ // that already exists.
+ expect(result.missing).not.toContain('Vents or cooling');
+ });
+
+ it('treats an explicit limitation as accounting for a component', () => {
+ // The gate is looking for silence, not for a negative answer: a model that
+ // consciously ruled a component out did the right thing and must not be
+ // told to go build it.
+ const result = findMissingFamilyComponents(specWith({
+ limitations: ['The reference crops the vehicle above its wheels, so none are modelled.'],
+ }), 'vehicle');
+ expect(result.missing).not.toContain('Ground contact or propulsion');
+ });
+
+ it('matches case-insensitively', () => {
+ const shouty = findMissingFamilyComponents(specWith({
+ parts: [{ name: 'PRIMARY HULL' }],
+ }), 'vehicle');
+ expect(shouty.missing).not.toContain('Chassis or hull');
+ });
+
+ it('tolerates a spec with no arrays where it expects them', () => {
+ // The evaluator's inputs come off a stored record, which may predate any of
+ // these fields; a throw here would take down the whole coverage pass.
+ const result = findMissingFamilyComponents({}, 'character');
+ expect(result.missing.length).toBe(getThreejsModelFamily('character').components.length);
+ });
+});
diff --git a/server/routes/threejsModels.js b/server/routes/threejsModels.js
index 9f6b211372..b42518c550 100644
--- a/server/routes/threejsModels.js
+++ b/server/routes/threejsModels.js
@@ -3,6 +3,11 @@ import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import { EFFORT_LEVELS } from '../lib/providerModels.js';
+import {
+ GENERAL_FAMILY_ID,
+ THREEJS_MODEL_FAMILY_IDS,
+ THREEJS_MODEL_FAMILY_OPTIONS,
+} from '../lib/threejsModelFamilies.js';
import { emptyToNull } from '../lib/zodCompat.js';
import {
listModels,
@@ -23,6 +28,14 @@ const galleryFilenameSchema = z.string().trim().min(1).max(256)
// which leaves the record's stored effort alone (see startGeneration).
const effortSchema = z.preprocess(emptyToNull, z.enum(EFFORT_LEVELS).nullable().optional());
+// Subject-family checklist. Unlike `effort` there is no "clear" state — the
+// picker's General choice submits the real `general` id, so an empty string is
+// normalized to it rather than to `null`.
+const familySchema = z.preprocess(
+ (value) => (value === '' ? GENERAL_FAMILY_ID : value),
+ z.enum(THREEJS_MODEL_FAMILY_IDS).optional(),
+);
+
const createSchema = z.object({
name: z.string().trim().min(1).max(120),
filename: galleryFilenameSchema,
@@ -30,6 +43,7 @@ const createSchema = z.object({
providerId: z.string().trim().min(1).max(128),
model: z.string().trim().max(256).optional(),
effort: effortSchema,
+ family: familySchema,
});
const generateSchema = z.object({
@@ -37,6 +51,7 @@ const generateSchema = z.object({
model: z.string().trim().max(256).optional(),
effort: effortSchema,
prompt: z.string().trim().max(2_000).optional(),
+ family: familySchema,
feedback: z.string().trim().max(2_000).default(''),
});
@@ -50,6 +65,13 @@ router.post('/', asyncHandler(async (req, res) => {
res.status(202).json(model);
}));
+// Registered ahead of `/:id` so the literal path is not read as a model id. The
+// taxonomy is served rather than mirrored into the client so the picker and the
+// prompt splice can never drift apart.
+router.get('/families', (_req, res) => {
+ res.json(THREEJS_MODEL_FAMILY_OPTIONS);
+});
+
router.get('/:id/source', asyncHandler(async (req, res) => {
const result = await getModelSource(req.params.id);
res.set('Content-Type', 'text/javascript; charset=utf-8');
diff --git a/server/routes/threejsModels.test.js b/server/routes/threejsModels.test.js
index 395a2727e1..ff774fc7ce 100644
--- a/server/routes/threejsModels.test.js
+++ b/server/routes/threejsModels.test.js
@@ -110,6 +110,57 @@ describe('Three.js model routes', () => {
expect(models.startGeneration).not.toHaveBeenCalled();
});
+ it('serves the family taxonomy ahead of the :id route', async () => {
+ // Registered after `/:id` this would be read as a model id and 404.
+ const res = await request(makeApp()).get('/api/threejs-models/families');
+ expect(res.status).toBe(200);
+ expect(res.body[0]).toMatchObject({ id: 'general' });
+ expect(res.body.map((option) => option.id)).toContain('vehicle');
+ expect(models.getModel).not.toHaveBeenCalled();
+ });
+
+ it('forwards a subject family on create and generate', async () => {
+ models.startGeneration.mockResolvedValueOnce({ id: 'threejs-1', status: 'generating' });
+ const res = await request(makeApp())
+ .post('/api/threejs-models/threejs-1/generate')
+ .send({ providerId: 'codex', family: 'weapon' });
+ expect(res.status).toBe(202);
+ expect(models.startGeneration).toHaveBeenCalledWith('threejs-1', {
+ providerId: 'codex',
+ family: 'weapon',
+ feedback: '',
+ });
+
+ models.createModel.mockResolvedValueOnce({ id: 'threejs-2', status: 'generating' });
+ await request(makeApp())
+ .post('/api/threejs-models')
+ .send({ name: 'R', filename: 'r.png', providerId: 'codex', family: 'character' });
+ expect(models.createModel).toHaveBeenCalledWith(expect.objectContaining({ family: 'character' }));
+ });
+
+ it('normalizes an empty family to general rather than to a null clear', async () => {
+ // Unlike effort there is no "unset" state — general IS the no-checklist
+ // value, and a null here would read as "keep whatever is stored".
+ models.startGeneration.mockResolvedValueOnce({ id: 'threejs-1', status: 'generating' });
+ const res = await request(makeApp())
+ .post('/api/threejs-models/threejs-1/generate')
+ .send({ providerId: 'codex', family: '' });
+ expect(res.status).toBe(202);
+ expect(models.startGeneration).toHaveBeenCalledWith('threejs-1', {
+ providerId: 'codex',
+ family: 'general',
+ feedback: '',
+ });
+ });
+
+ it('rejects a family that is not in the shipped taxonomy', async () => {
+ const res = await request(makeApp())
+ .post('/api/threejs-models/threejs-1/generate')
+ .send({ providerId: 'codex', family: 'kaiju-mecha-hybrid' });
+ expect(res.status).toBe(400);
+ expect(models.startGeneration).not.toHaveBeenCalled();
+ });
+
it('serves generated source as a JavaScript attachment', async () => {
models.getModelSource.mockResolvedValueOnce({
filename: 'example-robot.js',
diff --git a/server/services/threejsModels/db.js b/server/services/threejsModels/db.js
index 71b67dff73..c77d83dbfe 100644
--- a/server/services/threejsModels/db.js
+++ b/server/services/threejsModels/db.js
@@ -8,6 +8,7 @@
import { randomUUID } from 'crypto';
import { query, withTransaction } from '../../lib/db.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { GENERAL_FAMILY_ID } from '../../lib/threejsModelFamilies.js';
const rowToModel = (row) => row?.data ?? null;
@@ -67,6 +68,11 @@ export async function createModel(input) {
// field — records written before this shipped simply read back `undefined`,
// which every consumer treats the same as "no override".
effort: input.effort || null,
+ // Subject-family checklist to narrow generation with. Additive JSON field
+ // with the same contract as `effort`: a record written before this shipped
+ // reads back `undefined`, which every consumer treats as `general` — the
+ // no-checklist default that leaves the prompt unchanged.
+ family: input.family || GENERAL_FAMILY_ID,
status: 'draft',
spec: null,
// Assembly-coverage findings for `spec`, written alongside it by
diff --git a/server/services/threejsModels/index.js b/server/services/threejsModels/index.js
index 486f1857b3..e9d182303f 100644
--- a/server/services/threejsModels/index.js
+++ b/server/services/threejsModels/index.js
@@ -15,6 +15,7 @@ import {
threejsSculptSpecSchema,
} from '../../lib/threejsModel.js';
import { buildThreejsCoverageFeedback, evaluateThreejsPartCoverage } from '../../lib/threejsModelCoverage.js';
+import { GENERAL_FAMILY_ID } from '../../lib/threejsModelFamilies.js';
import { resolveCliEffort } from '../../lib/providerModels.js';
import { getProviderById } from '../providers.js';
import { buildThreejsGenerationPrompt } from './prompt.js';
@@ -75,6 +76,7 @@ async function executeGeneration({
requestedEffort,
sourcePath,
prompt,
+ family,
}) {
try {
const result = await runPromptThroughProvider({
@@ -101,7 +103,7 @@ async function executeGeneration({
// 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 coverage = evaluateThreejsPartCoverage(spec, { family });
// 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.
@@ -163,6 +165,7 @@ export async function createModel(input) {
model: input.model,
effort: input.effort,
prompt: input.prompt,
+ family: input.family,
});
}
@@ -171,6 +174,7 @@ export async function startGeneration(id, {
model,
effort,
prompt,
+ family,
feedback = '',
} = {}) {
const current = await store.getModel(id);
@@ -207,12 +211,19 @@ export async function startGeneration(id, {
// returns null for API/effort-less providers and clamps an out-of-range level
// to the tier the chosen model really has, matching the CLI arg builders.
const effectiveEffort = resolveCliEffort(requestedEffort, provider, model || provider.defaultModel || null);
+ // Absent keeps the record's stored family; the picker's "General" choice sends
+ // the explicit `general` id, which is a real value rather than a clear — it is
+ // how the user turns a checklist back OFF for the next pass.
+ const effectiveFamily = family === undefined
+ ? (current.family || GENERAL_FAMILY_ID)
+ : (family || GENERAL_FAMILY_ID);
const generationPrompt = buildThreejsGenerationPrompt({
sourcePath,
name: current.name,
prompt: effectivePrompt,
currentSpec: current.spec,
feedback: effectiveFeedback,
+ family: effectiveFamily,
});
const next = await store.mutateModel(id, (fresh) => {
if (fresh.status === 'generating') {
@@ -224,6 +235,7 @@ export async function startGeneration(id, {
providerId: provider.id,
model: model || provider.defaultModel || null,
effort: effectiveEffort,
+ family: effectiveFamily,
status: 'generating',
error: null,
generationOperationId: operationId,
@@ -235,6 +247,7 @@ export async function startGeneration(id, {
providerId: provider.id,
model: model || provider.defaultModel || null,
effort: effectiveEffort,
+ family: effectiveFamily,
feedback: effectiveFeedback || null,
startedAt,
completedAt: null,
@@ -255,6 +268,7 @@ export async function startGeneration(id, {
requestedEffort: effectiveEffort,
sourcePath,
prompt: generationPrompt,
+ family: effectiveFamily,
});
});
return next;
diff --git a/server/services/threejsModels/index.test.js b/server/services/threejsModels/index.test.js
index 508cdd9a77..7071e7139e 100644
--- a/server/services/threejsModels/index.test.js
+++ b/server/services/threejsModels/index.test.js
@@ -414,4 +414,89 @@ describe('Three.js model generation orchestration', () => {
expect(read().effort).toBeNull();
});
});
+
+ describe('subject-family threading', () => {
+ const primeRecord = (overrides = {}) => {
+ let current = {
+ id: 'threejs-family',
+ name: 'Example Beacon',
+ sourceImage: { filename: 'example.png' },
+ providerId: 'vision-api',
+ model: null,
+ prompt: '',
+ status: 'draft',
+ spec: null,
+ coverage: null,
+ runs: [],
+ ...overrides,
+ };
+ 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(spec),
+ runId: 'run-family',
+ provider: { id: 'vision-api' },
+ model: null,
+ });
+ return () => current;
+ };
+
+ it('splices the checklist into the prompt and gates coverage on it', async () => {
+ const read = primeRecord();
+
+ await startGeneration('threejs-family', { providerId: 'vision-api', family: 'device' });
+
+ await vi.waitFor(() => expect(read().status).toBe('ready'));
+ expect(runPromptThroughProvider).toHaveBeenCalledWith(expect.objectContaining({
+ prompt: expect.stringContaining('SUBJECT FAMILY — Device / machine'),
+ }));
+ expect(read().family).toBe('device');
+ expect(read().runs.at(-1)).toMatchObject({ family: 'device' });
+ // The beacon spec mentions almost nothing a device checklist expects, so
+ // the gate fires — which is the whole point of choosing a family.
+ expect(read().coverage.family).toMatchObject({ id: 'device' });
+ expect(read().coverage.findings.some((f) => f.code === 'missing-family-component')).toBe(true);
+ });
+
+ it('keeps the record family when the caller omits the key entirely', async () => {
+ const read = primeRecord({ family: 'vehicle' });
+
+ await startGeneration('threejs-family', { providerId: 'vision-api' });
+
+ await vi.waitFor(() => expect(read().status).toBe('ready'));
+ expect(runPromptThroughProvider).toHaveBeenCalledWith(expect.objectContaining({
+ prompt: expect.stringContaining('SUBJECT FAMILY — Vehicle'),
+ }));
+ expect(read().family).toBe('vehicle');
+ });
+
+ it('turns the checklist back off when the picker sends General', async () => {
+ // Unlike effort, `general` is a real value rather than a clear — it is how
+ // a user backs out of a family they picked by mistake.
+ const read = primeRecord({ family: 'vehicle' });
+
+ await startGeneration('threejs-family', { providerId: 'vision-api', family: 'general' });
+
+ await vi.waitFor(() => expect(read().status).toBe('ready'));
+ expect(runPromptThroughProvider).toHaveBeenCalledWith(expect.objectContaining({
+ prompt: expect.not.stringContaining('SUBJECT FAMILY'),
+ }));
+ expect(read().family).toBe('general');
+ expect(read().coverage.family).toBeNull();
+ });
+
+ it('carries an unmentioned component into the next unsteered refinement', async () => {
+ const read = primeRecord({ family: 'device' });
+
+ await startGeneration('threejs-family', { providerId: 'vision-api' });
+ await vi.waitFor(() => expect(read().status).toBe('ready'));
+
+ await startGeneration('threejs-family', { providerId: 'vision-api' });
+ expect(read().runs.at(-1).feedback).toContain('device / machine checklist expects');
+ });
+ });
});
diff --git a/server/services/threejsModels/prompt.js b/server/services/threejsModels/prompt.js
index 6fed14c763..3dcb57df61 100644
--- a/server/services/threejsModels/prompt.js
+++ b/server/services/threejsModels/prompt.js
@@ -5,6 +5,8 @@
* approach, while targeting PortOS's bounded JSON scene schema.
*/
+import { buildThreejsFamilyChecklist } from '../../lib/threejsModelFamilies.js';
+
const geometryContract = `
Allowed geometry definitions:
- {"type":"box","width":n,"height":n,"depth":n}
@@ -91,7 +93,11 @@ export function buildThreejsGenerationPrompt({
prompt = '',
currentSpec = null,
feedback = '',
+ family = null,
}) {
+ // Empty for the default `general` family, so a user who does not narrow the
+ // subject gets the same general-purpose prompt this contract always shipped.
+ const familyChecklist = buildThreejsFamilyChecklist(family);
const refinement = currentSpec
? `
This is a refinement pass. Preserve good existing work, but revise the scene spec to address the feedback.
@@ -110,7 +116,7 @@ REFERENCE IMAGE:
- A local/CLI/TUI agent can inspect the same image at: ${sourcePath}
- Target name: ${name}
- User direction: ${prompt || 'Faithfully reconstruct the main subject.'}
-${refinement}
+${refinement}${familyChecklist}
WORKFLOW:
1. Inspect the image before deciding geometry.
2. Classify the subject as object, character, or hybrid.
@@ -130,7 +136,11 @@ QUALITY GATE:
- 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.
+- Keep the full hierarchy at 160 parts or fewer.${familyChecklist ? `
+- Every required component in the subject-family checklist is either built and inventoried, or
+ named in limitations with the reason the reference does not support it. Silence on one is a failure.
+- The checklist is the floor: a spec that inventories only the checklist and nothing else has
+ under-observed the reference.` : ''}
${geometryContract}
${outputContract}`;
diff --git a/server/services/threejsModels/prompt.test.js b/server/services/threejsModels/prompt.test.js
index 90f6da3f59..9c08c352cd 100644
--- a/server/services/threejsModels/prompt.test.js
+++ b/server/services/threejsModels/prompt.test.js
@@ -45,4 +45,38 @@ describe('buildThreejsGenerationPrompt', () => {
expect(prompt).toContain('Thin the handle.');
expect(build()).not.toContain('This is a refinement pass');
});
+
+ describe('subject family', () => {
+ it('leaves the prompt byte-identical when no family is chosen', () => {
+ // The taxonomy is a narrowing the user opts into. If the default path
+ // drifted even slightly, every existing install's generations would change
+ // behavior without anyone asking for it.
+ const baseline = build();
+ expect(build({ family: null })).toBe(baseline);
+ expect(build({ family: 'general' })).toBe(baseline);
+ expect(build({ family: 'not-a-family' })).toBe(baseline);
+ expect(baseline).not.toContain('SUBJECT FAMILY');
+ });
+
+ it('splices the checklist and its extra quality gates when a family is chosen', () => {
+ const prompt = build({ family: 'vehicle' });
+ expect(prompt).toContain('SUBJECT FAMILY — Vehicle');
+ expect(prompt).toContain('Cockpit or cabin');
+ expect(prompt).toContain('subject-family checklist is either built and inventoried');
+ expect(prompt).toContain('The checklist is the floor');
+ });
+
+ it('keeps the family checklist alongside refinement feedback rather than replacing it', () => {
+ // A refinement is where an under-observed component is most likely to get
+ // fixed, so dropping the checklist on the second pass would defeat it.
+ const prompt = build({
+ family: 'architecture',
+ currentSpec: { schemaVersion: 1, name: 'Example Model' },
+ feedback: 'Deepen the window reveals.',
+ });
+ expect(prompt).toContain('This is a refinement pass');
+ expect(prompt).toContain('Deepen the window reveals.');
+ expect(prompt).toContain('SUBJECT FAMILY — Building / structure');
+ });
+ });
});