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: drop the machine repair of stored part scales and correct the negative-scale rationale (review round 1)
[._.]/ Adam Eivy3b05ecafcb7b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex fa2ad47ff5..d2701c38a0 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 inside-out or flat to nothing, and the schema called it valid.** 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, -1, 1]` reversed the winding order and the part rendered inside-out (you see its far interior wall, lit from within, silhouette unchanged), while `[1, 0, 1]` collapsed it to an invisible plane. Both validated, both exported, and neither throws at render time, so the failure survives a color or silhouette check and is indistinguishable from a modeling choice in the preview — the debugging cycle it costs is spent looking anywhere but the number. `scale` now takes its own tuple floored at `1e-4`, so zero, negative, and near-degenerate components are all rejected with a `parts.N.scale.M` path, and the generation prompt states the bound alongside the parts shape rather than letting the model discover it through a rejected generation. Mirroring belongs in `rotationDegrees`, which is unbounded in sign and always was. Nothing in the pipeline computes a scale — the value only ever comes from the provider's JSON, and the schema is the only place it can be caught. Tightening an accepted range does strand specs an older install already stored, though: they are re-validated on export, so a model generated since v2.34.0 with a bad scale would have started 500ing the download button with no in-app remedy. DB migration 008 normalizes those rows first — a negative component takes its magnitude (the size was the intent, the sign was the bug), a zero rises to the floor rather than popping a hidden part back to full size — without bumping `updated_at`, since a derived repair should not reorder the models list (#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. 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 fails loudly with the offending path instead of silently un-mirroring an asymmetric part or resizing a deliberately-collapsed one into view (#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 40868f8f80..41be780690 100644--- a/server/lib/threejsModel.js+++ b/server/lib/threejsModel.js@@ -15,12 +15,15 @@ const finite = z.number().finite().min(-10_000).max(10_000);const positive = z.number().finite().positive().max(10_000);const vec3Schema = z.tuple([finite, finite, finite]);-// A part `scale` is a multiplier, never a mirror. A negative component reverses-// the winding order, so the part renders inside-out — lit from within, silhouette-// unchanged, nothing thrown — and a component at (or near) zero collapses it to an-// invisible plane. Both are indistinguishable from a modeling choice in the preview,-// so a plain `finite` triple lets either through as a silent normals/geometry bug.-// Mirroring belongs in `rotationDegrees`.+// A part `scale` is a size multiplier, never a mirror or a visibility switch. A+// component at or near zero collapses the part to an invisible plane; a negative+// one reflects it, and three.js compensates for the negative world determinant by+// flipping the front face, so nothing throws and the preview looks plausible.+// That is what makes both expensive to chase: they are indistinguishable from a+// 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.const MIN_PART_SCALE = 1e-4;const scaleComponent = positive.min(MIN_PART_SCALE);const scale3Schema = z.tuple([scaleComponent, scaleComponent, scaleComponent]);diff --git a/server/lib/threejsModel.test.js b/server/lib/threejsModel.test.jsindex 6b58c6772c..c52481e421 100644--- a/server/lib/threejsModel.test.js+++ b/server/lib/threejsModel.test.js@@ -119,9 +119,9 @@ describe('threejsSculptSpecSchema', () => {expect(parsed.parts[0].children[0].scale).toEqual([1, 1, 1]);});- // A negative component flips the winding order (the part renders inside-out) and a- // zero collapses it to an invisible plane — neither throws at render time, so the- // schema is the only place they can be caught.+ // A zero component collapses the part to an invisible plane and a negative one+ // reflects it — neither throws at render time (three.js flips the front face for a+ // negative determinant), so the schema is the only place they can be caught.it('rejects a negative or zero part scale component, at any depth', () => {for (const bad of [[1, -1, 1], [1, 0, 1], [-1, -1, -1]]) {const spec = validSpec();diff --git a/server/scripts/db-migrations/008-threejs-part-scale-positive.js b/server/scripts/db-migrations/008-threejs-part-scale-positive.jsdeleted file mode 100644index b17712989a..0000000000--- a/server/scripts/db-migrations/008-threejs-part-scale-positive.js+++ /dev/null@@ -1,86 +0,0 @@-/**- * Repair non-positive `parts[].scale` components on Three.js model specs already- * in Postgres (#3484).- *- * `partSchema.scale` used to be a plain `finite` triple, so a provider-authored- * `[1, -1, 1]` validated and stored: a negative component reverses the winding- * order, which renders the part inside-out (lit from within, silhouette intact)- * rather than erroring, and `[1, 0, 1]` collapses it to an invisible plane. The- * schema now floors every component at 1e-4, which fixes new generations but- * would turn an already-stored spec into a hard parse failure the next time- * `buildThreejsFactorySource()` runs — i.e. the download button on a model an- * older install generated between v2.34.0 and now would start 500ing, with no- * in-app remedy short of regenerating. This normalizes those rows instead.- *- * The repair is deliberately conservative — it makes the stored spec- * representable without restyling the model:- * - a negative component takes its magnitude (`Math.abs`). The size was the- * intent; the sign was the normals bug, and dropping it un-flips the part.- * - a zero or sub-floor component is raised to the floor, which keeps it- * visually degenerate exactly as it renders today rather than popping a- * hidden part back to full size.- *- * The floor is a frozen point-in-time copy of `MIN_PART_SCALE` in- * `server/lib/threejsModel.js` rather than an import: a migration is a- * point-in-time transform and must not shift if that bound is later retuned.- *- * `updated_at` is deliberately NOT bumped — this is a derived normalization, not- * a user edit, and the models list orders by it. Three.js models are not- * federated (no `schemaVersions` entry, no peer-sync fan-out), so there is no LWW- * clock or checksum to disturb either.- *- * Tombstoned models are included: they can be restored, and a restored model- * should not be the one record whose export still throws.- *- * Idempotent: a spec whose scales are already positive is skipped, so a re-run- * writes nothing.- */--const MIN_PART_SCALE = 1e-4;--const repairComponent = (value) => {- if (typeof value !== 'number' || !Number.isFinite(value)) return value;- return Math.max(Math.abs(value), MIN_PART_SCALE);-};--/**- * Rewrite one part subtree, returning the SAME reference when nothing changed so- * the caller can tell a repaired row from an untouched one.- */-const repairPart = (part) => {- if (!part || typeof part !== 'object') return part;-- const scale = Array.isArray(part.scale) ? part.scale.map(repairComponent) : part.scale;- const scaleChanged = Array.isArray(part.scale)- && scale.some((value, index) => value !== part.scale[index]);-- const children = Array.isArray(part.children) ? part.children.map(repairPart) : part.children;- const childrenChanged = Array.isArray(part.children)- && children.some((child, index) => child !== part.children[index]);-- if (!scaleChanged && !childrenChanged) return part;- return { ...part, scale, children };-};--export async function up(client) {- const { rows } = await client.query(- `SELECT id, data FROM threejs_models- WHERE jsonb_typeof(data->'spec'->'parts') = 'array'- AND jsonb_array_length(data->'spec'->'parts') > 0`,- );- let touched = 0;- for (const row of rows) {- const parts = row.data?.spec?.parts;- if (!Array.isArray(parts)) continue;- const repaired = parts.map(repairPart);- if (repaired.every((part, index) => part === parts[index])) continue;- await client.query(- `UPDATE threejs_models- SET data = jsonb_set(data, '{spec,parts}', $1::jsonb, false)- WHERE id = $2`,- [JSON.stringify(repaired), row.id],- );- touched += 1;- }- console.log(`🧊 three.js part scale: repaired ${touched} of ${rows.length} model${rows.length === 1 ? '' : 's'} with a scene spec`);-}diff --git a/server/scripts/db-migrations/008-threejs-part-scale-positive.test.js b/server/scripts/db-migrations/008-threejs-part-scale-positive.test.jsdeleted file mode 100644index f236c2ccec..0000000000--- a/server/scripts/db-migrations/008-threejs-part-scale-positive.test.js+++ /dev/null@@ -1,98 +0,0 @@-import { describe, it, expect, vi } from 'vitest';-import { up } from './008-threejs-part-scale-positive.js';-import { threejsSculptSpecSchema } from '../../lib/threejsModel.js';--const makeClient = (rows) => {- const updates = [];- const query = vi.fn(async (sql, params) => {- if (sql.startsWith('SELECT')) return { rows };- updates.push({ sql, params });- return { rows: [] };- });- return { client: { query }, updates };-};--const modelRow = (id, parts) => ({ id, data: { spec: { parts } } });--describe('db-migration 008 — non-positive Three.js part scale', () => {- it('takes the magnitude of a negative component and floors a zero, writing only the parts path', async () => {- const { client, updates } = makeClient([- modelRow('threejs-a', [{ id: 'body', scale: [2, -3, 1], children: [{ id: 'trim', scale: [1, 0, 1], children: [] }] }]),- ]);-- await up(client);-- expect(updates).toHaveLength(1);- expect(updates[0].sql).toContain("jsonb_set(data, '{spec,parts}'");- // Never bumps updated_at — a derived normalization must not reorder the models list.- expect(updates[0].sql).not.toContain('updated_at');- expect(updates[0].params[1]).toBe('threejs-a');- const repaired = JSON.parse(updates[0].params[0]);- expect(repaired[0].scale).toEqual([2, 3, 1]);- expect(repaired[0].children[0].scale).toEqual([1, 1e-4, 1]);- });-- it('writes nothing for specs whose scales are already positive (idempotent re-run)', async () => {- const { client, updates } = makeClient([- modelRow('threejs-b', [{ id: 'body', scale: [1, 1, 1], children: [{ id: 'trim', scale: [0.5, 2, 1e-4], children: [] }] }]),- ]);-- await up(client);-- expect(updates).toEqual([]);- });-- it('leaves a part with no scale key alone', async () => {- const { client, updates } = makeClient([modelRow('threejs-c', [{ id: 'body', children: [] }])]);-- await up(client);-- expect(updates).toEqual([]);- });-- it('skips a row whose spec parts are not an array', async () => {- const { client, updates } = makeClient([- { id: 'threejs-d', data: { spec: { parts: null } } },- { id: 'threejs-e', data: { spec: null } },- { id: 'threejs-f', data: {} },- ]);-- await up(client);-- expect(updates).toEqual([]);- });-- it('produces parts the tightened schema now accepts', async () => {- const spec = {- schemaVersion: 1,- name: 'Example Beacon',- summary: 'A two-part beacon stored before the scale bound existed.',- subjectType: 'object',- background: '#111827',- camera: { position: [3, 2, 4], target: [0, 0, 0] },- materials: { shell: { type: 'standard', color: '#8b5a2b' } },- lights: [{ type: 'ambient', color: '#ffffff', intensity: 0.4 }],- parts: [{- id: 'shell',- name: 'Shell',- geometry: { type: 'box', width: 1, height: 1, depth: 1 },- material: 'shell',- scale: [1, -1, 0],- children: [],- }],- detailInventory: [{- feature: 'Ribbed shell',- evidence: 'Vertical ribs run the visible face.',- implementationPartIds: ['shell'],- }],- };- expect(threejsSculptSpecSchema.safeParse(spec).success).toBe(false);-- const { client, updates } = makeClient([{ id: 'threejs-g', data: { spec } }]);- await up(client);-- spec.parts = JSON.parse(updates[0].params[0]);- const parsed = threejsSculptSpecSchema.parse(spec);- expect(parsed.parts[0].scale).toEqual([1, 1, 1e-4]);- });-});diff --git a/server/services/threejsModels/prompt.js b/server/services/threejsModels/prompt.jsindex e58b750ce2..35959fe04d 100644--- a/server/services/threejsModels/prompt.js+++ b/server/services/threejsModels/prompt.js@@ -68,10 +68,11 @@ Return one raw JSON object and nothing else. It must have exactly this top-level}]}-Every part "scale" component (sx, sy, sz) must be a strictly positive multiplier of at-least 0.0001. Zero collapses the part to an invisible plane, and a negative component-reverses the winding order so the part renders inside-out — both are rejected. Mirror a-part with "rotationDegrees", never with a negative scale.+Every part "scale" component (sx, sy, sz) must be a strictly positive size multiplier of+at least 0.0001. Zero collapses the part to an invisible plane and a negative component+reflects it; both are rejected. This format has no reflection and no hidden parts — build+a mirrored counterpart as its own part with its own position and rotationDegrees, and+simply omit a part you do not want rendered.`;export function buildThreejsGenerationPrompt({