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

fix: refine parent scale audit findings (#4629)

[._.]/ Adam Eivy42db250c39d6
diff --git a/client/src/pages/ThreejsModelDetail.jsx b/client/src/pages/ThreejsModelDetail.jsx
index 0f4f2de299..1e4313a2e0 100644
--- a/client/src/pages/ThreejsModelDetail.jsx
+++ b/client/src/pages/ThreejsModelDetail.jsx
@@ -638,7 +638,7 @@ export default function ThreejsModelDetail() {
title="Physical audit"
findings={physicalAuditFindings}
cleanLabel="Assembly satisfies physical attachment, exposure, and coplanarity rules"
- footer={`This check inspects the model across resting and animation poses to detect floating parts, swallowed geometry, z-fighting coplanar surfaces, and unprovenanced appearing geometry.${
+ footer={`This check inspects the model across resting and animation poses to detect floating parts, swallowed geometry, z-fighting coplanar surfaces, unprovenanced appearing geometry, and non-uniform parent scales that distort nested parts.${
physicalAuditDefects.error + physicalAuditDefects.warning > 0
? ' Refining without your own feedback will also target physical conformance defects.'
: ''
diff --git a/server/lib/README.md b/server/lib/README.md
index 563201ec8f..1c23f1d0cb 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -184,7 +184,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `threejsModelEnvironment.js` | The image-based-lighting and render-profile half of the procedural sculpt contract, kept **dependency-free** so the client suite can import it to assert parity with `client/src/lib/threejsEnvironment.js` (`threejsModel.js` pulls in zod, which the client CI job does not install). `THREEJS_ENVIRONMENT_PRESETS` (`none`/`neutral`/`studio`) is the bounded preset list the spec schema builds its enum from; `resolveThreejsEnvironment(spec)` normalizes a spec's `{ preset, intensity }` block, reading an absent, partial, or unrecognized one as `DEFAULT_THREEJS_ENVIRONMENT` per field — a record stored before the block shipped has no key and was rendered with no environment, so `none` is the honest reading of it. `THREEJS_RENDER_PROFILE` is the output-colour-space / tone-mapping / exposure contract `buildThreejsFactorySource()` stamps onto every export. |
| `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. |
-| `threejsModelPhysicalAudit.js` | `evaluateThreejsPhysicalAudit(spec)` — pure bounds and pose audit gate over an already-validated Three.js spec: inspects static resting poses and animated clip poses to detect floating parts (`floating-part`), swallowed geometry (`buried-geometry`), z-fighting coplanar surfaces (`coplanar-surface`), and unprovenanced appearing geometry (`unprovenanced-transition`). `buildThreejsPhysicalAuditFeedback(physicalAudit)` turns actionable findings into default refinement feedback. |
+| `threejsModelPhysicalAudit.js` | `evaluateThreejsPhysicalAudit(spec)` — pure bounds and pose audit gate over an already-validated Three.js spec: inspects static resting poses and animated clip poses to detect floating parts (`floating-part`), swallowed geometry (`buried-geometry`), z-fighting coplanar surfaces (`coplanar-surface`), unprovenanced appearing geometry (`unprovenanced-transition`), and non-uniform parent scale cascading into descendants (`nonuniform-parent-scale`). `buildThreejsPhysicalAuditFeedback(physicalAudit)` turns actionable findings into default refinement feedback. |
| `threejsModelPlayerSource.js` | `THREEJS_PLAYER_SOURCE` — the fixed clip-player source `buildThreejsFactorySource` emits into every exported Three.js module, giving a standalone consumer `createSculptAnimationPlayer(root, { onCue })` (plus `evaluateSculptClipPose` / `collectSculptCues`) over the node map and validated `animation` block the factory already carries. A STRING constant, not generated text: nothing provider-authored is interpolated into it, so the export stays data-plus-PortOS-code. It takes `update(deltaSeconds)` from the host render loop rather than owning one, scrubs silently and fires cues only on playback (mirroring the preview), and clones a shared material before driving `opacity`. Semantics mirror `client/src/lib/threejsAnimation.js` — change one and change the other. |
| `threejsModelRig.js` | `evaluateThreejsRigReadiness(spec)` — honest rig-readiness report over an already-validated Three.js spec: `{ articulationReady, reasons, jointCount, socketCount, attachmentCount, rootJointId, subjectType }`. The schema proves the optional `articulation` graph is well *formed* (one root, no cycles or forward refs, joints and pivots pointed at real parts/sockets); this reports whether it is *useful* (more than a lone root, every child joint carrying a pivot axis) and names the reason when it is not. It reports rather than rejects, and never claims skinning: PortOS generates static assemblies and declared articulation intent, not skeletons or bind poses. |
| `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). |
diff --git a/server/lib/threejsModelPhysicalAudit.js b/server/lib/threejsModelPhysicalAudit.js
index 6c36e8dc7a..c289c9b975 100644
--- a/server/lib/threejsModelPhysicalAudit.js
+++ b/server/lib/threejsModelPhysicalAudit.js
@@ -18,6 +18,7 @@ const MAX_AUDIT_POSES = 16;
// One percent anisotropy is small enough to ignore authoring noise while still
// catching the intentional shape-squashing that distorts a child hierarchy.
const NONUNIFORM_SCALE_TOLERANCE = 0.01;
+const ANISOTROPY_COMPARISON_TOLERANCE = 0.01;
const degreesToRadians = (degrees) => (degrees * Math.PI) / 180;
@@ -374,13 +375,11 @@ const buildNonuniformParentScaleFinding = (part, scaleSamples, context = {}) =>
const mostAnisotropic = analyzedSamples.reduce((best, sample) => (
sample.anisotropy.ratio > best.anisotropy.ratio ? sample : best
));
- const minimumScale = [0, 1, 2].map((axis) => Math.min(...normalizedSamples.map((sample) => sample.scale[axis])));
- const maximumScale = [0, 1, 2].map((axis) => Math.max(...normalizedSamples.map((sample) => sample.scale[axis])));
const sequenceIds = [...new Set(analyzedSamples.map((sample) => sample.sequenceId).filter(Boolean))];
const { clipName, ...metadata } = context;
const descendantNames = descendants.map((descendant) => descendant.name);
const scope = clipName
- ? `In clip "${clipName}", part "${part.name || part.id}" is authored with non-uniform scale across range ${formatScale(minimumScale)} to ${formatScale(maximumScale)}`
+ ? `In clip "${clipName}", part "${part.name || part.id}" reaches authored non-uniform scale ${formatScale(mostAnisotropic.anisotropy.scale)}`
: `Part "${part.name || part.id}" is authored with non-uniform scale ${formatScale(mostAnisotropic.anisotropy.scale)}`;
const sequenceSuffix = sequenceIds.length > 0 ? ` in scale sequence${sequenceIds.length === 1 ? '' : 's'} ${formatNames(sequenceIds)}` : '';
@@ -388,11 +387,11 @@ const buildNonuniformParentScaleFinding = (part, scaleSamples, context = {}) =>
code: 'nonuniform-parent-scale',
severity: 'warning',
...metadata,
- sequenceId: sequenceIds.length > 0 ? sequenceIds.join(',') : metadata.sequenceId,
+ sequenceId: sequenceIds[0] ?? metadata.sequenceId,
+ sequenceIds,
partIds: [part.id, ...descendants.map((descendant) => descendant.id)],
affectedDescendantNames: descendantNames,
anisotropyRatio: mostAnisotropic.anisotropy.ratio,
- scaleRange: { min: minimumScale, max: maximumScale },
message: `${scope} (maximum anisotropy ratio ${mostAnisotropic.anisotropy.ratio.toFixed(2)})${sequenceSuffix}, which cascades onto non-relief descendants ${formatNames(descendantNames)} and can distort them.`,
};
};
@@ -428,6 +427,8 @@ export function evaluateThreejsPhysicalAudit(spec) {
const findings = [];
const seenKeys = new Set();
const parts = flattenParts(spec.parts);
+ const staticScaleFindings = new Map();
+ const strongestAnimatedScaleFindings = new Map();
const addFinding = (finding) => {
const key = `${finding.code}|${[...finding.partIds].sort().join(',')}|${finding.clipId || ''}|${finding.sequenceId || ''}`;
@@ -443,7 +444,10 @@ export function evaluateThreejsPhysicalAudit(spec) {
for (const part of parts) {
const finding = buildNonuniformParentScaleFinding(part, [{ scale: part.scale }]);
- if (finding) addFinding(finding);
+ if (finding) {
+ staticScaleFindings.set(part.id, finding);
+ addFinding(finding);
+ }
}
const visibleStaticVolumes = staticVolumes.filter((v) => v.visible && v.opacity > 0);
@@ -551,14 +555,21 @@ export function evaluateThreejsPhysicalAudit(spec) {
for (const part of parts) {
const scaleSamples = collectAnimatedScaleSamples(part, sequences);
- const finding = buildNonuniformParentScaleFinding(part, scaleSamples, {
- clipId: clip.id,
- clipName: clip.name || clip.id,
- });
- if (finding) addFinding(finding);
+ if (scaleSamples.length > 0) {
+ const finding = buildNonuniformParentScaleFinding(part, scaleSamples, {
+ clipId: clip.id,
+ clipName: clip.name || clip.id,
+ });
+ if (finding) {
+ const current = strongestAnimatedScaleFindings.get(part.id);
+ if (!current || finding.anisotropyRatio > current.anisotropyRatio) {
+ strongestAnimatedScaleFindings.set(part.id, finding);
+ }
+ }
+ }
}
- if (remainingBudget <= 0) break;
+ if (remainingBudget <= 0) continue;
const sampleTimes = new Set([0, clip.durationSeconds || 0]);
for (const seq of sequences) {
@@ -603,6 +614,14 @@ export function evaluateThreejsPhysicalAudit(spec) {
}
}
+ for (const [partId, finding] of strongestAnimatedScaleFindings) {
+ const staticFinding = staticScaleFindings.get(partId);
+ const staticRatio = staticFinding?.anisotropyRatio || 0;
+ if (!staticFinding || finding.anisotropyRatio > staticRatio * (1 + ANISOTROPY_COMPARISON_TOLERANCE)) {
+ addFinding(finding);
+ }
+ }
+
const countBy = (severity) => findings.filter((f) => f.severity === severity).length;
return {
diff --git a/server/lib/threejsModelPhysicalAudit.test.js b/server/lib/threejsModelPhysicalAudit.test.js
index aa817b71db..784de670bd 100644
--- a/server/lib/threejsModelPhysicalAudit.test.js
+++ b/server/lib/threejsModelPhysicalAudit.test.js
@@ -81,7 +81,6 @@ describe('threejsModelPhysicalAudit', () => {
partIds: ['torso', 'head'],
affectedDescendantNames: ['Head'],
anisotropyRatio: 15,
- scaleRange: { min: [3, 1, 0.2], max: [3, 1, 0.2] },
});
expect(finding.message).toContain('Torso');
expect(finding.message).toContain('Head');
@@ -200,12 +199,113 @@ describe('threejsModelPhysicalAudit', () => {
partIds: ['housing', 'lens'],
affectedDescendantNames: ['Lens'],
anisotropyRatio: 15,
- scaleRange: { min: [1, 1, 0.2], max: [3, 1, 1] },
});
+ expect(finding.message).toContain('[3, 1, 0.2]');
expect(finding.message).toContain('Deploy');
expect(finding.message).toContain('stretch-housing');
});
+ it('does not flag a non-uniformly scaled leaf without descendants', () => {
+ const res = evaluateThreejsPhysicalAudit({
+ name: 'Scaled Leaf Spec',
+ parts: [{
+ id: 'plate',
+ name: 'Plate',
+ geometry: { type: 'box', width: 2, height: 1, depth: 1 },
+ scale: [3, 1, 0.2],
+ }],
+ });
+
+ expect(res.findings.filter((finding) => finding.code === 'nonuniform-parent-scale')).toHaveLength(0);
+ });
+
+ it('uses a one-percent tolerance for non-uniform scale', () => {
+ const withScale = (scale) => evaluateThreejsPhysicalAudit({
+ name: 'Tolerance Spec',
+ parts: [{
+ id: 'parent',
+ name: 'Parent',
+ geometry: { type: 'box', width: 2, height: 1, depth: 1 },
+ scale,
+ children: [{
+ id: 'child',
+ name: 'Child',
+ geometry: { type: 'sphere', radius: 0.5 },
+ }],
+ }],
+ });
+
+ expect(withScale([1, 1, 1.005]).findings.filter((finding) => finding.code === 'nonuniform-parent-scale')).toHaveLength(0);
+ expect(withScale([1, 1, 1.02]).findings.filter((finding) => finding.code === 'nonuniform-parent-scale')).toHaveLength(1);
+ });
+
+ it('does not flag a uniformly animated parent scale', () => {
+ const res = evaluateThreejsPhysicalAudit({
+ name: 'Uniform Animation Spec',
+ parts: [{
+ id: 'housing',
+ name: 'Housing',
+ geometry: { type: 'box', width: 2, height: 1, depth: 1 },
+ children: [{
+ id: 'lens',
+ name: 'Lens',
+ geometry: { type: 'sphere', radius: 0.4 },
+ }],
+ }],
+ animation: {
+ clips: [{
+ id: 'inflate',
+ name: 'Inflate',
+ durationSeconds: 2,
+ sequences: [{
+ id: 'inflate-housing',
+ name: 'Inflate housing',
+ partId: 'housing',
+ startSeconds: 0.5,
+ endSeconds: 1.5,
+ channels: { scale: { from: [1, 1, 1], to: [2, 2, 2] } },
+ }],
+ }],
+ },
+ });
+
+ expect(res.findings.filter((finding) => finding.code === 'nonuniform-parent-scale')).toHaveLength(0);
+ });
+
+ it('coalesces an animated duplicate when the rest pose is already more anisotropic', () => {
+ const res = evaluateThreejsPhysicalAudit({
+ name: 'Duplicate Scale Spec',
+ parts: [{
+ id: 'housing',
+ name: 'Housing',
+ geometry: { type: 'box', width: 2, height: 1, depth: 1 },
+ scale: [3, 1, 0.2],
+ children: [{
+ id: 'lens',
+ name: 'Lens',
+ geometry: { type: 'sphere', radius: 0.4 },
+ }],
+ }],
+ animation: {
+ clips: [{
+ id: 'deploy',
+ name: 'Deploy',
+ durationSeconds: 2,
+ sequences: [{
+ id: 'repeat-scale',
+ name: 'Repeat scale',
+ partId: 'housing',
+ startSeconds: 0.5,
+ endSeconds: 1.5,
+ channels: { scale: { from: [1, 1, 1], to: [3, 1, 0.2] } },
+ }],
+ }],
+ },
+ });
+
+ expect(res.findings.filter((finding) => finding.code === 'nonuniform-parent-scale')).toHaveLength(1);
+ });
+
it('detects floating part touching nothing', () => {
const spec = {
name: 'Floating Spec',
@@ -233,6 +333,7 @@ describe('threejsModelPhysicalAudit', () => {
const feedback = buildThreejsPhysicalAuditFeedback(res);
expect(feedback).toContain('Floating Orb');
+ expect(feedback).not.toContain('For non-uniform parent scale findings');
});
it('detects buried geometry inside another part', () => {
diff --git a/server/services/threejsModels/index.js b/server/services/threejsModels/index.js
index 9384bff6f4..b06039c16b 100644
--- a/server/services/threejsModels/index.js
+++ b/server/services/threejsModels/index.js
@@ -119,7 +119,8 @@ async function executeGeneration({
// finding is recorded and fed back rather than thrown away.
const penetration = evaluateThreejsPenetration(spec);
// And likewise for deterministic physical-conformance audits: floating parts,
- // swallowed geometry, coplanar z-fighting surfaces, and unprovenanced clip transitions.
+ // swallowed geometry, coplanar z-fighting surfaces, unprovenanced clip transitions,
+ // and non-uniform parent scales cascading into nested parts.
const physicalAudit = evaluateThreejsPhysicalAudit(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