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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: split the part-scale bound into an authoring contract and a read contract (review round 3)
[._.]/ Adam Eivy50867c1cdb76
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex adc8dfe6ed..70eea40547 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -72,6 +72,6 @@- **`completeAgent` had three addresses, and the four callers that most needed one address were using the wrong one.** Continuing #3450's sequencing: `agentManagement.js`, `agentLifecycle.js`, `agentFinalization.js` and `agentCliSpawning.js` all reached the completion transition through the `cosAgents.js` barrel. These four are the callers the "move the caller above the facade" recipe cannot reach — the first two DEFINE transitions `agentOrchestrator.js` re-exports, so importing the facade from either is the cycle itself, and the other two are leaves those two must call to spawn and to finalize. So the rule they follow is the other half of the same property: above the facade's closure a transition comes from the facade, inside it from the module that DECLARES it (`cosAgentLifecycle.js`), and never from a barrel. `cleanupOrphanedAgents`'s `await import('./cos.js')` went with it — it was pulling `completeAgent` and `getAgents` through the `cos.js` re-export block while the module was already a static import three lines up, so the deferral bought no cycle protection at all. The new guard in `agentImportCycles.test.js` derives the transition names from the facade's export blocks and walks re-export edges to work out which modules forward them, so a barrel added later is covered without being named; it catches a named import, a renamed one, a namespace property read, a destructure off a namespace handle, and the three deferred spellings of the same reaches — including `const { completeAgent } = await import('./cos.js')`, the exact pattern this change deleted. Each bypass-probed.-- **A Three.js part could be scaled to nothing, or reflected into a mirrored node, and the schema called both a valid transform.** Every geometry dimension in the scene spec is bounded to a positive number, but `partSchema.scale` reused the plain `finite` triple — so a provider-authored `[1, 0, 1]` collapsed the part to an invisible plane, and `[1, -1, 1]` reflected it, which three.js absorbs by flipping the front face for the negative world determinant. Neither throws, both export, and both survive a colour or silhouette check, so the resulting "the part is missing" or "the detail reads backwards" is chased anywhere except the one number that caused it. `scale` is now its own tuple floored at `1e-4` — zero, negative, and near-degenerate components are rejected with a `parts.N.scale.M` path — and the generation prompt states the bound alongside the parts shape, so the model is told to build a mirrored counterpart as its own part and to omit a part it doesn't want rendered, rather than discovering the bound through a rejected generation. Nothing in PortOS computes a scale: the value only ever arrives in the provider's JSON, no UI edits it, and no seed or reference data carries one, so the schema is the only place it can be caught. A spec an older install already stored is left exactly as it is rather than machine-repaired — the preview path never re-validates, so nothing a user is looking at changes, and the one thing that does re-validate (the standalone-factory download) now answers with a 400 naming the exact part — `parts.0.children.0.scale.1` — instead of silently un-mirroring an asymmetric part or resizing a deliberately-collapsed one into view. That last part needed `buildThreejsFactorySource()` to stop calling bare `.parse`: a raw `ZodError` normalizes to an opaque 500, which is not something a user can act on, so it now routes through the shared `failValidation` the rest of PortOS speaks (#3484).+- **A Three.js part could be scaled to nothing, or reflected into a mirrored node, and the schema called both a valid transform.** Every geometry dimension in the scene spec is bounded to a positive number, but `partSchema.scale` reused the plain `finite` triple — so a provider-authored `[1, 0, 1]` collapsed the part to an invisible plane, and `[1, -1, 1]` reflected it, which three.js absorbs by flipping the front face for the negative world determinant. Neither throws, both export, and both survive a colour or silhouette check, so the resulting "the part is missing" or "the detail reads backwards" is chased anywhere except the one number that caused it. `scale` is now its own tuple floored at `1e-4` — zero, negative, and near-degenerate components are rejected with a `parts.N.scale.M` path — and the generation prompt states the bound alongside the parts shape, so the model is told to build a mirrored counterpart as its own part and to omit a part it doesn't want rendered, rather than discovering the bound through a rejected generation. Nothing in PortOS computes a scale: the value only ever arrives in the provider's JSON, no UI edits it, and no seed or reference data carries one, so the schema is the only place it can be caught. Tightening an authoring bound must not retroactively invalidate data accepted under the old one, though, so the bound applies to what a provider may *author*, not to what an install has already *stored*: `storedThreejsSculptSpecSchema` is the same schema with the original unbounded scale, and it is what the standalone-factory download validates against. An existing model therefore stays downloadable and exports exactly as it previews — the alternative was taking Copy/Download away from a `ready` record whose only remedy is a paid regeneration, or machine-repairing the stored spec, which would silently un-mirror an asymmetric part or resize a deliberately-collapsed one back into view. Both schemas come from one factory parameterized by the scale bound, so the 60-line reference/hierarchy `superRefine` is not duplicated to express the difference. `buildThreejsFactorySource()` also stopped calling bare `.parse` while it was there: a raw `ZodError` normalizes to an opaque 500, so a genuinely malformed stored spec now comes back as a 400 through the shared `failValidation`, naming the path (#3484).- **The "Pick from Gallery" picker could only be narrowed by typing, so finding one object in one universe meant recalling a word from its prompt.** It now carries two dropdowns beside the search box: a scope select that groups every universe and media collection under `<optgroup>`s, and a type select built from the `entryCategory`/`entryKind` tags the Universe Builder stamps onto sidecars, labelled through the same `humanizeCategory` the Builder uses. Those two are separate vocabularies — a user-authored bucket can legitimately be keyed `canon` — so the type options are prefixed by which field they filter and grouped under Categories/Entry kinds rather than flattened into one list where the bucket and the stage would silently match each other. All three filters AND-combine, and both dropdowns list only universes/collections/types that actually match an image currently in the picker — a scope that can only ever produce an empty grid isn't offered, and a selection that stops matching resets itself to "All" rather than silently blanking the grid. Collection membership is matched on the stored `{ kind, ref }` pair (the same `<kind>:<ref>` string `normalizeImage` puts on `item.key`), not on a bare filename, so a collection holding video refs alongside images filters correctly. Both option fetches are best-effort: if the collections or universes call fails the picker keeps working, falling back to the universe name stamped on each sidecar, and the fetched lists are dropped on close so a reopen can't filter fresh images against stale membership. Sidecars are unvalidated JSON that also arrive from peers, so a tag that isn't a usable string is skipped rather than crashing the render — which surfaced a latent bug in the shared `humanizeCategory`: its label lookup wasn't `hasOwn`-guarded, so a user-authored category keyed `constructor` or `toString` resolved to an inherited function and handed every caller a label that throws on the next string method (#3479).diff --git a/server/lib/threejsModel.js b/server/lib/threejsModel.jsindex 20861b52de..62af977779 100644--- a/server/lib/threejsModel.js+++ b/server/lib/threejsModel.js@@ -25,7 +25,8 @@ const vec3Schema = z.tuple([finite, finite, finite]);// modeling choice, and a plain `finite` triple accepts either. This spec has no// reflection concept — the prompt never asks for one, an LLM-authored negative// component is an authoring slip, and the exported factory is consumed by tools-// that do not all compensate for a mirrored node — so both are rejected here.+// that do not all compensate for a mirrored node — so the authoring contract+// rejects both. `storedThreejsSculptSpecSchema` keeps accepting them on read.const MIN_PART_SCALE = 1e-4;const scaleComponent = positive.min(MIN_PART_SCALE);const scale3Schema = z.tuple([scaleComponent, scaleComponent, scaleComponent]);@@ -279,19 +280,25 @@ export const threejsMaterialSchema = z.object({anisotropy: z.number().finite().min(0).max(1).default(0),});-let partSchema;-partSchema = z.lazy(() => z.object({- id: idSchema,- name: z.string().trim().min(1).max(120),- geometry: threejsGeometrySchema.optional(),- material: idSchema.optional(),- position: vec3Schema.default([0, 0, 0]),- rotationDegrees: vec3Schema.default([0, 0, 0]),- scale: scale3Schema.default([1, 1, 1]),- castShadow: z.boolean().default(true),- receiveShadow: z.boolean().default(true),- children: z.array(partSchema).max(40).default([]),-}));+// The scale bound is the ONE thing that differs between what a provider may+// author and what an install may already have stored, so the part hierarchy is+// built from it rather than written twice.+const makePartSchema = (scaleSchema) => {+ let partSchema;+ partSchema = z.lazy(() => z.object({+ id: idSchema,+ name: z.string().trim().min(1).max(120),+ geometry: threejsGeometrySchema.optional(),+ material: idSchema.optional(),+ position: vec3Schema.default([0, 0, 0]),+ rotationDegrees: vec3Schema.default([0, 0, 0]),+ scale: scaleSchema.default([1, 1, 1]),+ castShadow: z.boolean().default(true),+ receiveShadow: z.boolean().default(true),+ children: z.array(partSchema).max(40).default([]),+ }));+ return partSchema;+};const lightSchema = z.object({type: z.enum(['ambient', 'hemisphere', 'directional', 'point', 'spot']),@@ -317,7 +324,7 @@ const detailSchema = z.object({priority: z.enum(['identity', 'major', 'minor']).default('major'),});-export const threejsSculptSpecSchema = z.object({+const makeSpecSchema = (partSchema) => z.object({schemaVersion: z.literal(1),name: z.string().trim().min(1).max(120),summary: z.string().trim().min(1).max(1_000),@@ -385,6 +392,28 @@ export const threejsSculptSpecSchema = z.object({}});+/**+ * The AUTHORING contract: what a provider is allowed to hand back. Part scale is+ * floored here, so a spec that would render a part reflected or collapsed is+ * rejected at the one moment the model can still be asked for another pass.+ */+export const threejsSculptSpecSchema = makeSpecSchema(makePartSchema(scale3Schema));++/**+ * The READ contract for a spec an install has already stored. Identical except+ * that part scale keeps the original unbounded `finite` triple.+ *+ * Tightening an authoring bound must not retroactively invalidate data that was+ * accepted under the old one. A stored spec is rendered from the record verbatim+ * (the preview never re-validates), so rejecting it on the way OUT would take+ * Copy/Download away from a `ready` model whose only remedy is a paid+ * regeneration — and machine-repairing it instead would silently un-mirror an+ * asymmetric part or resize a collapsed one back into view. Neither is a repair+ * this schema is entitled to make, so an existing record exports exactly as it+ * renders, while the bound above keeps any NEW spec from acquiring the problem.+ */+export const storedThreejsSculptSpecSchema = makeSpecSchema(makePartSchema(vec3Schema));+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';@@ -396,12 +425,12 @@ const toIdentifier = (name) => {* Group factory. No model-authored JavaScript is executed by PortOS.*/export function buildThreejsFactorySource(input) {- // A spec is stored verbatim and re-validated only here, so this is where a- // record an older install generated under a looser bound surfaces. A raw- // ZodError normalizes to an opaque 500, which says nothing a user can act on;- // `failValidation` names the offending path (`parts.0.scale.1`) in a 400, so- // "the download fails" points at the one part to fix or regenerate.- const parsed = threejsSculptSpecSchema.safeParse(input);+ // Exporting reads a STORED spec, so it validates against the read contract —+ // an install's existing model stays downloadable even if it predates a bound.+ // The parse still has to happen (the emitted source must be well-formed), and+ // a raw ZodError would normalize to an opaque 500 saying nothing a user can act+ // on, so `failValidation` names the offending path in a 400 instead.+ const parsed = storedThreejsSculptSpecSchema.safeParse(input);if (!parsed.success) failValidation(parsed);const spec = parsed.data;const factoryName = `create${toIdentifier(spec.name)}Model`;diff --git a/server/lib/threejsModel.test.js b/server/lib/threejsModel.test.jsindex 95204c5cc1..17b8b98388 100644--- a/server/lib/threejsModel.test.js+++ b/server/lib/threejsModel.test.js@@ -1,5 +1,10 @@import { describe, expect, it } from 'vitest';-import { buildThreejsFactorySource, threejsGeometrySchema, threejsSculptSpecSchema } from './threejsModel.js';+import {+ buildThreejsFactorySource,+ storedThreejsSculptSpecSchema,+ threejsGeometrySchema,+ threejsSculptSpecSchema,+} from './threejsModel.js';const squareOutline = [[-1, -1], [1, -1], [1, 1], [-1, 1]];const validExtrude = () => ({@@ -137,6 +142,15 @@ describe('threejsSculptSpecSchema', () => {}});+ it('keeps accepting a legacy stored scale that the authoring contract now rejects', () => {+ for (const legacy of [[1, -1, 1], [1, 0, 1], [1, 5e-5, 1]]) {+ const spec = validSpec();+ spec.parts[0].children[0].scale = legacy;+ expect(threejsSculptSpecSchema.safeParse(spec).success).toBe(false);+ expect(storedThreejsSculptSpecSchema.parse(spec).parts[0].children[0].scale).toEqual(legacy);+ }+ });+it('rejects a near-zero part scale below the floor but accepts the floor itself', () => {const tooSmall = validSpec();tooSmall.parts[0].scale = [1, 5e-5, 1];@@ -317,19 +331,29 @@ describe('buildThreejsFactorySource', () => {}});- // Specs are stored verbatim and re-validated only here, so a record generated- // by an older install under the looser `finite` scale bound reaches this parse- // unrepaired. It must name the part rather than normalizing to an opaque 500.- it('rejects a legacy spec with a non-positive scale as a 400 naming the part path', () => {+ // A spec an older install stored under the looser bound must stay exportable —+ // tightening what a provider may author cannot retroactively take Copy/Download+ // away from a `ready` model — and it exports verbatim, since neither dropping+ // the sign nor flooring the zero is a repair this module is entitled to make.+ it('still exports a stored spec whose part scale predates the authoring bound', () => {const legacy = validSpec();- legacy.parts[0].children[0].scale = [1, -1, 1];+ legacy.parts[0].children[0].scale = [1, -1, 0];+ expect(threejsSculptSpecSchema.safeParse(legacy).success).toBe(false);++ const source = buildThreejsFactorySource(legacy);+ expect(source.replace(/\s+/g, '')).toContain('"scale":[1,-1,0]');+ });++ it('reports a malformed stored spec as a 400 naming the offending path', () => {+ const broken = validSpec();+ broken.parts[0].material = 'missing';let thrown = null;try {- buildThreejsFactorySource(legacy);+ buildThreejsFactorySource(broken);} catch (error) {thrown = error;}- expect(thrown?.message).toMatch(/parts\.0\.children\.0\.scale\.1/);+ expect(thrown?.message).toMatch(/parts\.0\.material: unknown material: missing/);expect(thrown?.status).toBe(400);expect(thrown?.code).toBe('VALIDATION_ERROR');});