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: flag implausible PBR material values against family priors (#3804)

[._.]/ Adam Eivyc7f9e0677e55
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3c662a0b3e..aeeb90b788 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -99,3 +99,4 @@
- **A server test run no longer drops fixture directories into the checkout.** Three AI-toolkit suites rooted their scratch directories at `process.cwd()` (`server/test-data`, `server/test-data-status`, `server/test-data-cli-resolve`), and their `afterEach` cleanup only ran when the worker survived the file — so a timed-out or killed worker left untracked cruft behind, one `git add -A` away from an unrelated commit (it reached a claim branch once). They now allocate a per-test temp directory under the OS temp dir, and the test-isolation guard grew a companion rule so a cwd-rooted fixture path fails the suite rather than the next `git status`. Reading cwd as a value — handing the checkout to code under test — stays legal.
- **A prompt change that skips the drift baseline no longer reddens `main` with an unreadable failure.** The stage-drift baseline is a deliberately independent hand-mirror of what the migrations export, so a prompt migration that ships a new body without carrying the baseline with it breaks a required check for every open PR — and the deep-equal it broke on reported only `expected { …(28) } to deeply equal { …(28) }`, which reads as the PR's own regression rather than an inherited one (three PRs were triaged past it before it was traced to `main`). The baseline now names the three stage prompts whose hashes moved, and the assertion reports the drifted files with their before/after hashes plus the fix to apply. The mirror stays hand-maintained on purpose: deriving it from the migrations' own exports would make it agree with them by construction and delete the guard.
- **PortOS now renders its intended typography with no route to the public internet, because the fonts ship with it.** #3808 stopped the app shell's Google Fonts stylesheet from blanking the page for ~60s on an install that can't reach Google, by loading it non-blocking — but non-blocking only meant the fonts failed *quietly*. They still never arrived, and this turned out to be broader than that fix assumed: four theme stacks in `themes/portosThemes.js` front Inter and one fronts IBM Plex Mono, so on the private-Tailscale deployment PortOS is designed for, five themes silently rendered in a system fallback and the typography was simply never seen. Both families are now vendored under `client/public/fonts/` as `woff2` and declared with `@font-face` in `client/src/index.css`, exactly as `GeistPixel-*` already was for CyberCity — scoped to the weights the stacks actually use (Inter 400/500/600/700, IBM Plex Mono 400/500/600) to keep the whole addition near 275KB. Both are SIL Open Font License 1.1, so each family's license text ships beside the files. The stylesheet `<link>`, its `<noscript>` fallback, and both `preconnect` hints are gone from `client/index.html`, which removes a third-party request from every boot; the service worker's dedicated cache for the Google font hosts went with them, since same-origin `/fonts/` was already covered by its static-asset path, and dropping it from the current-cache set means the stale one is deleted on activate. Verified in a headless browser against the built client with every external host blocked: all seven faces load, they measure differently from their fallbacks, and the page attempts zero external requests.
+- **A generated Three.js model's materials are now checked against the substance they're named for.** `threejsMaterialSchema` bounds every PBR channel to what Three.js accepts, which is a much weaker claim than it looks: metalness 0.9 oak and transmission 1.0 steel both validate, both persist, and both light completely wrong — a wooden crate that reads as chrome, a window that reads as concrete — with nothing anywhere pushing back. A new material-plausibility gate keys a small per-family prior table (metal, wood, plastic, glass, fabric, ceramic, rubber, stone, leather, paper) off tokens in each material's own id and reports the channels whose values that substance doesn't support, in both directions: metal that isn't metallic and glass that doesn't transmit are as much a finding as wood that does. It is advisory by construction and never clamps, because a stylized model is entitled to break every prior in the table — and the matching is deliberately conservative to match: a material keys a prior only when its id names exactly one family, so `mat_primary` and `wood_metal_trim` produce no feedback rather than a wrong one, and a channel the material's `type` never forwards to Three.js is skipped rather than reported as a defect the user can't see. Findings land on the record, show up in a new panel on the model detail page, and an unsteered refinement now asks for values that match the substance alongside the existing coverage, depth, and penetration feedback.
diff --git a/client/src/pages/ThreejsModelDetail.jsx b/client/src/pages/ThreejsModelDetail.jsx
index e1a114b4a8..a8a74a0d87 100644
--- a/client/src/pages/ThreejsModelDetail.jsx
+++ b/client/src/pages/ThreejsModelDetail.jsx
@@ -353,6 +353,9 @@ 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 penetrationFindings = Array.isArray(record.penetration?.findings) ? record.penetration.findings : null;
+ const materialFindings = Array.isArray(record.materialPlausibility?.findings)
+ ? record.materialPlausibility.findings
+ : null;
// Undecided contact is a note the reader is meant to judge, never something a
// refinement is told to fix — so the footer only promises a refinement when
// there is an actual defect above it.
@@ -563,6 +566,21 @@ export default function ThreejsModelDetail() {
/>
)}
+ {materialFindings && (
+ <GatePanel
+ title="Material plausibility"
+ findings={materialFindings}
+ cleanLabel={record.materialPlausibility?.matchedMaterialCount > 0
+ ? 'Recognized materials match their substance'
+ : 'No material named a substance to check'}
+ footer={`Every channel here is already inside what Three.js accepts, so this check asks the other question: whether the values suit the substance the material is named for — metallic wood and opaque glass both parse. Only materials whose id names exactly one substance are checked, and nothing is ever adjusted.${
+ materialFindings.length > 0
+ ? ' Refining without your own feedback will also ask for values that match the substance — keep any deliberate stylization in your own feedback.'
+ : ''
+ }`}
+ />
+ )}
+
{record.spec && (
<RigReadinessPanel
rig={record.rig && typeof record.rig === 'object' ? record.rig : null}
diff --git a/client/src/pages/ThreejsModelDetail.test.jsx b/client/src/pages/ThreejsModelDetail.test.jsx
index 19b4ac4090..975e6e84c1 100644
--- a/client/src/pages/ThreejsModelDetail.test.jsx
+++ b/client/src/pages/ThreejsModelDetail.test.jsx
@@ -235,6 +235,63 @@ describe('ThreejsModelDetail cross-part penetration gate', () => {
});
});
+describe('ThreejsModelDetail material plausibility gate', () => {
+ beforeEach(resetMocks);
+
+ const implausible = {
+ materialCount: 3,
+ matchedMaterialCount: 2,
+ implausibleMaterialCount: 1,
+ errorCount: 0,
+ warningCount: 1,
+ noteCount: 0,
+ findings: [{
+ code: 'implausible-material-values',
+ severity: 'warning',
+ materialIds: ['oakPanel'],
+ family: 'wood',
+ channels: [{ channel: 'metalness', value: 0.9, min: 0, max: 0.15 }],
+ message: 'Material "oakPanel" reads as wood, but metalness 0.9 is outside the 0–0.15 a wood surface normally sits in.',
+ }],
+ };
+
+ it('lists the finding and says an unsteered refinement will target it', async () => {
+ getThreejsModel.mockResolvedValue({ ...baseRecord, materialPlausibility: implausible });
+ renderDetail();
+
+ await waitFor(() => expect(screen.getByText('Material plausibility')).toBeInTheDocument());
+ expect(screen.getByText(implausible.findings[0].message)).toBeInTheDocument();
+ expect(screen.getByText('0 error · 1 warning · 0 note')).toBeInTheDocument();
+ expect(screen.getByText(/values that match the substance/)).toBeInTheDocument();
+ });
+
+ it('separates a clean pass from one where no material named a substance', async () => {
+ getThreejsModel.mockResolvedValue({
+ ...baseRecord,
+ materialPlausibility: { materialCount: 2, matchedMaterialCount: 2, findings: [] },
+ });
+ const { unmount } = renderDetail();
+ await waitFor(() => expect(screen.getByText('Recognized materials match their substance')).toBeInTheDocument());
+ expect(screen.queryByText(/values that match the substance/)).not.toBeInTheDocument();
+ unmount();
+
+ getThreejsModel.mockResolvedValue({
+ ...baseRecord,
+ materialPlausibility: { materialCount: 2, matchedMaterialCount: 0, findings: [] },
+ });
+ renderDetail();
+ await waitFor(() => expect(screen.getByText('No material named a substance to check')).toBeInTheDocument());
+ });
+
+ it('hides the section for a record generated before the gate existed', async () => {
+ getThreejsModel.mockResolvedValue({ ...baseRecord, materialPlausibility: null });
+ renderDetail();
+
+ await waitFor(() => expect(screen.getByText('Example Beacon')).toBeInTheDocument());
+ expect(screen.queryByText('Material plausibility')).not.toBeInTheDocument();
+ });
+});
+
describe('ThreejsModelDetail subject family', () => {
beforeEach(resetMocks);
diff --git a/server/lib/README.md b/server/lib/README.md
index 987da170f5..ba463ffaa1 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -158,7 +158,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `imageClean.js` | `cleanImageBuffer(buf, { metadata, denoise })` (composable opt-in pipeline: lossless metadata/C2PA strip + optional median/sharpen denoise) · `stripPngMetadataChunks` / `stripPngC2PAChunk` (lossless PNG-chunk removers) · `compositeIgnoreZone(base, original, mask, { feather })` (preserve-region compositing: restore original pixels into a feathered mask over a diffused result) · `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer` and appends a CPU light diffusion pass (`applyLightRegen` from `services/imageGen/regen.js`) for the `diffusion=light` SynthID-disruption step. |
| `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. |
| `localImageFilename.js` | `localImageFilename(urlOrPath)` resolves a stored image reference to the bare gallery-image filename under `data/images/` (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (`headshotImageFilename`/`portraitImageFilename`/`coverImageFilename`/`startingImageFilename` are thin wrappers). Also exports `assetBasename(pathOrName)`, the shared strip-querystring→basename primitive (reused by moodBoard's `imageUrlToAppAsset`). |
-| `threejsModel.js` | Validated declarative procedural-model schema plus deterministic standalone Three.js factory export for the Three.js Models workspace. 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. |
+| `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. Also the material-plausibility gate: `evaluateThreejsMaterialPlausibility(spec)` keys a bounded per-family prior table (metal, wood, plastic, glass, fabric, ceramic, rubber, stone, leather, paper) off tokens in each material's id and reports channels whose values the named substance does not support — metalness 0.9 oak, transmission 1.0 steel — skipping any id that names no family or two, and any channel the material's `type` never forwards to Three.js. Advisory only: it never clamps, because a stylized model may legitimately break every prior. `buildThreejsMaterialFeedback(plausibility)` turns that 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. |
| `threejsModelPenetration.js` | `evaluateThreejsPenetration(spec)` — cross-part penetration gate over an already-validated Three.js spec, the one check that compares two parts to each other. Rebuilds each part's world placement (the same `THREE.Euler` 'XYZ' composition the preview applies), derives an analytic solid per geometry type, and samples one part's interior against another's to flag a part entirely buried inside an unrelated one (`error`) or unrelated parts occupying substantially the same space (`warning`). Parts in the same subtree and declared `attachmentPartIds` are exempt — embedding is what those relationships are *for* — and a shallow or transparent-container overlap is reported as an undecided `note`, never as a defect. `buildThreejsPenetrationFeedback(penetration)` turns the errors and warnings (never the undecided notes) into default refinement feedback. |
diff --git a/server/lib/threejsModel.js b/server/lib/threejsModel.js
index 063d7a019e..db19c67f59 100644
--- a/server/lib/threejsModel.js
+++ b/server/lib/threejsModel.js
@@ -711,6 +711,198 @@ export function buildThreejsFlatnessFeedback(flatness) {
].join('\n');
}
+// Material-plausibility gate. `threejsMaterialSchema` bounds every PBR channel
+// to what Three.js itself accepts, which says nothing about whether the values
+// describe the substance the material is named for: metalness 0.9 oak and
+// transmission 1.0 steel both parse, and both light completely wrong.
+//
+// The priors below are per-family plausible ranges, keyed off tokens in the
+// material's own id — the only name a material carries in the spec. Matching is
+// deliberately conservative: a material keys a prior only when exactly ONE
+// family's keywords appear in it, so an unrecognized id (`mat_primary`) or a
+// genuinely mixed one (`wood_metal_trim`) produces no feedback rather than a
+// wrong one. That trade is affordable because this gate NEVER clamps — a
+// stylized model is entitled to break every prior here, and the only cost of a
+// missed match is a skipped hint.
+//
+// Bounds are stated only where a family really constrains the channel, and only
+// in the direction it constrains: `undefined` is "this family says nothing",
+// which is different from a bound of 0. Channels left out entirely (thickness,
+// iridescence, anisotropy, emissive) are art direction, not substance.
+const MATERIAL_FAMILY_PRIORS = [
+ {
+ family: 'metal',
+ keywords: ['metal', 'metallic', 'steel', 'iron', 'chrome', 'brass', 'bronze', 'copper', 'aluminum', 'aluminium', 'silver', 'gold', 'gilt', 'titanium', 'pewter', 'nickel', 'alloy', 'gunmetal'],
+ // The one family with a metalness FLOOR: a bare metal surface that is not
+ // metallic is the single most common way a generated spec reads as plastic.
+ channels: { metalness: [0.6, 1], roughness: [0.02, 0.6], transmission: [0, 0.05], sheen: [0, 0.1] },
+ },
+ {
+ family: 'wood',
+ keywords: ['wood', 'wooden', 'timber', 'oak', 'walnut', 'birch', 'maple', 'pine', 'mahogany', 'teak', 'bamboo', 'plank', 'lumber'],
+ channels: { metalness: [0, 0.15], roughness: [0.35, 1], transmission: [0, 0.05], sheen: [0, 0.3] },
+ },
+ {
+ family: 'plastic',
+ keywords: ['plastic', 'abs', 'pvc', 'nylon', 'resin', 'acrylic', 'vinyl', 'polymer', 'polycarbonate'],
+ channels: { metalness: [0, 0.1], roughness: [0.05, 0.95], ior: [1.3, 1.8] },
+ },
+ {
+ family: 'glass',
+ keywords: ['glass', 'crystal', 'lens', 'glazing', 'pane', 'windshield', 'quartz'],
+ // The transmission floor is the point of this entry: opaque "glass" is the
+ // mirror image of the metalness case above.
+ channels: { metalness: [0, 0.1], roughness: [0, 0.35], transmission: [0.4, 1], ior: [1.3, 1.9] },
+ },
+ {
+ family: 'fabric',
+ keywords: ['fabric', 'cloth', 'cotton', 'linen', 'wool', 'velvet', 'silk', 'canvas', 'denim', 'textile', 'felt', 'upholstery', 'curtain'],
+ channels: { metalness: [0, 0.1], roughness: [0.5, 1], clearcoat: [0, 0.2], transmission: [0, 0.15] },
+ },
+ {
+ family: 'ceramic',
+ keywords: ['ceramic', 'porcelain', 'clay', 'terracotta', 'tile', 'earthenware'],
+ channels: { metalness: [0, 0.1], roughness: [0.03, 0.7], transmission: [0, 0.2], ior: [1.3, 1.9] },
+ },
+ {
+ family: 'rubber',
+ keywords: ['rubber', 'tire', 'tyre', 'tread', 'silicone', 'neoprene', 'gasket'],
+ channels: { metalness: [0, 0.1], roughness: [0.5, 1], clearcoat: [0, 0.2], transmission: [0, 0.05] },
+ },
+ {
+ family: 'stone',
+ keywords: ['stone', 'rock', 'granite', 'marble', 'concrete', 'cement', 'slate', 'brick', 'asphalt', 'sandstone'],
+ channels: { metalness: [0, 0.15], roughness: [0.3, 1], transmission: [0, 0.1] },
+ },
+ {
+ family: 'leather',
+ keywords: ['leather', 'suede', 'hide'],
+ channels: { metalness: [0, 0.1], roughness: [0.3, 0.95], transmission: [0, 0.05] },
+ },
+ {
+ family: 'paper',
+ keywords: ['paper', 'cardboard', 'carton', 'paperboard', 'parchment'],
+ channels: { metalness: [0, 0.1], roughness: [0.5, 1], transmission: [0, 0.2] },
+ },
+];
+
+const MATERIAL_KEYWORD_FAMILIES = new Map(
+ MATERIAL_FAMILY_PRIORS.flatMap((prior) => prior.keywords.map((keyword) => [keyword, prior]))
+);
+
+// `basic` is unlit, so none of these channels reach the renderer at all; the
+// physical-only ones are parsed for every type but only forwarded by
+// `type: 'physical'` (see `createMaterial`). Reporting a channel that cannot
+// affect the render would be a finding the user can do nothing useful with.
+const MATERIAL_CHANNELS_BY_TYPE = {
+ basic: [],
+ standard: ['metalness', 'roughness'],
+ physical: ['metalness', 'roughness', 'clearcoat', 'ior', 'transmission', 'sheen'],
+};
+
+/**
+ * Split a material id into lowercase word tokens, breaking on separators AND on
+ * camelCase boundaries so `oakTrim` and `oak_trim` tokenize the same. A trailing
+ * plural is folded in as an extra candidate token rather than replacing the
+ * original, so `planks` matches `plank` without `abs` losing its own keyword.
+ */
+const tokenizeMaterialId = (id) => {
+ const words = String(id || '')
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
+ .toLowerCase()
+ .split(/[^a-z0-9]+/)
+ .filter(Boolean);
+ const tokens = new Set(words);
+ for (const word of words) {
+ if (word.length > 3 && word.endsWith('s')) tokens.add(word.slice(0, -1));
+ }
+ return [...tokens];
+};
+
+/**
+ * The single family a material id names, or `null` when it names none or more
+ * than one. Ambiguity is deliberately NOT resolved by precedence — picking one
+ * of two competing substances is how a prior table starts producing confident
+ * nonsense.
+ */
+const matchMaterialFamily = (id) => {
+ const matched = new Set();
+ for (const token of tokenizeMaterialId(id)) {
+ const prior = MATERIAL_KEYWORD_FAMILIES.get(token);
+ if (prior) matched.add(prior);
+ }
+ return matched.size === 1 ? [...matched][0] : null;
+};
+
+/**
+ * Report PBR channels whose values are implausible for the substance a material
+ * id names. Advisory ONLY — nothing here rewrites a spec, because a stylized
+ * model may legitimately break every prior in the table.
+ *
+ * @param {object} spec a spec that has already passed `threejsSculptSpecSchema`
+ * @returns {{findings: Array, errorCount: number, warningCount: number, noteCount: number,
+ * materialCount: number, matchedMaterialCount: number, implausibleMaterialCount: number}}
+ */
+export function evaluateThreejsMaterialPlausibility(spec) {
+ const materials = (spec?.materials && typeof spec.materials === 'object') ? spec.materials : {};
+ const findings = [];
+ let matched = 0;
+
+ for (const [id, material] of Object.entries(materials)) {
+ const prior = matchMaterialFamily(id);
+ if (!prior) continue;
+ matched += 1;
+ const channels = MATERIAL_CHANNELS_BY_TYPE[material?.type] || MATERIAL_CHANNELS_BY_TYPE.standard;
+ const offenders = [];
+ for (const channel of channels) {
+ const range = prior.channels[channel];
+ const value = material?.[channel];
+ // A stored spec predating a channel reads back undefined — unevaluated,
+ // not out of range.
+ if (!range || typeof value !== 'number' || !Number.isFinite(value)) continue;
+ const [min, max] = range;
+ if (value >= min && value <= max) continue;
+ offenders.push({ channel, value, min, max });
+ }
+ if (offenders.length === 0) continue;
+ findings.push({
+ code: 'implausible-material-values',
+ severity: 'warning',
+ materialIds: [id],
+ family: prior.family,
+ channels: offenders,
+ message: `Material "${id}" reads as ${prior.family}, but ${offenders
+ .map(({ channel, value, min, max }) => `${channel} ${value} is outside the ${min}–${max} a ${prior.family} surface normally sits in`)
+ .join(', and ')}. Re-derive those channels from the substance (or rename the material if it is not ${prior.family} at all) — unless the look is deliberately stylized, in which case leave it.`,
+ });
+ }
+
+ return {
+ findings,
+ errorCount: 0,
+ warningCount: findings.length,
+ noteCount: 0,
+ materialCount: Object.keys(materials).length,
+ matchedMaterialCount: matched,
+ implausibleMaterialCount: findings.length,
+ };
+}
+
+/**
+ * Default refinement feedback derived from a stored material-plausibility
+ * result. Returns '' when every recognized material is plausible, so the caller
+ * falls through to whatever other feedback it has.
+ */
+export function buildThreejsMaterialFeedback(plausibility) {
+ const warnings = (plausibility?.findings || []).filter((finding) => finding.severity === 'warning');
+ if (warnings.length === 0) return '';
+ return [
+ 'The previous pass gave some materials values that do not match the substance they are named for:',
+ ...warnings.map((finding, index) => `${index + 1}. ${finding.message}`),
+ 'Set each channel from what the surface actually is — bare metal is metallic and fairly smooth, wood and stone are rough dielectrics, glass transmits — and keep any deliberate stylization you still want.',
+ ].join('\n');
+}
+
const toIdentifier = (name) => {
const words = String(name || 'Procedural').replace(/[^A-Za-z0-9]+/g, ' ').trim().split(/\s+/).filter(Boolean);
const joined = words.map((word) => word[0].toUpperCase() + word.slice(1)).join('') || 'Procedural';
diff --git a/server/lib/threejsModel.test.js b/server/lib/threejsModel.test.js
index 7ab349b7fb..10495c205e 100644
--- a/server/lib/threejsModel.test.js
+++ b/server/lib/threejsModel.test.js
@@ -2,7 +2,9 @@ import { describe, expect, it } from 'vitest';
import {
buildThreejsFactorySource,
buildThreejsFlatnessFeedback,
+ buildThreejsMaterialFeedback,
evaluateThreejsFlatness,
+ evaluateThreejsMaterialPlausibility,
storedThreejsSculptSpecSchema,
threejsGeometrySchema,
threejsSculptSpecSchema,
@@ -738,3 +740,122 @@ describe('buildThreejsFactorySource articulation', () => {
expect(thrown?.message).toMatch(/not a joint declared before it/);
});
});
+
+// The plausibility gate reads materials only, so the fixture keeps the shared
+// crate hierarchy and swaps the material map. Every material is parsed through
+// the real schema first, so a fixture can never assert on a value the authoring
+// contract would have rejected anyway.
+const materialSpec = (materials) => threejsSculptSpecSchema.parse({
+ ...validSpec(),
+ materials,
+ parts: [{ ...validSpec().parts[0], children: [], material: Object.keys(materials)[0] }],
+ sockets: [],
+ detailInventory: [{
+ feature: 'Crate body silhouette',
+ evidence: 'Visible in the reference image.',
+ implementationPartIds: ['crateBody'],
+ priority: 'identity',
+ }],
+});
+
+describe('evaluateThreejsMaterialPlausibility', () => {
+ it('flags metallic wood and names the channel, the value, and the plausible range', () => {
+ const result = evaluateThreejsMaterialPlausibility(materialSpec({
+ oakPanel: { type: 'standard', color: '#8b5a2b', metalness: 0.9, roughness: 0.7 },
+ }));
+ expect(result.warningCount).toBe(1);
+ expect(result.errorCount).toBe(0);
+ expect(result.matchedMaterialCount).toBe(1);
+ const [finding] = result.findings;
+ expect(finding.code).toBe('implausible-material-values');
+ expect(finding.family).toBe('wood');
+ expect(finding.materialIds).toEqual(['oakPanel']);
+ expect(finding.channels).toEqual([{ channel: 'metalness', value: 0.9, min: 0, max: 0.15 }]);
+ expect(finding.message).toContain('metalness 0.9');
+ expect(finding.message).toContain('0–0.15');
+ });
+
+ it('flags a transmissive metal and an opaque glass — the two directions of the same error', () => {
+ const result = evaluateThreejsMaterialPlausibility(materialSpec({
+ steelPlate: { type: 'physical', color: '#8a8f98', metalness: 0.95, roughness: 0.3, transmission: 1 },
+ windowGlass: { type: 'physical', color: '#cfe8ff', metalness: 0, roughness: 0.05, transmission: 0 },
+ }));
+ expect(result.warningCount).toBe(2);
+ expect(result.findings.map((finding) => finding.family)).toEqual(['metal', 'glass']);
+ expect(result.findings[0].channels[0].channel).toBe('transmission');
+ expect(result.findings[1].channels[0]).toMatchObject({ channel: 'transmission', value: 0, min: 0.4 });
+ });
+
+ it('flags bare metal that is not metallic at all', () => {
+ const result = evaluateThreejsMaterialPlausibility(materialSpec({
+ brassFitting: { type: 'standard', color: '#d4af37', metalness: 0, roughness: 0.3 },
+ }));
+ expect(result.findings[0].channels).toEqual([{ channel: 'metalness', value: 0, min: 0.6, max: 1 }]);
+ });
+
+ it('reports every offending channel of one material in a single finding', () => {
+ const result = evaluateThreejsMaterialPlausibility(materialSpec({
+ rubberTire: { type: 'physical', color: '#1b1b1b', metalness: 0.5, roughness: 0.05, clearcoat: 1 },
+ }));
+ expect(result.findings).toHaveLength(1);
+ expect(result.findings[0].channels.map((entry) => entry.channel)).toEqual(['metalness', 'roughness', 'clearcoat']);
+ });
+
+ it('stays silent on plausible materials, unrecognized ids, and mixed-substance ids', () => {
+ const result = evaluateThreejsMaterialPlausibility(materialSpec({
+ oakPanel: { type: 'standard', color: '#8b5a2b', metalness: 0, roughness: 0.7 },
+ primarySurface: { type: 'standard', color: '#334155', metalness: 0.9, roughness: 0.05 },
+ woodAndMetalTrim: { type: 'standard', color: '#8b5a2b', metalness: 0.9, roughness: 0.05 },
+ }));
+ expect(result.findings).toEqual([]);
+ expect(result.materialCount).toBe(3);
+ // Only the plausible oak matched a family — the other two were skipped.
+ expect(result.matchedMaterialCount).toBe(1);
+ });
+
+ it('tokenizes camelCase, separators, and plurals the same way', () => {
+ for (const id of ['oakPlanks', 'oak_planks', 'oak-planks-01']) {
+ const result = evaluateThreejsMaterialPlausibility(materialSpec({
+ [id]: { type: 'standard', color: '#8b5a2b', metalness: 0.9, roughness: 0.7 },
+ }));
+ expect(result.findings[0]?.family).toBe('wood');
+ }
+ });
+
+ it('ignores channels the material type never forwards to Three.js', () => {
+ // `transmission` is physical-only and `basic` is unlit, so neither material
+ // renders the implausible value it carries.
+ const result = evaluateThreejsMaterialPlausibility(materialSpec({
+ steelPanel: { type: 'standard', color: '#8a8f98', metalness: 0.9, roughness: 0.3, transmission: 1 },
+ chromeDecal: { type: 'basic', color: '#8a8f98', metalness: 0, roughness: 1 },
+ }));
+ expect(result.findings).toEqual([]);
+ });
+
+ it('returns a clean result for a missing spec', () => {
+ expect(evaluateThreejsMaterialPlausibility(null)).toMatchObject({
+ findings: [],
+ materialCount: 0,
+ matchedMaterialCount: 0,
+ });
+ });
+});
+
+describe('buildThreejsMaterialFeedback', () => {
+ it('returns empty for a missing or clean plausibility result', () => {
+ expect(buildThreejsMaterialFeedback(null)).toBe('');
+ expect(buildThreejsMaterialFeedback({ findings: [] })).toBe('');
+ });
+
+ it('turns the warnings into a numbered instruction naming each material', () => {
+ const feedback = buildThreejsMaterialFeedback(evaluateThreejsMaterialPlausibility(materialSpec({
+ oakPanel: { type: 'standard', color: '#8b5a2b', metalness: 0.9, roughness: 0.7 },
+ steelPlate: { type: 'standard', color: '#8a8f98', metalness: 0, roughness: 0.3 },
+ })));
+ expect(feedback).toContain('do not match the substance');
+ expect(feedback).toContain('1. ');
+ expect(feedback).toContain('2. ');
+ expect(feedback).toContain('oakPanel');
+ expect(feedback).toContain('steelPlate');
+ });
+});
diff --git a/server/services/threejsModels/db.js b/server/services/threejsModels/db.js
index 52cf484bf5..c6c3abb89c 100644
--- a/server/services/threejsModels/db.js
+++ b/server/services/threejsModels/db.js
@@ -95,6 +95,11 @@ export async function createModel(input) {
// which every consumer renders as an unevaluated STATIC assembly — never as
// "articulation-ready".
rig: null,
+ // Material-plausibility findings for `spec`, written alongside it by
+ // `evaluateThreejsMaterialPlausibility`. Same additive-field contract as
+ // `coverage` and `flatness`: an older record reads back undefined, which
+ // every consumer treats as "not evaluated" rather than "plausible".
+ materialPlausibility: null,
error: null,
generationOperationId: null,
runs: [],
diff --git a/server/services/threejsModels/index.js b/server/services/threejsModels/index.js
index afcef43aad..aa3c9fce6e 100644
--- a/server/services/threejsModels/index.js
+++ b/server/services/threejsModels/index.js
@@ -11,7 +11,9 @@ import { extractJson } from '../../lib/jsonExtract.js';
import {
buildThreejsFactorySource,
buildThreejsFlatnessFeedback,
+ buildThreejsMaterialFeedback,
evaluateThreejsFlatness,
+ evaluateThreejsMaterialPlausibility,
threejsSculptSpecSchema,
} from '../../lib/threejsModel.js';
import { buildThreejsCoverageFeedback, evaluateThreejsPartCoverage } from '../../lib/threejsModelCoverage.js';
@@ -114,6 +116,11 @@ async function executeGeneration({
// still renders, and from the hero angle it still looks right, so the
// finding is recorded and fed back rather than thrown away.
const penetration = evaluateThreejsPenetration(spec);
+ // And likewise for a spec whose materials parse cleanly but describe the
+ // wrong substance — metalness 0.9 oak, transmission 1.0 steel. Advisory by
+ // construction: a stylized model is entitled to break the priors, so the
+ // finding is recorded and fed back and nothing is ever clamped.
+ const materialPlausibility = evaluateThreejsMaterialPlausibility(spec);
// Nothing PortOS generates is skinned, so what gets recorded is whether the
// spec declared an articulation graph a later rig path could attach to — and
// when it did not, the reason. A model with no graph reports not-ready with
@@ -135,6 +142,7 @@ async function executeGeneration({
flatness,
penetration,
rig,
+ materialPlausibility,
error: null,
generationOperationId: null,
generatedAt: completedAt,
@@ -157,6 +165,9 @@ async function executeGeneration({
if (penetration.errorCount > 0 || penetration.warningCount > 0) {
console.warn(`⚠️ Three.js model ${id} cross-part penetration: ${penetration.errorCount} error, ${penetration.warningCount} warning finding(s) over ${penetration.comparedPairCount} compared pair(s)`);
}
+ if (materialPlausibility.warningCount > 0) {
+ console.warn(`⚠️ Three.js model ${id} material plausibility: ${materialPlausibility.implausibleMaterialCount} of ${materialPlausibility.matchedMaterialCount} recognized material(s) carry values their substance does not support`);
+ }
if (rig.articulationReady) {
console.log(`🦴 Three.js model ${id} declares an articulation graph: ${rig.jointCount} joint(s), ${rig.socketCount} pivot socket(s)`);
}
@@ -214,13 +225,15 @@ export async function startGeneration(id, {
const effectivePrompt = prompt ?? current.prompt ?? '';
// A refinement the user did not steer aims at what the last pass measurably
// got wrong — the promises it did not build, the identity parts it built
- // without a cross-section, and the parts it modelled inside each other —
+ // without a cross-section, the parts it modelled inside each other, and the
+ // materials whose values contradict the substance they are named for —
// instead of a generic "improve it". All are sent when all fired: they are
// independent defects with independent remedies.
const effectiveFeedback = (feedback || '').trim() || [
buildThreejsCoverageFeedback(current.coverage),
buildThreejsFlatnessFeedback(current.flatness),
buildThreejsPenetrationFeedback(current.penetration),
+ buildThreejsMaterialFeedback(current.materialPlausibility),
].filter(Boolean).join('\n\n');
// Absent (`undefined`) keeps whatever the record already had; an explicit
// `null` — what the picker's "Default effort" choice sends — clears it.
diff --git a/server/services/threejsModels/index.test.js b/server/services/threejsModels/index.test.js
index 100c9ba111..43de0a9177 100644
--- a/server/services/threejsModels/index.test.js
+++ b/server/services/threejsModels/index.test.js
@@ -381,6 +381,54 @@ describe('Three.js model generation orchestration', () => {
expect(current.runs.at(-1).feedback).toContain('cross-part penetration check');
});
+ it('records the material-plausibility gate and folds it into an unsteered refinement', async () => {
+ // The body is named for oak and lit like polished chrome — valid against the
+ // schema, implausible against the substance the id names.
+ const woodSpec = {
+ ...spec,
+ materials: {
+ ...spec.materials,
+ oakBody: { color: '#8b5a2b', metalness: 0.9, roughness: 0.05 },
+ },
+ parts: spec.parts.map((part) => ({ ...part, material: 'oakBody' })),
+ };
+ let current = {
+ id: 'threejs-materials',
+ name: 'Example Beacon',
+ sourceImage: { filename: 'example.png' },
+ providerId: 'vision-api',
+ model: null,
+ prompt: '',
+ status: 'draft',
+ spec: null,
+ materialPlausibility: 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(woodSpec),
+ runId: 'run-materials',
+ provider: { id: 'vision-api' },
+ model: null,
+ });
+
+ await startGeneration(current.id, { providerId: 'vision-api' });
+ await vi.waitFor(() => expect(current.status).toBe('ready'));
+ expect(current.materialPlausibility).toMatchObject({ errorCount: 0 });
+ const woodFinding = current.materialPlausibility.findings.find((finding) => finding.family === 'wood');
+ expect(woodFinding).toMatchObject({ code: 'implausible-material-values', materialIds: ['oakBody'] });
+ // Nothing is clamped — the stored spec keeps the values the model authored.
+ expect(current.spec.materials.oakBody.metalness).toBe(0.9);
+
+ await startGeneration(current.id, { providerId: 'vision-api' });
+ expect(current.runs.at(-1).feedback).toContain('do not match the substance');
+ });
+
it('gives CLI agents a gallery path without passing an API attachment', async () => {
getProviderById.mockResolvedValue({
id: 'local-agent',