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
feat: explain Eidoverse objects and save explicit display aliases (#6275)
[._.]/ Adam Eivyed71f5acd94d
diff --git a/client/src/components/eidoverse/EidoverseObjectLegend.jsx b/client/src/components/eidoverse/EidoverseObjectLegend.jsxnew file mode 100644index 0000000000..ae244b9a18--- /dev/null+++ b/client/src/components/eidoverse/EidoverseObjectLegend.jsx@@ -0,0 +1,58 @@+const ASSET_REASONS = {+ 'user-override': 'Override — your chosen asset',+ preferred: 'Preferred — recipe match',+ query: 'Fallback — library search match',+ fallback: 'Fallback — recipe fallback',+ 'catalog-fallback': 'Fallback — available library asset',+ lock: 'Saved asset — original resolution reason unavailable',+ unresolved: 'Resolution not verified for this model — refresh the world',+};++export default function EidoverseObjectLegend({ objects, districts = [], aliases = {}, onAliasChange, busy, onAssets }) {+ const groups = new Map();+ for (const object of objects || []) {+ if (!groups.has(object.districtId)) groups.set(object.districtId, []);+ groups.get(object.districtId).push(object);+ }+ return (+ <section aria-label="Projected object labels" className="space-y-3">+ <h3 className="text-base font-semibold text-white">What the objects represent</h3>+ <p className="text-sm text-gray-400">The last successful projection, including saved asset choices. Refresh the world to update this legend.</p>+ <p className="text-xs leading-5 text-gray-400">Optional display aliases are written to this world's history. Enter only names you intend world visitors to see; blank uses the generic label.</p>+ {!objects && <p className="text-sm text-port-warning">Refresh the world to load its object labels.</p>}+ {objects?.length === 0 && <p className="text-sm text-gray-400">No labelled objects in the last projection.</p>}+ {[...groups].map(([districtId, entries]) => (+ <details key={districtId} open className="rounded-xl border border-port-border bg-port-bg p-3">+ <summary className="min-h-[44px] cursor-pointer py-2 font-medium text-white">+ {districts.find(({ id }) => id === districtId)?.label || 'World landmarks'} — {entries.length} objects+ </summary>+ <div className="mt-2 grid gap-3 sm:grid-cols-2">+ {entries.map((object) => (+ <article key={object.id} className="min-w-0 rounded-lg border border-port-border p-3">+ <h4 className="break-words text-sm font-medium text-white">{object.name}</h4>+ <p className="mt-1 text-xs leading-5 text-gray-400">{object.description}</p>+ <dl className="mt-2 space-y-1 text-xs">+ <div><dt className="inline text-gray-400">Label mode: </dt><dd className="inline text-gray-200">{object.visibility}</dd></div>+ <div><dt className="text-gray-400">Asset choice</dt><dd className="break-all text-port-accent">{object.asset?.path || 'No model recorded'}</dd></div>+ <div><dt className="sr-only">Resolution reason</dt><dd className="text-gray-300">{ASSET_REASONS[object.asset?.reason] || ASSET_REASONS.unresolved}</dd></div>+ </dl>+ {object.resourceKey && (+ <label className="mt-3 block text-xs text-gray-300" htmlFor={`eidoverse-alias-${object.resourceKey}`}>+ Display alias for {object.name}+ <input id={`eidoverse-alias-${object.resourceKey}`} maxLength={72} disabled={busy}+ className="mt-1 min-h-[44px] w-full rounded border border-port-border bg-port-card px-2 text-sm text-white"+ value={aliases[object.resourceKey] || ''} placeholder="Use generic label"+ onChange={(event) => onAliasChange(object.resourceKey, event.target.value)} />+ </label>+ )}+ </article>+ ))}+ </div>+ </details>+ ))}+ <button type="button" onClick={onAssets} className="min-h-[44px] rounded-lg border border-port-border px-3 py-2 text-sm text-port-accent">+ Change or reset asset choices+ </button>+ </section>+ );+}diff --git a/client/src/components/eidoverse/EidoverseWorldDrawer.jsx b/client/src/components/eidoverse/EidoverseWorldDrawer.jsxindex 95d809b746..5db38b1493 100644--- a/client/src/components/eidoverse/EidoverseWorldDrawer.jsx+++ b/client/src/components/eidoverse/EidoverseWorldDrawer.jsx@@ -3,6 +3,8 @@ import { Compass, Database, Palette, RefreshCw } from 'lucide-react';import { Link } from 'react-router';import Drawer from '../Drawer';import useDrawerTab from '../../hooks/useDrawerTab';+import { EIDOVERSE_SOURCE_ROUTES as SOURCE_ROUTES } from '../../lib/eidoverseFrame';+import EidoverseObjectLegend from './EidoverseObjectLegend';import { formatBytes } from '../../utils/formatters';const TABS = [@@ -12,12 +14,7 @@ const TABS = [{ id: 'updates', label: 'Updates & Advanced', icon: RefreshCw },];const TAB_IDS = TABS.map(({ id }) => id);-const SOURCE_ROUTES = {- apps: '/apps', agents: '/cos/agents', tasks: '/cos/tasks', features: '/settings/features',- peers: '/instances', health: '/cos/health', productivity: '/cos/productivity',- activity: '/cos/productivity', goals: '/goals/list', memory: '/brain/memory',- storage: '/settings/database', jira: '/goals/list', operations: '/cos/health',-};+const fieldClass = 'mt-1 min-h-[42px] w-full rounded-lg border border-port-border bg-port-bg px-3 text-sm text-white focus:border-port-accent focus:outline-none';const secondaryButton = 'inline-flex min-h-[40px] items-center justify-center rounded-lg border border-port-border px-3 py-2 text-sm text-gray-200 transition-colors hover:border-port-accent hover:text-white disabled:cursor-wait disabled:opacity-50';@@ -43,6 +40,12 @@ export default function EidoverseWorldDrawer({setHumanName,recipeDraft,assetOverridesDraft,+ labelAliasesDraft,+ mutateLabelAlias,+ frameConnection,+ labelVisibility,+ onLabelVisibilityChange,+ appId,mutateRecipe,mutateAssetOverride,markDirty,@@ -94,6 +97,12 @@ export default function EidoverseWorldDrawer({});};+ const labelSupport = frameConnection?.status === 'ready'+ ? frameConnection.capabilities.objectLabels+ : reconciliation.runtimeVersion?.capabilities?.objectLabels === 1;+ const labelSupportChecked = frameConnection?.status !== 'checking'+ || Boolean(reconciliation.runtimeVersion);+const identityFields = (<div className="space-y-4"><div className="rounded-xl border border-port-accent/25 bg-port-accent/5 p-4">@@ -103,6 +112,35 @@ export default function EidoverseWorldDrawer({A luminous systems garden where PortOS apps, agents, goals, memory, data, peers, and activity each have a legible home.</p></div>+ <section className="rounded-xl border border-port-border bg-port-bg p-4">+ <h3 className="font-medium text-white">Object labels</h3>+ {labelSupportChecked && !labelSupport && (+ <p className="mt-2 text-sm text-port-warning" role="status">+ This renderer does not report object-label support. Update Eidoverse Worlds, then reload this page.+ {' '}<Link className="underline" to={appId ? `/apps/${appId}/overview` : '/apps'}>Manage renderer updates</Link>+ {' '}Your design, aliases, and asset choices stay saved. The object legend below remains available.+ </p>+ )}+ {labelSupport && (frameConnection?.status === 'unsupported' || (frameConnection?.status === 'ready'+ && (!frameConnection.capabilities.portosNavigation || !frameConnection.capabilities.labelPreferences))) && (+ <p className="mt-2 text-sm text-port-warning" role="status">+ Reload or update the renderer to enable label controls and Open in PortOS.+ </p>+ )}+ <label className="mt-3 block text-sm text-gray-300" htmlFor="eidoverse-label-visibility">+ Floating labels+ <select id="eidoverse-label-visibility" className={fieldClass} value={labelVisibility}+ onChange={(event) => onLabelVisibilityChange(event.target.value)}>+ <option value="nearby">Nearby — respect each object's label mode</option>+ <option value="all-nearby">All nearby — include inspect-only objects</option>+ <option value="off">Off — inspect selected objects only</option>+ </select>+ </label>+ <p className="mt-2 text-xs text-gray-400">Saved in this browser; changing visibility does not rewrite the world. Object details remain available with labels off.</p>+ {!frameConnection?.capabilities?.labelPreferences && (+ <p className="mt-1 text-xs text-gray-400">The preference will apply when a compatible renderer connects.</p>+ )}+ </section><label className="block text-sm text-gray-300" htmlFor="eidoverse-world-name">World name<input@@ -235,6 +273,14 @@ export default function EidoverseWorldDrawer({</div></section>))}+ <EidoverseObjectLegend+ objects={projectionSummary.objects}+ districts={worldState?.recipe?.districts}+ aliases={labelAliasesDraft}+ onAliasChange={mutateLabelAlias}+ busy={busy}+ onAssets={() => setActiveTab('appearance')}+ /></div>);diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex ad040c4404..a78f71fdab 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -228,3 +228,9 @@ grep -i "what you want to do" client/src/hooks/README.md| `useChordPlayer` | Chord-sheet play-along transport for a SongBook `tab`/`chordpro` sheet (#4104) — the chord counterpart of `useDrumPlayer`: parses the (already-transposed) text, owns one `createChordPlayer`, the practice settings (tempo + beats-per-chord persisted per song, count-in, machine-global click) and the sounding-chord highlight read off the audio clock. Returns `{ chordCount, hasChords, writtenTempo, bpm, setBpm, setBpmPercent, beatsPerBar, setBeatsPerBar, countInBars, setCountInBars, clickEnabled, setClickEnabled, playing, pulse, sounding, getPlayhead, toggle, stop }`. Timing edits stop playback rather than re-time a running schedule. | `<ChordTransportBar>` + `<ChordPreview>` (SongBook viewer/editor/importer). || `useDrumPlayer` | Drum play-along transport for a SongBook `drum` chart (#3115): parses the chart (`lib/drumNotation.js`), owns one `createDrumPlayer` per chart plus the practice settings and the sheet playhead. Returns `{ chart, barCount, writtenTempo, bpm, setBpm, setBpmPercent, countInBars, setCountInBars, loopEnabled, setLoopEnabled, loopFrom, loopTo, setLoopRange, clickEnabled, setClickEnabled, clickVolume, setClickVolume, kitId, setKitId, playing, activeStep, currentBar, toggle, stop }`. The practice tempo persists per song in `safeStorage` (never into the record) while the selected kit (`songbook:drumKit`), the click toggle (`songbook:drumClick`) and the click level (`songbook:drumClickVolume`) persist per MACHINE; a timing-critical edit (tempo / count-in / loop) STOPS playback rather than re-timing already-scheduled audio, while the click toggle, the click level and the kit swap apply live (raising the level off silence also unmutes, so the slider is never a dead control); the player + its interval + scheduled hits tear down on stop, chart change and unmount. | The SongBook viewer and snapshot-based drum previews. Don't hand-wire `createDrumPlayer` + BPM persistence + playhead state again. || `useMidiPlayer` | React wrapper over `lib/midiPlayback.js` (#2490): one synth player per parsed MIDI view-model, torn down when the data changes/unmounts so oscillators never outlive the roll. Returns `{ playing, toggle, seek(sec), getPosition }` — `getPosition` is the stable ref the `<MidiPianoRoll>` rAF playhead reads; no AudioContext is touched until the first toggle. A resume failure resets `playing` instead of lying. | `<MidiVisualization>` (Rounds ReferenceAnalysis + Music Video). |++## Hosted worlds++| Hook | Purpose | Use when |+|---|---|---|+| `useEidoverseFrame` | Per-load Eidoverse handshake with origin/window/session validation and browser-only label preferences. | Embedding the managed Eidoverse renderer. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex d98e0e8db8..5778eefe7b 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -211,3 +211,4 @@ export * from './useVideoGenForm.js';export * from './useVideoGenSubmitFlow.js';export * from './useVideoGenValidation.js';export * from './useVoiceUiSync.js';+export { default as useEidoverseFrame } from './useEidoverseFrame.js';diff --git a/client/src/hooks/useEidoverseFrame.js b/client/src/hooks/useEidoverseFrame.jsnew file mode 100644index 0000000000..bd012345c1--- /dev/null+++ b/client/src/hooks/useEidoverseFrame.js@@ -0,0 +1,91 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { useNavigate } from 'react-router';+import {+ EIDOVERSE_FRAME_VERSION,+ EIDOVERSE_LABEL_PREFERENCES,+ 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);+ return EIDOVERSE_LABEL_PREFERENCES.includes(stored) ? stored : 'nearby';+};++export default function useEidoverseFrame(hostUrl, objects = []) {+ const frameRef = useRef(null);+ const objectsRef = useRef(objects);+ objectsRef.current = 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 preferenceRef = useRef(labelVisibility);+ const navigate = useNavigate();++ const onFrameLoad = useCallback(() => {+ sessionRef.current = null;+ setConnection({ status: 'checking', capabilities: {} });+ setLoaded((current) => ({ id: current.id + 1, url: hostUrl }));+ }, [hostUrl]);++ useEffect(() => {+ if (!hostUrl || loaded.url !== hostUrl || !frameRef.current?.contentWindow) return undefined;+ const source = frameRef.current.contentWindow;+ const origin = new URL(hostUrl).origin;+ const nonce = Array.from(crypto.getRandomValues(new Uint8Array(16)),+ (byte) => byte.toString(16).padStart(2, '0')).join('');+ const session = { source, origin, nonce, capabilities: {} };+ sessionRef.current = session;+ const timer = setTimeout(() => {+ setConnection({ status: 'unsupported', capabilities: {} });+ }, 5000);+ const receive = (event) => {+ if (sessionRef.current !== session || frameRef.current?.contentWindow !== source+ || !isEidoverseFrameMessage(event, session)) return;+ const data = event.data;+ if (data.type === 'eidoverse:ready') {+ clearTimeout(timer);+ session.capabilities = Object.fromEntries(['objectLabels', 'portosNavigation', 'labelPreferences']+ .map((key) => [key, data.capabilities?.[key] === 1]));+ setConnection({ status: 'ready', capabilities: session.capabilities });+ if (session.capabilities.labelPreferences) source.postMessage({+ type: 'portos:label-preference', version: EIDOVERSE_FRAME_VERSION, nonce,+ labelVisibility: preferenceRef.current,+ }, origin);+ } else if (data.type === 'eidoverse:navigate' && session.capabilities.portosNavigation) {+ const target = eidoverseNavigationTarget(data, objectsRef.current);+ if (target) navigate(target);+ }+ };+ window.addEventListener('message', receive);+ source.postMessage({+ type: 'portos:connect', version: EIDOVERSE_FRAME_VERSION, nonce,+ capabilities: { portosNavigation: 1, labelPreferences: 1 },+ labelVisibility: preferenceRef.current,+ }, origin);+ return () => {+ clearTimeout(timer);+ window.removeEventListener('message', receive);+ if (sessionRef.current === session) sessionRef.current = null;+ };+ }, [hostUrl, loaded, navigate]);++ const changeLabelVisibility = useCallback((value) => {+ 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({+ type: 'portos:label-preference', version: EIDOVERSE_FRAME_VERSION,+ nonce: session.nonce, labelVisibility: value,+ }, session.origin);+ }+ }, []);++ return { frameRef, onFrameLoad, connection, labelVisibility, changeLabelVisibility };+}diff --git a/client/src/hooks/useEidoverseFrame.test.jsx b/client/src/hooks/useEidoverseFrame.test.jsxnew file mode 100644index 0000000000..83c5a3614c--- /dev/null+++ b/client/src/hooks/useEidoverseFrame.test.jsx@@ -0,0 +1,91 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { act, fireEvent, render, screen } from '@testing-library/react';+import { MemoryRouter, useLocation } from 'react-router';+import useEidoverseFrame from './useEidoverseFrame';+import { safeRemoveStorage } from '../lib/safeStorage';++const hostUrl = 'https://world.example.com/';+const objects = [{ id: 'portos-design-v2-signal-app-example', route: '/apps' }];+function Harness() {+ const frame = useEidoverseFrame(hostUrl, objects);+ const location = useLocation();+ return <>+ <iframe title="Test renderer" ref={frame.frameRef} onLoad={frame.onFrameLoad} />+ <output aria-label="Route">{location.pathname}</output>+ <output aria-label="Bridge status">{frame.connection.status}</output>+ <button onClick={() => frame.changeLabelVisibility('off')}>Hide labels</button>+ </>;+}+const mount = () => render(<MemoryRouter initialEntries={['/eidoverse']}><Harness /></MemoryRouter>);+const send = (source, data, extra = {}) => act(() => {+ window.dispatchEvent(new MessageEvent('message', { source, origin: new URL(hostUrl).origin, data, ...extra }));+});++afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+ safeRemoveStorage('portos-eidoverse-label-visibility');+});++describe('hosted Eidoverse frame navigation', () => {+ it('requires the hosted window, exact origin, current handshake and projected section route', () => {+ mount();+ const frame = screen.getByTitle('Test renderer');+ const source = frame.contentWindow;+ const post = vi.spyOn(source, 'postMessage').mockImplementation(() => {});+ 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: 'nearby' });+ 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.+ expect(screen.getByLabelText('Route')).toHaveTextContent('/eidoverse');+ const ready = { type: 'eidoverse:ready', version: 1, nonce: hello.nonce, capabilities: { objectLabels: 1, portosNavigation: 1, labelPreferences: 1 } };+ send(source, { ...ready, version: 0 });+ send(source, navigation);+ expect(screen.getByLabelText('Route')).toHaveTextContent('/eidoverse');+ send(source, ready);+ for (const [data, extra] of [+ [navigation, { origin: 'https://attacker.example.com' }],+ [navigation, { source: window }],+ [{ ...navigation, nonce: 'old-session' }, {}],+ [{ ...navigation, version: 99 }, {}],+ [{ ...navigation, route: 'https://attacker.example.com/' }, {}],+ [{ ...navigation, route: '//attacker.example.com/' }, {}],+ [{ ...navigation, route: '/apps?redirect=https://attacker.example.com' }, {}],+ [{ ...navigation, route: '/apps/../settings' }, {}],+ [{ ...navigation, route: '/settings/database' }, {}],+ [{ ...navigation, entityId: 'foreign-object' }, {}],+ ]) {+ send(source, data, extra);+ expect(screen.getByLabelText('Route')).toHaveTextContent('/eidoverse');+ }+ fireEvent.click(screen.getByRole('button', { name: 'Hide labels' }));+ expect(post.mock.calls.at(-1)).toEqual([{+ type: 'portos:label-preference', version: 1, nonce: hello.nonce, labelVisibility: 'off',+ }, origin]);+ fireEvent.load(frame);+ const [nextHello] = post.mock.calls.at(-1);+ expect(nextHello.nonce).not.toBe(hello.nonce);+ expect(nextHello.labelVisibility).toBe('off');+ send(source, ready);+ send(source, navigation);+ expect(screen.getByLabelText('Route')).toHaveTextContent('/eidoverse');+ send(source, { ...ready, nonce: nextHello.nonce });+ send(source, { ...navigation, nonce: nextHello.nonce });+ expect(screen.getByLabelText('Route')).toHaveTextContent('/apps');+ });++ it('marks an unresponsive older renderer unsupported without waiting in production time', () => {+ vi.useFakeTimers();+ const view = mount();+ const iframe = screen.getByTitle('Test renderer');+ vi.spyOn(iframe.contentWindow, 'postMessage').mockImplementation(() => {});+ fireEvent.load(iframe);+ act(() => vi.advanceTimersByTime(5000));+ expect(screen.getByLabelText('Bridge status')).toHaveTextContent('unsupported');+ view.unmount();+ expect(vi.getTimerCount()).toBe(0);+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 3720974533..cc88451938 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -18,6 +18,7 @@ grep -i "what you want to do" client/src/lib/README.md```| `navFeatures.js` | `filterNavByFeatures(navEntries, isFeatureEnabled)` — drops nav-manifest entries whose optional instance feature (`post`, `datadog`, `jira`, `gsd`) is off. The single gate for BROWSE surfaces (sidebar, ⌘K); routes stay reachable by URL, bookmark, and voice. Pair with `useInstanceFeatures`. |+| `eidoverseFrame.js` | Versioned hosted Eidoverse message guards, exact section navigation allowlist, and browser label preferences. || `eidoverseWorldReset.js` | Client reset-reconciliation maps for Eidoverse source kinds and district asset slots; parity-tested against the authoritative server world-design contracts. || `postQuickSession.js` | Pure Quick POST duration presets, local-observation estimator, deterministic budget composer, and preview metadata. || `postRotation.js` | Pure deterministic day-based rotation for POST practice selection — `orderByRecencyRotation` sorts candidates fresh-before-recently-practiced, then by priority, and rotates equivalent ones by local day. Mirrored from `server/lib/postRotation.js`. |diff --git a/client/src/lib/eidoverseFrame.js b/client/src/lib/eidoverseFrame.jsnew file mode 100644index 0000000000..f4d7327e41--- /dev/null+++ b/client/src/lib/eidoverseFrame.js@@ -0,0 +1,25 @@+// Versioned, data-only bridge to the sole hosted renderer. Never accept a URL+// or a private record from the frame; navigation names an already-projected+// entity and exactly one known section route.+export const EIDOVERSE_FRAME_VERSION = 1;+export const EIDOVERSE_LABEL_PREFERENCES = ['nearby', 'all-nearby', 'off'];+export const EIDOVERSE_SOURCE_ROUTES = Object.freeze({+ apps: '/apps', agents: '/cos/agents', tasks: '/cos/tasks', features: '/settings/features',+ peers: '/instances', health: '/cos/health', productivity: '/cos/productivity',+ activity: '/cos/productivity', goals: '/goals/list', memory: '/brain/memory',+ storage: '/settings/database', jira: '/goals/list', operations: '/cos/health',+});+const ROUTES = new Set([...Object.values(EIDOVERSE_SOURCE_ROUTES), '/eidoverse']);++export function isEidoverseFrameMessage(event, { source, origin, nonce }) {+ const data = event.data;+ return Boolean(source && event.source === source && event.origin === origin+ && data && typeof data === 'object' && !Array.isArray(data)+ && data.version === EIDOVERSE_FRAME_VERSION && data.nonce === nonce);+}++export function eidoverseNavigationTarget(data, objects) {+ if (typeof data.entityId !== 'string' || !ROUTES.has(data.route)) return null;+ return objects.some((object) => object.id === data.entityId && object.route === data.route)+ ? data.route : null;+}diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex c5a399fcfe..240ffe905f 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -194,3 +194,4 @@ export * from './writingGuide.js';export * from './qrCode.js';export * from './riggingReasons.js';export * from './usdzExport.js';+export * from './eidoverseFrame.js';diff --git a/client/src/pages/Eidoverse.jsx b/client/src/pages/Eidoverse.jsxindex b0f5a5b983..0115579878 100644--- a/client/src/pages/Eidoverse.jsx+++ b/client/src/pages/Eidoverse.jsx@@ -10,6 +10,7 @@ import {import { Link } from 'react-router';import PageHeader from '../components/PageHeader';import BrailleSpinner from '../components/BrailleSpinner';+import useEidoverseFrame from '../hooks/useEidoverseFrame';import EidoverseWorldDrawer from '../components/eidoverse/EidoverseWorldDrawer';import {EIDOVERSE_SOURCE_KIND as SOURCE_KIND,@@ -146,6 +147,15 @@ function reconcileResetAssetOverrides(current, submitted, after, reset, sources);}+function reconcileResetAliases(current, submitted, after, reset, sources) {+ if (reset.scope === 'all') return reconcileActionDraft(current, submitted, submitted, after);+ if (reset.scope !== 'district') return current;+ const kinds = sources.map((source) => SOURCE_KIND[source]).filter(Boolean);+ const keys = new Set([...Object.keys(current), ...Object.keys(submitted), ...Object.keys(after)]);+ return mergeSubmittedKeys(current, submitted, after,+ [...keys].filter((key) => kinds.some((kind) => key.startsWith(`${kind}-`))));+}+export default function Eidoverse() {const requestGeneration = useRef(0);const configDraftRevision = useRef(0);@@ -163,6 +173,7 @@ export default function Eidoverse() {const [humanName, setHumanName] = useState('');const [recipeDraft, setRecipeDraft] = useState(null);const [assetOverridesDraft, setAssetOverridesDraft] = useState({});+ const [labelAliasesDraft, setLabelAliasesDraft] = useState({});const [projectionStatus, setProjectionStatus] = useState('idle');const [projectionError, setProjectionError] = useState('');const [configStatus, setConfigStatus] = useState('');@@ -170,6 +181,8 @@ export default function Eidoverse() {const [settingsOpen, setSettingsOpen] = useState(false);const [iframeReady, setIframeReady] = useState(false);+ const frame = useEidoverseFrame(hostUrl, worldState?.projection?.lastSummary?.objects);+const applyWorldResponse = useCallback((updated, { replaceDraft = true } = {}) => {setWorldState((current) => current? { ...current, ...updated, identity: updated.identity || updated.human || current.identity }@@ -177,6 +190,7 @@ export default function Eidoverse() {if (replaceDraft) {if (updated?.recipe) setRecipeDraft(updated.recipe);setAssetOverridesDraft(updated?.design?.userOverrides?.assets || {});+ setLabelAliasesDraft(updated?.design?.labelAliases || {});if (updated?.world) setWorldName(updated.world);if (updated?.identity?.name || updated?.human?.name) setHumanName(updated.identity?.name || updated.human.name);savedDraftRevision.current = configDraftRevision.current;@@ -198,6 +212,7 @@ export default function Eidoverse() {setWorldState(null);setRecipeDraft(null);setAssetOverridesDraft({});+ setLabelAliasesDraft({});setProjectionStatus('idle');setProjectionError('');setConfigStatus('');@@ -288,6 +303,7 @@ export default function Eidoverse() {if (replaceDraft && result.recipe) {setRecipeDraft(result.recipe);setAssetOverridesDraft(result.design?.userOverrides?.assets || {});+ setLabelAliasesDraft(result.design?.labelAliases || {});}setProjectionStatus('complete');return result;@@ -342,6 +358,16 @@ export default function Eidoverse() {});}, [markConfigDirty]);+ const mutateLabelAlias = useCallback((key, value) => {+ markConfigDirty();+ setLabelAliasesDraft((current) => {+ const next = { ...current };+ if (value.trim()) next[key] = value;+ else delete next[key];+ return next;+ });+ }, [markConfigDirty]);+const saveWorldConfig = useCallback(async () => {if (!recipeDraft) return;const submittedRevision = configDraftRevision.current;@@ -351,6 +377,7 @@ export default function Eidoverse() {humanName: humanName.trim() || null,recipe: recipeDraft,assetOverrides: assetOverridesDraft,+ labelAliases: labelAliasesDraft,}, silent).catch((reason) => {setConfigStatus(reason?.message || 'Could not save the Eidoverse world configuration.');return null;@@ -365,13 +392,14 @@ export default function Eidoverse() {: hostUrl;if (nextHostUrl !== hostUrl) setHostUrl(nextHostUrl);else void runProjection().catch(() => {});- }, [applyWorldResponse, assetOverridesDraft, hostInfo, hostUrl, humanName, recipeDraft, runProjection, setupState, worldName]);+ }, [applyWorldResponse, assetOverridesDraft, labelAliasesDraft, hostInfo, hostUrl, humanName, recipeDraft, runProjection, setupState, worldName]);const runConfigAction = useCallback(async (payload) => {const submittedRevision = configDraftRevision.current;const submittedDraftWasClean = submittedRevision === savedDraftRevision.current;const submittedRecipeDraft = recipeDraft;const submittedAssetOverrides = assetOverridesDraft;+ const submittedAliases = labelAliasesDraft;const serverRecipeBeforeAction = worldState?.recipe;const serverAssetOverridesBefore = worldState?.design?.userOverrides?.assets || {};setConfigStatus('saving');@@ -386,6 +414,10 @@ export default function Eidoverse() {if (replaceDraft) configDraftRevision.current += 1;applyWorldResponse(updated, { replaceDraft });if (!replaceDraft && payload.reset) {+ setLabelAliasesDraft((current) => reconcileResetAliases(+ current, submittedAliases, updated.design?.labelAliases || {}, payload.reset,+ updated.recipe?.districts?.find(({ id }) => id === payload.reset.districtId)?.sources || [],+ ));if (updated.recipe) {setRecipeDraft((current) => reconcileResetRecipe(current,@@ -419,7 +451,7 @@ export default function Eidoverse() {}setConfigStatus(replaceDraft ? 'saved' : '');void runProjection().catch(() => {});- }, [applyWorldResponse, assetOverridesDraft, recipeDraft, runProjection, worldState]);+ }, [applyWorldResponse, assetOverridesDraft, labelAliasesDraft, recipeDraft, runProjection, worldState]);const actions = (<>@@ -494,12 +526,13 @@ export default function Eidoverse() {{phase === 'ready' && (<main className="relative min-h-0 flex-1 overflow-hidden bg-port-bg"><iframe+ ref={frame.frameRef}src={hostUrl}title="Eidoverse Worlds"className="absolute inset-0 h-full w-full border-0 bg-port-bg"allow="camera; microphone; fullscreen; gamepad; xr-spatial-tracking"allowFullScreen- onLoad={() => setIframeReady(true)}+ onLoad={() => { setIframeReady(true); frame.onFrameLoad(); }}/>{showLoadingCurtain && (@@ -566,6 +599,12 @@ export default function Eidoverse() {setHumanName={setHumanName}recipeDraft={recipeDraft}assetOverridesDraft={assetOverridesDraft}+ labelAliasesDraft={labelAliasesDraft}+ mutateLabelAlias={mutateLabelAlias}+ frameConnection={frame.connection}+ labelVisibility={frame.labelVisibility}+ onLabelVisibilityChange={frame.changeLabelVisibility}+ appId={appId}mutateRecipe={mutateRecipe}mutateAssetOverride={mutateAssetOverride}markDirty={markConfigDirty}diff --git a/client/src/pages/Eidoverse.test.jsx b/client/src/pages/Eidoverse.test.jsxindex f8c907ae42..3fd164504c 100644--- a/client/src/pages/Eidoverse.test.jsx+++ b/client/src/pages/Eidoverse.test.jsx@@ -1,3 +1,4 @@+// @vitest-environment-options {"settings":{"navigation":{"disableChildFrameNavigation":true}}}import { beforeEach, describe, expect, it, vi } from 'vitest';import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';@@ -164,6 +165,62 @@ describe('Eidoverse hosted page', () => {expect(screen.getByText('App Terraces')).toBeInTheDocument();});+ it('keeps label visibility browser-only and saves or clears explicit aliases from the object legend', async () => {+ const user = userEvent.setup();+ const key = 'app-0123456789ab';+ const object = {+ id: 'portos-design-v2-signal-app-example', kind: 'app', resourceKey: key,+ districtId: 'apps', name: 'Managed app 012345', description: 'An app this install manages. Data is current.',+ visibility: 'nearby', route: '/apps',+ asset: { slot: 'app', path: 'eidoverse/assets/models/orb.glb', reason: 'catalog-fallback' },+ };+ const summary = { ...worldResponse.projection.lastSummary, objects: [object] };+ api.projectEidoverseWorld.mockResolvedValue({+ success: true, recipe, design, projection: { lastSummary: summary },+ });+ renderPage();+ await screen.findByTitle('Eidoverse Worlds');+ await waitFor(() => expect(api.projectEidoverseWorld).toHaveBeenCalledTimes(1));+ await user.click(screen.getByRole('button', { name: 'World controls' }));+ api.projectEidoverseWorld.mockClear();+ await user.selectOptions(screen.getByLabelText('Floating labels'), 'off');+ expect(api.updateEidoverseWorldConfig).not.toHaveBeenCalled();+ expect(api.projectEidoverseWorld).not.toHaveBeenCalled();+ await user.click(screen.getByRole('tab', { name: 'Districts & Data' }));+ const legend = screen.getByRole('region', { name: 'Projected object labels' });+ expect(within(legend).getByText('Managed app 012345')).toBeInTheDocument();+ expect(within(legend).getByText('Fallback — available library asset')).toBeInTheDocument();+ const alias = screen.getByLabelText('Display alias for Managed app 012345');+ expect(alias).toHaveValue('');+ await user.type(alias, 'Example tower');+ api.updateEidoverseWorldConfig.mockRejectedValueOnce(new Error('Example save failure'));+ await user.click(screen.getByRole('button', { name: 'Save and project' }));+ expect(await screen.findByText('Example save failure')).toBeInTheDocument();+ expect(alias).toHaveValue('Example tower');+ expect(api.updateEidoverseWorldConfig).toHaveBeenLastCalledWith(+ expect.objectContaining({ labelAliases: { [key]: 'Example tower' } }), { silent: true },+ );+ expect(api.projectEidoverseWorld).not.toHaveBeenCalled();+ await user.clear(alias);+ await user.click(screen.getByRole('button', { name: 'Save and project' }));+ await waitFor(() => expect(api.updateEidoverseWorldConfig).toHaveBeenLastCalledWith(+ expect.objectContaining({ labelAliases: {} }), { silent: true },+ ));+ });++ it('shows a renderer update link while preserving the saved recipe on older clients', async () => {+ const user = userEvent.setup();+ const oldDesign = { ...design, reconciliation: { ...design.reconciliation,+ runtimeVersion: { sha: 'example-old-build', capabilities: { objectLabels: null } } } };+ api.projectEidoverseWorld.mockResolvedValue({ success: true, recipe, design: oldDesign });+ renderPage();+ await screen.findByTitle('Eidoverse Worlds');+ await user.click(screen.getByRole('button', { name: 'World controls' }));+ expect(await screen.findByText(/does not report object-label support/)).toBeInTheDocument();+ expect(screen.getByRole('link', { name: 'Manage renderer updates' })).toHaveAttribute('href', '/apps/app-eidoverse/overview');+ expect(screen.getByText('Luminous Systems Garden')).toBeInTheDocument();+ });+it('keeps an unknown indicator count distinct from a projected empty world', async () => {const user = userEvent.setup();api.getEidoverseWorldStatus.mockResolvedValueOnce({@@ -444,6 +501,13 @@ describe('Eidoverse hosted page', () => {it('merges a scoped reset into the draft without discarding unrelated unsaved edits', async () => {const user = userEvent.setup();+ const objects = ['app', 'agent'].map((kind) => ({+ id: `portos-design-v2-signal-${kind}-example`, kind, resourceKey: `${kind}-0123456789ab`,+ districtId: `${kind}s`, name: `Example ${kind} signal`, visibility: 'nearby',+ description: 'An example aggregate signal.', asset: { path: 'store/example', reason: 'user-override' },+ }));+ api.projectEidoverseWorld.mockResolvedValue({ success: true, recipe, design,+ projection: { lastSummary: { ...worldResponse.projection.lastSummary, objects } } });renderPage();await screen.findByTitle('Eidoverse Worlds');await waitFor(() => expect(api.projectEidoverseWorld).toHaveBeenCalledOnce());@@ -454,6 +518,8 @@ describe('Eidoverse hosted page', () => {await user.clear(sunHour);await user.type(sunHour, '8.4');await user.click(screen.getByRole('tab', { name: 'Districts & Data' }));+ await user.type(screen.getByLabelText('Display alias for Example app signal'), 'Unsaved app alias');+ await user.type(screen.getByLabelText('Display alias for Example agent signal'), 'Keep agent alias');const appsSection = screen.getByRole('heading', { name: 'App Terraces' }).closest('section');const appsLimit = within(appsSection).getByRole('spinbutton', { name: 'Cap' });await user.clear(appsLimit);@@ -477,6 +543,7 @@ describe('Eidoverse hosted page', () => {await user.click(save);await waitFor(() => expect(api.updateEidoverseWorldConfig).toHaveBeenCalledTimes(2));const saved = api.updateEidoverseWorldConfig.mock.calls.at(-1)[0];+ expect(saved.labelAliases).toEqual({ 'agent-0123456789ab': 'Keep agent alias' });expect(saved.recipe.environment.sky.hours).toBe(8.4);expect(saved.recipe.limits.apps).toBe(8);});diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 02956ae22e..ac9e6a7ae4 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -62,7 +62,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- Writers Room draft bodies — `data/writers-room/works/{workId}/drafts/{draftId}.md`. Keep `.md` file-backed; store metadata/index rows in DB.- MortalLoom / Health / Meatspace health data — `data/health`, `data/meatspace`, MortalLoom iCloud store. Kept file-backed to preserve iCloud/file sync and avoid routing sensitive health records through the app DB before that boundary is designed.- App scaffolds / cloned repos / browser profiles — `data/repos`, `data/browser-profile` — inherently filesystem-oriented.-- Eidoverse PortOS integration and world logs — `data/eidoverse/portos-world.json` stores the PortOS-owned private-world identity, versioned design selection, user overrides, deterministic asset-resolution lock (paths, fingerprints, size, and provenance only; never model bytes), migration report, and last-good reconciliation checkpoint; `data/eidoverse/worlds` stores the external runtime's append-only world files. Both are `file-primary`, included in filesystem backups, and intentionally machine-local — never federated by PortOS. PortOS selects the runtime's world-store location through `.env.portos` but does not edit the external checkout to build content. The separately licensed git checkouts and Eidoverse-owned asset library/cache live under the existing re-cloneable `data/repos/` backup class.+- Eidoverse PortOS integration and world logs — `data/eidoverse/portos-world.json` stores the PortOS-owned private-world identity, versioned design selection, explicit display aliases keyed by opaque resource identity (never backfilled from records), user overrides, deterministic asset-resolution lock (paths, fingerprints, size, and provenance only; never model bytes), migration report, and last-good reconciliation checkpoint; `data/eidoverse/worlds` stores the external runtime's append-only world files. Both are `file-primary`, included in filesystem backups, and intentionally machine-local — never federated by PortOS. PortOS selects the runtime's world-store location through `.env.portos` but does not edit the external checkout to build content. The separately licensed git checkouts and Eidoverse-owned asset library/cache live under the existing re-cloneable `data/repos/` backup class.- Sprite animation-track definitions — `data/sprites/animation-tracks.json` (#3152). A small hand-editable authoring config: which animation types exist beyond the compiled-in `walk` (label, directionality, frame/fps bounds, prompt template, and the on-disk `setKind` strings). `file-primary` rather than `db-primary` because it is **machine-local and inseparable from the on-disk sprite tree it describes** — a row names the `setKind` an approved set under `data/sprites/{id}/` already carries, so the two travel together or neither means anything — and because it has no cross-record queries, no relationships beyond `kinds` strings, and no sync cursor. Read synchronously and cached per process (`server/services/sprites/animationTrackStore.js`): `server/lib/validation.js` builds sprite Zod ranges from it at module load, so it must resolve without `await`. Seeded from `data.reference/sprites/animation-tracks.json` (migration 211), which is also the fallback read when no user copy exists yet. Backed up in full by the rsync snapshot.- Quota-burn plan — `data/cos/quota-burn.json` (#3390). The install's burn plan: master switch, poll interval, and per-provider-family windows + ordered job list. `file-primary` and **intentionally machine-local — never federated**: quota belongs to a particular machine and provider account, so a synced plan would have each peer spending against the other's window budget, and the plan's `agent-prompt` jobs name managed apps that only exist on this machine. No sync cursor, no tombstone. Its four companions are `ephemeral-file` — regenerable telemetry, all safe to delete: `data/cos/quota-burn-dispatches.json` (per-window dispatch counts, self-pruning at 30 days), `data/cos/quota-burn-runs.json` (capped run log), `data/cos/quota-burn-inflight.json` (entries a burn job has enqueued but whose renders have not completed, self-pruning at 6 hours — deleting it only risks re-queueing a render already in flight), and `data/cos/quota-burn-denials.json` (per-family blocks from an observed provider refusal, cleared by the next successful burn or a 5-hour TTL — deleting it only risks one dispatch into a still-exhausted window). Backed up with the rest of `data/cos/`; a restored plan simply re-applies on this machine. See [Quota Burn](./QUOTA-BURN.md).- YouTube brain ingests — `data/brain/youtube/{videoId}.md` (transcript), `{videoId}.mp3` (optional audio), plus `data/brain/youtube/index.json` (the ingest index) and `data/brain/youtube-ingest-settings.json`. The transcript IS an external file: it is mirrored into the user's Obsidian vault, edited there, and syncs through iCloud — the same boundary that keeps the Daily Log file-backed. The index is **intentionally machine-local — never federated**: every field in it is a local filesystem path, an Obsidian vault id, or a local video-history id, so a peer's copy would be meaningless and would poison brain reconcile exactly the way the daily log's `journal-obsidian-locations.json` sidecar would. The playlist/video reference shelf at `data/youtube/playlists.json` follows the same local-only rule: it is a bounded cache of browser-scraped YouTube metadata and links, not a federated Brain record. The durable, federated record of "I consumed and kept this" is the brain `links` entry (`db-primary` via the brain store) plus a `media.watch` row in `human_activity_events`. No tombstone. Adapters: `server/services/youtubeIngest.js` and `server/services/youtubePlaylists.js`.diff --git a/docs/features/eidoverse.md b/docs/features/eidoverse.mdindex bd84134208..e39aa46e1a 100644--- a/docs/features/eidoverse.md+++ b/docs/features/eidoverse.md@@ -198,7 +198,7 @@ are exhausted. Catalog entries without byte metadata remain usable with## Versioning, updates, and recovery-`data/eidoverse/portos-world.json` schema V2 records+`data/eidoverse/portos-world.json` schema V3 records`selectedDesignVersion`, `lastAppliedDesignVersion`, `pendingDesignVersion`,`userOverrides`, `assetRecipeVersion`, `assetResolutions`, `migrationReport`,and the reconciliation checkpoint/error. The immutable V1 and V2 registries are@@ -316,3 +316,87 @@ The hosted page, identity bridge, projection service, and CoS tools are explicitPortOS adapters across the two projects' public protocols. They remaindeterministic and install-local: opening PortOS does not call an AI provider,and no raw Eidoverse world log is copied to another machine by federation.+++## Object labels, aliases, and the saved legend++PortOS emits a generic `comp.label` beside each owned object's `comp.portos`:+`{name, description?, visibility: 'nearby' | 'always' | 'inspect', offset?}`.+District and world landmarks use `always`, bounded by the renderer's range;+live indicators use `nearby`; walkway markers use `inspect`. Ordinary refresh+adds labels to existing worlds. One projector helper updates the label and the+saved object legend together, including stale retained indicators. Repeating an+unchanged projection emits no label verbs. Removed managed entities take their+labels with them; foreign entities and their labels are preserved.++**World controls → Districts & Data** shows the last successful projection by+district: semantic name, meaning, label mode, model path, and resolution reason.+Search matches and catalog/recipe fallbacks are explicitly called fallbacks.+A retained model whose path differs from the current resolution lock reports+unverified provenance. The link to **Appearance & Assets** uses the existing+asset override, refresh, and reset controls. The legend remains readable with+floating labels off and on older renderers.++Optional aliases name individual live indicators using stable opaque resource+keys, never private record IDs or titles. The configuration accepts at most 128+aliases, each plain text of at most 72 characters. Clear the field to restore+the generic label. Saving an alias explicitly publishes that display text into+the private world's append-only history; removing it changes the current label,+not older history. Asset resets preserve aliases; district/all resets clear the+matching aliases. Migration 343 upgrades existing config to schema V3, preserving+custom recipes and asset locks, and initializes an empty alias map without+reading private records. No config seed or raw-data backfill ships. Older PortOS+versions reject the newer config schema rather than discarding the aliases.++## Renderer capabilities and frame contract V1++The external Worlds checkout remains the sole renderer. This PortOS contract+can ship before its companion implementation in+[Worlds issue 5](https://github.com/atomantic/eidoverse-worlds/issues/5).+End-to-end label/picking/touch/keyboard acceptance requires that companion;+producer and frame-contract tests alone do not establish it.++`GET /version` advertises independently versioned capabilities alongside its+existing build identity:++```json+{"sha":"example-build","commitTime":"2026-01-01T00:00:00Z","capabilities":{"objectLabels":1,"portosNavigation":1,"labelPreferences":1}}+```++Missing, malformed, or unknown capability versions do not block projection.+The drawer shows an update/reload action when label support or the frame bridge+is unavailable. Updating the managed checkout preserves PortOS design settings,+explicit aliases, and asset overrides. The actual frame handshake takes+precedence over the server capability report, so a stale browser bundle cannot+pretend it supports the updated runtime.++After each iframe load, PortOS posts to its **exact hosted origin**:++```json+{"type":"portos:connect","version":1,"nonce":"fresh-opaque-session","capabilities":{"portosNavigation":1,"labelPreferences":1},"labelVisibility":"nearby"}+```++The renderer validates `event.source === parent` and the embedding PortOS origin,+then replies to that exact origin with `eidoverse:ready`, echoing `version` and+`nonce` and advertising its supported capabilities. The renderer must obtain+the expected parent origin from its trusted embedding configuration; accepting+an arbitrary opener as the parent is not sufficient. Each later message carries+the same version and nonce. A reload invalidates the prior session. Unsupported+clients simply ignore the handshake and continue rendering.++For a user-triggered **Open in PortOS**, the renderer sends+`{type:'eidoverse:navigate', version:1, nonce, entityId, route}`. PortOS requires+all of: the current iframe window, its exact origin, the current nonce, a V1+navigation-capable handshake, an entity present in the saved projection legend,+and exact equality between the requested route and that object's known PortOS+section route. Only the fixed source-section routes (plus `/eidoverse`) are+allowed. URLs, query strings, encoded/relative paths, record payloads, and+unknown entities cannot navigate. No URL proxy is exposed.++Floating-label preference is browser-only: `nearby` respects authored modes,+`all-nearby` includes inspect-only objects within the renderer's bounded range,+and `off` hides floating labels while keeping selected-object details accessible.+PortOS sends `portos:label-preference` with `version`, `nonce`, and+`labelVisibility` only after the frame advertises V1 preference support. A+preference change never sends a world verb or rewrites configuration. The+renderer owns distance culling, object picking, and accessible selected details.diff --git a/scripts/lib/migrationOwnedPaths.js b/scripts/lib/migrationOwnedPaths.jsindex 1954089eea..979570047d 100644--- a/scripts/lib/migrationOwnedPaths.js+++ b/scripts/lib/migrationOwnedPaths.js@@ -11,6 +11,7 @@/** Paths relative to `data/` (and to `data.reference/`), always posix-spelled. */export const MIGRATION_OWNED_PATHS = new Set([+ 'eidoverse/portos-world.json', // Per-install state and explicit aliases; never seed over it.// Migration 339 lifts the durable CoS config out of data/cos/state.json.// Absent, `loadConfig()` in server/services/cosState.js returns DEFAULT_CONFIG.'cos/config.json',diff --git a/scripts/migrations/323-eidoverse-world-design-v2.js b/scripts/migrations/323-eidoverse-world-design-v2.jsindex 1047eede3f..b1fd2a3262 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 } from '../../server/lib/eidoverseWorldDesign.js';+import { migrateEidoverseWorldState, 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 === 2 && state.selectedDesignVersion === 2+ if (state.schemaVersion === EIDOVERSE_WORLD_STATE_SCHEMA_VERSION && state.selectedDesignVersion === 2&& 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 8506b72882..3dacce1f04 100644--- a/scripts/migrations/323-eidoverse-world-design-v2.test.js+++ b/scripts/migrations/323-eidoverse-world-design-v2.test.js@@ -27,7 +27,7 @@ describe('migration 323 — Eidoverse World Design V2', () => {await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 1, preservedOverrides: [] });expect(await readState()).toMatchObject({- schemaVersion: 2,+ schemaVersion: 3,world: 'example-world',selectedDesignVersion: 2,lastAppliedDesignVersion: 1,diff --git a/scripts/migrations/343-eidoverse-label-aliases.js b/scripts/migrations/343-eidoverse-label-aliases.jsnew file mode 100644index 0000000000..9a71198ba6--- /dev/null+++ b/scripts/migrations/343-eidoverse-label-aliases.js@@ -0,0 +1,25 @@+/** Add opt-in aliases to existing config without reading any private records. */+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/scripts/migrations/343-eidoverse-label-aliases.test.js b/scripts/migrations/343-eidoverse-label-aliases.test.jsnew file mode 100644index 0000000000..9aaa47dbbd--- /dev/null+++ b/scripts/migrations/343-eidoverse-label-aliases.test.js@@ -0,0 +1,36 @@+import { afterEach, describe, expect, it } from 'vitest';+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import migration from './343-eidoverse-label-aliases.js';++let rootDir;+afterEach(async () => {+ if (rootDir) await rm(rootDir, { recursive: true, force: true });+ rootDir = null;+});++describe('Eidoverse alias state migration', () => {+ it('preserves V2 custom recipes and asset locks without deriving aliases from records', async () => {+ rootDir = await mkdtemp(join(tmpdir(), 'eidoverse-aliases-'));+ const path = join(rootDir, 'data/eidoverse/portos-world.json');+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'no-state' });+ await mkdir(join(rootDir, 'data/eidoverse'), { recursive: true });+ const userOverrides = { name: 'Example garden', assets: { app: 'store/example-custom' }, limits: { apps: 2 } };+ const assetResolutions = { app: { path: 'store/example-custom', userOverride: true } };+ 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.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 }));+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });+ expect(JSON.parse(await readFile(path, 'utf8')).labelAliases).toEqual(aliases);+ for (const raw of ['{invalid', JSON.stringify({ schemaVersion: 99, labelAliases: aliases })]) {+ await writeFile(path, raw);+ expect((await migration.up({ rootDir })).updated).toBe(0);+ expect(await readFile(path, 'utf8')).toBe(raw);+ }+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex a987f9f6d9..b7afe69aa3 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -480,7 +480,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `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. |-| `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)` 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 `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. |+| `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`. || `fetchErrorChain.js` | `describeFetchError(err)` flattens a fetch rejection's whole `cause` chain (depth-bounded, cycle-guarded) into one searchable `code: message` string — undici reports every network failure as the same opaque `TypeError: fetch failed` with the real reason nested inside, so a classifier reading only `err.message` misjudges every one of them. `isReplayableConnectionError(err)` is the narrow predicate over that string for connection-REUSE artifacts (HTTP/2 GOAWAY, reset, hang-up) that are safe to replay once via `fetchWithTimeout`'s `shouldRetry`; it deliberately EXCLUDES timeouts, which broader classifiers like `ollamaManager`'s `isTransientPullError` include. |diff --git a/server/lib/eidoverseValidation.js b/server/lib/eidoverseValidation.jsindex de16f9a864..8762e58c88 100644--- a/server/lib/eidoverseValidation.js+++ b/server/lib/eidoverseValidation.js@@ -301,6 +301,10 @@ export const eidoverseWorldConfigPatchSchema = z.object({]),eidoverseModelAssetOverrideSchema,).optional(),+ labelAliases: z.record(+ z.string().regex(/^(?:app|agent|task|feature|peer|health|productivity|activity|goal|memory|storage|jira|operations)-[0-9a-f]{12}$/),+ z.string().trim().min(1).max(72).regex(/^[^\u0000-\u001f\u007f]+$/),+ ).refine((aliases) => Object.keys(aliases).length <= 128, 'at most 128 display aliases may be configured').optional(),refreshAssets: z.boolean().optional(),reset: z.object({scope: z.enum(['all', 'assets', 'district']),diff --git a/server/lib/eidoverseWorldDesign.js b/server/lib/eidoverseWorldDesign.jsindex ea54fba666..0d3c025893 100644--- a/server/lib/eidoverseWorldDesign.js+++ b/server/lib/eidoverseWorldDesign.js@@ -6,10 +6,11 @@* resulting paths in its machine-local world state.*/+import { normalizeEidoverseLabelAliases } from './eidoverseWorldLabels.js';import { createHash } from 'node:crypto';import { canonicalStringify, deepMerge } from './objects.js';-export const EIDOVERSE_WORLD_STATE_SCHEMA_VERSION = 2;+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_MAX_LIVE_ENTITIES = 48;@@ -498,7 +499,7 @@ export function migrateEidoverseWorldState(raw, { now = new Date().toISOString()};}- if (inputSchema === EIDOVERSE_WORLD_STATE_SCHEMA_VERSION) {+ if (inputSchema >= 2) {const userOverrides = isObject(input.userOverrides)? input.userOverrides: extractEidoverseDesignOverrides(input.recipe);@@ -516,6 +517,7 @@ export function migrateEidoverseWorldState(raw, { now = new Date().toISOString()state: {...input,schemaVersion: EIDOVERSE_WORLD_STATE_SCHEMA_VERSION,+ labelAliases: normalizeEidoverseLabelAliases(input.labelAliases),selectedDesignVersion: EIDOVERSE_WORLD_DESIGN_VERSION,assetRecipeVersion: EIDOVERSE_ASSET_RECIPE_VERSION,userOverrides,@@ -548,6 +550,7 @@ export function migrateEidoverseWorldState(raw, { now = new Date().toISOString()state: {...input,schemaVersion: EIDOVERSE_WORLD_STATE_SCHEMA_VERSION,+ labelAliases: {},selectedDesignVersion: EIDOVERSE_WORLD_DESIGN_VERSION,lastAppliedDesignVersion: 1,pendingDesignVersion: EIDOVERSE_WORLD_DESIGN_VERSION,diff --git a/server/lib/eidoverseWorldDesign.test.js b/server/lib/eidoverseWorldDesign.test.jsindex 1f0521ac6b..ae36930ee5 100644--- a/server/lib/eidoverseWorldDesign.test.js+++ b/server/lib/eidoverseWorldDesign.test.js@@ -30,7 +30,7 @@ describe('Eidoverse World Design V2', () => {expect(migrated.compatible).toBe(true);expect(migrated.state).toMatchObject({- schemaVersion: 2,+ schemaVersion: 3,selectedDesignVersion: 2,lastAppliedDesignVersion: 1,pendingDesignVersion: 2,diff --git a/server/lib/eidoverseWorldLabels.js b/server/lib/eidoverseWorldLabels.jsindex 33c411d674..f1ba80bcea 100644--- a/server/lib/eidoverseWorldLabels.js+++ b/server/lib/eidoverseWorldLabels.js@@ -9,13 +9,30 @@** Every string here is generated from PortOS's own vocabulary — district and* kind names, coarse status, freshness — plus an opaque hashed resource ref.- * Nothing that could name a record, a machine, a network, or a filesystem ever- * reaches the append-only world log, and a label describes what an object+ * Raw private records never supply names; explicit user-authored aliases are+ * the sole opt-in exception to generic names in the append-only world log, and a label describes what an object* represents rather than the decorative asset standing in for it.*/export const EIDOVERSE_LABEL_COMPONENT_TYPE = 'label';export const EIDOVERSE_LABEL_VISIBILITIES = Object.freeze(['always', 'nearby', 'inspect']);+export const EIDOVERSE_LABEL_ALIAS_KEY = /^(?:app|agent|task|feature|peer|health|productivity|activity|goal|memory|storage|jira|operations)-[0-9a-f]{12}$/;++/** Only explicit display aliases belong here; never infer one from a record. */+export function normalizeEidoverseLabelAliases(value) {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return {};+ return Object.fromEntries(Object.entries(value)+ .filter(([key, alias]) => EIDOVERSE_LABEL_ALIAS_KEY.test(key) && typeof alias === 'string')+ .slice(0, 128)+ .map(([key, alias]) => [key, safeWorldText(alias, '', 72)])+ .filter(([, alias]) => alias));+}++/** Feature versions, independent of the checkout SHA and world-design version. */+export function eidoverseLabelCapabilities(version) {+ return Object.fromEntries(['objectLabels', 'portosNavigation', 'labelPreferences']+ .map((key) => [key, version?.capabilities?.[key] === 1 ? 1 : null]));+}const MAX_NAME_CHARS = 72;const MAX_DESCRIPTION_CHARS = 240;@@ -139,7 +156,11 @@ const LABEL_BUILDERS = Object.freeze({* `comp.portos` component already computed for it. Returns `null` for anything* PortOS does not own, so a caller can never label somebody else's entity.*/-export function buildEidoverseLabel(component) {+export function buildEidoverseLabel(component, alias) {if (!component || component.managedBy !== 'portos') return null;- return (LABEL_BUILDERS[component.kind] || signalLabel)(component);+ const result = (LABEL_BUILDERS[component.kind] || signalLabel)(component);+ const name = EIDOVERSE_LABEL_ALIAS_KEY.test(component.resourceKey || '')+ ? safeWorldText(alias, '', MAX_NAME_CHARS)+ : '';+ return result && name ? { ...result, name } : result;}diff --git a/server/routes/eidoverseWorldRoutes.test.js b/server/routes/eidoverseWorldRoutes.test.jsindex 75f128a088..d497540585 100644--- a/server/routes/eidoverseWorldRoutes.test.js+++ b/server/routes/eidoverseWorldRoutes.test.js@@ -72,6 +72,24 @@ describe('Eidoverse world routes', () => {expect(mocks.updateConfig).toHaveBeenCalledWith({ humanName: 'Example User' });});+ it('accepts explicit opaque-key aliases and rejects raw identities and unbounded text', async () => {+ const key = 'app-0123456789ab';+ const valid = await request(makeApp()).put('/api/eidoverse/world/config').send({ labelAliases: { [key]: ' Example observatory ' } });+ expect(valid.status).toBe(200);+ expect(mocks.updateConfig).toHaveBeenLastCalledWith({ labelAliases: { [key]: 'Example observatory' } });+ const clear = await request(makeApp()).put('/api/eidoverse/world/config').send({ labelAliases: {} });+ expect(clear.status).toBe(200);+ mocks.updateConfig.mockClear();+ for (const labelAliases of [+ { 'Example private app': 'Alias' }, { [key]: 'x'.repeat(73) }, { [key]: '' }, { [key]: 'line\nbreak' },+ Object.fromEntries(Array.from({ length: 129 }, (_, i) => [`app-${i.toString(16).padStart(12, '0')}`, 'Alias'])),+ ]) {+ const rejected = await request(makeApp()).put('/api/eidoverse/world/config').send({ labelAliases });+ expect(rejected.status).toBe(400);+ }+ expect(mocks.updateConfig).not.toHaveBeenCalled();+ });+it('validates scoped reset and asset-refresh actions', async () => {const district = await request(makeApp()).put('/api/eidoverse/world/config').send({reset: { scope: 'district', districtId: 'apps' },diff --git a/server/services/eidoverseWorld.js b/server/services/eidoverseWorld.jsindex fdd5a550af..ac9297b131 100644--- a/server/services/eidoverseWorld.js+++ b/server/services/eidoverseWorld.js@@ -14,6 +14,7 @@ import { WebSocket } from 'ws';import { atomicWrite, dataPath, ensureDir, readJSONFile } from '../lib/fileUtils.js';import { createMutex } from '../lib/asyncMutex.js';import { ServerError } from '../lib/errorHandler.js';+import { eidoverseLabelCapabilities, normalizeEidoverseLabelAliases } from '../lib/eidoverseWorldLabels.js';import { canonicalStringify } from '../lib/objects.js';import { getSelf, ensureSelf, getInstanceId } from './instances.js';import { getInstanceFeatures } from './instanceFeatures.js';@@ -84,6 +85,7 @@ const DEFAULT_STATE = {lastAppliedDesignVersion: null,pendingDesignVersion: EIDOVERSE_WORLD_DESIGN_VERSION,userOverrides: {},+ labelAliases: {},assetRecipeVersion: EIDOVERSE_ASSET_RECIPE_VERSION,assetResolutions: {},migrationReport: null,@@ -320,6 +322,7 @@ function normalizeState(raw) {? input.pendingDesignVersion: EIDOVERSE_WORLD_DESIGN_VERSION),userOverrides: clone(userOverrides),+ labelAliases: normalizeEidoverseLabelAliases(input.labelAliases),assetRecipeVersion: EIDOVERSE_ASSET_RECIPE_VERSION,assetResolutions: clone(assetResolutions),migrationReport: input.migrationReport || migration.report || null,@@ -386,6 +389,7 @@ function configFromState(state, presence = cosPresence) {},design: {name: state.recipe.name,+ labelAliases: clone(state.labelAliases),selectedVersion: state.selectedDesignVersion,lastAppliedVersion: state.lastAppliedDesignVersion,pendingVersion: state.pendingDesignVersion,@@ -497,6 +501,7 @@ export async function updateEidoverseWorldConfig(patch) {if (patch.cosEnabled !== undefined) state.cos.enabled = patch.cosEnabled;if (fullReset) {state.userOverrides = {};+ state.labelAliases = {};state.assetResolutions = {};state.ownership.retired = [];state.human.role = null;@@ -524,6 +529,8 @@ export async function updateEidoverseWorldConfig(patch) {delete state.userOverrides.limits?.[sourceKey];}for (const kind of districtKinds) delete state.userOverrides.scale?.[kind];+ state.labelAliases = Object.fromEntries(Object.entries(state.labelAliases)+ .filter(([key]) => !districtKinds.some((kind) => key.startsWith(`${kind}-`))));const districtAssetSlots = new Set([...(EIDOVERSE_ASSET_SLOTS_BY_DISTRICT[district.id] || ['district']),...districtKinds,@@ -534,6 +541,10 @@ export async function updateEidoverseWorldConfig(patch) {}designChanged = true;}+ if (patch.labelAliases !== undefined) {+ state.labelAliases = normalizeEidoverseLabelAliases(patch.labelAliases);+ designChanged = true;+ }if (patch.refreshAssets) {state.assetResolutions = {};designChanged = true;@@ -1198,6 +1209,7 @@ async function preflightEidoverseProtocol({ signal } = {}) {});}return {+ capabilities: eidoverseLabelCapabilities(version),sha: safeText(version.sha, 'unknown', 80),commitTime: safeText(version.commitTime, 'unknown', 80),};@@ -1637,6 +1649,8 @@ export async function projectEidoverseWorld({ signal } = {}) {const plan = buildProjectionPlan({source,recipe: lockedConfig.recipe,+ labelAliases: lockedConfig.design.labelAliases,+ assetResolutions: lockedConfig.design.assetResolutions,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 9d79129862..3dc688f5fc 100644--- a/server/services/eidoverseWorld.runtime.test.js+++ b/server/services/eidoverseWorld.runtime.test.js@@ -263,7 +263,7 @@ describe('Eidoverse private-world lifecycle', () => {}),]));expect(mocks.persistedState).toMatchObject({- schemaVersion: 2,+ schemaVersion: 3,lastAppliedDesignVersion: 2,pendingDesignVersion: null,migrationReport: { status: 'applied' },@@ -701,6 +701,32 @@ describe('Eidoverse private-world lifecycle', () => {expect(JSON.stringify(metaComp.args.data)).not.toContain(mocks.self.name);});+ it('round-trips explicit aliases and the object legend across projection and reconnect', async () => {+ mocks.appStatuses = [{ id: 'app-example', name: 'Example private title', overallStatus: 'online' }];+ fetch.mockImplementationOnce(async () => Response.json({+ sha: 'example-label-build', commitTime: '2026-01-01T00:00:00.000Z',+ capabilities: { objectLabels: 1, portosNavigation: 1, labelPreferences: 99 },+ }));+ const first = await world.projectEidoverseWorld();+ expect(first.design.reconciliation.runtimeVersion.capabilities).toEqual({ objectLabels: 1, portosNavigation: 1, labelPreferences: null });+ const object = first.summary.objects.find(({ kind }) => kind === 'app');+ expect(object).toBeDefined();+ await world.updateEidoverseWorldConfig({ labelAliases: { [object.resourceKey]: 'Example tower' } });+ const next = await world.projectEidoverseWorld();+ expect(next.summary.objects.find(({ id }) => id === object.id).name).toBe('Example tower');+ // A legacy renderer remains usable even though it advertises no label capabilities.+ expect(next.design.reconciliation.runtimeVersion.capabilities.objectLabels).toBeNull();+ await world.closeEidoverseWorldConnections();+ const reloaded = await world.getEidoverseWorldStatus();+ expect(reloaded.design.labelAliases).toEqual({ [object.resourceKey]: 'Example tower' });+ expect(reloaded.projection.lastSummary.objects).toEqual(next.summary.objects);+ expect(JSON.stringify(next.summary.objects)).not.toContain('Example private title');+ await world.updateEidoverseWorldConfig({ reset: { scope: 'assets' } });+ expect((await world.getEidoverseWorldStatus()).design.labelAliases).toEqual({ [object.resourceKey]: 'Example tower' });+ await world.updateEidoverseWorldConfig({ reset: { scope: 'district', districtId: 'apps' } });+ expect((await world.getEidoverseWorldStatus()).design.labelAliases).toEqual({});+ });+it('preflights and locks recipe assets before completing a V2 reconciliation', async () => {const result = await world.projectEidoverseWorld();@@ -722,7 +748,7 @@ describe('Eidoverse private-world lifecycle', () => {});expect(Object.keys(result.design.assetResolutions)).toHaveLength(10);expect(mocks.persistedState).toMatchObject({- schemaVersion: 2,+ schemaVersion: 3,lastAppliedDesignVersion: 2,pendingDesignVersion: null,reconciliation: { status: 'complete' },diff --git a/server/services/eidoverseWorld.test.js b/server/services/eidoverseWorld.test.jsindex cef3b1ce27..32df63c7d0 100644--- a/server/services/eidoverseWorld.test.js+++ b/server/services/eidoverseWorld.test.js@@ -969,3 +969,44 @@ describe('Eidoverse projection labels', () => {expect(labelFor(unavailable, entityId).description).toContain('data is stale');});});+++describe('Eidoverse saved object legend and aliases', () => {+ it('keeps alias, asset provenance, stale retention and removal in the projection contract', () => {+ const source = appSource();+ const path = 'store/example-display-model';+ const recipe = { ...DEFAULT_EIDOVERSE_PROJECTION_RECIPE, assets: { app: path } };+ const assetResolutions = { app: { path, strategy: 'user-override', userOverride: true } };+ const first = buildProjectionPlan({ source, recipe, assetResolutions });+ const object = first.summary.objects.find(({ kind }) => kind === 'app');+ expect(object).toMatchObject({+ name: expect.stringMatching(/^Managed app /), visibility: 'nearby', route: '/apps',+ asset: { slot: 'app', path, reason: 'user-override' },+ });+ const labelAliases = { [object.resourceKey]: 'Example observatory' };+ const renamed = buildProjectionPlan({+ source, recipe, assetResolutions, labelAliases, currentState: snapshotFromPlan(first),+ });+ expect(renamed.operations.filter(({ args }) => args.type === 'label')).toEqual([+ expect.objectContaining({ args: expect.objectContaining({ id: object.id, data: expect.objectContaining({ name: 'Example observatory' }) }) }),+ ]);+ const renamedState = snapshotFromPlan(first);+ renamedState.entities[object.id].comp.label.name = 'Example observatory';+ const noop = buildProjectionPlan({ source, recipe, assetResolutions, labelAliases, currentState: renamedState });+ expect(noop.operations).toEqual([]);+ expect(noop.summary.objects).toEqual(renamed.summary.objects);+ const stale = buildProjectionPlan({ source: { ...source, apps: null }, recipe, assetResolutions, labelAliases, currentState: renamedState });+ expect(stale.summary.objects.find(({ id }) => id === object.id)).toMatchObject({+ name: 'Example observatory', description: expect.stringContaining('data is stale'),+ asset: { path, reason: 'user-override' },+ });+ const mismatchedLock = buildProjectionPlan({ source: { ...source, apps: null }, recipe,+ assetResolutions: { app: { path: 'store/example-replacement', strategy: 'preferred' } }, currentState: renamedState });+ expect(mismatchedLock.summary.objects.find(({ id }) => id === object.id).asset.reason).toBe('unresolved');+ const cleared = buildProjectionPlan({ source, recipe, assetResolutions, labelAliases: {}, currentState: renamedState });+ expect(cleared.summary.objects.find(({ id }) => id === object.id).name).toBe(object.name);+ const removed = buildProjectionPlan({ source: { ...source, apps: [] }, recipe, labelAliases, currentState: renamedState });+ expect(removed.summary.objects.some(({ id }) => id === object.id)).toBe(false);+ expect(removed.operations).toContainEqual({ layer: 'reconciliation', verb: 'remove', args: { id: object.id } });+ });+});diff --git a/server/services/eidoverseWorldProjection.js b/server/services/eidoverseWorldProjection.jsindex 217f9e02de..7cbb8bfee0 100644--- a/server/services/eidoverseWorldProjection.js+++ b/server/services/eidoverseWorldProjection.js@@ -259,14 +259,40 @@ function nexusStatusLight(light, source, existing) {* `null` when the entity already carries exactly this label, which is what* keeps a no-op projection from emitting label verbs.*/-function labelOperation({ prior, id, component, layer }) {- const label = buildEidoverseLabel(component);+function labelOperation({ prior, id, component, layer, lib, labelContext }) {+ const { aliases, objects, recipe, assetResolutions } = labelContext;+ const label = buildEidoverseLabel(component, aliases[component.resourceKey]);+ const kind = component.kind === 'district'+ ? (component.districtId === 'nexus' ? 'operations' : null)+ : component.kind;+ const semanticSlot = component.kind === 'district'+ ? (DISTRICT_ASSET_SLOT[component.districtId] || 'district')+ : (EIDOVERSE_PROJECTION_KINDS.find((entry) => entry.kind === kind)?.slot || 'district');+ const slot = recipe.assets?.[kind] ? kind : semanticSlot;+ const resolution = assetResolutions[slot];+ objects.push({+ id, kind: component.kind,+ districtId: component.districtId || component.toDistrictId || 'nexus',+ resourceKey: component.resourceKey || null,+ route: component.route,+ ...label,+ asset: {+ path: lib,+ slot,+ // A stale retained model can differ from today's lock. Never describe+ // it as preferred/overridden using provenance for a different path.+ reason: resolution?.path === lib+ ? (resolution.userOverride ? 'user-override' : (resolution.strategy || resolution.source || 'lock'))+ : 'unresolved',+ },+ });if (equal(prior ?? null, label)) return null;return { layer, verb: 'comp', args: { id, type: EIDOVERSE_LABEL_COMPONENT_TYPE, data: label } };}function upsertModel({operations,+ labelContext,stateEntities,desiredIds,id,@@ -309,7 +335,7 @@ function upsertModel({operations.push({ layer, verb: 'comp', args: { id, type: COMPONENT_TYPE, data: component } });if (existing) updated += 1;}- const labelOp = labelOperation({ prior: priorComponents?.[EIDOVERSE_LABEL_COMPONENT_TYPE], id, component, layer });+ const labelOp = labelOperation({ prior: priorComponents?.[EIDOVERSE_LABEL_COMPONENT_TYPE], id, component, layer, lib, labelContext });if (labelOp) {operations.push(labelOp);if (existing) updated += 1;@@ -330,8 +356,10 @@ function equal(valueA, valueB) {* intentionally exported so recipe changes can be tested without a live* Eidoverse process and so future renderers can reuse the same projection.*/-export function buildProjectionPlan({ source = {}, recipe = DEFAULT_EIDOVERSE_PROJECTION_RECIPE, currentState = {}, meta = null }) {+export function buildProjectionPlan({ source = {}, recipe = DEFAULT_EIDOVERSE_PROJECTION_RECIPE, currentState = {}, meta = null, labelAliases = {}, assetResolutions = {} }) {const effectiveRecipe = mergeRecipe(recipe);+ const objects = [];+ const labelContext = { aliases: labelAliases, objects, recipe: effectiveRecipe, assetResolutions };const stateEntities = currentState?.entities && typeof currentState.entities === 'object'? currentState.entities: {};@@ -423,6 +451,7 @@ export function buildProjectionPlan({ source = {}, recipe = DEFAULT_EIDOVERSE_PRconst districtScale = DISTRICT_SCALE[district.id] ?? 1;const delta = upsertModel({operations,+ labelContext,stateEntities,desiredIds,id,@@ -452,6 +481,7 @@ export function buildProjectionPlan({ source = {}, recipe = DEFAULT_EIDOVERSE_PRconst id = `${EIDOVERSE_MANAGED_PREFIX}path-${path.id}-${index + 1}`;const delta = upsertModel({operations,+ labelContext,stateEntities,desiredIds,id,@@ -488,6 +518,7 @@ export function buildProjectionPlan({ source = {}, recipe = DEFAULT_EIDOVERSE_PRif (meta) {const delta = upsertModel({operations,+ labelContext,stateEntities,desiredIds,id: EIDOVERSE_META_ENTITY_ID,@@ -635,6 +666,8 @@ export function buildProjectionPlan({ source = {}, recipe = DEFAULT_EIDOVERSE_PRid,component: staleComponent,layer: 'live',+ lib: existing.lib,+ labelContext,});if (staleLabelOp) {operations.push(staleLabelOp);@@ -665,6 +698,7 @@ export function buildProjectionPlan({ source = {}, recipe = DEFAULT_EIDOVERSE_PRconst shouldMove = signal.severity !== 'normal' || ['agent', 'activity', 'goal', 'jira', 'memory'].includes(kind);const delta = upsertModel({operations,+ labelContext,stateEntities,desiredIds,id,@@ -702,6 +736,7 @@ export function buildProjectionPlan({ source = {}, recipe = DEFAULT_EIDOVERSE_PRreturn {operations,summary: {+ objects,created,updated,removed,