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

harden the flatness gate against baked rotation, zero-thickness bevels, and small parts (#3482)

[._.]/ Adam Eivyc34bc6bf14bf
diff --git a/server/lib/README.md b/server/lib/README.md
index f3af4dc704..880237f1bb 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -148,7 +148,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `imageClean.js` | `cleanImageBuffer(buf, { metadata, denoise })` (composable opt-in pipeline: lossless metadata/C2PA strip + optional median/sharpen denoise) · `stripPngMetadataChunks` / `stripPngC2PAChunk` (lossless PNG-chunk removers) · `compositeIgnoreZone(base, original, mask, { feather })` (preserve-region compositing: restore original pixels into a feathered mask over a diffused result) · `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer` and appends a CPU light diffusion pass (`applyLightRegen` from `services/imageGen/regen.js`) for the `diffusion=light` SynthID-disruption step. |
| `imageWatermark.js` | `removeCornerWatermark` (erases the visible Gemini/Nano-Banana bottom-right ✦ via dependency-free harmonic/Laplace inpaint) + pure helpers `resolveWatermarkRegion` / `inpaintRegion`. Distinct from SynthID regen — this targets the *visible* corner logo. |
| `localImageFilename.js` | `localImageFilename(urlOrPath)` resolves a stored image reference to the bare gallery-image filename under `data/images/` (or null for empty/external-URL/non-image-path) — the unit the peer-sync asset pipeline hashes + transfers. Single source of truth for the authors/artists/albums/Creative-Director filename resolvers (`headshotImageFilename`/`portraitImageFilename`/`coverImageFilename`/`startingImageFilename` are thin wrappers). Also exports `assetBasename(pathOrName)`, the shared strip-querystring→basename primitive (reused by moodBoard's `imageUrlToAppAsset`). |
-| `threejsModel.js` | Validated declarative procedural-model schema plus deterministic standalone Three.js factory export for the Three.js Models workspace. Also the cross-section gate: `evaluateThreejsFlatness(spec)` counts distinct vertex planes per axis (and treats an unbevelled `extrude` as a two-plane slab) to report when the majority of identity-priority features are built only from flat parts — a model that reads right head-on and like cardboard when orbited. `buildThreejsFlatnessFeedback(flatness)` turns that into default refinement feedback; `listSpecNames(names)` is the shared capped name-list formatter both gates use in finding messages. |
+| `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 one mesh, geometry claimed by no detail, and details nothing was built for (folded minor relief stays a `note`). `buildThreejsCoverageFeedback(coverage)` turns the error findings into default refinement feedback. |
| `pgFileFacade.js` | Shared PG/file store-backend backbone for the six storage dispatchers (pipeline series/issues, story builder, universe builder, catalog user-types, writers room). `isFileBackend()` (dev/test escape-hatch predicate) · `resolvePgBackend({ requirement, migrate?, loadDb, makePg })` (health-check → `ensureSchema` → one-time migration → import `db.js` → build the PG backend) · `createPgFileFacade({ makeFile, makePg })` (promise-memoized lazy selection so concurrent first calls don't run the migration twice; returns `{ getBackend, getBackendName, reset }`). Each store keeps its own `makeFile`/`makePg` factories + public surface. `createRecordStoreBackendSelector({ label, loadFileBackend, loadDbBackend, requireDbMessage?, isTestMode?, onDbReady? })` wraps the same backbone for the stores whose backends are whole MODULES rather than built objects (Creative Director, Music Video, Sprites) → `{ selectBackend, getBackendName }` where the name is `'file'`/`'postgres'`; `isTestMode` lets a store use the stronger `isTestRunner()` signal (Sprites). |
| `multipart.js` | Streaming multipart/form-data parser. |
diff --git a/server/lib/threejsModel.js b/server/lib/threejsModel.js
index 933b35f377..a815ad08bb 100644
--- a/server/lib/threejsModel.js
+++ b/server/lib/threejsModel.js
@@ -440,7 +440,8 @@ export const listSpecNames = (names) => (names.length > MAX_NAMES_IN_MESSAGE
// Evidence of form is PLANE count, not triangle count: a fan of four hundred
// triangles sharing one Z value has no profile at all. So a `custom` mesh is
// slab-like when its thinnest axis carries fewer distinct coordinates than a
-// curved surface needs to read as curved, and an unbevelled `extrude` is one by
+// curved surface needs to read as curved (or when the cloud has no volume in
+// any orientation), and an `extrude` with no bevel thickness is one by
// construction — its sweep has exactly two depth planes no matter how many
// `steps` subdivide the side walls.
//
@@ -450,7 +451,24 @@ export const listSpecNames = (names) => (names.length > MAX_NAMES_IN_MESSAGE
// fires on geometry that should not have been custom triangles in the first
// place.
const SLAB_PLANE_THRESHOLD = 11;
-const PLANE_QUANTUM = 1e-3;
+
+// Planes are quantized relative to the mesh's own size rather than in absolute
+// units: a fixed 1e-3 grid would report a 0.005-unit detail mesh as having five
+// planes on every axis no matter how round it is, so the gate would punish
+// small parts for being small. A thousandth of the largest extent asks the
+// scale-free question the gate actually means — does this axis carry structure
+// at the scale of the part itself.
+const RELATIVE_PLANE_QUANTUM = 1e-3;
+
+// Plane counting is axis-aligned, which a cut-out whose ROTATION was baked into
+// its vertices (rather than carried by the part's `rotationDegrees`) slips past
+// — turned 45°, a single flat fan samples a distinct value on all three axes. A
+// point cloud with no volume is flat in every orientation, so the covariance
+// determinant, normalized by the mean variance so it is scale-free, catches
+// that case however the mesh is turned. The bound is deliberately strict: only
+// an essentially zero-thickness cloud qualifies, leaving thin-but-real parts to
+// the plane count above rather than double-jeopardy here.
+const COPLANAR_DETERMINANT = 1e-6;
// Aggregate, never per-part: `extrude` is the RIGHT answer for a plate, a badge,
// or a sign, so a flat part is only evidence when the model's identity rides on
@@ -458,21 +476,60 @@ const PLANE_QUANTUM = 1e-3;
// once the majority of buildable identity features are backed by nothing else.
const FLAT_IDENTITY_RATIO_THRESHOLD = 0.6;
+const axisExtent = (vertices, axis) => {
+ let min = Infinity;
+ let max = -Infinity;
+ for (let index = axis; index < vertices.length; index += 3) {
+ if (vertices[index] < min) min = vertices[index];
+ if (vertices[index] > max) max = vertices[index];
+ }
+ return max - min;
+};
+
const countAxisPlanes = (vertices) => {
+ const quantum = Math.max(axisExtent(vertices, 0), axisExtent(vertices, 1), axisExtent(vertices, 2))
+ * RELATIVE_PLANE_QUANTUM;
+ // Every vertex sits on one point, so there is exactly one plane per axis.
+ if (!(quantum > 0)) return [1, 1, 1];
const axes = [new Set(), new Set(), new Set()];
- vertices.forEach((value, index) => axes[index % 3].add(Math.round(value / PLANE_QUANTUM)));
+ vertices.forEach((value, index) => axes[index % 3].add(Math.round(value / quantum)));
return axes.map((axis) => axis.size);
};
+const isCoplanarCloud = (vertices) => {
+ const count = vertices.length / 3;
+ const mean = [0, 0, 0];
+ vertices.forEach((value, index) => { mean[index % 3] += value / count; });
+ let xx = 0; let yy = 0; let zz = 0; let xy = 0; let xz = 0; let yz = 0;
+ for (let index = 0; index < count; index += 1) {
+ const x = vertices[index * 3] - mean[0];
+ const y = vertices[(index * 3) + 1] - mean[1];
+ const z = vertices[(index * 3) + 2] - mean[2];
+ xx += (x * x) / count; yy += (y * y) / count; zz += (z * z) / count;
+ xy += (x * y) / count; xz += (x * z) / count; yz += (y * z) / count;
+ }
+ const determinant = (xx * ((yy * zz) - (yz * yz)))
+ - (xy * ((xy * zz) - (yz * xz)))
+ + (xz * ((xy * yz) - (yy * xz)));
+ const meanVariance = (xx + yy + zz) / 3;
+ if (!(meanVariance > 0)) return true;
+ return Math.abs(determinant) / (meanVariance ** 3) < COPLANAR_DETERMINANT;
+};
+
const isSlabGeometry = (geometry) => {
if (!geometry) return false;
- // `bevelEnabled` defaults to false in the schema, so a parsed spec always
- // carries it; `!== true` also reads an older stored spec that predates it.
- if (geometry.type === 'extrude') return geometry.bevelEnabled !== true;
+ if (geometry.type === 'extrude') {
+ // `bevelEnabled` defaults to false in the schema, so a parsed spec always
+ // carries it; `!== true` also reads a stored spec that predates it. The
+ // thickness matters as much as the flag: a bevel of zero thickness adds no
+ // depth plane, and flipping the boolean alone is the cheapest way for a
+ // model to answer this gate without changing the geometry at all.
+ return geometry.bevelEnabled !== true || !(geometry.bevelThickness > 0);
+ }
if (geometry.type !== 'custom') return false;
const vertices = Array.isArray(geometry.vertices) ? geometry.vertices : [];
if (vertices.length < 9) return false;
- return Math.min(...countAxisPlanes(vertices)) < SLAB_PLANE_THRESHOLD;
+ return Math.min(...countAxisPlanes(vertices)) < SLAB_PLANE_THRESHOLD || isCoplanarCloud(vertices);
};
const collectMeshes = (part, out = []) => {
diff --git a/server/lib/threejsModel.test.js b/server/lib/threejsModel.test.js
index af6fead1a9..0a3b0cec01 100644
--- a/server/lib/threejsModel.test.js
+++ b/server/lib/threejsModel.test.js
@@ -484,6 +484,36 @@ describe('evaluateThreejsFlatness', () => {
expect(flatness).toMatchObject({ flatIdentityDetailCount: 0, flatRatio: 0, slabPartIds: [] });
});
+ it('still catches a flat fan whose rotation was baked into its vertices', () => {
+ // Turned 45° about X, the fan samples a distinct value on every axis, so
+ // axis-aligned plane counting alone would read it as solid.
+ const turned = flatFanGeometry();
+ const half = Math.SQRT1_2;
+ for (let index = 0; index < turned.vertices.length; index += 3) {
+ const y = turned.vertices[index + 1];
+ const z = turned.vertices[index + 2];
+ turned.vertices[index + 1] = Number(((y * half) - (z * half)).toFixed(6));
+ turned.vertices[index + 2] = Number(((y * half) + (z * half)).toFixed(6));
+ }
+ const distinctPerAxis = [0, 1, 2].map((axis) => new Set(
+ turned.vertices.filter((_, index) => index % 3 === axis),
+ ).size);
+ // Every axis is now well past the 11-plane threshold the counter uses.
+ expect(Math.min(...distinctPerAxis)).toBeGreaterThan(11);
+
+ const flatness = evaluateThreejsFlatness(flatnessSpec([geometryPart('badge', turned)]));
+ expect(flatness.findings.map((finding) => finding.code)).toEqual(['flat-identity-parts']);
+ });
+
+ it('does not punish a small part for being small', () => {
+ // A fixed absolute plane grid would give a 0.005-unit mesh five planes per
+ // axis however round it is; the quantum is relative to the mesh's own size.
+ const tiny = solidShellGeometry();
+ tiny.vertices = tiny.vertices.map((value) => Number((value * 0.005).toFixed(6)));
+ const flatness = evaluateThreejsFlatness(flatnessSpec([geometryPart('rivet', tiny)]));
+ expect(flatness).toMatchObject({ flatIdentityDetailCount: 0, findings: [] });
+ });
+
it('reads an unbevelled extrude as a slab and a bevelled one as solid', () => {
const unbevelled = { ...validExtrude(), bevelEnabled: false };
const bevelled = { ...validExtrude(), bevelEnabled: true, bevelThickness: 0.15, bevelSize: 0.1 };
@@ -497,6 +527,14 @@ describe('evaluateThreejsFlatness', () => {
expect(solid.flatRatio).toBe(0);
});
+ it('does not accept a zero-thickness bevel as depth', () => {
+ // Flipping the flag while leaving the bevel flat is the cheapest way to
+ // answer the gate without touching the geometry, so it stays a slab.
+ const pretend = { ...validExtrude(), bevelEnabled: true, bevelThickness: 0, bevelSize: 0.2 };
+ const flatness = evaluateThreejsFlatness(flatnessSpec([geometryPart('plate', pretend)]));
+ expect(flatness.findings.map((finding) => finding.code)).toEqual(['flat-identity-parts']);
+ });
+
it('stays quiet while flat parts are the minority — extrude is right for a plate', () => {
const flatness = evaluateThreejsFlatness(flatnessSpec([
geometryPart('badge', { ...validExtrude(), bevelEnabled: false }),