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
Build PortOS Commons around a grassy pedestrian park (#6324)
[._.]/b80742a3501a
diff --git a/client/src/components/eidoverse/EidoverseWorldDrawer.jsx b/client/src/components/eidoverse/EidoverseWorldDrawer.jsxindex 15c1c82569..026a56e217 100644--- a/client/src/components/eidoverse/EidoverseWorldDrawer.jsx+++ b/client/src/components/eidoverse/EidoverseWorldDrawer.jsx@@ -109,7 +109,7 @@ export default function EidoverseWorldDrawer({<p className="text-xs font-medium uppercase tracking-[0.18em] text-port-accent">World Design V{design.selectedVersion || recipeDraft?.version}</p><h3 className="mt-1 text-lg font-semibold text-white">{design.name || recipeDraft?.name}</h3><p className="mt-2 text-sm leading-6 text-gray-400">- A luminous systems garden where PortOS apps, agents, goals, memory, data, peers, and activity each have a legible home.+ A walkable commons of a grassy arrival park, inward-facing halls, and workspaces for PortOS apps, agents, goals, memory, data, peers, and activity.</p></div><section className="rounded-xl border border-port-border bg-port-bg p-4">@@ -136,7 +136,7 @@ export default function EidoverseWorldDrawer({<option value="off">Off — hide floating labels</option></select></label>- <p className="mt-2 text-xs text-gray-400">Labels appear above objects in the world. Click or tap a label to learn what it represents. Saved in this browser; turning labels off keeps already-open details available.</p>+ <p className="mt-2 text-xs text-gray-400">Labels appear above objects in the world. Click or tap a label to learn what it represents. Off at the start of each visit. Use Labels in the toolbar when you want to inspect objects; turning labels off keeps already-open details available.</p>{!frameConnection?.capabilities?.labelPreferences && (<p className="mt-1 text-xs text-gray-400">The preference will apply when a compatible renderer connects.</p>)}@@ -289,7 +289,7 @@ export default function EidoverseWorldDrawer({<div className="space-y-5"><section className="rounded-xl border border-port-border bg-port-bg p-4"><h3 className="font-medium text-white">Dawn atmosphere</h3>- <p className="mt-1 text-xs leading-5 text-gray-500">Lightweight skymesh, three authored lights, restrained fog, and sparse wind grass.</p>+ <p className="mt-1 text-xs leading-5 text-gray-500">Lightweight skymesh, three authored lights, restrained fog, and a grassy meeting park.</p><div className="mt-4 grid gap-4 sm:grid-cols-2">{[['hours', 'Sun hour', 0, 24, 0.1],@@ -555,7 +555,7 @@ export default function EidoverseWorldDrawer({open={open}onClose={onClose}title="PortOS World Design"- subtitle={`${design.name || 'Luminous Systems Garden'} · recipe V${design.assetRecipeVersion || 2}`}+ subtitle={`${design.name || 'PortOS Commons'} · recipe V${design.assetRecipeVersion || 3}`}size="lg"tabs={TABS}activeTab={activeTab}diff --git a/client/src/hooks/useEidoverseFrame.js b/client/src/hooks/useEidoverseFrame.jsindex bacced0b1d..8cf2dc4f73 100644--- a/client/src/hooks/useEidoverseFrame.js+++ b/client/src/hooks/useEidoverseFrame.js@@ -6,15 +6,6 @@ import {eidoverseNavigationTarget,isEidoverseFrameMessage,} from '../lib/eidoverseFrame';-import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage';--const PREFERENCE_KEY = 'portos-eidoverse-label-visibility';-const readPreference = () => {- const stored = safeReadStorage(PREFERENCE_KEY);- // PortOS opts into world annotations; the standalone framework defaults off.- return EIDOVERSE_LABEL_PREFERENCES.includes(stored) ? stored : 'all-nearby';-};-export default function useEidoverseFrame(hostUrl, objects = []) {const frameRef = useRef(null);const objectsRef = useRef(objects);@@ -22,7 +13,7 @@ export default function useEidoverseFrame(hostUrl, objects = []) {const sessionRef = useRef(null);const [loaded, setLoaded] = useState({ id: 0, url: null });const [connection, setConnection] = useState({ status: 'checking', capabilities: {} });- const [labelVisibility, setLabelVisibility] = useState(readPreference);+ const [labelVisibility, setLabelVisibility] = useState('off');const preferenceRef = useRef(labelVisibility);const navigate = useNavigate();@@ -78,7 +69,6 @@ export default function useEidoverseFrame(hostUrl, objects = []) {if (!EIDOVERSE_LABEL_PREFERENCES.includes(value)) return;preferenceRef.current = value;setLabelVisibility(value);- safeWriteStorage(PREFERENCE_KEY, value);const session = sessionRef.current;if (session?.capabilities.labelPreferences) {session.source.postMessage({diff --git a/client/src/hooks/useEidoverseFrame.test.jsx b/client/src/hooks/useEidoverseFrame.test.jsxindex ecd1047341..61c71c720d 100644--- a/client/src/hooks/useEidoverseFrame.test.jsx+++ b/client/src/hooks/useEidoverseFrame.test.jsx@@ -36,7 +36,7 @@ describe('hosted Eidoverse frame navigation', () => {fireEvent.load(frame);const [hello, origin] = post.mock.calls.at(-1);expect(origin).toBe('https://world.example.com');- expect(hello).toMatchObject({ type: 'portos:connect', version: 1, labelVisibility: 'all-nearby' });+ expect(hello).toMatchObject({ type: 'portos:connect', version: 1, labelVisibility: 'off' });expect(Object.keys(hello).sort()).toEqual(['capabilities', 'labelVisibility', 'nonce', 'type', 'version']);const navigation = { type: 'eidoverse:navigate', version: 1, nonce: hello.nonce, entityId: objects[0].id, route: '/apps' };send(source, navigation); // No handshake yet.@@ -77,8 +77,8 @@ describe('hosted Eidoverse frame navigation', () => {expect(screen.getByLabelText('Route')).toHaveTextContent('/apps');});- it('preserves an explicit saved opt-out when a new renderer connects', () => {- safeWriteStorage('portos-eidoverse-label-visibility', 'off');+ it('starts hidden even if an older visit saved always-on labels', () => {+ safeWriteStorage('portos-eidoverse-label-visibility', 'all-nearby');mount();const iframe = screen.getByTitle('Test renderer');const post = vi.spyOn(iframe.contentWindow, 'postMessage').mockImplementation(() => {});diff --git a/client/src/lib/eidoverseWorldReset.js b/client/src/lib/eidoverseWorldReset.jsindex 095bdfa247..91f42f0213 100644--- a/client/src/lib/eidoverseWorldReset.js+++ b/client/src/lib/eidoverseWorldReset.js@@ -15,14 +15,14 @@ export const EIDOVERSE_SOURCE_KIND = Object.freeze({});export const EIDOVERSE_RESET_ASSET_SLOTS = Object.freeze({- nexus: Object.freeze(['nexus', 'health', 'operations', 'feature', 'district']),- apps: Object.freeze(['app']),- agents: Object.freeze(['agent', 'task']),- goals: Object.freeze(['goal', 'jira']),- memory: Object.freeze(['memory']),- data: Object.freeze(['storage']),- federation: Object.freeze(['peer']),- activity: Object.freeze(['activity', 'productivity']),+ nexus: Object.freeze(['nexus', 'health', 'operations', 'feature', 'district', 'activity', 'tree']),+ apps: Object.freeze(['app', 'desk', 'activity', 'tree']),+ agents: Object.freeze(['agent', 'task', 'desk', 'app', 'barrel', 'activity', 'tree']),+ goals: Object.freeze(['goal', 'jira', 'desk', 'app', 'activity', 'tree']),+ memory: Object.freeze(['memory', 'activity', 'tree']),+ data: Object.freeze(['storage', 'app', 'desk', 'barrel', 'task', 'activity', 'tree']),+ federation: Object.freeze(['peer', 'barrel', 'task', 'activity', 'tree']),+ activity: Object.freeze(['activity', 'productivity', 'tree']),});const CUSTOM_DISTRICT_ASSET_SLOTS = Object.freeze(['district']);diff --git a/client/src/pages/Eidoverse.jsx b/client/src/pages/Eidoverse.jsxindex 746515af35..89f55a1213 100644--- a/client/src/pages/Eidoverse.jsx+++ b/client/src/pages/Eidoverse.jsx@@ -6,6 +6,7 @@ import {RotateCcw,Settings,SlidersHorizontal,+ Tags,} from 'lucide-react';import { Link } from 'react-router';import PageHeader from '../components/PageHeader';@@ -467,6 +468,16 @@ export default function Eidoverse() {<>{phase === 'ready' && (<>+ <button+ type="button"+ aria-label="Show object labels"+ aria-pressed={frame.labelVisibility !== 'off'}+ onClick={() => frame.changeLabelVisibility(frame.labelVisibility === 'off' ? 'nearby' : 'off')}+ title="Toggle object labels for this visit"+ className="inline-flex min-h-[40px] items-center gap-1.5 rounded-lg border border-port-border px-3 text-sm text-gray-200 hover:border-port-accent hover:text-white aria-pressed:border-port-accent aria-pressed:text-port-accent"+ >+ <Tags size={16} aria-hidden="true" />Labels+ </button><buttontype="button"aria-label="Refresh world"diff --git a/client/src/pages/Eidoverse.test.jsx b/client/src/pages/Eidoverse.test.jsxindex a0d6d86156..bd2dbddc15 100644--- a/client/src/pages/Eidoverse.test.jsx+++ b/client/src/pages/Eidoverse.test.jsx@@ -151,6 +151,12 @@ describe('Eidoverse hosted page', () => {expect(screen.getByRole('button', { name: 'Refresh world' })).toHaveAttribute('aria-label', 'Refresh world');expect(screen.getByRole('button', { name: 'Refresh world' })).not.toHaveClass('port-media-overlay');+ const labels = screen.getByRole('button', { name: 'Show object labels' });+ expect(labels).toHaveAttribute('aria-pressed', 'false');+ await user.click(labels);+ expect(labels).toHaveAttribute('aria-pressed', 'true');+ await user.click(labels);+ expect(labels).toHaveAttribute('aria-pressed', 'false');expect(screen.queryByText('Your PortOS, made spatial')).not.toBeInTheDocument();expect(screen.queryByRole('region', { name: 'PortOS district legend' })).not.toBeInTheDocument();expect(screen.queryByText('12/48 live signals')).not.toBeInTheDocument();diff --git a/docs/features/eidoverse.md b/docs/features/eidoverse.mdindex a0da8c8b59..cd48c69a37 100644--- a/docs/features/eidoverse.md+++ b/docs/features/eidoverse.md@@ -136,6 +136,43 @@ local Agent Tools (MCP) controls; generic PortOS write access does not imply it.This makes both the human and CoS roles durable in the Eidoverse world ratherthan browser-session conveniences.+## World Design V3: PortOS Commons++Commons arranges eight inward-facing halls around a grassy arrival park.+A broad circular promenade and short paths link rounded gathering terraces;+trees, planted beds, and timber seating soften the edges. The center stays+clear for pedestrian agents, Persistent Mind avatars, and human guests.+Buildings use Eidoverse's existing `comp.structure` grammar: tiled floors,+glass frontage, open archways, walls, and roofs, with native collision.+A deterministic GLB adds walking surfaces, decorative seating, and physical+district signs through Eidoverse's ordinary content-addressed upload API.+Each install reuses the verified recipe-derived asset on later projections.++Library geometry summaries are measured once per resolved path and retained+in the asset locks. Placement compensates model-origin offsets and fits a+semantic size envelope; native structure anchors and the city surface retain+their authored coordinates. Desktop computers sit at the measured desk height.++The portable recipe resolves desks, retro terminals, crates, barrels, palms,+and streetlights from each install's own library. Furniture stays inside the+buildings or beside entrances. Arcade computers sit on individual desks, with the first eight workstations+inside the hall and overflow on its terrace. Other bounded live signals occupy+distinct bays beside the entrance aisle, sharing the existing 48-signal budget. Decorative furniture+has no floating label. Semantic landmarks and signals keep their optional+annotations, hidden at the start of each visit until the user activates the+Labels toolbar toggle or chooses a label mode in World controls.++V1 and V2 defaults remain immutable migration baselines. The V3 migration+preserves explicit overrides, aliases, and the last successfully applied+version. Changed asset slots invalidate their resolution fingerprints;+unchanged locks remain reusable. Existing managed identifiers stay stable,+obsolete trail markers are retired by normal reconciliation, and unrelated+visitor-built entities remain untouched. Failure compensation restores native+structure components through the existing component rollback path.++No Eidoverse framework change is required. Physical signs are authored scene geometry; camera-facing clickable labels are+a separate, optional renderer capability. Building room labels describe topology and do not render signs.+## World Design V2: Luminous Systems GardenPortOS ships a versioned world-design recipe, not a one-instance scene. World@@ -445,8 +482,9 @@ allowed. URLs, query strings, encoded/relative paths, record payloads, andunknown entities cannot navigate. No URL proxy is exposed.The Eidoverse framework leaves object labels off by default. PortOS explicitly enables-them through its trusted frame session, defaulting to `all-nearby` when this browser-has no saved preference. Existing saved choices, including `off`, are preserved.+them through its trusted frame session only after the user enables Labels. Each+visit starts with `off`; an older stored always-on preference does not enable+an overlay. The toggle and World controls change only this visit's view.Labels are positioned over their objects; clicking or tapping one opens its semanticname and description, with Open in PortOS supplied only by our fork. The old detachedobject dropdown and armed inspection buttons are removed.diff --git a/scripts/migrations/323-eidoverse-world-design-v2.js b/scripts/migrations/323-eidoverse-world-design-v2.jsindex b1fd2a3262..7d1d3c875d 100644--- a/scripts/migrations/323-eidoverse-world-design-v2.js+++ b/scripts/migrations/323-eidoverse-world-design-v2.js@@ -10,7 +10,7 @@import { readFile } from 'fs/promises';import { join } from 'path';import { atomicWrite, safeJSONParse } from '../../server/lib/fileUtils.js';-import { migrateEidoverseWorldState, EIDOVERSE_WORLD_STATE_SCHEMA_VERSION } from '../../server/lib/eidoverseWorldDesign.js';+import { migrateEidoverseWorldState, EIDOVERSE_WORLD_DESIGN_VERSION, EIDOVERSE_WORLD_STATE_SCHEMA_VERSION } from '../../server/lib/eidoverseWorldDesign.js';export default {async up({ rootDir }) {@@ -32,7 +32,7 @@ export default {console.warn(`⚠️ migration 323: skipped incompatible Eidoverse world state (${reason}); the feature will surface repair or update guidance when opened`);return { updated: 0, reason };}- if (state.schemaVersion === EIDOVERSE_WORLD_STATE_SCHEMA_VERSION && state.selectedDesignVersion === 2+ if (state.schemaVersion === EIDOVERSE_WORLD_STATE_SCHEMA_VERSION && state.selectedDesignVersion === EIDOVERSE_WORLD_DESIGN_VERSION&& JSON.stringify(migration.state) === JSON.stringify(state)) {return { updated: 0, reason: 'already-applied' };}diff --git a/scripts/migrations/323-eidoverse-world-design-v2.test.js b/scripts/migrations/323-eidoverse-world-design-v2.test.jsindex 3dacce1f04..aeaadeeb8e 100644--- a/scripts/migrations/323-eidoverse-world-design-v2.test.js+++ b/scripts/migrations/323-eidoverse-world-design-v2.test.js@@ -29,9 +29,9 @@ describe('migration 323 — Eidoverse World Design V2', () => {expect(await readState()).toMatchObject({schemaVersion: 3,world: 'example-world',- selectedDesignVersion: 2,+ selectedDesignVersion: 3,lastAppliedDesignVersion: 1,- pendingDesignVersion: 2,+ pendingDesignVersion: 3,reconciliation: { status: 'pending', checkpoint: 'migration-complete' },});});@@ -52,7 +52,7 @@ describe('migration 323 — Eidoverse World Design V2', () => {expect(await readState()).toMatchObject({extraLocalField: { preserve: true },userOverrides: { includes: { jira: false }, limits: { apps: 2 } },- recipe: { version: 2, includes: { jira: false }, limits: { apps: 2 } },+ recipe: { version: 3, includes: { jira: false }, limits: { apps: 2 } },});});diff --git a/scripts/migrations/343-eidoverse-label-aliases.test.js b/scripts/migrations/343-eidoverse-label-aliases.test.jsindex 9aaa47dbbd..8f4ea02a7e 100644--- a/scripts/migrations/343-eidoverse-label-aliases.test.js+++ b/scripts/migrations/343-eidoverse-label-aliases.test.js@@ -21,7 +21,7 @@ describe('Eidoverse alias state migration', () => {await writeFile(path, JSON.stringify({ schemaVersion: 2, userOverrides, assetResolutions, world: 'example-world' }));await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 1 });const state = JSON.parse(await readFile(path, 'utf8'));- expect(state).toMatchObject({ schemaVersion: 3, selectedDesignVersion: 2, labelAliases: {}, userOverrides, assetResolutions });+ expect(state).toMatchObject({ schemaVersion: 3, selectedDesignVersion: 3, labelAliases: {}, userOverrides, assetResolutions });expect(state.recipe).toMatchObject({ name: 'Example garden', assets: { app: 'store/example-custom' }, limits: { apps: 2 } });const aliases = { 'app-0123456789ab': 'Example tower' };await writeFile(path, JSON.stringify({ ...state, labelAliases: aliases }));diff --git a/scripts/migrations/349-eidoverse-commons.js b/scripts/migrations/349-eidoverse-commons.jsnew file mode 100644index 0000000000..309e65ebc5--- /dev/null+++ b/scripts/migrations/349-eidoverse-commons.js@@ -0,0 +1,25 @@+/** Adopt the Commons design while preserving explicit overrides and the applied version. */+import { readFile } from 'node:fs/promises';+import { join } from 'node:path';+import { atomicWrite, safeJSONParse } from '../../server/lib/fileUtils.js';+import { migrateEidoverseWorldState } from '../../server/lib/eidoverseWorldDesign.js';++export default {+ async up({ rootDir }) {+ const path = join(rootDir, 'data', 'eidoverse', 'portos-world.json');+ const raw = await readFile(path, 'utf8').catch((error) => {+ if (error.code === 'ENOENT') return null;+ throw error;+ });+ if (raw === null) return { updated: 0, reason: 'no-state' };+ const state = safeJSONParse(raw, null, { logError: false });+ if (!state || typeof state !== 'object' || Array.isArray(state)) {+ return { updated: 0, reason: 'invalid-json' };+ }+ const migration = migrateEidoverseWorldState(state);+ if (!migration.compatible) return { updated: 0, reason: migration.report.reason };+ if (JSON.stringify(state) === JSON.stringify(migration.state)) return { updated: 0, reason: 'already-applied' };+ await atomicWrite(path, migration.state);+ return { updated: 1 };+ },+};diff --git a/server/lib/README.md b/server/lib/README.mdindex 2216c2b2d5..6eec2d3404 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -482,7 +482,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `dispatchLabels.js` | slashdo dispatch-hint contract: `model:light/medium/heavy` + `effort:low/medium/high/xhigh/max` vocabulary, prescribed forge colors, validation (`normalizeDispatchModel` / `normalizeDispatchEffort`), GitHub/GitLab vs Jira label formatting, optional contributor labels (`good first issue` / `help wanted`, never implied by `model:light`, and released at claim time by `formatContributorLabelReleaseCommands` — one best-effort command per label, since a forge fails the whole edit when a named label is absent), the one shared volunteer-claim policy (`volunteerClaimLabels` / `formatVolunteerClaimCommands` — a human comment claiming an unassigned issue is resolved by BOTH issueWatcher.js's deterministic pass and the claim prompt's Phase 1 handoff, so both stamp `in-progress` and retire the invitations rather than writing opposite state), the open-ended planner-attribution axis (`planner:<model>`, `normalizePlannerId` / `resolvePlannerId` / `formatPlannerLabelGuidance` — records WHICH model wrote the plan, prefix-matched by `dispatchLabelSpec` so it lazily creates like the fixed labels; a filing agent takes the value from its prompt, never from self-identification), the workflow-state markers (`EPIC_LABEL`/`EPIC_DECOMPOSED_LABEL` and `IN_PROGRESS_LABEL` — state, not hints: shared with perpetualWork.js#isActionableIssue, issueReconcile.js's zombie scan, issueWatcher.js's volunteer assignment, and the claim prompts), lazy-create command text, the optional `--label` slots a rendered `issue create` example offers (`OPTIONAL_ISSUE_LABEL_FLAG_SLOTS` / `formatOptionalIssueLabelFlags` — one list so a new axis reaches every prompt template's copy-pasteable command, not just its prose), and shared dispatch plus issue-quality guidance (`ISSUE_QUALITY_GUIDANCE`, `DISPATCH_HINT_GUIDANCE`, `JIRA_DISPATCH_HINT_GUIDANCE`). Omit an unjustified axis; never invent `medium`; reject future-only/speculative work while keeping useful current refactors claimable. Consumed by work-tracker instructions, quota-burn audits, Layered Intelligence filing, and claim follow-up prompts. || `domainAutonomy.js` | Per-domain autonomy guardrails (pure). `AUTONOMY_DOMAINS`/`DOMAIN_IDS`/`DOMAIN_MODES` (`off`/`dry-run`/`execute`), `getDomainMode(config, id)`, and `normalizeDomainAutonomy(raw)` to coerce a hand-edited/partial map. Default per domain is `execute` (reproduces pre-#711 behavior, so no migration needed). Also `CREATIVE_DOMAIN`/`getCreativeAutonomyMode(config)` (#2183) — the Creative Director orchestrator domain, kept out of `DOMAIN_IDS` and defaulting to mirror the `cos` mode. || `domainBudgets.js` | Per-domain daily autonomy budgets (pure). `BUDGET_LIMIT_FIELDS` (`maxActionsPerDay`/`maxMinutesPerDay`), `getDomainBudget(config, id)`, `normalizeDomainBudgets(raw)`, `hasBudget(budget)`, and `evaluateBudget(budget, usage)` → `{ withinBudget, exceeded }`. A `null`/non-positive cap means unlimited (default per domain, so no migration needed). Token/$ caps are intentionally absent — CLI subscription providers expose no per-run metering. Usage ledger + gate wiring live in `services/domainUsage.js`. |-| `eidoverseWorldDesign.js` | Immutable Eidoverse World Design V1/V2 registry, legacy override migration, semantic district contract, 48-signal ceiling, and deterministic library-only asset-recipe resolution/locking for the PortOS Luminous Systems Garden. |+| `eidoverseWorldDesign.js` | Immutable Eidoverse World Design V1/V2/V3 registry, override migration, semantic districts, 48-signal ceiling, and install-local asset locks for PortOS Commons. || `eidoverseWorldLabels.js` | The `comp.label` component PortOS attaches to every entity it projects into Eidoverse (eidoverse-worlds#5), so a rendered building says what it represents instead of only naming its decorative model. `buildEidoverseLabel(component, alias?)` reads one already-built `comp.portos` payload and returns `{name, description?, visibility, offset?}` — district and world-identity landmarks always visible, live indicators labelled `nearby`, path markers `inspect`-only so a walkway cannot bury the district it leads to — and `null` for anything not `managedBy: 'portos'`, so a caller cannot label somebody else's entity. Names and descriptions are built from PortOS's own vocabulary (district label, kind label, resource category, coarse status, freshness) plus an opaque hashed resource ref for disambiguation, never from record contents, machine identity, addresses, or filesystem paths — the append-only world log is the strictest privacy boundary PortOS writes to. Also owns bounded opaque-key alias normalization and V1 renderer capability parsing; aliases are explicit opt-in names and are never inferred from private records. Owns `safeWorldText`, the one control-character/length sanitizer shared with `services/eidoverseWorldProjection.js` so a component field and the label built from it cannot disagree about what is safe. Pure. || `errorHandler.js` | `ServerError` + `asyncHandler` middleware, plus `sendErrorResponse`/`buildErrorEnvelope` for the standard `{ error, code, timestamp }` body outside a handler's catch. || `extensionErrors.js` | `isExtensionError(payload)` — true when a client error report came from a browser extension's injected content script (extension URL scheme in `source`/`stack`/`message`, or a short list of vendor/runtime message signatures) rather than from PortOS. Consumed by `services/clientErrors.js` to keep un-actionable extension noise out of the Review Hub *and* out of the 1/sec throttle slot, where it would displace real errors. **Authoritative copy** — mirrored at `client/src/lib/extensionErrors.js`, parity enforced by `extensionErrors.mirror.test.js`. |@@ -544,3 +544,6 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `runtimeEnv.js` | `isTestRunner()` — NODE_ENV=test **or** the VITEST env var, so a run that dropped NODE_ENV is still armed. Dependency-free and deliberately apart from `db.js`, which used to own it: the lowest-level file primitives need the same answer and must not pull in `pg`, and the many suites spelling `vi.mock('../lib/db.js', () => ({ query }))` used to strip it out of the graph for every other consumer. || `testDataIsolation.js` | Runtime backstop against a test WRITING into the install's real `data/` tree — the filesystem analogue of `db.js`'s row-write guard. `isInsideRealDataRoot(path)` canonicalizes a target through symlinked ancestors (it need not exist yet) and tests containment with `pathSafety.js#isPathAtOrInsideDir`, so a `..` climb, a relative path, a `data-archive` sibling, or a differently-cased spelling on a case-insensitive filesystem can't walk in sideways; the real root is re-derived through `dataRoot.js` rather than read from `PATHS`, so a suite that redirects `PATHS.data` to a temp root can't also redirect the guard. `assertNotRealDataWrite(path, operation)` throws under the test runner from `atomicWrite`, the guarded wrappers in `fileCore.js` (`writeFileGuarded`, `appendFileGuarded`, `copyFileGuarded`, `rmGuarded`, `unlinkGuarded`, `createWriteStreamGuarded`), and `collectionStore`'s record delete; `assertNotNewRealDataDir(dir)` is the create-only variant `ensureDir` uses, since `mkdir -p` on an existing directory mutates nothing. Inert outside the runner — the `isTestRunner()` check precedes every syscall. Services mutating files under `data/` route through these guarded wrappers. Closes the write half of the bug class `testDataIsolation.guards.test.js` covers statically and the two-run probe covers for reads (#6176, after #6171, #6203). || `testHelper.js` | Test helpers: `request()` (supertest-style HTTP) + `mockJsonResponse`/`mockTextResponse` (fetch `Response` mocks with `.text()`, `.json()`, and a `headers.get` content-type), `startLoopbackServer(app)`/`closeLoopbackServer(server)`/`waitForAbort(signal)` for tests that need a real socket (raw disconnects, SSE streaming) that `request()`'s run-to-completion fetch harness can't model, plus the source-scan pair `collectServerSources()` / `readServerSource(rel)` (and `SERVER_DIR`) used by the whole-tree guard suites — `spawnCwd.test.js` (#3193) and `cliChildEnv.test.js` (#3194). Those guards overlap deliberately, so they share one definition of "a source file"; change the ignore rules here and both move together. Cross-platform trio: `posixPath(v)` normalizes a RECEIVED path before comparing it to a POSIX-spelled literal (no-op on POSIX — never normalize the expectation, which would hide a genuinely wrong path), and `resolveTestPython()` returns an interpreter that actually runs, probing by execution because Windows ships a `python` Store-alias stub that exists but fails; `null` when there is none, for `describe.skipIf`; `pinPlatform(value)` pins `process.platform` and returns a restore that reinstates the ORIGINAL descriptor (deleting the pin when there was none) — it carries the one hazard every hand-rolled pin had to rediscover: never pin above an import that loads a native addon, which picks its prebuilt binary off the platform at load time (#4085). Python-shelling suites also take their two nested budgets from here: `PY_TEST_TIMEOUT_MS` (vitest per-test, passed as `it()`'s third argument — a real interpreter's wall time tracks machine load, not the assertion, so a ~4s case crosses the tight global 10s `testTimeout` on a contended full-suite worker) and the strictly smaller `PY_SUBPROCESS_TIMEOUT_MS` (every `execFileSync` spawn's own `timeout`, so a hung interpreter trips the spawn guard first and names the command instead of producing a bare vitest timeout; a subprocess allowance ABOVE the vitest budget is dead intent — vitest always wins). |++| `eidoverseCityLayout.js` | Portable native building components, curated furniture placement, and ordered signal bays for PortOS Commons. |+| `eidoverseCitySurface.js` | Deterministic GLB pedestrian paths, gathering terraces, and physical district signs, generated without AI and stored through Eidoverse's content-addressed upload API. |diff --git a/server/lib/eidoverseCityLayout.js b/server/lib/eidoverseCityLayout.jsnew file mode 100644index 0000000000..f53a65a24f--- /dev/null+++ b/server/lib/eidoverseCityLayout.js@@ -0,0 +1,118 @@+/** Authored city blocks using Eidoverse's existing gridded building component. */++export function eidoverseDistrictYaw(district) {+ return Math.atan2(-district.anchor[0], -district.anchor[2]);+}++export function eidoverseDistrictPoint(district, x, y, z) {+ const yaw = eidoverseDistrictYaw(district);+ return [district.anchor[0] + Math.cos(yaw) * x + Math.sin(yaw) * z,+ district.anchor[1] + y, district.anchor[2] - Math.sin(yaw) * x + Math.cos(yaw) * z];+}++export function eidoverseDesktopHeight(assets = {}) {+ const bounds = eidoverseModelBounds(assets.desk?.bounds);+ const size = bounds?.max.map((value, axis) => value - bounds.min[axis]);+ return 0.1 + (size ? 2.25 * size[1] / Math.max(...size) : 1.05);+}++function hall(label, width = 8, height = 3.8) {+ const tiles = [];+ const walls = [];+ const apertures = [];+ const left = -width / 2;+ const right = width / 2;+ for (let x = left; x < right; x += 1) {+ for (let z = -6; z < -2; z += 1) tiles.push([x, z]);+ walls.push([0, x, -6], [0, x, -2]);+ apertures.push([0, x, -6, 'window']);+ apertures.push([0, x, -2, Math.abs(x + 0.5) < 2 ? 'arch' : 'window']);+ }+ for (let z = -6; z < -2; z += 1) {+ walls.push([1, left, z], [1, right, z]);+ apertures.push([1, left, z, 'window'], [1, right, z, 'window']);+ }+ return { tile: 2, wallH: height, wallT: 0.2, slabT: 0.1,+ labels: { [`${left},-6`]: label }, levels: [{ y: 0, tiles, walls, apertures }] };+}++/** Each building is one bounded component, including its navigable doorways. */+export function eidoverseCityArchitecture(districts) {+ return districts.map((district) => ({+ key: `hall-${district.id}`, districtId: district.id,+ pos: district.anchor, yaw: eidoverseDistrictYaw(district), structure: hall(district.label, district.id === 'nexus' ? 6 : 8,+ district.id === 'nexus' ? 5.2 : 3.8),+ }));+}++/** Furniture sits beside entrances; the forecourt and street stay unobstructed. */+export function eidoverseCityFurniture(districts, assets = {}) {+ const desktopHeight = eidoverseDesktopHeight(assets);+ const furniture = districts.flatMap((district) => {+ const at = (x, y, z) => eidoverseDistrictPoint(district, x, y, z);+ const props = [+ { key: `${district.id}-lamp`, slot: 'activity', pos: at(9, 0, -2), scale: 1, size: 3.4 },+ ...[-1, 1].flatMap((side) => [+ { key: `${district.id}-tree-${side}`, slot: 'tree', pos: at(side * 11, 0, -6), scale: 1, size: 5.5 },+ { key: `${district.id}-garden-tree-${side}`, slot: 'tree', pos: at(side * 9, 0, 9), scale: 1, size: 4 },+ ]),+ ];+ if (district.id === 'apps') props.push({ key: 'apps-landmark-desk', slot: 'desk', pos: at(-5, 0.1, 3), scale: 1, size: 2.25 });+ if (['agents', 'goals'].includes(district.id)) {+ props.push({ key: `${district.id}-desk`, slot: 'desk', pos: at(-5, 0.1, -7), scale: 1, size: 2.25 });+ props.push({ key: `${district.id}-desktop`, slot: 'app', pos: at(-5, desktopHeight, -7), scale: 1, size: 0.7 });+ }+ if (['agents', 'data', 'federation'].includes(district.id)) {+ props.push({ key: `${district.id}-barrel`, slot: 'barrel', pos: at(6, 0.1, -7), scale: 0.65 });+ props.push({ key: `${district.id}-crate`, slot: 'task', pos: at(3, 0.1, -9), scale: 0.65 });+ }+ if (district.id === 'data') {+ props.push({ key: `${district.id}-terminal-desk`, slot: 'desk', pos: at(5, 0.1, -6), scale: 1, size: 2.25 });+ props.push({ key: `${district.id}-terminal`, slot: 'app', pos: at(5, desktopHeight, -6), scale: 1, size: 0.7 });+ }+ return props.map((prop) => ({ ...prop, yaw: eidoverseDistrictYaw(district), districtId: district.id }));+ });+ return [...furniture, ...Array.from({ length: 6 }, (_, i) => {+ const angle = i / 6 * Math.PI * 2;+ return { key: `park-tree-${i}`, slot: 'tree', districtId: 'nexus',+ pos: [Math.sin(angle) * 18, 0, Math.cos(angle) * 18], scale: 1, size: 5 + i % 2 };+ })];+}++/** Ordered display bays, facing the plaza. No hash-scattered overlapping rings. */+export function eidoverseCitySignalPosition(district, index, indoors = false) {+ const column = index % 4;+ const row = Math.floor(index / 4);+ // Two pairs of bays leave a generous aisle through the entrance.+ const x = [-6, -3.5, 3.5, 6][column];+ const outdoorRow = row - (indoors ? 2 : 0);+ // Large custom limits expand behind the hall, never across the promenade.+ const z = indoors && row < 2 ? -9.5 + row * 3+ : outdoorRow < 3 ? 1 + outdoorRow * 2.5 : -15 - (outdoorRow - 3) * 2.5;+ return eidoverseDistrictPoint(district, x, indoors && row < 2 ? 0.1 : 0.03, z);+}++/** Accept only finite, non-degenerate geometry summaries from the library. */+export function eidoverseModelBounds(value) {+ if (!value || !['min', 'max'].every((key) => Array.isArray(value[key])+ && value[key].length === 3 && value[key].every(Number.isFinite))) return null;+ const size = value.max.map((n, index) => n - value.min[index]);+ if (size.some((n) => n < 0) || Math.max(...size) < 0.000001) return null;+ return { min: [...value.min], max: [...value.max] };+}++/** Place the measured bottom-center at an authored point, at a useful size. */+export function eidoverseModelPlacement({ bounds, pos, yaw, scale, size = 2 }) {+ const box = eidoverseModelBounds(bounds);+ if (!box) return { pos, yaw, scale };+ const extent = Math.max(...box.max.map((n, index) => n - box.min[index]));+ const fittedScale = size * scale / extent;+ const x = (box.min[0] + box.max[0]) * 0.5 * fittedScale;+ const z = (box.min[2] + box.max[2]) * 0.5 * fittedScale;+ return {+ pos: [pos[0] - Math.cos(yaw) * x - Math.sin(yaw) * z,+ pos[1] - box.min[1] * fittedScale,+ pos[2] + Math.sin(yaw) * x - Math.cos(yaw) * z],+ yaw, scale: fittedScale,+ };+}diff --git a/server/lib/eidoverseCityLayout.test.js b/server/lib/eidoverseCityLayout.test.jsnew file mode 100644index 0000000000..1463a152d0--- /dev/null+++ b/server/lib/eidoverseCityLayout.test.js@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest';+import { eidoverseModelBounds, eidoverseModelPlacement } from './eidoverseCityLayout.js';++describe('library geometry placement', () => {+ it('centers an offset, rotated model on the authored ground point at the requested size', () => {+ const bounds = { min: [10, -2, -40], max: [18, 8, -20] };+ const placement = eidoverseModelPlacement({ bounds, pos: [4, 0.1, 6], yaw: Math.PI / 2, scale: 1, size: 8 });+ expect(placement.scale).toBe(0.4);+ // Transform the source model's bottom-center, independently of the fitter.+ const ground = [14, -2, -30].map((n) => n * placement.scale);+ expect(placement.pos[0] + ground[2]).toBeCloseTo(4);+ expect(placement.pos[1] + ground[1]).toBeCloseTo(0.1);+ expect(placement.pos[2] - ground[0]).toBeCloseTo(6);+ expect(eidoverseModelBounds({ min: [0, 0, 0], max: [0, 0, 0] })).toBeNull();+ expect(eidoverseModelBounds({ min: [0, 0, NaN], max: [1, 1, 1] })).toBeNull();+ });+});diff --git a/server/lib/eidoverseCitySurface.js b/server/lib/eidoverseCitySurface.jsnew file mode 100644index 0000000000..d1369b8fd2--- /dev/null+++ b/server/lib/eidoverseCitySurface.js@@ -0,0 +1,147 @@+/** Deterministic paving and physical signs, uploaded through Eidoverse's GLB door. */+import { createHash } from 'node:crypto';+import { eidoverseDistrictPoint, eidoverseDistrictYaw } from './eidoverseCityLayout.js';++// A small architectural stencil. Geometry, not a font download or raster asset.+const GLYPHS = {+ A: '01110/10001/10001/11111/10001/10001/10001', B: '11110/10001/10001/11110/10001/10001/11110',+ C: '01111/10000/10000/10000/10000/10000/01111', D: '11110/10001/10001/10001/10001/10001/11110',+ E: '11111/10000/10000/11110/10000/10000/11111', F: '11111/10000/10000/11110/10000/10000/10000',+ G: '01111/10000/10000/10111/10001/10001/01111', H: '10001/10001/10001/11111/10001/10001/10001',+ I: '11111/00100/00100/00100/00100/00100/11111', J: '00111/00010/00010/00010/10010/10010/01100',+ K: '10001/10010/10100/11000/10100/10010/10001', L: '10000/10000/10000/10000/10000/10000/11111',+ M: '10001/11011/10101/10101/10001/10001/10001', N: '10001/11001/10101/10011/10001/10001/10001',+ O: '01110/10001/10001/10001/10001/10001/01110', P: '11110/10001/10001/11110/10000/10000/10000',+ Q: '01110/10001/10001/10001/10101/10010/01101', R: '11110/10001/10001/11110/10100/10010/10001',+ S: '01111/10000/10000/01110/00001/00001/11110', T: '11111/00100/00100/00100/00100/00100/00100',+ U: '10001/10001/10001/10001/10001/10001/01110', V: '10001/10001/10001/10001/10001/01010/00100',+ W: '10001/10001/10001/10101/10101/10101/01010', X: '10001/10001/01010/00100/01010/10001/10001',+ Y: '10001/10001/01010/00100/00100/00100/00100', Z: '11111/00001/00010/00100/01000/10000/11111',+ '-': '00000/00000/00000/11111/00000/00000/00000',+};++const linearColor = (hex) => [1, 3, 5].map((start) => {+ const s = parseInt(hex.slice(start, start + 2), 16) / 255;+ return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;+});++function surfaceGeometry(districts) {+ const groups = [{ positions: [], normals: [], colors: [], indices: [] },+ { positions: [], normals: [], colors: [], indices: [] }];+ let districtFrame = null;+ const quad = (points, normal, color, material = 0) => {+ if (districtFrame) {+ points = points.map(([x, y, z]) => eidoverseDistrictPoint(districtFrame, x, y, z));+ const yaw = eidoverseDistrictYaw(districtFrame);+ normal = [Math.cos(yaw) * normal[0] + Math.sin(yaw) * normal[2], normal[1], -Math.sin(yaw) * normal[0] + Math.cos(yaw) * normal[2]];+ }+ const group = groups[material];+ const start = group.positions.length / 3;+ const rgb = linearColor(color);+ for (const point of points) {+ group.positions.push(...point); group.normals.push(...normal); group.colors.push(...rgb);+ }+ group.indices.push(start, start + 1, start + 2, start, start + 2, start + 3);+ };+ const floor = (x0, z0, x1, z1, y, color) => quad(+ [[x0, y, z0], [x0, y, z1], [x1, y, z1], [x1, y, z0]], [0, 1, 0], color);+ const sign = (x0, y0, x1, y1, z, color) => quad(+ [[x0, y0, z], [x1, y0, z], [x1, y1, z], [x0, y1, z]], [0, 0, 1], color, 1);+ const ring = (cx, cz, inner, outer, y, color, steps = 96) => {+ for (let i = 0; i < steps; i += 1) {+ const a = i / steps * Math.PI * 2, b = (i + 1) / steps * Math.PI * 2;+ quad([[cx + Math.sin(a) * inner, y, cz + Math.cos(a) * inner],+ [cx + Math.sin(a) * outer, y, cz + Math.cos(a) * outer],+ [cx + Math.sin(b) * outer, y, cz + Math.cos(b) * outer],+ [cx + Math.sin(b) * inner, y, cz + Math.cos(b) * inner]], [0, 1, 0], color);+ }+ };+ // A shared pedestrian promenade encircles the grassy arrival park.+ ring(0, 0, 27.7, 32.3, 0.015, '#dad3bd');+ ring(0, 0, 28, 32, 0.02, '#b7b59f');+ for (const district of districts) {+ districtFrame = district;+ const x = 0, y = 0, z = 0;+ // Rounded forecourts leave planted ground between neighboring halls.+ ring(0, 3, 0, 10.8, 0.018, '#d0c7b1', 48);+ floor(-8.4, -12.4, 8.4, -3.4, 0.02, '#d0c7b1');+ const distance = Math.hypot(district.anchor[0], district.anchor[2]);+ floor(-1.8, 3, 1.8, Math.max(4, distance - 30), 0.025, '#e1d9c3');+ // Low flower beds and timber seats frame the gathering terrace.+ for (const side of [-1, 1]) {+ ring(side * 8.5, 7, 0, 1.6, 0.03, '#527449', 20);+ for (let flower = 0; flower < 12; flower += 1) {+ const angle = flower / 12 * Math.PI * 2;+ ring(side * 8.5 + Math.sin(angle), 7 + Math.cos(angle), 0, 0.16, 0.09,+ flower % 2 ? '#e5c677' : district.accent, 6);+ }+ floor(side * 6 - 1.2, 7, side * 6 + 1.2, 7.6, 0.48, '#977654');+ sign(side * 6 - 1.2, 0.48, side * 6 + 1.2, 0.95, 7.62, '#977654');+ sign(side * 6 - 1, 0, side * 6 - 0.85, 0.48, 7.3, '#4a5147');+ sign(side * 6 + 0.85, 0, side * 6 + 1, 0.48, 7.3, '#4a5147');+ }+ const text = String(district.label).toUpperCase().replace(/[^A-Z -]/g, '').slice(0, 24);+ const cell = Math.min(0.12, 12 / Math.max(1, text.length * 6));+ const width = text.length * 6 * cell;+ const bottom = y + (district.id === 'nexus' ? 4.05 : 2.75);+ const faceZ = z - 3.86;+ sign(x - width / 2 - 0.35, bottom - 0.15, x + width / 2 + 0.35, bottom + 7 * cell + 0.15, faceZ, '#172c3e');+ sign(x - width / 2 - 0.35, bottom - 0.22, x + width / 2 + 0.35, bottom - 0.16, faceZ + 0.002, district.accent);+ [...text].forEach((letter, index) => {+ for (const [row, bits] of (GLYPHS[letter] || '').split('/').entries()) {+ for (const [column, bit] of [...bits].entries()) {+ if (bit !== '1') continue;+ const left = x - width / 2 + (index * 6 + column) * cell;+ const base = bottom + (6 - row) * cell;+ sign(left, base, left + cell * 0.9, base + cell * 0.9, faceZ + 0.005, '#e3f4ef');+ }+ }+ });+ }+ districtFrame = null;+ return groups;+}++/** Minimal standard glTF 2.0: two meshes, vertex colors, no external resources. */+export function buildEidoverseCitySurface(districts) {+ if (!Array.isArray(districts) || !districts.length || districts.length > 12+ || districts.some(({ anchor }) => !Array.isArray(anchor) || anchor.length !== 3+ || anchor.some((n) => !Number.isFinite(n) || Math.abs(n) > 10_000))) {+ throw new RangeError('City districts need finite anchors within 10,000 metres.');+ }+ const ordered = [...districts].sort((a, b) => a.id.localeCompare(b.id));+ const geometry = surfaceGeometry(ordered);+ const chunks = [], bufferViews = [], accessors = [];+ let byteOffset = 0;+ const attribute = (values, components, integer = false) => {+ const bytes = Buffer.alloc(values.length * 4);+ values.forEach((value, index) => integer ? bytes.writeUInt32LE(value, index * 4) : bytes.writeFloatLE(value, index * 4));+ const min = Array(components).fill(Infinity), max = Array(components).fill(-Infinity);+ values.forEach((value, index) => { const axis = index % components; const encoded = integer ? value : Math.fround(value); min[axis] = Math.min(min[axis], encoded); max[axis] = Math.max(max[axis], encoded); });+ chunks.push(bytes);+ bufferViews.push({ buffer: 0, byteOffset, byteLength: bytes.length, target: integer ? 34963 : 34962 });+ byteOffset += bytes.length;+ accessors.push({ bufferView: bufferViews.length - 1, componentType: integer ? 5125 : 5126,+ count: values.length / components, type: components === 1 ? 'SCALAR' : 'VEC3', min, max });+ return accessors.length - 1;+ };+ const meshes = geometry.map((group, material) => ({ primitives: [{+ attributes: { POSITION: attribute(group.positions, 3), NORMAL: attribute(group.normals, 3), COLOR_0: attribute(group.colors, 3) },+ indices: attribute(group.indices, 1, true), material,+ }] }));+ const gltf = { asset: { version: '2.0', generator: 'PortOS Commons' }, scene: 0,+ scenes: [{ nodes: [0, 1] }], nodes: [{ mesh: 0, name: 'Paving' }, { mesh: 1, name: 'District signs' }], meshes,+ materials: [{ pbrMetallicRoughness: { baseColorFactor: [1, 1, 1, 1], metallicFactor: 0, roughnessFactor: 1 } },+ { pbrMetallicRoughness: { baseColorFactor: [1, 1, 1, 1], metallicFactor: 0, roughnessFactor: 1 }, extensions: { KHR_materials_unlit: {} } }],+ extensionsUsed: ['KHR_materials_unlit'], buffers: [{ byteLength: byteOffset }], bufferViews, accessors };+ const json = Buffer.from(JSON.stringify(gltf));+ const jsonLength = Math.ceil(json.length / 4) * 4;+ const header = Buffer.alloc(20);+ header.writeUInt32LE(0x46546c67, 0); header.writeUInt32LE(2, 4);+ header.writeUInt32LE(28 + jsonLength + byteOffset, 8);+ header.writeUInt32LE(jsonLength, 12); header.writeUInt32LE(0x4e4f534a, 16);+ const binHeader = Buffer.alloc(8); binHeader.writeUInt32LE(byteOffset, 0); binHeader.writeUInt32LE(0x004e4942, 4);+ const bytes = Buffer.concat([header, json, Buffer.alloc(jsonLength - json.length, 0x20), binHeader, ...chunks]);+ const hash = createHash('sha256').update(bytes).digest('hex').slice(0, 16);+ return { bytes, path: `store/${hash}.glb`, fingerprint: hash };+}diff --git a/server/lib/eidoverseCitySurface.test.js b/server/lib/eidoverseCitySurface.test.jsnew file mode 100644index 0000000000..f1463e47f3--- /dev/null+++ b/server/lib/eidoverseCitySurface.test.js@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest';+import { createHash } from 'node:crypto';+import { buildEidoverseCitySurface } from './eidoverseCitySurface.js';+import { EIDOVERSE_WORLD_DESIGN_V3 } from './eidoverseWorldDesign.js';++// Serialization boundary: readers require exact chunk lengths, finite accessors,+// valid indices, and an entirely self-contained artifact on every install.+describe('Commons portable GLB', () => {+ it('encodes valid self-contained geometry at a stable content address', () => {+ const first = buildEidoverseCitySurface(EIDOVERSE_WORLD_DESIGN_V3.districts);+ expect(buildEidoverseCitySurface([...EIDOVERSE_WORLD_DESIGN_V3.districts].reverse())).toEqual(first);+ const { bytes } = first;+ expect(bytes.length).toBeLessThan(1_000_000);+ expect(bytes.readUInt32LE(0)).toBe(0x46546c67);+ expect(bytes.readUInt32LE(4)).toBe(2);+ expect(bytes.readUInt32LE(8)).toBe(bytes.length);+ const jsonLength = bytes.readUInt32LE(12);+ const gltf = JSON.parse(bytes.subarray(20, 20 + jsonLength).toString());+ const binStart = 28 + jsonLength;+ expect(bytes.readUInt32LE(24 + jsonLength)).toBe(0x004e4942);+ expect(gltf.buffers).toEqual([{ byteLength: bytes.length - binStart }]);+ expect(gltf.images).toBeUndefined();+ for (const mesh of gltf.meshes) for (const primitive of mesh.primitives) {+ const positions = gltf.accessors[primitive.attributes.POSITION];+ expect(positions.count).toBeGreaterThan(0);+ const indices = gltf.accessors[primitive.indices];+ const view = gltf.bufferViews[indices.bufferView];+ const references = Array.from({ length: indices.count }, (_, i) => bytes.readUInt32LE(binStart + view.byteOffset + i * 4));+ expect(references.every((index) => index < positions.count)).toBe(true);+ }+ for (const accessor of gltf.accessors) {+ expect([...accessor.min, ...accessor.max].every(Number.isFinite)).toBe(true);+ const view = gltf.bufferViews[accessor.bufferView];+ expect(view.byteOffset + view.byteLength).toBeLessThanOrEqual(gltf.buffers[0].byteLength);+ expect(view.byteOffset % 4).toBe(0);+ }+ expect(first.path).toBe(`store/${createHash('sha256').update(bytes).digest('hex').slice(0, 16)}.glb`);+ const renamed = structuredClone(EIDOVERSE_WORLD_DESIGN_V3.districts);+ renamed[0].label = 'Example civic hall';+ expect(buildEidoverseCitySurface(renamed).path).not.toBe(first.path);+ });+});diff --git a/server/lib/eidoverseValidation.js b/server/lib/eidoverseValidation.jsindex e1b19934c0..fb552aa596 100644--- a/server/lib/eidoverseValidation.js+++ b/server/lib/eidoverseValidation.js@@ -189,6 +189,9 @@ const eidoverseAssetSlotsSchema = z.object({peer: eidoverseAssetSlotSchema,activity: eidoverseAssetSlotSchema,district: eidoverseAssetSlotSchema,+ desk: eidoverseAssetSlotSchema.optional(),+ barrel: eidoverseAssetSlotSchema.optional(),+ tree: eidoverseAssetSlotSchema.optional(),}).strict();const eidoverseResolvedAssetsSchema = z.record(z.string().trim().min(1).max(40), eidoverseAssetPathSchema)@@ -229,7 +232,7 @@ const eidoverseProjectionEnvironmentSchema = z.object({}).strict();const eidoverseProjectionRecipeV2Schema = z.object({- version: z.literal(2),+ version: z.union([z.literal(2), z.literal(3)]),name: z.string().trim().min(1).max(80),maxEntities: z.number().int().min(1).max(48),includes: eidoverseProjectionIncludesSchema,@@ -251,7 +254,7 @@ const eidoverseProjectionRecipeV2Schema = z.object({nodes: z.array(eidoverseVector3Schema).min(1).max(8),}).strict()).max(16),environment: eidoverseProjectionEnvironmentSchema,- assetRecipe: z.object({ version: z.literal(2), slots: eidoverseAssetSlotsSchema }).strict(),+ assetRecipe: z.object({ version: z.union([z.literal(2), z.literal(3)]), slots: eidoverseAssetSlotsSchema }).strict(),assets: eidoverseResolvedAssetsSchema,}).strict();@@ -295,6 +298,7 @@ export const eidoverseWorldConfigPatchSchema = z.object({assetOverrides: z.partialRecord(z.enum(['nexus', 'app', 'agent', 'task', 'goal', 'memory', 'storage', 'peer', 'activity', 'district',+ 'desk', 'barrel', 'tree',// V1 used resource-kind keys. Keep accepting them so an upgraded install// can round-trip its preserved custom paths while the V2 semantic slots// become the preferred editing surface.diff --git a/server/lib/eidoverseWorldDesign.js b/server/lib/eidoverseWorldDesign.jsindex 0d3c025893..c80784b32c 100644--- a/server/lib/eidoverseWorldDesign.js+++ b/server/lib/eidoverseWorldDesign.js@@ -11,8 +11,8 @@ import { createHash } from 'node:crypto';import { canonicalStringify, deepMerge } from './objects.js';export const EIDOVERSE_WORLD_STATE_SCHEMA_VERSION = 3;-export const EIDOVERSE_WORLD_DESIGN_VERSION = 2;-export const EIDOVERSE_ASSET_RECIPE_VERSION = 2;+export const EIDOVERSE_WORLD_DESIGN_VERSION = 3;+export const EIDOVERSE_ASSET_RECIPE_VERSION = 3;export const EIDOVERSE_MAX_LIVE_ENTITIES = 48;export const EIDOVERSE_LIBRARY_MODEL_ROOT = 'eidoverse/assets/models/';export const EIDOVERSE_MANAGED_PREFIX = 'portos-design-v2-';@@ -97,7 +97,7 @@ const assetSlot = ({ preferredPaths, fallbackQueries, requiredTokens, excludedTo// Paths are preferences, not bundled payloads. Queries allow a future library// to satisfy the same semantic role even when its filenames evolve.export const EIDOVERSE_ASSET_RECIPE_V2 = Object.freeze({- version: EIDOVERSE_ASSET_RECIPE_VERSION,+ version: 2,slots: {nexus: assetSlot({preferredPaths: [`${MODEL_ROOT}scifi_perimeter_watchtower_standalone_or_with_wall_middle_four_way.glb`],@@ -176,14 +176,14 @@ export const EIDOVERSE_DISTRICTS_V2 = Object.freeze([export const EIDOVERSE_ASSET_SLOTS_BY_DISTRICT = Object.freeze({// Include retired V1 kind keys as well as V2 semantic slots. A scoped reset// must clear hidden preserved overrides that can still win assetPathFor().- nexus: ['nexus', 'health', 'operations', 'feature', 'district'],- apps: ['app'],- agents: ['agent', 'task'],- goals: ['goal', 'jira'],- memory: ['memory'],- data: ['storage'],- federation: ['peer'],- activity: ['activity', 'productivity'],+ nexus: ['nexus', 'health', 'operations', 'feature', 'district', 'activity', 'tree'],+ apps: ['app', 'desk', 'activity', 'tree'],+ agents: ['agent', 'task', 'desk', 'app', 'barrel', 'activity', 'tree'],+ goals: ['goal', 'jira', 'desk', 'app', 'activity', 'tree'],+ memory: ['memory', 'activity', 'tree'],+ data: ['storage', 'app', 'desk', 'barrel', 'task', 'activity', 'tree'],+ federation: ['peer', 'barrel', 'task', 'activity', 'tree'],+ activity: ['activity', 'productivity', 'tree'],});export const EIDOVERSE_PATHS_V2 = Object.freeze(EIDOVERSE_DISTRICTS_V2@@ -200,7 +200,7 @@ export const EIDOVERSE_PATHS_V2 = Object.freeze(EIDOVERSE_DISTRICTS_V2})));export const EIDOVERSE_WORLD_DESIGN_V2 = Object.freeze({- version: EIDOVERSE_WORLD_DESIGN_VERSION,+ version: 2,name: 'Luminous Systems Garden',maxEntities: EIDOVERSE_MAX_LIVE_ENTITIES,includes: Object.fromEntries(EIDOVERSE_SOURCE_KEYS.map((key) => [key, true])),@@ -241,6 +241,71 @@ export const EIDOVERSE_WORLD_DESIGN_V2 = Object.freeze({assets: {},});+// V2 remains frozen as the exact migration baseline. V3 uses the framework's+// existing structure component; the shared architecture contains no user data.+export const EIDOVERSE_ASSET_RECIPE_V3 = {+ version: 3,+ slots: {+ ...EIDOVERSE_ASSET_RECIPE_V2.slots,+ app: { ...EIDOVERSE_ASSET_RECIPE_V2.slots.app,+ preferredPaths: [`${MODEL_ROOT}scif_cyberpunk_crt_retro_computer_monitor_screen_keyboard_tower.glb`],+ fallbackQueries: ['retro computer', 'computer terminal'], requiredTokens: ['computer'], maxBytes: 44_000_000 },+ storage: { ...EIDOVERSE_ASSET_RECIPE_V2.slots.storage,+ preferredPaths: [`${MODEL_ROOT}single_loose_computer_server.glb`],+ fallbackQueries: ['computer server'], requiredTokens: ['server'] },+ task: { ...EIDOVERSE_ASSET_RECIPE_V2.slots.task,+ preferredPaths: [`${MODEL_ROOT}crate_large_blue.glb`] },+ desk: assetSlot({+ preferredPaths: [`${MODEL_ROOT}scifi_art_deco_office_desk.glb`],+ fallbackQueries: ['office desk'], requiredTokens: ['desk'], maxBytes: 24_000_000,+ fallback: `${MODEL_ROOT}crate_large_blue.glb`,+ }),+ barrel: assetSlot({+ preferredPaths: [`${MODEL_ROOT}scifi_barrels_single.glb`],+ fallbackQueries: ['barrel'], requiredTokens: ['barrel'], maxBytes: 16_000_000,+ fallback: `${MODEL_ROOT}crate_large_blue.glb`,+ }),+ tree: assetSlot({+ preferredPaths: [`${MODEL_ROOT}palm_date_tree_tropical_deseert_oasis_plant.glb`],+ fallbackQueries: ['palm tree'], requiredTokens: ['tree'], maxBytes: 24_000_000,+ fallback: `${MODEL_ROOT}stylized_yucca_joshua_tree_desert_cactus_plant.glb`,+ }),+ },+};++export const EIDOVERSE_WORLD_DESIGN_V3 = {+ ...structuredClone(EIDOVERSE_WORLD_DESIGN_V2),+ version: 3,+ name: 'PortOS Commons',+ districts: EIDOVERSE_DISTRICTS_V2.map((district) => ({+ ...district,+ anchor: ({+ nexus: [-44, 0, 0], apps: [-31.11, 0, -31.11], agents: [0, 0, -44],+ goals: [31.11, 0, -31.11], memory: [44, 0, 0], data: [31.11, 0, 31.11],+ federation: [-31.11, 0, 31.11], activity: [0, 0, 44],+ })[district.id],+ label: ({ apps: 'App Arcade', memory: 'Memory Library', data: 'Data Depot', federation: 'Federation Terminal', activity: 'Activity Exchange' })[district.id] || district.label,+ landmark: ({ nexus: 'civic spire', apps: 'console arcade', agents: 'workshop courtyard', goals: 'beacon hall', memory: 'reading hall', data: 'storage depot', federation: 'arrival gate', activity: 'exchange hall' })[district.id],+ direction: ({ nexus: 'West', memory: 'East', data: 'Southeast', activity: 'South' })[district.id] || district.direction,+ })),+ // A pedestrian promenade links inward-facing halls around the arrival park.+ paths: [],+ environment: {+ ...structuredClone(EIDOVERSE_WORLD_DESIGN_V2.environment),+ sky: { ...structuredClone(EIDOVERSE_WORLD_DESIGN_V2.environment.sky), hours: 10, fog: 0.16, exposure: 1.15 },+ terrain: {+ seed: 'portos-commons-v3', size: 180, segments: 96,+ amplitude: 0.7, flatRadius: 65,+ layers: [{ color: '#527044', repeat: 32 }, { color: '#738459', repeat: 18 }],+ },+ grass: {+ species: 'grass', width: 38, depth: 38, center: [0, 0],+ height: 0.24, color: 'emerald', density: 0.7,+ },+ },+ assetRecipe: EIDOVERSE_ASSET_RECIPE_V3,+};+const EIDOVERSE_V2_DEFAULT_CHANGES = Object.freeze([{ area: 'Composition', from: 'uniform resource lanes', to: 'eight semantic districts and circulation paths' },{ area: 'Atmosphere', from: 'terrain only', to: 'warm dawn sky, authored light, restrained fog, and sparse grass' },@@ -251,6 +316,7 @@ const EIDOVERSE_V2_DEFAULT_CHANGES = Object.freeze([export const EIDOVERSE_WORLD_DESIGNS = Object.freeze({1: EIDOVERSE_WORLD_DESIGN_V1,2: EIDOVERSE_WORLD_DESIGN_V2,+ 3: EIDOVERSE_WORLD_DESIGN_V3,});function freezeWorldContract(value) {@@ -269,6 +335,8 @@ freezeWorldContract(EIDOVERSE_DISTRICTS_V2);freezeWorldContract(EIDOVERSE_ASSET_SLOTS_BY_DISTRICT);freezeWorldContract(EIDOVERSE_PATHS_V2);freezeWorldContract(EIDOVERSE_WORLD_DESIGN_V2);+freezeWorldContract(EIDOVERSE_ASSET_RECIPE_V3);+freezeWorldContract(EIDOVERSE_WORLD_DESIGN_V3);freezeWorldContract(EIDOVERSE_WORLD_DESIGNS);const isObject = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);@@ -289,9 +357,9 @@ function diffLeaves(value, baseline) {}export function resolveEidoverseDesign(userOverrides = {}, assetResolutions = {}) {- const resolved = mergeDesign(EIDOVERSE_WORLD_DESIGN_V2, userOverrides);+ const resolved = mergeDesign(EIDOVERSE_WORLD_DESIGN_V3, userOverrides);resolved.version = EIDOVERSE_WORLD_DESIGN_VERSION;- resolved.assetRecipe = clone(EIDOVERSE_ASSET_RECIPE_V2);+ resolved.assetRecipe = clone(EIDOVERSE_ASSET_RECIPE_V3);resolved.assets = { ...(resolved.assets || {}) };for (const [slot, resolution] of Object.entries(assetResolutions || {})) {const path = typeof resolution === 'string' ? resolution : resolution?.path;@@ -310,7 +378,8 @@ export function extractEidoverseDesignOverrides(recipe) {for (const section of ['name', 'maxEntities', 'includes', 'limits', 'scale', 'districts', 'paths', 'environment']) {if (recipe[section] !== undefined) candidate[section] = clone(recipe[section]);}- return diffLeaves(mergeDesign(EIDOVERSE_WORLD_DESIGN_V2, candidate), EIDOVERSE_WORLD_DESIGN_V2) || {};+ const baseline = EIDOVERSE_WORLD_DESIGNS[recipe.version] || EIDOVERSE_WORLD_DESIGN_V3;+ return diffLeaves(mergeDesign(baseline, candidate), baseline) || {};}const validLibraryPath = (path) => typeof path === 'string'@@ -504,7 +573,13 @@ export function migrateEidoverseWorldState(raw, { now = new Date().toISOString()? input.userOverrides: extractEidoverseDesignOverrides(input.recipe);const assetResolutions = isObject(input.assetResolutions) ? input.assetResolutions : {};- const report = removedMachineDerivedIdentity+ const upgradingDesign = Number(input.selectedDesignVersion ?? input.recipe?.version ?? 2) < 3;+ const report = upgradingDesign+ ? { ...(input.migrationReport || {}),+ ...(removedMachineDerivedIdentity ? { removedMachineDerivedIdentity: true } : {}),+ status: 'ready', fromDesignVersion: Number(input.selectedDesignVersion ?? input.recipe?.version ?? 2),+ toDesignVersion: 3, preservedOverrides: Object.keys(userOverrides), at: now }+ : removedMachineDerivedIdentity? {...(input.migrationReport || {}),status: input.migrationReport?.status || 'applied',@@ -519,6 +594,7 @@ export function migrateEidoverseWorldState(raw, { now = new Date().toISOString()schemaVersion: EIDOVERSE_WORLD_STATE_SCHEMA_VERSION,labelAliases: normalizeEidoverseLabelAliases(input.labelAliases),selectedDesignVersion: EIDOVERSE_WORLD_DESIGN_VERSION,+ ...(upgradingDesign ? { pendingDesignVersion: 3 } : {}),assetRecipeVersion: EIDOVERSE_ASSET_RECIPE_VERSION,userOverrides,assetResolutions,@@ -629,7 +705,7 @@ function addCatalogCandidate(catalog, candidate) {export function inspectEidoverseAssetResolutionLocks({ existing = {}, overrides = {} } = {}) {const resolutions = {};const invalidated = [];- for (const [slotName, slot] of Object.entries(EIDOVERSE_ASSET_RECIPE_V2.slots)) {+ for (const [slotName, slot] of Object.entries(EIDOVERSE_ASSET_RECIPE_V3.slots)) {const lock = isObject(existing[slotName]) ? existing[slotName] : null;const overridePath = overrides[slotName];const hasOverride = isValidEidoverseAssetOverridePath(overridePath);@@ -672,7 +748,7 @@ export function resolveEidoverseAssetRecipe({.digest('hex').slice(0, 16);const resolutions = {};const missing = [];- for (const [slotName, slot] of Object.entries(EIDOVERSE_ASSET_RECIPE_V2.slots)) {+ for (const [slotName, slot] of Object.entries(EIDOVERSE_ASSET_RECIPE_V3.slots)) {const recipeFingerprint = contractFingerprint(slot);const overridePath = overrides[slotName];const locked = isObject(existing[slotName]) ? existing[slotName] : { path: existing[slotName] };@@ -685,6 +761,7 @@ export function resolveEidoverseAssetRecipe({catalogFingerprint: prior?.catalogFingerprint || fingerprint,recipeFingerprint,bytes: prior?.bytes ?? bytes,+ ...(prior?.bounds ? { bounds: clone(prior.bounds) } : {}),strategy,// `source` is retained for the V2 UI and pre-metadata lock readers.source: strategy,diff --git a/server/lib/eidoverseWorldDesign.test.js b/server/lib/eidoverseWorldDesign.test.jsindex ae36930ee5..0c7f9c46f1 100644--- a/server/lib/eidoverseWorldDesign.test.js+++ b/server/lib/eidoverseWorldDesign.test.js@@ -1,8 +1,9 @@import { describe, expect, it } from 'vitest';import {- EIDOVERSE_ASSET_RECIPE_V2,+ EIDOVERSE_ASSET_RECIPE_V3,EIDOVERSE_WORLD_DESIGN_V1,EIDOVERSE_WORLD_DESIGN_V2,+ EIDOVERSE_WORLD_DESIGN_V3,EIDOVERSE_WORLD_DESIGNS,extractEidoverseDesignOverrides,inspectEidoverseAssetResolutionLocks,@@ -10,7 +11,7 @@ import {resolveEidoverseAssetRecipe,} from './eidoverseWorldDesign.js';-const catalog = () => Object.values(EIDOVERSE_ASSET_RECIPE_V2.slots).flatMap((slot) => [+const catalog = () => Object.values(EIDOVERSE_ASSET_RECIPE_V3.slots).flatMap((slot) => [{ path: slot.preferredPaths[0], size: Math.min(slot.maxBytes, 10_000_000) },{ path: slot.fallback, size: 4_000_000 },]);@@ -18,9 +19,9 @@ const catalog = () => Object.values(EIDOVERSE_ASSET_RECIPE_V2.slots).flatMap((sldescribe('Eidoverse World Design V2', () => {it('keeps the shipped migration baselines deeply immutable', () => {expect(Object.isFrozen(EIDOVERSE_WORLD_DESIGN_V1.assets)).toBe(true);- expect(Object.isFrozen(EIDOVERSE_ASSET_RECIPE_V2.slots.app.preferredPaths)).toBe(true);+ expect(Object.isFrozen(EIDOVERSE_ASSET_RECIPE_V3.slots.app.preferredPaths)).toBe(true);expect(Object.isFrozen(EIDOVERSE_WORLD_DESIGN_V2.environment.lights[0])).toBe(true);- expect(EIDOVERSE_WORLD_DESIGNS).toEqual({ 1: EIDOVERSE_WORLD_DESIGN_V1, 2: EIDOVERSE_WORLD_DESIGN_V2 });+ expect(EIDOVERSE_WORLD_DESIGNS).toEqual({ 1: EIDOVERSE_WORLD_DESIGN_V1, 2: EIDOVERSE_WORLD_DESIGN_V2, 3: EIDOVERSE_WORLD_DESIGN_V3 });});it('upgrades untouched V1 leaves to V2 without manufacturing overrides', () => {@@ -31,15 +32,31 @@ describe('Eidoverse World Design V2', () => {expect(migrated.compatible).toBe(true);expect(migrated.state).toMatchObject({schemaVersion: 3,- selectedDesignVersion: 2,+ selectedDesignVersion: 3,lastAppliedDesignVersion: 1,- pendingDesignVersion: 2,+ pendingDesignVersion: 3,userOverrides: {},- recipe: { version: 2, name: 'Luminous Systems Garden' },+ recipe: { version: 3, name: 'PortOS Commons' },});expect(migrated.report).toMatchObject({ status: 'ready', preservedOverrides: [] });});+ it('upgrades the shipped V2 design while retaining explicit customization and the last applied version', () => {+ const pristine = migrateEidoverseWorldState({ schemaVersion: 3, selectedDesignVersion: 2,+ lastAppliedDesignVersion: 2, recipe: EIDOVERSE_WORLD_DESIGN_V2 });+ expect(pristine.state.userOverrides).toEqual({});+ expect(pristine.state.recipe).toEqual(EIDOVERSE_WORLD_DESIGN_V3);+ expect(pristine.state).toMatchObject({ lastAppliedDesignVersion: 2, pendingDesignVersion: 3 });+ const customized = migrateEidoverseWorldState({ schemaVersion: 3, selectedDesignVersion: 2,+ lastAppliedDesignVersion: 2, migrationReport: { unsupportedOverrides: { customExtension: 'retained' }, ignoredLegacyLayout: ['districts'], removedMachineDerivedIdentity: true }, userOverrides: { name: 'Example Commons', includes: { apps: false },+ assets: { app: 'store/example-custom.glb' } }, labelAliases: { 'app-0123456789ab': 'Example alias' } });+ expect(customized.state.recipe).toMatchObject({ name: 'Example Commons', includes: { apps: false },+ assets: { app: 'store/example-custom.glb' }, version: 3 });+ expect(customized.state.migrationReport).toMatchObject({ unsupportedOverrides: { customExtension: 'retained' }, ignoredLegacyLayout: ['districts'], removedMachineDerivedIdentity: true, toDesignVersion: 3 });+ expect(customized.state.labelAliases).toEqual({ 'app-0123456789ab': 'Example alias' });+ expect(migrateEidoverseWorldState(customized.state).state).toEqual(customized.state);+ });+it('preserves customized V1 leaves while inheriting new V2 defaults', () => {const migrated = migrateEidoverseWorldState({schemaVersion: 1,@@ -55,7 +72,7 @@ describe('Eidoverse World Design V2', () => {assets: { app: 'store/example-local-model' },});expect(migrated.state.recipe).toMatchObject({- version: 2,+ version: 3,limits: { apps: 3, agents: EIDOVERSE_WORLD_DESIGN_V2.limits.agents },assets: { app: 'store/example-local-model' },});@@ -97,9 +114,9 @@ describe('Eidoverse World Design V2', () => {});expect(migrated.state.recipe.environment.terrain).toMatchObject({seed: 'example-custom',- size: EIDOVERSE_WORLD_DESIGN_V2.environment.terrain.size,- segments: EIDOVERSE_WORLD_DESIGN_V2.environment.terrain.segments,- layers: EIDOVERSE_WORLD_DESIGN_V2.environment.terrain.layers,+ size: EIDOVERSE_WORLD_DESIGN_V3.environment.terrain.size,+ segments: EIDOVERSE_WORLD_DESIGN_V3.environment.terrain.segments,+ layers: EIDOVERSE_WORLD_DESIGN_V3.environment.terrain.layers,});});@@ -209,7 +226,7 @@ describe('Eidoverse World Design V2', () => {});expect(migrateEidoverseWorldState({schemaVersion: 2,- selectedDesignVersion: 2,+ selectedDesignVersion: 3,assetRecipeVersion: 99,})).toMatchObject({compatible: false,@@ -225,19 +242,19 @@ describe('Eidoverse World Design V2', () => {});expect(first.missing).toEqual([]);- expect(Object.keys(first.resolutions)).toHaveLength(10);+ expect(Object.keys(first.resolutions)).toHaveLength(13);expect(second).toEqual(first);expect(Object.values(first.resolutions).every(({ path }) => path.startsWith('eidoverse/assets/models/'))).toBe(true);expect(first.resolutions.storage.path).not.toBe(first.resolutions.app.path);expect(first.resolutions.app).toMatchObject({- designVersion: 2,- assetRecipeVersion: 2,+ designVersion: 3,+ assetRecipeVersion: 3,slot: 'app',strategy: 'preferred',shippedDefault: true,userOverride: false,});- expect(JSON.stringify(EIDOVERSE_ASSET_RECIPE_V2)).not.toMatch(/\.glb\s*data:|base64/i);+ expect(JSON.stringify(EIDOVERSE_ASSET_RECIPE_V3)).not.toMatch(/\.glb\s*data:|base64/i);});it('invalidates only a slot whose recipe fingerprint changed', () => {@@ -299,21 +316,21 @@ describe('Eidoverse World Design V2', () => {});it('uses deterministic search results when a preferred library path is absent', () => {- const appSlot = EIDOVERSE_ASSET_RECIPE_V2.slots.app;+ const appSlot = EIDOVERSE_ASSET_RECIPE_V3.slots.app;const searchedPath = 'eidoverse/assets/models/example_server_console.glb';const withoutApp = catalog().filter(({ path }) => (path !== appSlot.preferredPaths[0] && path !== appSlot.fallback));const result = resolveEidoverseAssetRecipe({files: withoutApp,- searchResults: { 'computer server': [{ path: searchedPath, size: 2_000_000 }] },+ searchResults: { 'retro computer': [{ path: searchedPath, size: 2_000_000 }] },});expect(result.resolutions.app).toMatchObject({ path: searchedPath, source: 'query' });});it('accepts renamed search hits without substring-matching excluded whole tokens', () => {- const taskSlot = EIDOVERSE_ASSET_RECIPE_V2.slots.task;+ const taskSlot = EIDOVERSE_ASSET_RECIPE_V3.slots.task;const renamedPath = 'eidoverse/assets/models/example_cargo_pod_blue.glb';const withoutTask = catalog().filter(({ path }) => (path !== taskSlot.preferredPaths[0] && path !== taskSlot.fallback@@ -327,7 +344,7 @@ describe('Eidoverse World Design V2', () => {});it('keeps catalog entries with unknown sizes and records nullable lock bytes', () => {- const appPath = EIDOVERSE_ASSET_RECIPE_V2.slots.app.preferredPaths[0];+ const appPath = EIDOVERSE_ASSET_RECIPE_V3.slots.app.preferredPaths[0];const files = catalog().map((candidate) => (candidate.path === appPath ? { path: candidate.path } : candidate));@@ -341,7 +358,7 @@ describe('Eidoverse World Design V2', () => {});it('uses a safe catalog GLB as a last resort after semantic searches are exhausted', () => {- const taskSlot = EIDOVERSE_ASSET_RECIPE_V2.slots.task;+ const taskSlot = EIDOVERSE_ASSET_RECIPE_V3.slots.task;const files = catalog().filter(({ path }) => (path !== taskSlot.preferredPaths[0] && path !== taskSlot.fallback));@@ -355,7 +372,7 @@ describe('Eidoverse World Design V2', () => {});it('searches before accepting an explicit fallback asset', () => {- const appSlot = EIDOVERSE_ASSET_RECIPE_V2.slots.app;+ const appSlot = EIDOVERSE_ASSET_RECIPE_V3.slots.app;const files = catalog().filter(({ path }) => path !== appSlot.preferredPaths[0]);const beforeSearch = resolveEidoverseAssetRecipe({ files });const afterSearch = resolveEidoverseAssetRecipe({diff --git a/server/lib/eidoverseWorldLabels.js b/server/lib/eidoverseWorldLabels.jsindex f1ba80bcea..6605ced911 100644--- a/server/lib/eidoverseWorldLabels.js+++ b/server/lib/eidoverseWorldLabels.js@@ -36,10 +36,7 @@ export function eidoverseLabelCapabilities(version) {const MAX_NAME_CHARS = 72;const MAX_DESCRIPTION_CHARS = 240;-// Landmarks are large and read from across a district; indicators and the-// world-identity marker are small, so their plaques sit just above the model.-const LANDMARK_OFFSET = Object.freeze([0, 4, 0]);-const MARKER_OFFSET = Object.freeze([0, 1.5, 0]);+// Omit a fixed offset: the optional renderer anchors labels to actual geometry./*** The one sanitizer for text PortOS writes into a world: control characters@@ -103,7 +100,6 @@ function districtLabel(component) {enabled.length ? `projecting ${enabled.join(', ')}` : 'no sources enabled',].join('. ')}.`,visibility: 'always',- offset: LANDMARK_OFFSET,});}@@ -123,7 +119,6 @@ function worldMetaLabel(component) {name: component.meta?.title,description: 'This world is projected by PortOS. Every landmark and indicator in it is generated from aggregate signals, never from record contents.',visibility: 'always',- offset: MARKER_OFFSET,});}@@ -141,7 +136,6 @@ function signalLabel(component) {`status is ${safeWorldText(component.status, 'unknown', 24)} and ${freshness}`,].join('. ')}.`,visibility: 'nearby',- offset: MARKER_OFFSET,});}diff --git a/server/lib/index.js b/server/lib/index.jsindex b69ab42b43..5379b2960e 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -519,3 +519,6 @@ export * from './testDataIsolation.js';export * from './testHelper.js';export * from './videoFailure.js';++export * from './eidoverseCityLayout.js';+export * from './eidoverseCitySurface.js';diff --git a/server/routes/eidoverseWorldRoutes.test.js b/server/routes/eidoverseWorldRoutes.test.jsindex d497540585..ca2013736e 100644--- a/server/routes/eidoverseWorldRoutes.test.js+++ b/server/routes/eidoverseWorldRoutes.test.js@@ -117,6 +117,9 @@ describe('Eidoverse world routes', () => {const payload = {assetOverrides: {app: 'store/example-local-asset',+ desk: 'store/example-desk',+ barrel: 'store/example-barrel',+ tree: 'store/example-tree',operations: 'eidoverse/assets/models/example-legacy-operations.glb',},};diff --git a/server/services/dataManager.categories.test.js b/server/services/dataManager.categories.test.jsindex 02899b3860..4f7448e4c3 100644--- a/server/services/dataManager.categories.test.js+++ b/server/services/dataManager.categories.test.js@@ -37,7 +37,7 @@ const DATA_DIR_PATTERNS = [/\bdataPath\(\s*'([a-z0-9._-]+)'/g,/PATHS\.data,\s*'([a-z0-9._-]+)'/g,/\$\{PATHS\.data\}\/([a-z0-9._-]+)/g,- /,\s*'data',\s*'([a-z0-9._-]+)'/g+ /\b(?:join|resolve)\(\s*[^,;]+,\s*'data',\s*'([a-z0-9._-]+)'/g];// `join(PATHS.data, TYPE)` — the collection-store idiom, where the directory@@ -100,6 +100,19 @@ function discoverDataDirs() {}describe('dataManager CATEGORIES coverage (#3285)', () => {+ it('discovers literal data paths without treating domain-name arrays as paths', () => {+ const source = `+ const a = join(rootDir, 'data', 'example-one');+ const b = path.resolve(+ tmpdir(),+ 'data', 'example-two'+ );+ const districts = ['agents', 'data', 'federation'];+ `;+ expect(DATA_DIR_PATTERNS.flatMap((pattern) => [...source.matchAll(pattern)].map((match) => match[1])))+ .toEqual(['example-one', 'example-two']);+ });+it('classifies every top-level data/ directory the codebase can create', () => {const discovered = discoverDataDirs();expect(discovered.size).toBeGreaterThan(20); // discovery itself must not silently breakdiff --git a/server/services/eidoverseWorld.js b/server/services/eidoverseWorld.jsindex 0c90cfc9db..6e5ce29ccc 100644--- a/server/services/eidoverseWorld.js+++ b/server/services/eidoverseWorld.js@@ -8,6 +8,8 @@* external checkout or calls an AI provider.*/+import { buildEidoverseCitySurface } from '../lib/eidoverseCitySurface.js';+import { eidoverseModelBounds } from '../lib/eidoverseCityLayout.js';import { createHash } from 'node:crypto';import { join } from 'node:path';import { WebSocket } from 'ws';@@ -1275,6 +1277,62 @@ async function persistAssetLock(resolutions, runtimeVersion) {});}+async function measureAssetLocks(resolutions, overrides, existing, { signal } = {}) {+ const locks = { ...resolutions };+ for (const [slot, path] of Object.entries(overrides)) {+ if (locks[slot]?.path === path) continue;+ locks[slot] = { slot, path, userOverride: true };+ }+ const byPath = new Map();+ for (const lock of [...Object.values(existing), ...Object.values(locks)]) {+ const bounds = eidoverseModelBounds(lock?.bounds);+ if (bounds) byPath.set(lock.path, Promise.resolve(bounds));+ }+ for (const lock of Object.values(locks)) {+ if (byPath.has(lock.path)) continue;+ byPath.set(lock.path, fetchLibraryJson('/geom', { lib: lock.path }, { signal }).then((geometry) => {+ const bounds = eidoverseModelBounds(geometry?.bbox);+ if (!bounds) throw new ServerError('Eidoverse returned invalid model bounds. Update its model geometry and retry.', {+ status: 503, code: 'EIDOVERSE_ASSET_GEOMETRY_INVALID',+ });+ return bounds;+ }));+ }+ return Object.fromEntries(await Promise.all(Object.entries(locks).map(async ([slot, lock]) =>+ [slot, { ...lock, bounds: await byPath.get(lock.path) }])));+}++async function prepareCityAssetLock(resolutions, config, runtimeVersion, { signal } = {}) {+ const overrides = config.design?.userOverrides?.assets || {};+ const measured = await measureAssetLocks(resolutions, overrides, config.design?.assetResolutions || {}, { signal });+ if (!overrides.citySurface) {+ const surface = buildEidoverseCitySurface(config.recipe.districts);+ const head = await waitWithSignal(fetch(libraryUrl(`/library/${surface.path}`), { method: 'HEAD', signal }), signal);+ if (head.status === 404) {+ const response = await waitWithSignal(fetch(libraryUrl('/upload', { by: 'portos', name: 'PortOS Commons paving and signs' }), {+ method: 'POST', headers: { 'content-type': 'model/gltf-binary' }, body: surface.bytes, signal,+ }), signal);+ if (!response.ok) throw new ServerError(`Eidoverse could not accept the Commons scene asset (HTTP ${response.status}).`, {+ status: 503, code: 'EIDOVERSE_CITY_ASSET_UNAVAILABLE',+ });+ const uploaded = await response.json();+ if (uploaded?.path !== surface.path) throw new ServerError('Eidoverse returned an unexpected Commons asset address.', {+ status: 503, code: 'EIDOVERSE_CITY_ASSET_INVALID',+ });+ await verifyLibraryAsset(surface.path, { signal });+ } else if (!head.ok) {+ throw new ServerError(`Eidoverse could not verify the Commons scene asset (HTTP ${head.status}).`, {+ status: 503, code: 'EIDOVERSE_CITY_ASSET_UNAVAILABLE',+ });+ }+ measured.citySurface = { slot: 'citySurface', path: surface.path, bytes: surface.bytes.length,+ designVersion: EIDOVERSE_WORLD_DESIGN_VERSION, assetRecipeVersion: EIDOVERSE_ASSET_RECIPE_VERSION,+ recipeFingerprint: surface.fingerprint, strategy: 'generated', source: 'generated',+ shippedDefault: true, userOverride: false };+ }+ return persistAssetLock(measured, runtimeVersion);+}+async function resolveAndLockAssets(config, { signal } = {}) {const runtimeVersion = await preflightEidoverseProtocol({ signal });const existing = config.design?.assetResolutions || {};@@ -1303,7 +1361,7 @@ async function resolveAndLockAssets(config, { signal } = {}) {});}if (lockInspection.current && unavailablePaths.size === 0) {- return persistAssetLock(lockInspection.resolutions, runtimeVersion);+ return prepareCityAssetLock(lockInspection.resolutions, config, runtimeVersion, { signal });}const files = await fetchLibraryJson('/library-list', { dir: 'eidoverse/assets/models' }, { signal });@@ -1368,7 +1426,7 @@ async function resolveAndLockAssets(config, { signal } = {}) {};const result = await resolveVerified();- return persistAssetLock(result.resolutions, runtimeVersion);+ return prepareCityAssetLock(result.resolutions, config, runtimeVersion, { signal });}function createVerbPacing() {@@ -1655,7 +1713,10 @@ export async function projectEidoverseWorld({ signal, compact = false } = {}) {// Preflight verifies legacy kind overrides too, even though only the// semantic slots have durable resolution locks....Object.fromEntries(Object.entries(lockedConfig.design.userOverrides?.assets || {})- .map(([slot, path]) => [slot, { path, userOverride: true }])),+ .map(([slot, path]) => [slot, {+ ...(lockedConfig.design.assetResolutions[slot]?.path === path ? lockedConfig.design.assetResolutions[slot] : {}),+ path, userOverride: true,+ }])),},currentState: presence.snapshot?.state || {},meta: { title: lockedConfig.design.name, hostId },diff --git a/server/services/eidoverseWorld.runtime.test.js b/server/services/eidoverseWorld.runtime.test.jsindex 76db3c0b23..7c71e3bdec 100644--- a/server/services/eidoverseWorld.runtime.test.js+++ b/server/services/eidoverseWorld.runtime.test.js@@ -1,3 +1,4 @@+import { createHash } from 'node:crypto';import { homedir, hostname, userInfo } from 'node:os';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -203,11 +204,19 @@ beforeEach(async () => {{ path: slot.preferredPaths[0], size: Math.min(slot.maxBytes, 1_000_000) },{ path: slot.fallback, size: 1_000_000 },]);+ const uploadedAssets = new Set();vi.stubGlobal('fetch', vi.fn(async (input, init) => {const url = new URL(String(input));if (url.pathname === '/version') return Response.json({ sha: 'example-build', commitTime: '2026-01-01T00:00:00.000Z' });if (url.pathname === '/library-list') return Response.json(libraryFiles);if (url.pathname === '/library-models') return Response.json([]);+ if (url.pathname === '/geom') return Response.json({ bbox: { min: [-1, 0, -1], max: [1, 2, 1] } });+ if (url.pathname === '/upload') {+ const path = `store/${createHash('sha256').update(init.body).digest('hex').slice(0, 16)}.glb`;+ uploadedAssets.add(`/library/${path}`);+ return Response.json({ path });+ }+ if (/^\/library\/store\/[0-9a-f]{16}\.glb$/.test(url.pathname) && !uploadedAssets.has(url.pathname)) return new Response(null, { status: 404 });if (url.pathname.startsWith('/library/')) return new Response(init?.method === 'HEAD' ? null : '', { status: 200 });return new Response(null, { status: 404 });}));@@ -242,7 +251,7 @@ describe('Eidoverse private-world lifecycle', () => {});expect(fetch).not.toHaveBeenCalled();expect(mocks.sent).toEqual([]);- expect(mocks.persistedState.pendingDesignVersion).toBe(2);+ expect(mocks.persistedState.pendingDesignVersion).toBe(3);});it('reconciles a migrated V1 world through the normal online boot path', async () => {@@ -264,7 +273,7 @@ describe('Eidoverse private-world lifecycle', () => {]));expect(mocks.persistedState).toMatchObject({schemaVersion: 3,- lastAppliedDesignVersion: 2,+ lastAppliedDesignVersion: 3,pendingDesignVersion: null,migrationReport: { status: 'applied' },reconciliation: { status: 'complete', checkpoint: 'projection-committed' },@@ -279,7 +288,7 @@ describe('Eidoverse private-world lifecycle', () => {const progress = await world.getEidoverseWorldProjectionStatus();expect(progress).toMatchObject({- design: { selectedVersion: 2, pendingVersion: 2 },+ design: { selectedVersion: 3, pendingVersion: 3 },projection: { lastRunAt: null },});expect(mocks.appStatusReads).toBe(0);@@ -292,7 +301,7 @@ describe('Eidoverse private-world lifecycle', () => {mocks.persistedState.migrationReport = {status: 'ready',fromDesignVersion: 1,- toDesignVersion: 2,+ toDesignVersion: 3,};mocks.featureEnabled = false;@@ -302,7 +311,7 @@ describe('Eidoverse private-world lifecycle', () => {});expect(fetch).not.toHaveBeenCalled();expect(mocks.sent).toEqual([]);- expect(mocks.persistedState.pendingDesignVersion).toBe(2);+ expect(mocks.persistedState.pendingDesignVersion).toBe(3);});it('leaves a prepared boot-time design update pending without starting an offline runtime', async () => {@@ -311,7 +320,7 @@ describe('Eidoverse private-world lifecycle', () => {mocks.persistedState.migrationReport = {status: 'ready',fromDesignVersion: 1,- toDesignVersion: 2,+ toDesignVersion: 3,};mocks.eidoverseStatus.runtimeStatus = 'stopped';@@ -321,7 +330,7 @@ describe('Eidoverse private-world lifecycle', () => {});expect(fetch).not.toHaveBeenCalled();expect(mocks.sent).toEqual([]);- expect(mocks.persistedState.pendingDesignVersion).toBe(2);+ expect(mocks.persistedState.pendingDesignVersion).toBe(3);});it('marks a persisted in-flight projection as interrupted before boot reconciliation', async () => {@@ -346,7 +355,7 @@ describe('Eidoverse private-world lifecycle', () => {operationCount: 20,appliedOperations: 5,});- expect(mocks.persistedState.pendingDesignVersion).toBe(2);+ expect(mocks.persistedState.pendingDesignVersion).toBe(3);expect(fetch).not.toHaveBeenCalled();expect(mocks.sent).toEqual([]);});@@ -401,7 +410,7 @@ describe('Eidoverse private-world lifecycle', () => {expect(updated.design.userOverrides).toEqual({});expect(updated.recipe).toMatchObject({- version: 2,+ version: 3,limits: {apps: world.DEFAULT_EIDOVERSE_PROJECTION_RECIPE.limits.apps,tasks: world.DEFAULT_EIDOVERSE_PROJECTION_RECIPE.limits.tasks,@@ -420,7 +429,7 @@ describe('Eidoverse private-world lifecycle', () => {recipe.name = 'Example Systems Garden';recipe.maxEntities = 12;recipe.districts[0].label = 'Example Nexus';- recipe.paths[0].label = 'Example Route';+ recipe.paths = [{ id: 'example-route', label: 'Example Route', toDistrictId: 'apps', nodes: [[1, 0, 1]] }];const updated = await world.updateEidoverseWorldConfig({ recipe });@@ -694,7 +703,7 @@ describe('Eidoverse private-world lifecycle', () => {expect(metaComp?.args.data).toMatchObject({kind: 'world-meta',managedBy: 'portos',- designVersion: 2,+ designVersion: 3,meta: { title: expect.any(String), hostId: expect.stringMatching(/^hst_[0-9a-f]{12}$/) },});expect(JSON.stringify(metaComp.args.data)).not.toContain(mocks.self.instanceId);@@ -737,26 +746,26 @@ describe('Eidoverse private-world lifecycle', () => {it('preflights and locks recipe assets before completing a V2 reconciliation', async () => {const result = await world.projectEidoverseWorld();- const expectedSlots = ['nexus', 'app', 'agent', 'task', 'goal', 'memory', 'storage', 'peer', 'activity', 'district'];+ const expectedSlots = ['nexus', 'app', 'agent', 'task', 'goal', 'memory', 'storage', 'peer', 'activity', 'district', 'desk', 'barrel', 'tree', 'citySurface'];expect(Object.keys(result.design.assetResolutions)).toEqual(expectedSlots);expect(Object.keys(mocks.persistedState.assetResolutions)).toEqual(expectedSlots);- expect(fetch.mock.calls.filter(([input]) => String(input).includes('/library/eidoverse/'))).toHaveLength(10);+ expect(fetch.mock.calls.filter(([input]) => String(input).includes('/library/eidoverse/'))).toHaveLength(13);expect(result.summary.assetCatalogFingerprint).toEqual(expect.any(String));expect(result).toMatchObject({success: true,- summary: { designVersion: 2, maxLiveEntities: 48, assetRecipeVersion: 2 },+ summary: { designVersion: 3, maxLiveEntities: 48, assetRecipeVersion: 3 },design: {- selectedVersion: 2,- lastAppliedVersion: 2,+ selectedVersion: 3,+ lastAppliedVersion: 3,pendingVersion: null,reconciliation: { status: 'complete', checkpoint: 'projection-committed' },},});- expect(Object.keys(result.design.assetResolutions)).toHaveLength(10);+ expect(Object.keys(result.design.assetResolutions)).toHaveLength(14);expect(mocks.persistedState).toMatchObject({schemaVersion: 3,- lastAppliedDesignVersion: 2,+ lastAppliedDesignVersion: 3,pendingDesignVersion: null,reconciliation: { status: 'complete' },});@@ -772,7 +781,7 @@ describe('Eidoverse private-world lifecycle', () => {await world.projectEidoverseWorld();expect(fetch.mock.calls.filter(([input]) => String(input).includes('/library-list'))).toHaveLength(0);expect(fetch.mock.calls.filter(([input]) => String(input).includes('/library-models'))).toHaveLength(0);- expect(fetch.mock.calls.filter(([input]) => String(input).includes('/library/eidoverse/'))).toHaveLength(10);+ expect(fetch.mock.calls.filter(([input]) => String(input).includes('/library/eidoverse/'))).toHaveLength(13);await expect(world.reconcilePendingEidoverseWorld()).resolves.toEqual({ reconciled: false, reason: 'current' });});@@ -822,6 +831,28 @@ describe('Eidoverse private-world lifecycle', () => {}});+ it('measures and uploads the shared city once, then reuses its assets', async () => {+ const first = await world.projectEidoverseWorld();+ expect(first.design.assetResolutions.citySurface).toMatchObject({ strategy: 'generated', userOverride: false });+ expect(fetch.mock.calls.filter(([input]) => new URL(String(input)).pathname === '/upload')).toHaveLength(1);+ expect(fetch.mock.calls.some(([input]) => new URL(String(input)).pathname === '/geom')).toBe(true);+ fetch.mockClear();+ await world.projectEidoverseWorld();+ expect(fetch.mock.calls.filter(([input]) => ['/geom', '/upload'].includes(new URL(String(input)).pathname))).toEqual([]);+ });++ it('keeps the prior world authoritative if model geometry is invalid', async () => {+ await world.ensureEidoverseWorldConfig();+ mocks.persistedState.lastAppliedDesignVersion = 2;+ const original = fetch.getMockImplementation();+ fetch.mockImplementation((input, init) => new URL(String(input)).pathname === '/geom'+ ? Promise.resolve(Response.json({ bbox: { min: [0, 0, 0], max: [0, 0, 0] } }))+ : original(input, init));+ await expect(world.projectEidoverseWorld()).rejects.toMatchObject({ code: 'EIDOVERSE_ASSET_GEOMETRY_INVALID' });+ expect(mocks.persistedState.lastAppliedDesignVersion).toBe(2);+ expect(mocks.sent.some(({ type }) => type === 'verb')).toBe(false);+ });+it('excludes a catalog-listed asset whose bytes disappeared and locks a verified fallback', async () => {const slots = world.DEFAULT_EIDOVERSE_PROJECTION_RECIPE.assetRecipe.slots;const appPreferred = slots.app.preferredPaths[0];@@ -834,6 +865,7 @@ describe('Eidoverse private-world lifecycle', () => {if (url.pathname === '/version') return Response.json({ sha: 'example-build', commitTime: '2026-01-01T00:00:00.000Z' });if (url.pathname === '/library-list') return Response.json(libraryFiles);if (url.pathname === '/library-models') return Response.json([]);+ if (url.pathname === '/geom') return Response.json({ bbox: { min: [-1, 0, -1], max: [1, 2, 1] } });if (url.pathname === `/library/${appPreferred}` && init?.method === 'HEAD') return new Response(null, { status: 404 });if (url.pathname.startsWith('/library/')) return new Response(null, { status: 200 });return new Response(null, { status: 404 });@@ -872,7 +904,7 @@ describe('Eidoverse private-world lifecycle', () => {expect(mocks.sent.some(({ type }) => type === 'verb')).toBe(false);expect(mocks.persistedState).toMatchObject({lastAppliedDesignVersion: null,- pendingDesignVersion: 2,+ pendingDesignVersion: 3,reconciliation: { status: 'failed' },});});@@ -886,7 +918,7 @@ describe('Eidoverse private-world lifecycle', () => {});expect(mocks.sent.some(({ type }) => type === 'verb')).toBe(false);expect(mocks.persistedState).toMatchObject({- pendingDesignVersion: 2,+ pendingDesignVersion: 3,reconciliation: {status: 'failed',errorCode: 'EIDOVERSE_WORLD_UNAVAILABLE',@@ -911,7 +943,7 @@ describe('Eidoverse private-world lifecycle', () => {expect(mocks.sent.some(({ type }) => type === 'verb')).toBe(false);expect(mocks.persistedState).toMatchObject({lastAppliedDesignVersion: 1,- pendingDesignVersion: 2,+ pendingDesignVersion: 3,reconciliation: {status: 'failed',errorCode: 'EIDOVERSE_ASSET_RECIPE_UNRESOLVED',@@ -953,7 +985,7 @@ describe('Eidoverse private-world lifecycle', () => {expect(reset.design.userOverrides.assets?.app).toBeUndefined();expect(reset.design.assetResolutions.app).toBeUndefined();expect(reset.design.assetResolutions.agent).toBeTruthy();- expect(reset.design.pendingVersion).toBe(2);+ expect(reset.design.pendingVersion).toBe(3);const nexusReset = await world.updateEidoverseWorldConfig({ reset: { scope: 'district', districtId: 'nexus' } });expect(nexusReset.design.userOverrides.assets?.operations).toBeUndefined();@@ -1011,7 +1043,7 @@ describe('Eidoverse private-world lifecycle', () => {}));expect(mocks.persistedState).toMatchObject({lastAppliedDesignVersion: null,- pendingDesignVersion: 2,+ pendingDesignVersion: 3,reconciliation: {status: 'failed',checkpoint: 'compensation-complete',diff --git a/server/services/eidoverseWorld.test.js b/server/services/eidoverseWorld.test.jsindex 32df63c7d0..399f5c1985 100644--- a/server/services/eidoverseWorld.test.js+++ b/server/services/eidoverseWorld.test.js@@ -69,14 +69,14 @@ describe('Eidoverse PortOS projection plan', () => {expect(second).toEqual(first);expect(first.summary).toMatchObject({- designVersion: 2,+ designVersion: 3,liveEntityCount: 2,- infrastructureCount: 29,+ infrastructureCount: 76,sourceAvailability: { apps: true, agents: true, health: true, environment: true },});expect(first.operations).toEqual(expect.arrayContaining([expect.objectContaining({ verb: 'terrain' }),- expect.objectContaining({ verb: 'sky', args: expect.objectContaining({ system: 'skymesh', hours: 7.2 }) }),+ expect.objectContaining({ verb: 'sky', args: expect.objectContaining({ system: 'skymesh', hours: 10 }) }),expect.objectContaining({ verb: 'grass' }),expect.objectContaining({ verb: 'light', args: expect.objectContaining({ id: 'portos-design-v2-light-nexus' }) }),expect.objectContaining({ verb: 'spawn', args: expect.objectContaining({ id: expect.stringContaining('signal-app-'), lib: APP_FALLBACK }) }),@@ -90,6 +90,28 @@ describe('Eidoverse PortOS projection plan', () => {}));});+ it('builds a bounded walkable city and retains it without repeat writes', () => {+ const first = buildProjectionPlan({ source: appSource() });+ const structures = first.operations.filter(({ verb, args }) => verb === 'comp' && args.type === 'structure');+ expect(structures).toHaveLength(8);+ for (const { args } of structures) {+ expect(JSON.stringify(args.data).length).toBeLessThan(8192);+ expect(args.data.levels[0].tiles.length).toBeGreaterThan(0);+ expect(args.data.levels[0].apertures.some((edge) => edge[3] === 'arch')).toBe(true);+ }+ const state = snapshotFromPlan(first, { foldModelDefaults: true });+ state.entities['visitor-building'] = { lib: 'store/example.glb', comp: { structure: { levels: [] } } };+ const next = buildProjectionPlan({ source: appSource(), currentState: state });+ expect(next.operations).toEqual([]);+ const crowded = buildProjectionPlan({ source: { ...emptySources(),+ agents: Array.from({ length: 6 }, (_, i) => ({ id: `example-agent-${i}` })),+ tasks: Array.from({ length: 6 }, (_, i) => ({ id: `example-task-${i}` })),+ } });+ const positions = crowded.operations.filter(({ verb, args }) => verb === 'spawn' && args.id.includes('-signal-'))+ .map(({ args }) => `${args.pos[0]},${args.pos[2]}`);+ expect(new Set(positions).size).toBe(12);+ });+it('uses the install-local materialized asset lock in projection operations', () => {const lockedApp = 'eidoverse/assets/models/example_locked_app.glb';const recipe = {@@ -111,6 +133,7 @@ describe('Eidoverse PortOS projection plan', () => {const pathMarker = 'store/example-path-marker';const recipe = {...DEFAULT_EIDOVERSE_PROJECTION_RECIPE,+ paths: [{ id: 'example-path', label: 'Example walkway', toDistrictId: 'apps', nodes: [[-14, 0, -14]] }],assets: {...DEFAULT_EIDOVERSE_PROJECTION_RECIPE.assets,feature: legacyFeature,@@ -215,7 +238,8 @@ describe('Eidoverse PortOS projection plan', () => {verb === 'comp' && args.id === signal.args.id && args.type === 'portos'));- expect(landmark.args.pos).toEqual([50, 0, 50]);+ expect(landmark.args.pos[0]).toBeCloseTo(51.4142, 3);+ expect(landmark.args.pos[2]).toBeCloseTo(44.3431, 3);expect(component.args.data).toMatchObject({districtId: 'apps',districtLabel: 'Example App Garden',@@ -667,7 +691,7 @@ describe('Eidoverse PortOS projection plan', () => {});const goal = signalSpawn(plan, 'goal');- expect(goal.args.pos[1]).toBeCloseTo(5.625, 3);+ expect(goal.args.pos[1]).toBeCloseTo(5.655, 3);});it('turns enabled feature flags into district affordances instead of extra props', () => {@@ -718,6 +742,29 @@ describe('Eidoverse PortOS projection plan', () => {expect(appsLandmark(capped).args.scale).toBe(appsLandmark(empty).args.scale);});+ it('grounds arcade computers on desks facing the park, retaining both through a source outage', () => {+ const assetResolutions = {+ app: { path: 'store/example-computer.glb', bounds: { min: [-2, -1, 4], max: [0, 2, 6] } },+ desk: { path: 'store/example-desk.glb', bounds: { min: [5, -2, -1], max: [8, -1, 1] } },+ };+ const recipe = { ...DEFAULT_EIDOVERSE_PROJECTION_RECIPE, assets: Object.fromEntries(Object.entries(assetResolutions).map(([slot, asset]) => [slot, asset.path])) };+ const plan = buildProjectionPlan({ source: { ...appSource(), apps: [{ id: 'app-example', status: 'error' }] }, recipe, assetResolutions });+ const currentState = snapshotFromPlan(plan);+ const computer = signalSpawn(plan, 'app').args;+ const desk = Object.values(currentState.entities).find((entity) => entity.id.startsWith('portos-design-v2-city-desk-'));+ expect(computer.pos[1] + assetResolutions.app.bounds.min[1] * computer.scale)+ .toBeCloseTo(desk.pos[1] + assetResolutions.desk.bounds.max[1] * desk.scale);+ expect(currentState.entities[computer.id].comp.motion ?? null).toBeNull();+ const hall = currentState.entities['portos-design-v2-city-hall-apps'];+ const distance = Math.hypot(hall.pos[0], hall.pos[2]);+ expect(Math.sin(hall.yaw) * -hall.pos[0] + Math.cos(hall.yaw) * -hall.pos[2]).toBeCloseTo(distance);+ const outage = buildProjectionPlan({ source: { ...emptySources(), apps: null }, currentState, recipe, assetResolutions });+ expect(outage.operations.some(({ verb, args }) => verb === 'remove' && [desk.id, computer.id].includes(args.id))).toBe(false);+ expect(outage.operations.some(({ verb, args }) => verb === 'comp' && args.id === computer.id && args.type === 'motion' && args.data)).toBe(false);+ const removed = buildProjectionPlan({ source: emptySources(), currentState, recipe, assetResolutions });+ for (const id of [desk.id, computer.id]) expect(removed.operations).toContainEqual({ layer: 'reconciliation', verb: 'remove', args: { id } });+ });+it('keeps authored architecture identical across installs while local signals differ', () => {const first = buildProjectionPlan({ source: {...emptySources(),@@ -876,21 +923,20 @@ describe('Eidoverse projection labels', () => {// Landmarks read from across a district; the walkway markers that lead to// them are numerous, so only landmarks and the world identity float.- expect(district).toMatchObject({ name: 'App Terraces', visibility: 'always' });- expect(district.description).toContain('service pylons');+ expect(district).toMatchObject({ name: 'App Arcade', visibility: 'always' });+ expect(district.description).toContain('console arcade');expect(district.description).toContain('apps');- expect(pathNode).toMatchObject({ visibility: 'inspect' });- expect(pathNode.name).toBe('Nexus to App Terraces');+ expect(pathNode).toBeUndefined();expect(worldMeta).toMatchObject({ name: 'Example Garden', visibility: 'always' });expect(signal).toMatchObject({ visibility: 'nearby' });expect(signal.name).toMatch(/^Managed app [0-9a-f]{6}$/);- expect(signal.description).toContain('App Terraces');+ expect(signal.description).toContain('App Arcade');expect(signal.description).toContain('an app this install manages');// Every managed model carries one, and none of them describes the// decorative asset that happens to stand in for it.const managedSpawns = plan.operations- .filter(({ verb, args }) => verb === 'spawn' && args.id.startsWith('portos-design-v2-'))+ .filter(({ verb, args }) => verb === 'spawn' && args.id.startsWith('portos-design-v2-') && !args.id.includes('-city-')).map(({ args }) => args.id);expect(labelOps(plan).map(({ args }) => args.id).sort()).toEqual(managedSpawns.sort());expect(labelOps(plan).every(({ args }) => !/\.glb|assets\/models/.test(JSON.stringify(args.data)))).toBe(true);diff --git a/server/services/eidoverseWorldProjection.js b/server/services/eidoverseWorldProjection.jsindex 39a8a55a26..5db385bfe1 100644--- a/server/services/eidoverseWorldProjection.js+++ b/server/services/eidoverseWorldProjection.js@@ -5,6 +5,7 @@* identical environment, infrastructure, live, ambient, and cleanup verbs.*/+import { eidoverseCityArchitecture, eidoverseCityFurniture, eidoverseCitySignalPosition, eidoverseModelPlacement, eidoverseDistrictPoint, eidoverseDistrictYaw, eidoverseDesktopHeight } from '../lib/eidoverseCityLayout.js';import { createHash } from 'node:crypto';import { canonicalStringify } from '../lib/objects.js';import {@@ -14,7 +15,7 @@ import {EIDOVERSE_META_ENTITY_ID,EIDOVERSE_PROJECTION_PREFIX,EIDOVERSE_WORLD_DESIGN_V1,- EIDOVERSE_WORLD_DESIGN_V2,+ EIDOVERSE_WORLD_DESIGN_V3,EIDOVERSE_WORLD_DESIGN_VERSION,extractEidoverseDesignOverrides,migrateEidoverseWorldState,@@ -59,7 +60,7 @@ const DISTRICT_ASSET_SLOT = Object.freeze({});// Just off the nexus and clear of every nexus->district path lane, whose first// node sits at 27% of the district anchor.-const META_ENTITY_POS = Object.freeze([2.4, 0.08, 2.4]);+const META_ENTITY_POS = Object.freeze([-2.4, 0.08, 2.4]);const DISTRICT_SCALE = Object.freeze({nexus: 1.15,apps: 1.1,@@ -71,7 +72,7 @@ const DISTRICT_SCALE = Object.freeze({activity: 0.72,});-export const DEFAULT_EIDOVERSE_PROJECTION_RECIPE = EIDOVERSE_WORLD_DESIGN_V2;+export const DEFAULT_EIDOVERSE_PROJECTION_RECIPE = EIDOVERSE_WORLD_DESIGN_V3;const shortHash = (value) => createHash('sha256').update(String(value)).digest('hex').slice(0, 12);@@ -137,25 +138,6 @@ function districtForSource(districts, sourceKey) {|| EIDOVERSE_DISTRICTS_V2[0];}-function entityPosition(sourceId, sourceKey, districts) {- const district = districtForSource(districts, sourceKey);- if (district.id === 'activity') {- const along = (stableEidoverseUnit(`${district.id}:${sourceId}:along`) * 2 - 1) * 9;- const bend = Math.sin(along / 4.5) * 1.8;- return [- Number((district.anchor[0] + along).toFixed(2)),- district.anchor[1] + 0.2,- Number((district.anchor[2] + bend).toFixed(2)),- ];- }- const angle = stableEidoverseUnit(`${district.id}:${sourceId}:angle`) * Math.PI * 2;- const radius = 5.5 + stableEidoverseUnit(`${district.id}:${sourceId}:radius`) * 7.5;- return [- Number((district.anchor[0] + Math.cos(angle) * radius).toFixed(2)),- district.anchor[1],- Number((district.anchor[2] + Math.sin(angle) * radius).toFixed(2)),- ];-}function worldSignal(kind, sourceKey, item, districts) {const district = districtForSource(districts, sourceKey);@@ -261,6 +243,7 @@ function nexusStatusLight(light, source, existing) {*/function labelOperation({ prior, id, component, layer, lib, labelContext }) {const { aliases, objects, recipe, assetResolutions } = labelContext;+ if (['architecture', 'furniture'].includes(component.kind)) return null;const label = buildEidoverseLabel(component, aliases[component.resourceKey]);const kind = component.kind === 'district'? (component.districtId === 'nexus' ? 'operations' : null)@@ -300,12 +283,17 @@ function upsertModel({pos,yaw = 0,scale = 1,+ modelSize = 2,+ normalizeModel = true,collide = 'box',component,motion = null,+ structure = null,layer = 'live',motionLayer = 'ambient',}) {+ const measuredAsset = Object.values(labelContext.assetResolutions).find((asset) => asset?.path === lib);+ if (!structure && normalizeModel) ({ pos, yaw, scale } = eidoverseModelPlacement({ bounds: measuredAsset?.bounds, pos, yaw, scale, size: modelSize }));const existing = stateEntities[id];desiredIds.add(id);let created = 0;@@ -331,6 +319,10 @@ function upsertModel({updated += 1;}const priorComponents = respawned ? undefined : existing.comp;+ if (!equal(priorComponents?.structure ?? null, structure)) {+ operations.push({ layer, verb: 'comp', args: { id, type: 'structure', data: structure } });+ if (existing) updated += 1;+ }if (!equal(priorComponents?.[COMPONENT_TYPE], component)) {operations.push({ layer, verb: 'comp', args: { id, type: COMPONENT_TYPE, data: component } });if (existing) updated += 1;@@ -406,6 +398,32 @@ export function buildProjectionPlan({ source = {}, recipe = DEFAULT_EIDOVERSE_PR}}+ let cityEntityCount = 0;+ if (effectiveRecipe.assets.citySurface) {+ const delta = upsertModel({ operations, labelContext, stateEntities, desiredIds,+ id: `${EIDOVERSE_MANAGED_PREFIX}city-surface`, lib: effectiveRecipe.assets.citySurface,+ pos: [0, 0, 0], normalizeModel: false, collide: null,+ component: { schemaVersion: 1, managedBy: 'portos', designVersion: EIDOVERSE_WORLD_DESIGN_VERSION,+ kind: 'architecture', districtId: 'nexus' }, layer: 'infrastructure' });+ created += delta.created; updated += delta.updated; removed += delta.removed;+ cityEntityCount += 1;+ }+ for (const item of [...eidoverseCityArchitecture(districts), ...eidoverseCityFurniture(districts, assetResolutions)]) {+ const delta = upsertModel({ operations, labelContext, stateEntities, desiredIds,+ id: `${EIDOVERSE_MANAGED_PREFIX}city-${item.key}`,+ lib: assetPathFor(effectiveRecipe, null, item.slot || 'task'),+ pos: item.pos, yaw: item.yaw || 0, scale: item.scale || 1, modelSize: item.size || 2, collide: item.structure ? null : 'box',+ structure: item.structure || null,+ component: { schemaVersion: 1, managedBy: 'portos', designVersion: EIDOVERSE_WORLD_DESIGN_VERSION,+ kind: item.structure ? 'architecture' : 'furniture', districtId: item.districtId },+ layer: 'infrastructure',+ });+ created += delta.created;+ updated += delta.updated;+ removed += delta.removed;+ cityEntityCount += 1;+ }+for (const district of districts) {const id = `${EIDOVERSE_MANAGED_PREFIX}infra-${district.id}`;const enabledSources = district.sources.filter((key) => effectiveRecipe.includes[key]);@@ -456,8 +474,10 @@ export function buildProjectionPlan({ source = {}, recipe = DEFAULT_EIDOVERSE_PRdesiredIds,id,lib: assetPathFor(effectiveRecipe, district.id === 'nexus' ? 'operations' : null, districtSlot),- pos: district.anchor,- yaw: stableEidoverseUnit(`${district.id}:yaw`) * Math.PI * 2,+ pos: eidoverseDistrictPoint(district, district.id === 'nexus' ? 5 : (district.id === 'apps' ? -5 : 0),+ district.id === 'apps' ? eidoverseDesktopHeight(assetResolutions) : 0, district.id === 'apps' ? 3 : -2),+ yaw: eidoverseDistrictYaw(district) + (district.id === 'federation' ? Math.PI / 2 : 0),+ modelSize: ({ nexus: 7, apps: 0.7, agents: 2.5, goals: 3.2, memory: 2.4, data: 2.8, federation: 10, activity: 3.5 })[district.id] || 2,scale: Number((districtScale * (1 + Math.min(affordances.length, 3) * 0.035)).toFixed(3)),component,motion: ['agents', 'goals', 'memory'].includes(district.id)@@ -628,6 +648,10 @@ export function buildProjectionPlan({ source = {}, recipe = DEFAULT_EIDOVERSE_PRif (!id.startsWith(`${PROJECTION_ID_PREFIX}${kind}-`)) continue;if (!retainedStaleIds.has(id)) continue;desiredIds.add(id);+ if (kind === 'app') {+ const deskId = `${EIDOVERSE_MANAGED_PREFIX}city-desk-${id.slice(PROJECTION_ID_PREFIX.length)}`;+ if (stateEntities[deskId]) { desiredIds.add(deskId); cityEntityCount += 1; }+ }const priorComponent = existing?.comp?.[COMPONENT_TYPE] || {};const priorMetrics = priorComponent.metrics || {};const district = districtForSource(districts, sourceKey);@@ -673,7 +697,7 @@ export function buildProjectionPlan({ source = {}, recipe = DEFAULT_EIDOVERSE_PRoperations.push(staleLabelOp);updated += 1;}- const staleMotion = {+ const staleMotion = kind === 'app' ? null : {type: 'bob', amp: 0.12, period: 6,phase: Number((stableEidoverseUnit(`${id}:stale`) * Math.PI * 2).toFixed(4)),};@@ -687,15 +711,26 @@ export function buildProjectionPlan({ source = {}, recipe = DEFAULT_EIDOVERSE_PRif (!slot) continue;for (const signal of selectedSignals.get(kind) || []) {const id = projectionEntityId(kind, signal.id);- const pos = entityPosition(signal.id, sourceKey, districts);+ const district = districtForSource(districts, sourceKey);+ const pos = eidoverseCitySignalPosition(district, districtCounts[district.id], kind === 'app');+ if (kind === 'app') {+ const desk = upsertModel({ operations, labelContext, stateEntities, desiredIds,+ id: `${EIDOVERSE_MANAGED_PREFIX}city-desk-${id.slice(PROJECTION_ID_PREFIX.length)}`, lib: assetPathFor(effectiveRecipe, null, 'desk'), pos: [...pos],+ yaw: eidoverseDistrictYaw(district), modelSize: 2.25,+ component: { schemaVersion: 1, managedBy: 'portos', designVersion: EIDOVERSE_WORLD_DESIGN_VERSION,+ kind: 'furniture', districtId: district.id }, layer: 'live' });+ created += desk.created; updated += desk.updated; removed += desk.removed;+ cityEntityCount += 1;+ pos[1] += eidoverseDesktopHeight(assetResolutions) - 0.1;+ }if (kind === 'goal' && typeof signal.metrics.progress === 'number') {pos[1] += 1.5 + Math.max(0, Math.min(100, signal.metrics.progress)) * 0.055;}const scaleVariation = 0.92 + stableEidoverseUnit(`${signal.id}:scale`) * 0.16;const statusScale = signal.severity === 'error' ? 1.22 : (signal.severity === 'attention' ? 1.1 : 1);- if (signal.severity === 'error') pos[1] += 1.6;- else if (signal.severity === 'attention') pos[1] += 0.7;- const shouldMove = signal.severity !== 'normal' || ['agent', 'activity', 'goal', 'jira', 'memory'].includes(kind);+ if (kind !== 'app' && signal.severity === 'error') pos[1] += 1.6;+ else if (kind !== 'app' && signal.severity === 'attention') pos[1] += 0.7;+ const shouldMove = kind !== 'app' && (signal.severity !== 'normal' || ['agent', 'activity', 'goal', 'jira', 'memory'].includes(kind));const delta = upsertModel({operations,labelContext,@@ -704,7 +739,8 @@ export function buildProjectionPlan({ source = {}, recipe = DEFAULT_EIDOVERSE_PRid,lib: assetPathFor(effectiveRecipe, kind, slot),pos,- yaw: stableEidoverseUnit(`${signal.id}:yaw`) * Math.PI * 2,+ yaw: eidoverseDistrictYaw(district),+ modelSize: kind === 'app' ? 0.7 : 1.5,scale: Number(((effectiveRecipe.scale[kind] || 1) * scaleVariation * statusScale).toFixed(3)),component: signal,motion: shouldMove ? {@@ -744,7 +780,7 @@ export function buildProjectionPlan({ source = {}, recipe = DEFAULT_EIDOVERSE_PRdesignVersion: EIDOVERSE_WORLD_DESIGN_VERSION,liveEntityCount,maxLiveEntities: liveEntityLimit,- infrastructureCount: districts.length + pathNodeCount + metaEntityCount,+ infrastructureCount: districts.length + pathNodeCount + metaEntityCount + cityEntityCount,districtCounts,sourceAvailability,truncated: Object.keys(droppedBySource).length > 0,