Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: make Eidoverse the private PortOS world (#5487)

[._.]/ Adam Eivye1a4f38f8318
diff --git a/README.md b/README.md
index 278aff3b40..c166c51ec3 100644
--- a/README.md
+++ b/README.md
@@ -52,9 +52,9 @@ These tools develop PortOS, and PortOS in turn uses them to manage projects, its
|:-:|:-:|:-:|
| ![App Wizard](./docs/media/portos_4.png) | ![PM2 Processes](./docs/media/portos_5.png) | ![Chief of Staff Tasks](./docs/media/portos_6.png) |
-| Login | OpenWorld |
+| Login | Historical OpenWorld |
|:-:|:-:|
-| ![Login](./docs/media/portos_0.png) | ![OpenWorld](./docs/media/portos_7.png) |
+| ![Login](./docs/media/portos_0.png) | ![Historical OpenWorld](./docs/media/portos_7.png) |
---
@@ -229,7 +229,7 @@ Everything you need to manage your dev environment without leaving the browser.
- **Action History** — Searchable log of all executed actions with filtering and statistics
- **Usage** — Token spend and cost tracking across all configured AI providers
- **Quota Burn** — Automated spending of subscription-backed CLI quota before expiry (`/devtools/quota-burn`) ([Quota Burn docs](./docs/QUOTA-BURN.md))
-- **OpenWorld** — 3D voxel visualization of your apps and agents in real-time ([OpenWorld docs](./docs/features/openworld.md))
+- **Eidoverse Worlds** — private, install-local 3D world for you and your agents, with durable identity and deterministic PortOS resource projection ([Eidoverse docs](./docs/features/eidoverse.md))
- **Browser Control** — Remote Chrome DevTools Protocol integration for headless browser management ([Browser docs](./docs/features/browser.md))
- **Code Runner** — In-app code execution with syntax highlighting
- **Reference Repos** — Cross-app index of reference repositories (libraries you read but don't own) for grounding agents
@@ -444,7 +444,8 @@ Full catalog (including design plans, ADRs, and research notes): [docs/README.md
- [App Wizard](./docs/features/app-wizard.md) — App registration and scaffolding
- [Autofixer](./docs/features/autofixer.md) — Autonomous crash detection and repair
- [Browser](./docs/features/browser.md) — Headless browser automation
-- [OpenWorld](./docs/features/openworld.md) — 3D systems visualization
+- [Eidoverse Worlds](./docs/features/eidoverse.md) — private 3D systems world and PortOS resource projection
+- [OpenWorld historical reference](./docs/features/openworld.md) — retired compatibility surface
- [Prompt Manager](./docs/features/prompt-manager.md) — Customizable AI prompt templates
- [JIRA Sprint Manager](./docs/features/jira-sprint-manager.md) — Autonomous JIRA triage and implementation
- [Writers Room](./docs/features/writers-room.md) — Prose-to-media writing environment with explicit AI passes
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 08d515701a..cb9ee46abd 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -24,7 +24,6 @@ const DataDog = lazyWithReload(() => import('./pages/DataDog'));
const FlowsDoc = lazyWithReload(() => import('./pages/FlowsDoc'));
const GitHub = lazyWithReload(() => import('./pages/GitHub'));
const Eidoverse = lazyWithReload(() => import('./pages/Eidoverse'));
-const OpenWorld = lazyWithReload(() => import('./pages/OpenWorld'));
const AppDetail = lazyWithReload(() => import('./pages/AppDetail'));
const FeatureAgents = lazyWithReload(() => import('./pages/FeatureAgents'));
const FeatureAgentDetail = lazyWithReload(() => import('./pages/FeatureAgentDetail'));
@@ -198,11 +197,6 @@ const MEDIA_TRAINING_PREFIX = /^\/media\/training/;
// is what a bookmark, a typed URL, or a half-remembered path lands on — alias it
// rather than letting the catch-all swallow it (issue #3793).
const ANNOTATE_PREFIX = /^\/annotate/;
-// The old city page became OpenWorld. Bookmarks, pinned sidebar entries, stored palette
-// history, and peers' deep links all still say /city — alias the whole prefix
-// (including /city/settings and /city/apps/:appId) rather than 404ing them.
-const LEGACY_CITY_PREFIX = /^\/city/;
-
// Normalize a tab-less /creative-director/:id URL to its overview tab while
// preserving any query string + hash. A bare `<Navigate to="overview">` would
// drop them; building the relative target from useLocation keeps deep-link
@@ -393,12 +387,12 @@ export default function App() {
<Route path="jira" element={<Navigate to="/devtools/jira" replace />} />
<Route path="devtools/jira" element={<Jira />} />
<Route path="devtools/jira/reports" element={<JiraReports />} />
- <Route path="openworld" element={<OpenWorld />} />
- <Route path="openworld/settings" element={<OpenWorld />} />
- <Route path="openworld/apps/:appId" element={<OpenWorld />} />
- <Route path="openworld/region/:regionId" element={<OpenWorld />} />
- <Route path="city" element={<PrefixRedirect from={LEGACY_CITY_PREFIX} to="/openworld" />} />
- <Route path="city/*" element={<PrefixRedirect from={LEGACY_CITY_PREFIX} to="/openworld" />} />
+ {/* OpenWorld is retired: preserve old bookmarks by landing in the
+ persistent private Eidoverse world, including query/hash state. */}
+ <Route path="openworld" element={<RedirectWithSearch to="/eidoverse" />} />
+ <Route path="openworld/*" element={<RedirectWithSearch to="/eidoverse" />} />
+ <Route path="city" element={<RedirectWithSearch to="/eidoverse" />} />
+ <Route path="city/*" element={<RedirectWithSearch to="/eidoverse" />} />
<Route path="data" element={<DataManager />} />
<Route path="character" element={<CharacterSheet />} />
<Route path="ask" element={<Ask />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index ddc6606665..1f3ae1157c 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -47,7 +47,6 @@ import {
SquareTerminal,
Globe,
Newspaper,
- Globe2,
Orbit,
Ticket,
Network,
@@ -168,7 +167,6 @@ export const NAV_PRESENTATION = {
'/': { icon: Home, single: true },
'/review': { icon: ClipboardList, single: true },
'/eidoverse': { icon: Orbit, single: true },
- '/openworld': { icon: Globe2, single: true },
'/apps': { icon: Package, dynamic: 'apps' },
'/brain/config': { icon: Settings },
'/brain/daily-log': { icon: NotebookPen },
@@ -402,7 +400,7 @@ const sectionNavItem = (section) => {
return { label: section, feature: sharedFeature, children, ...SECTION_PRESENTATION[section] };
};
-const mainRows = ['/', '/review', '/eidoverse', '/openworld'].map(navRowForPath);
+const mainRows = ['/', '/review', '/eidoverse'].map(navRowForPath);
const appsCommand = navRowForPath('/apps');
const goalsRow = navRowForPath('/goals/list');
const sectionRows = Object.fromEntries(SECTION_ORDER.map((section) => [section, sectionNavItem(section)]));
@@ -466,7 +464,7 @@ function WorkingSetRow({ entry, pinned, onTogglePin, onNavigate, isActive }) {
);
}
-// A top-level *single* nav row (Dashboard / Review Hub / OpenWorld / Goals). Unlike a
+// A top-level *single* nav row (Dashboard / Review Hub / Eidoverse / Goals). Unlike a
// section, it links straight to one destination — and unlike WorkingSetRow it
// carries the heavier top-level row weight plus the optional badge (Chief of
// Staff unread count) and the collapsed-rail layout (icon-only, centered, badge
@@ -617,7 +615,6 @@ const FULL_WIDTH_PATH_PREFIXES = [
'/writers-room',
'/agents',
'/shell/',
- '/openworld',
'/timeline/',
// Every SongBook route — index (/songbook), import (/songbook/import),
// and viewer (/songbook/:id) — is full-bleed and owns its own scroll
diff --git a/client/src/components/Layout.test.jsx b/client/src/components/Layout.test.jsx
index 85dd61d5e2..e3a61069f3 100644
--- a/client/src/components/Layout.test.jsx
+++ b/client/src/components/Layout.test.jsx
@@ -7,7 +7,7 @@ import { INSTANCE_FEATURES_CHANGED } from '../constants/events.js';
// This suite locks the *integration* path that SingleNavRow.test.jsx can't reach:
// pinning a top-level `single: true` row (Dashboard `/`, Review Hub `/review`,
-// OpenWorld `/openworld`, Goals `/goals/list`) must make it render in the sidebar Pinned
+// Eidoverse `/eidoverse`, Goals `/goals/list`) must make it render in the sidebar Pinned
// section. That resolution lives in Layout itself — `navEntryByPath` indexes
// `item.single` leaves, `resolveNavEntry` maps a stored path to a row, and
// `useNavWorkingSet` feeds the Pinned-section render. We exercise the real
@@ -71,7 +71,14 @@ vi.mock('../services/api', () => ({
getApps: vi.fn(() => Promise.resolve([])),
listPipelineSeries: vi.fn(() => Promise.resolve([])),
listUniverses: vi.fn(() => Promise.resolve([])),
- getPaletteManifest: vi.fn(() => Promise.resolve({ nav: [] })),
+ getPaletteManifest: vi.fn(() => Promise.resolve({
+ nav: [{
+ path: '/eidoverse',
+ label: 'Eidoverse Worlds',
+ feature: 'eidoverse',
+ previousPaths: ['/openworld', '/city'],
+ }],
+ })),
getDailyActions: vi.fn(() => Promise.resolve({ actions: [] })),
getInstanceFeatures: vi.fn(() => Promise.resolve({ features: featureMock.features })),
}));
@@ -181,7 +188,7 @@ describe('Layout — pinned single nav rows', () => {
const pinned = pinnedSection();
expect(within(pinned).getByRole('link', { name: /Dashboard/i })).toHaveAttribute('href', '/');
expect(within(pinned).getByRole('link', { name: /Review Hub/i })).toHaveAttribute('href', '/review');
- expect(within(pinned).getByRole('link', { name: /OpenWorld/i })).toHaveAttribute('href', '/openworld');
+ expect(within(pinned).getByRole('link', { name: /Eidoverse/i })).toHaveAttribute('href', '/eidoverse');
expect(within(pinned).getByRole('link', { name: /Goals/i })).toHaveAttribute('href', '/goals/list');
});
@@ -200,7 +207,7 @@ describe('Layout — pinned single nav rows', () => {
const pinned = pinnedSection();
expect(pinned).toBeTruthy();
- expect(within(pinned).getByRole('link', { name: /OpenWorld/i })).toHaveAttribute('href', '/openworld');
+ expect(within(pinned).getByRole('link', { name: /Eidoverse/i })).toHaveAttribute('href', '/eidoverse');
// The unknown path contributes no row.
expect(within(pinned).getAllByRole('link')).toHaveLength(1);
});
diff --git a/client/src/components/cos/PersistentMindTaskAccessControls.jsx b/client/src/components/cos/PersistentMindTaskAccessControls.jsx
index 0926589376..d36620ced9 100644
--- a/client/src/components/cos/PersistentMindTaskAccessControls.jsx
+++ b/client/src/components/cos/PersistentMindTaskAccessControls.jsx
@@ -3,9 +3,10 @@ import * as api from '../../services/api';
import toast from '../ui/Toast';
const normalizeCapabilities = (value) => ({
- schemaVersion: 4,
+ schemaVersion: 5,
createTasks: value?.createTasks === true,
manageMind: value?.manageMind === true,
+ manageEidoverse: value?.manageEidoverse === true,
callUser: value?.callUser === true,
readPortos: value?.readPortos === true,
writePortos: value?.writePortos === true,
@@ -32,6 +33,11 @@ const OPTIONS = [
label: 'Allow mind to queue CoS agent tasks',
hint: 'Queues typed tasks through isolated worktrees, capacity, budget, review, CI, and landing-policy gates.',
},
+ {
+ key: 'manageEidoverse',
+ label: 'Allow private Eidoverse world management',
+ hint: 'Lets the mind project PortOS resources, apply bounded world-building and role operations, and speak as the persistent CoS identity. This does not grant generic PortOS record writes.',
+ },
{
key: 'manageMind',
label: 'Allow mind to clean up its mindspace',
@@ -59,7 +65,7 @@ export default function PersistentMindTaskAccessControls({
useEffect(() => {
if (!saving) setDraft(normalizeCapabilities(capabilities));
- }, [capabilities?.schemaVersion, capabilities?.createTasks, capabilities?.manageMind, capabilities?.callUser, capabilities?.readPortos, capabilities?.writePortos, capabilities?.taskModelAllowlist, capabilities?.taskModelAllowlistInvalid, capabilities?.allowedAppIds?.join('\0'), saving]);
+ }, [capabilities?.schemaVersion, capabilities?.createTasks, capabilities?.manageMind, capabilities?.manageEidoverse, capabilities?.callUser, capabilities?.readPortos, capabilities?.writePortos, capabilities?.taskModelAllowlist, capabilities?.taskModelAllowlistInvalid, capabilities?.allowedAppIds?.join('\0'), saving]);
const save = async (key, enabled) => {
const previous = draft;
diff --git a/client/src/components/cos/tabs/MindTab.test.jsx b/client/src/components/cos/tabs/MindTab.test.jsx
index 8a3a6ee5d1..a72243112c 100644
--- a/client/src/components/cos/tabs/MindTab.test.jsx
+++ b/client/src/components/cos/tabs/MindTab.test.jsx
@@ -332,7 +332,7 @@ describe('MindTab', () => {
await user.click(taskAccess);
await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(
- { persistentMindCapabilities: { schemaVersion: 4, createTasks: true, manageMind: false, callUser: false, readPortos: false, writePortos: false, taskModelAllowlist: [] } },
+ { persistentMindCapabilities: { schemaVersion: 5, createTasks: true, manageMind: false, manageEidoverse: false, callUser: false, readPortos: false, writePortos: false, taskModelAllowlist: [] } },
{ silent: true },
));
expect(screen.getAllByText(/code review then merge/i).length).toBeGreaterThan(0);
diff --git a/client/src/components/settings/ApiAccessTab.jsx b/client/src/components/settings/ApiAccessTab.jsx
index 2810264142..75bc90f1f1 100644
--- a/client/src/components/settings/ApiAccessTab.jsx
+++ b/client/src/components/settings/ApiAccessTab.jsx
@@ -11,7 +11,7 @@ const DEFAULT_AGENT_CONTEXT = {
enabled: false,
profile: 'metadata',
scopes: ['navigation', 'workspaces'],
- actions: { readPortos: false, writePortos: false },
+ actions: { readPortos: false, writePortos: false, manageEidoverse: false },
};
const AGENT_CONTEXT_SCOPES = [
{ id: 'navigation', label: 'Navigation', hint: 'PortOS page labels, aliases, and paths.' },
@@ -314,9 +314,17 @@ export function ApiAccessTab() {
label="Allow semantic PortOS updates"
hint="Typed Brain, journal, goals, health-log, and feed-state actions; no raw routes or shell."
/>
+ <Toggle
+ id="agent-context-action-eidoverse"
+ checked={agentContext.actions.manageEidoverse}
+ disabled={savingId !== null}
+ onChange={(value) => patchAgentContextAction('manageEidoverse', value)}
+ label="Allow private Eidoverse world management"
+ hint="Project resources, build bounded content, manage world roles, and speak as the persistent CoS identity."
+ />
</div>
<p className="text-xs text-gray-500">
- Both default off. MCP advertises only granted actions, with schemas generated from the same contracts used at runtime.
+ All grants default off. MCP advertises only granted actions, with schemas generated from the same contracts used at runtime.
</p>
</fieldset>
diff --git a/client/src/components/settings/ApiAccessTab.test.jsx b/client/src/components/settings/ApiAccessTab.test.jsx
index fbd3f29532..7f3efcaff5 100644
--- a/client/src/components/settings/ApiAccessTab.test.jsx
+++ b/client/src/components/settings/ApiAccessTab.test.jsx
@@ -169,6 +169,7 @@ describe('ApiAccessTab', () => {
expect(screen.getByLabelText('Disclosure profile').value).toBe('metadata');
expect(screen.getByLabelText('Allow semantic PortOS reads').checked).toBe(false);
expect(screen.getByLabelText('Allow semantic PortOS updates').checked).toBe(false);
+ expect(screen.getByLabelText('Allow private Eidoverse world management').checked).toBe(false);
});
it('persists the complete agent-context opt-in configuration', async () => {
@@ -180,14 +181,19 @@ describe('ApiAccessTab', () => {
enabled: true,
profile: 'metadata',
scopes: ['navigation', 'workspaces'],
- actions: { readPortos: false, writePortos: false },
+ actions: { readPortos: false, writePortos: false, manageEidoverse: false },
},
}, { silent: true }));
});
it('persists semantic MCP grants independently of context scopes', async () => {
getSettings.mockResolvedValue({
- agentContext: { enabled: true, profile: 'metadata', scopes: ['navigation'], actions: { readPortos: false, writePortos: false } },
+ agentContext: {
+ enabled: true,
+ profile: 'metadata',
+ scopes: ['navigation'],
+ actions: { readPortos: false, writePortos: false, manageEidoverse: false },
+ },
});
await renderTab();
fireEvent.click(screen.getByLabelText('Allow semantic PortOS reads'));
@@ -196,7 +202,21 @@ describe('ApiAccessTab', () => {
enabled: true,
profile: 'metadata',
scopes: ['navigation'],
- actions: { readPortos: true, writePortos: false },
+ actions: { readPortos: true, writePortos: false, manageEidoverse: false },
+ },
+ }, { silent: true }));
+ });
+
+ it('persists the dedicated Eidoverse MCP grant independently', async () => {
+ getSettings.mockResolvedValue({});
+ await renderTab();
+ fireEvent.click(screen.getByLabelText('Allow private Eidoverse world management'));
+ await waitFor(() => expect(updateSettings).toHaveBeenCalledWith({
+ agentContext: {
+ enabled: false,
+ profile: 'metadata',
+ scopes: ['navigation', 'workspaces'],
+ actions: { readPortos: false, writePortos: false, manageEidoverse: true },
},
}, { silent: true }));
});
diff --git a/client/src/pages/ApiExplorer.test.jsx b/client/src/pages/ApiExplorer.test.jsx
index 6863ade2d5..27fbcdf24d 100644
--- a/client/src/pages/ApiExplorer.test.jsx
+++ b/client/src/pages/ApiExplorer.test.jsx
@@ -42,7 +42,11 @@ const semanticTools = {
}],
};
const agentSemanticTools = { stats: { total: 0, read: 0, write: 0, granted: 0 }, tools: [] };
-const agentContext = { enabled: false, tools: [], actions: { readPortos: false, writePortos: false } };
+const agentContext = {
+ enabled: false,
+ tools: [],
+ actions: { readPortos: false, writePortos: false, manageEidoverse: false },
+};
const socketEvents = {
stats: { events: 229, sourceFiles: 73, clientToServer: 41, serverToClient: 189, modeled: 13, generated: 216 },
domains: [{ id: 'cos', label: 'Cos', events: 1 }],
diff --git a/client/src/pages/Eidoverse.jsx b/client/src/pages/Eidoverse.jsx
index 609fc17055..d00718d643 100644
--- a/client/src/pages/Eidoverse.jsx
+++ b/client/src/pages/Eidoverse.jsx
@@ -5,9 +5,12 @@ import PageHeader from '../components/PageHeader';
import BrailleSpinner from '../components/BrailleSpinner';
import {
getApp,
+ getEidoverseWorldStatus,
getInstanceFeatures,
+ projectEidoverseWorld,
startApp,
startEidoverseHost,
+ updateEidoverseWorldConfig,
} from '../services/api';
const silent = { silent: true };
@@ -16,22 +19,86 @@ const RUNNING_STATUSES = new Set(['online', 'launching', 'unknown']);
const failedStart = (result) => Object.values(result?.results || {})
.find((entry) => entry?.success === false);
-export const hostUrlFor = (host, setup, location = window.location) => {
+export const hostUrlFor = (host, setup, location = window.location, identity = null) => {
+ let baseUrl;
if (location.protocol === 'https:') {
if (host.protocol !== 'https') {
throw new Error('PortOS is using HTTPS, but the Eidoverse host could not load the shared certificate.');
}
- return `https://${location.hostname}:${host.port}/`;
+ baseUrl = `https://${location.hostname}:${host.port}/`;
+ } else {
+ baseUrl = `http://${location.hostname}:${setup.uiPort}/`;
}
- return `http://${location.hostname}:${setup.uiPort}/`;
+ if (!identity) return baseUrl;
+
+ const url = new URL(baseUrl);
+ if (identity.world) url.searchParams.set('world', identity.world);
+ if (identity.name) url.searchParams.set('name', identity.name);
+ if (identity.avatar) url.searchParams.set('avatar', identity.avatar);
+ return url.toString();
+};
+
+const RECIPE_INCLUDE_KEYS = [
+ 'apps',
+ 'agents',
+ 'tasks',
+ 'features',
+ 'peers',
+ 'health',
+ 'productivity',
+ 'activity',
+ 'goals',
+ 'memory',
+ 'storage',
+ 'jira',
+ 'operations',
+];
+
+const RECIPE_KIND_BY_SOURCE = {
+ apps: 'app',
+ agents: 'agent',
+ tasks: 'task',
+ features: 'feature',
+ peers: 'peer',
+ health: 'health',
+ productivity: 'productivity',
+ activity: 'activity',
+ goals: 'goal',
+ memory: 'memory',
+ storage: 'storage',
+ jira: 'jira',
+ operations: 'operations',
};
+const RECIPE_LAYOUT_KEYS = ['spacing', 'laneGap', 'columns'];
+const RECIPE_TERRAIN_KEYS = ['size', 'segments', 'amplitude', 'flatRadius'];
+// Mirror the server's case-insensitive, slash-normalized path contract. HTML
+// patterns have no flag syntax, so spell out the case-insensitive prefixes and
+// accept either path separator explicitly.
+const EIDOVERSE_ASSET_PATTERN = '(?:[Ee][Ii][Dd][Oo][Vv][Ee][Rr][Ss][Ee]|[Ss][Tt][Oo][Rr][Ee])[\\\\/](?!.*\\.\\.).*';
+
+const worldIdentityFor = (world) => ({
+ world: world?.world,
+ name: world?.identity?.name || world?.human?.name,
+ avatar: world?.identity?.avatar || world?.human?.avatar,
+});
+
export default function Eidoverse() {
const requestGeneration = useRef(0);
+ const configDraftRevision = useRef(0);
const [phase, setPhase] = useState('loading');
const [error, setError] = useState('');
const [hostUrl, setHostUrl] = useState('');
+ const [hostInfo, setHostInfo] = useState(null);
+ const [setupState, setSetupState] = useState(null);
const [appId, setAppId] = useState(null);
+ const [worldState, setWorldState] = useState(null);
+ const [worldName, setWorldName] = useState('');
+ const [humanName, setHumanName] = useState('');
+ const [recipeDraft, setRecipeDraft] = useState(null);
+ const [projectionStatus, setProjectionStatus] = useState('idle');
+ const [projectionError, setProjectionError] = useState('');
+ const [configStatus, setConfigStatus] = useState('');
const prepare = useCallback(() => {
const generation = ++requestGeneration.current;
@@ -41,6 +108,14 @@ export default function Eidoverse() {
setPhase('loading');
setError('');
setHostUrl('');
+ setHostInfo(null);
+ setSetupState(null);
+ setWorldState(null);
+ setRecipeDraft(null);
+ setProjectionStatus('idle');
+ setProjectionError('');
+ setConfigStatus('');
+ configDraftRevision.current = 0;
const load = async () => {
const featureState = await getInstanceFeatures(silent);
@@ -60,10 +135,14 @@ export default function Eidoverse() {
updatePhase('connecting');
const host = await startEidoverseHost(silent);
if (!host?.running) throw new Error('The Eidoverse host did not start.');
+ const world = await getEidoverseWorldStatus(silent);
return {
phase: 'ready',
appId: setup.appId,
- hostUrl: hostUrlFor(host, setup),
+ setup,
+ host,
+ world,
+ hostUrl: hostUrlFor(host, setup, window.location, worldIdentityFor(world)),
};
};
@@ -71,6 +150,12 @@ export default function Eidoverse() {
if (!isCurrent()) return;
setPhase(result.phase);
setAppId(result.appId);
+ setSetupState(result.setup || null);
+ setHostInfo(result.host || null);
+ setWorldState(result.world || null);
+ setWorldName(result.world?.world || '');
+ setHumanName(result.world?.identity?.name || result.world?.human?.name || '');
+ setRecipeDraft(result.world?.recipe || null);
setHostUrl(result.hostUrl || '');
}, (reason) => {
if (!isCurrent()) return;
@@ -79,6 +164,129 @@ export default function Eidoverse() {
});
}, []);
+ const runProjection = useCallback(async () => {
+ setProjectionStatus('running');
+ setProjectionError('');
+ try {
+ const result = await projectEidoverseWorld(silent);
+ setWorldState((current) => current
+ ? {
+ ...current,
+ projection: result.projection || current.projection,
+ presence: result.presence || current.presence,
+ }
+ : current);
+ setProjectionStatus('complete');
+ return result;
+ } catch (reason) {
+ setProjectionStatus('error');
+ setProjectionError(reason?.message || 'PortOS could not project its current state into Eidoverse.');
+ throw reason;
+ }
+ }, []);
+
+ useEffect(() => {
+ if (phase !== 'ready' || !hostUrl) return undefined;
+ void runProjection().catch(() => {});
+ return undefined;
+ }, [phase, hostUrl, runProjection]);
+
+ const saveWorldConfig = useCallback(async () => {
+ if (!recipeDraft) return;
+ const submittedRevision = configDraftRevision.current;
+ setConfigStatus('saving');
+ let updated;
+ try {
+ updated = await updateEidoverseWorldConfig({
+ world: worldName.trim(),
+ humanName: humanName.trim() || null,
+ recipe: recipeDraft,
+ }, silent);
+ setWorldState((current) => current
+ ? { ...current, ...updated, identity: updated.human }
+ : current);
+ if (configDraftRevision.current === submittedRevision) {
+ setWorldName(updated.world || '');
+ setHumanName(updated.human?.name || '');
+ setRecipeDraft(updated.recipe || recipeDraft);
+ setConfigStatus('saved');
+ } else {
+ setConfigStatus('');
+ }
+ } catch (reason) {
+ setConfigStatus(reason?.message || 'Could not save the Eidoverse world configuration.');
+ return;
+ }
+
+ const nextHostUrl = hostInfo && setupState
+ ? hostUrlFor(hostInfo, setupState, window.location, worldIdentityFor(updated))
+ : hostUrl;
+ if (nextHostUrl !== hostUrl) setHostUrl(nextHostUrl);
+ else void runProjection().catch(() => {});
+ }, [humanName, hostInfo, hostUrl, recipeDraft, runProjection, setupState, worldName]);
+
+ const markConfigDirty = () => {
+ configDraftRevision.current += 1;
+ setConfigStatus((current) => current === 'saving' ? current : '');
+ };
+
+ const toggleRecipeInclude = (key) => {
+ markConfigDirty();
+ setRecipeDraft((current) => current
+ ? { ...current, includes: { ...current.includes, [key]: !current.includes[key] } }
+ : current);
+ };
+
+ const updateRecipeLimit = (key, value) => {
+ markConfigDirty();
+ setRecipeDraft((current) => current
+ ? { ...current, limits: { ...current.limits, [key]: value === '' ? 0 : Number(value) } }
+ : current);
+ };
+
+ const updateRecipeNumber = (section, key, value) => {
+ markConfigDirty();
+ setRecipeDraft((current) => current
+ ? {
+ ...current,
+ [section]: {
+ ...current[section],
+ [key]: value === '' ? '' : Number(value),
+ },
+ }
+ : current);
+ };
+
+ const updateRecipeText = (section, key, value) => {
+ markConfigDirty();
+ setRecipeDraft((current) => current
+ ? { ...current, [section]: { ...current[section], [key]: value } }
+ : current);
+ };
+
+ const updateRecipeOrigin = (index, value) => {
+ markConfigDirty();
+ setRecipeDraft((current) => current
+ ? {
+ ...current,
+ layout: {
+ ...current.layout,
+ origin: current.layout?.origin?.map((part, partIndex) => partIndex === index
+ ? (value === '' ? '' : Number(value))
+ : part) || [0, 0, 0],
+ },
+ }
+ : current);
+ };
+
+ const updateRecipeAsset = (sourceKey, value) => {
+ const kind = RECIPE_KIND_BY_SOURCE[sourceKey];
+ markConfigDirty();
+ setRecipeDraft((current) => kind && current
+ ? { ...current, assets: { ...current.assets, [kind]: value } }
+ : current);
+ };
+
useEffect(() => {
prepare();
return () => { requestGeneration.current += 1; };
@@ -109,6 +317,234 @@ export default function Eidoverse() {
</>
);
+ const worldControls = phase === 'ready' && worldState && recipeDraft ? (
+ <div className="max-h-[55vh] shrink-0 overflow-y-auto overscroll-contain border-b border-port-border bg-port-bg px-3 py-2 sm:px-4">
+ <div className="flex flex-wrap items-center justify-between gap-2 text-xs text-gray-300">
+ <div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1">
+ <span className="rounded-full border border-port-accent/40 px-2 py-0.5 text-port-accent">Private PortOS world</span>
+ <span>World: <span className="text-white">{worldState.world}</span></span>
+ <span>User: <span className="text-white">{worldState.identity?.name || 'not configured'}</span></span>
+ <span>CoS: <span className="text-white">{worldState.presence?.connected ? 'connected' : 'ready to reconnect'}</span>{worldState.presence?.role ? ` · ${worldState.presence.role}` : ''}</span>
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => { void runProjection().catch(() => {}); }}
+ disabled={projectionStatus === 'running'}
+ className="inline-flex min-h-[36px] items-center gap-1.5 rounded-lg border border-port-border px-2.5 py-1.5 text-gray-200 transition-colors hover:border-port-accent hover:text-white disabled:cursor-wait disabled:opacity-50"
+ >
+ <RotateCcw size={14} aria-hidden="true" />
+ {projectionStatus === 'running' ? 'Projecting…' : 'Project PortOS now'}
+ </button>
+ <Link
+ to="/cos/jobs"
+ className="inline-flex min-h-[36px] items-center rounded-lg border border-port-border px-2.5 py-1.5 text-gray-200 transition-colors hover:border-port-accent hover:text-white"
+ >
+ CoS tasks
+ </Link>
+ </div>
+ </div>
+ {projectionError && (
+ <p className="mt-1 text-xs text-port-error" role="status">{projectionError}</p>
+ )}
+ <details className="mt-2 text-xs text-gray-300">
+ <summary className="cursor-pointer text-gray-400 hover:text-white">World identity and projection recipe</summary>
+ <form
+ className="mt-3 grid gap-3 rounded-lg border border-port-border bg-port-card p-3 sm:grid-cols-[minmax(0,1fr)_minmax(0,2fr)_auto] sm:items-end"
+ onSubmit={(event) => { event.preventDefault(); void saveWorldConfig(); }}
+ >
+ <label className="flex flex-col gap-1" htmlFor="eidoverse-world-name">
+ <span className="text-gray-400">World name</span>
+ <input
+ id="eidoverse-world-name"
+ value={worldName}
+ onChange={(event) => {
+ markConfigDirty();
+ setWorldName(event.target.value);
+ }}
+ className="min-h-[36px] rounded border border-port-border bg-port-bg px-2 text-sm text-white"
+ maxLength={64}
+ pattern="[A-Za-z0-9_-]+"
+ required
+ />
+ </label>
+ <label className="flex flex-col gap-1" htmlFor="eidoverse-human-name">
+ <span className="text-gray-400">My Eidoverse name</span>
+ <input
+ id="eidoverse-human-name"
+ value={humanName}
+ onChange={(event) => {
+ markConfigDirty();
+ setHumanName(event.target.value);
+ }}
+ className="min-h-[36px] rounded border border-port-border bg-port-bg px-2 text-sm text-white"
+ maxLength={64}
+ placeholder="Clear to use the persistent PortOS instance identity"
+ />
+ </label>
+ <button
+ type="submit"
+ disabled={configStatus === 'saving'}
+ className="inline-flex min-h-[36px] items-center justify-center rounded-lg bg-port-accent px-3 py-1.5 font-medium text-black transition-opacity hover:opacity-90 disabled:opacity-50"
+ >
+ {configStatus === 'saving' ? 'Saving…' : 'Save and project'}
+ </button>
+ <fieldset className="sm:col-span-3">
+ <legend className="mb-1 text-gray-400">Draw PortOS resources</legend>
+ <div className="flex flex-wrap gap-x-4 gap-y-2">
+ {RECIPE_INCLUDE_KEYS.map((key) => (
+ <label key={key} className="inline-flex items-center gap-1.5 capitalize">
+ <input
+ type="checkbox"
+ checked={recipeDraft.includes?.[key] === true}
+ onChange={() => toggleRecipeInclude(key)}
+ />
+ {key}
+ </label>
+ ))}
+ </div>
+ </fieldset>
+ <fieldset className="sm:col-span-3">
+ <legend className="mb-1 text-gray-400">Per-resource caps</legend>
+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-4 lg:grid-cols-7">
+ {RECIPE_INCLUDE_KEYS.map((key) => (
+ <label key={key} className="flex flex-col gap-1 capitalize" htmlFor={`eidoverse-limit-${key}`}>
+ <span className="text-gray-500">{key}</span>
+ <input
+ id={`eidoverse-limit-${key}`}
+ type="number"
+ min="0"
+ max="100"
+ required
+ value={recipeDraft.limits?.[key] ?? ''}
+ onChange={(event) => updateRecipeLimit(key, event.target.value)}
+ className="min-h-[34px] rounded border border-port-border bg-port-bg px-2 text-sm text-white"
+ />
+ </label>
+ ))}
+ </div>
+ </fieldset>
+ <fieldset className="sm:col-span-3">
+ <legend className="mb-1 text-gray-400">World layout</legend>
+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-5">
+ {RECIPE_LAYOUT_KEYS.map((key) => (
+ <label key={key} className="flex flex-col gap-1 capitalize" htmlFor={`eidoverse-layout-${key}`}>
+ <span className="text-gray-500">{key}</span>
+ <input
+ id={`eidoverse-layout-${key}`}
+ type="number"
+ min={key === 'columns' ? 1 : 2}
+ max={key === 'columns' ? 32 : 100}
+ step={key === 'columns' ? 1 : 'any'}
+ required
+ value={recipeDraft.layout?.[key] ?? ''}
+ onChange={(event) => updateRecipeNumber('layout', key, event.target.value)}
+ className="min-h-[34px] rounded border border-port-border bg-port-bg px-2 text-sm text-white"
+ />
+ </label>
+ ))}
+ {['x', 'y', 'z'].map((axis, index) => (
+ <label key={axis} className="flex flex-col gap-1" htmlFor={`eidoverse-origin-${axis}`}>
+ <span className="text-gray-500">Origin {axis}</span>
+ <input
+ id={`eidoverse-origin-${axis}`}
+ type="number"
+ step="any"
+ required
+ value={recipeDraft.layout?.origin?.[index] ?? ''}
+ onChange={(event) => updateRecipeOrigin(index, event.target.value)}
+ className="min-h-[34px] rounded border border-port-border bg-port-bg px-2 text-sm text-white"
+ />
+ </label>
+ ))}
+ </div>
+ </fieldset>
+ <fieldset className="sm:col-span-3">
+ <legend className="mb-1 text-gray-400">Models and scales</legend>
+ <div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
+ {RECIPE_INCLUDE_KEYS.map((sourceKey) => {
+ const kind = RECIPE_KIND_BY_SOURCE[sourceKey];
+ return (
+ <div key={sourceKey} className="rounded border border-port-border/70 p-2">
+ <span className="capitalize text-gray-400">{sourceKey}</span>
+ <label className="mt-1 flex flex-col gap-1" htmlFor={`eidoverse-asset-${kind}`}>
+ <span className="text-gray-500">Asset path</span>
+ <input
+ id={`eidoverse-asset-${kind}`}
+ value={recipeDraft.assets?.[kind] ?? ''}
+ onChange={(event) => updateRecipeAsset(sourceKey, event.target.value)}
+ className="min-h-[34px] rounded border border-port-border bg-port-bg px-2 text-xs text-white"
+ maxLength={512}
+ pattern={EIDOVERSE_ASSET_PATTERN}
+ required
+ />
+ </label>
+ <label className="mt-1 flex items-center gap-2" htmlFor={`eidoverse-scale-${kind}`}>
+ <span className="text-gray-500">Scale</span>
+ <input
+ id={`eidoverse-scale-${kind}`}
+ type="number"
+ min="0"
+ max="20"
+ step="any"
+ required
+ value={recipeDraft.scale?.[kind] ?? ''}
+ onChange={(event) => {
+ event.currentTarget.setCustomValidity(
+ event.currentTarget.valueAsNumber > 0 ? '' : 'Scale must be greater than zero.',
+ );
+ updateRecipeNumber('scale', kind, event.target.value);
+ }}
+ className="min-h-[32px] w-24 rounded border border-port-border bg-port-bg px-2 text-xs text-white"
+ />
+ </label>
+ </div>
+ );
+ })}
+ </div>
+ </fieldset>
+ <fieldset className="sm:col-span-3">
+ <legend className="mb-1 text-gray-400">Procedural terrain</legend>
+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-5">
+ <label className="flex flex-col gap-1" htmlFor="eidoverse-terrain-seed">
+ <span className="text-gray-500">Seed</span>
+ <input
+ id="eidoverse-terrain-seed"
+ value={recipeDraft.terrain?.seed ?? ''}
+ onChange={(event) => updateRecipeText('terrain', 'seed', event.target.value)}
+ className="min-h-[34px] rounded border border-port-border bg-port-bg px-2 text-sm text-white"
+ maxLength={64}
+ required
+ />
+ </label>
+ {RECIPE_TERRAIN_KEYS.map((key) => (
+ <label key={key} className="flex flex-col gap-1 capitalize" htmlFor={`eidoverse-terrain-${key}`}>
+ <span className="text-gray-500">{key}</span>
+ <input
+ id={`eidoverse-terrain-${key}`}
+ type="number"
+ min={key === 'segments' ? 2 : (key === 'size' ? 0.01 : 0)}
+ max={key === 'amplitude' ? 100 : (key === 'flatRadius' ? 256 : 512)}
+ step={key === 'segments' ? 1 : 'any'}
+ required
+ value={recipeDraft.terrain?.[key] ?? ''}
+ onChange={(event) => updateRecipeNumber('terrain', key, event.target.value)}
+ className="min-h-[34px] rounded border border-port-border bg-port-bg px-2 text-sm text-white"
+ />
+ </label>
+ ))}
+ </div>
+ </fieldset>
+ {configStatus && configStatus !== 'saving' && (
+ <p className="sm:col-span-3 text-xs text-gray-400" role="status">
+ {configStatus === 'saved' ? 'Saved locally.' : configStatus}
+ </p>
+ )}
+ </form>
+ </details>
+ </div>
+ ) : null;
+
return (
<div className="flex h-full min-h-0 flex-col bg-black">
<PageHeader
@@ -119,6 +555,8 @@ export default function Eidoverse() {
className="bg-port-bg"
/>
+ {worldControls}
+
{phase === 'ready' && (
<iframe
src={hostUrl}
diff --git a/client/src/pages/Eidoverse.test.jsx b/client/src/pages/Eidoverse.test.jsx
index 55642ae7e1..27b3625b4e 100644
--- a/client/src/pages/Eidoverse.test.jsx
+++ b/client/src/pages/Eidoverse.test.jsx
@@ -5,9 +5,12 @@ import { MemoryRouter } from 'react-router';
vi.mock('../services/api', () => ({
getApp: vi.fn(),
+ getEidoverseWorldStatus: vi.fn(),
getInstanceFeatures: vi.fn(),
+ projectEidoverseWorld: vi.fn(),
startApp: vi.fn(),
startEidoverseHost: vi.fn(),
+ updateEidoverseWorldConfig: vi.fn(),
}));
import * as api from '../services/api';
@@ -28,6 +31,38 @@ const featureResponse = (overrides = {}) => ({
}],
});
+const worldResponse = {
+ world: 'portos',
+ identity: { name: 'example-portos-user' },
+ human: { name: 'example-portos-user' },
+ cos: { id: 'portos-cos', enabled: true },
+ recipe: {
+ version: 1,
+ includes: {
+ apps: true, agents: true, tasks: true, features: true, peers: true, health: true,
+ productivity: true, activity: true, goals: true, memory: true, storage: true, jira: true, operations: true,
+ },
+ limits: {
+ apps: 10, agents: 10, tasks: 10, features: 10, peers: 10, health: 1,
+ productivity: 1, activity: 10, goals: 10, memory: 10, storage: 10, jira: 10, operations: 1,
+ },
+ layout: { origin: [0, 0, 0], spacing: 7, laneGap: 6, columns: 8 },
+ scale: {
+ app: 1, agent: 1, task: 1, feature: 1, peer: 1, health: 1,
+ productivity: 1, activity: 1, goal: 1, memory: 1, storage: 1, jira: 1, operations: 1,
+ },
+ assets: Object.fromEntries([
+ 'app', 'agent', 'task', 'feature', 'peer', 'health', 'productivity', 'activity',
+ 'goal', 'memory', 'storage', 'jira', 'operations',
+ ].map((kind) => [kind, `eidoverse/assets/models/${kind}.glb`])),
+ terrain: {
+ seed: 'example', size: 128, segments: 64, amplitude: 1.8, flatRadius: 28,
+ layers: [{ color: '#142338', repeat: 18 }],
+ },
+ },
+ presence: { connected: false },
+};
+
const renderPage = () => render(
<MemoryRouter initialEntries={['/eidoverse']}>
<Eidoverse />
@@ -41,16 +76,25 @@ describe('Eidoverse hosted page', () => {
api.getApp.mockResolvedValue({ id: setup.appId, overallStatus: 'online' });
api.startApp.mockResolvedValue({ success: true, results: {} });
api.startEidoverseHost.mockResolvedValue({ running: true, protocol: 'http', port: 5563 });
+ api.getEidoverseWorldStatus.mockResolvedValue(worldResponse);
+ api.projectEidoverseWorld.mockResolvedValue({
+ success: true,
+ projection: { lastSuccessAt: '2026-01-01T00:00:00.000Z' },
+ presence: { connected: true, role: 'owner' },
+ });
+ api.updateEidoverseWorldConfig.mockResolvedValue({ ...worldResponse, human: worldResponse.identity });
});
it('loads the installed managed app even when the optional nav entry is disabled', async () => {
renderPage();
const frame = await screen.findByTitle('Eidoverse Worlds');
- expect(frame).toHaveAttribute('src', `http://${window.location.hostname}:8940/`);
+ expect(frame).toHaveAttribute('src', `http://${window.location.hostname}:8940/?world=portos&name=example-portos-user`);
expect(api.getApp).toHaveBeenCalledWith('app-eidoverse', { silent: true });
expect(api.startApp).not.toHaveBeenCalled();
expect(api.startEidoverseHost).toHaveBeenCalledWith({ silent: true });
+ expect(api.getEidoverseWorldStatus).toHaveBeenCalledWith({ silent: true });
+ await waitFor(() => expect(api.projectEidoverseWorld).toHaveBeenCalledWith({ silent: true }));
expect(screen.getByRole('link', { name: 'Manage app' })).toHaveAttribute('href', '/apps/app-eidoverse/overview');
});
@@ -108,4 +152,105 @@ describe('Eidoverse hosted page', () => {
await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('did not become ready'));
expect(screen.queryByTitle('Eidoverse Worlds')).toBeNull();
});
+
+ it('keeps a successful local save visible when the follow-up projection fails', async () => {
+ const user = userEvent.setup();
+ renderPage();
+ await screen.findByTitle('Eidoverse Worlds');
+ await waitFor(() => expect(api.projectEidoverseWorld).toHaveBeenCalledTimes(1));
+ api.projectEidoverseWorld.mockRejectedValueOnce(new Error('Example projection failure'));
+
+ await user.click(screen.getByText('World identity and projection recipe'));
+ await user.click(screen.getByRole('button', { name: 'Save and project' }));
+
+ expect(await screen.findByText('Saved locally.')).toBeInTheDocument();
+ expect(await screen.findByText('Example projection failure')).toBeInTheDocument();
+ expect(api.updateEidoverseWorldConfig).toHaveBeenCalledOnce();
+ });
+
+ it('clears the saved marker as soon as the local recipe draft changes again', async () => {
+ const user = userEvent.setup();
+ renderPage();
+ await screen.findByTitle('Eidoverse Worlds');
+ await user.click(screen.getByText('World identity and projection recipe'));
+ await user.click(screen.getByRole('button', { name: 'Save and project' }));
+ expect(await screen.findByText('Saved locally.')).toBeInTheDocument();
+
+ await user.type(screen.getByLabelText('My Eidoverse name'), '-edited');
+ expect(screen.queryByText('Saved locally.')).not.toBeInTheDocument();
+ });
+
+ it('keeps newer draft edits intact while an earlier save is in flight', async () => {
+ let resolveSave;
+ api.updateEidoverseWorldConfig.mockReturnValueOnce(new Promise((resolve) => {
+ resolveSave = resolve;
+ }));
+ const user = userEvent.setup();
+ renderPage();
+ await screen.findByTitle('Eidoverse Worlds');
+ await user.click(screen.getByText('World identity and projection recipe'));
+
+ const nameInput = screen.getByLabelText('My Eidoverse name');
+ const saveButton = screen.getByRole('button', { name: 'Save and project' });
+ await user.click(saveButton);
+ expect(screen.getByRole('button', { name: 'Saving…' })).toBeDisabled();
+
+ await user.type(nameInput, '-edited');
+ expect(screen.getByRole('button', { name: 'Saving…' })).toBeDisabled();
+ resolveSave({ ...worldResponse, human: worldResponse.identity });
+
+ await waitFor(() => expect(screen.getByRole('button', { name: 'Save and project' })).toBeEnabled());
+ expect(nameInput).toHaveValue('example-portos-user-edited');
+ expect(screen.queryByText('Saved locally.')).not.toBeInTheDocument();
+ expect(api.updateEidoverseWorldConfig).toHaveBeenCalledOnce();
+ });
+
+ it('reloads the durable browser identity and reports projection failure separately after a world rename', async () => {
+ const user = userEvent.setup();
+ const renamed = { ...worldResponse, world: 'portos-two', human: worldResponse.identity };
+ renderPage();
+ await screen.findByTitle('Eidoverse Worlds');
+ await waitFor(() => expect(api.projectEidoverseWorld).toHaveBeenCalledTimes(1));
+ api.updateEidoverseWorldConfig.mockResolvedValueOnce(renamed);
+ api.projectEidoverseWorld.mockRejectedValueOnce(new Error('Example renamed-world failure'));
+
+ await user.click(screen.getByText('World identity and projection recipe'));
+ const worldInput = screen.getByLabelText('World name');
+ await user.clear(worldInput);
+ await user.type(worldInput, 'portos-two');
+ await user.click(screen.getByRole('button', { name: 'Save and project' }));
+
+ expect(await screen.findByText('Saved locally.')).toBeInTheDocument();
+ expect(await screen.findByText('Example renamed-world failure')).toBeInTheDocument();
+ expect(screen.getByTitle('Eidoverse Worlds')).toHaveAttribute(
+ 'src',
+ `http://${window.location.hostname}:8940/?world=portos-two&name=example-portos-user`,
+ );
+ });
+
+ it('mirrors the strict world recipe constraints in the browser form', async () => {
+ const user = userEvent.setup();
+ renderPage();
+ await screen.findByTitle('Eidoverse Worlds');
+ await user.click(screen.getByText('World identity and projection recipe'));
+
+ expect(screen.getByLabelText('World name')).toHaveAttribute('pattern', '[A-Za-z0-9_-]+');
+ const assetInput = screen.getByLabelText('Asset path', { selector: '#eidoverse-asset-app' });
+ expect(assetInput).toBeRequired();
+ expect(assetInput).toHaveAttribute(
+ 'pattern',
+ '(?:[Ee][Ii][Dd][Oo][Vv][Ee][Rr][Ss][Ee]|[Ss][Tt][Oo][Rr][Ee])[\\\\/](?!.*\\.\\.).*',
+ );
+ await user.clear(assetInput);
+ await user.type(assetInput, 'EIDOVERSE\\assets\\models\\example.glb');
+ expect(assetInput).toBeValid();
+
+ const scaleInput = screen.getByLabelText('Scale', { selector: '#eidoverse-scale-app' });
+ await user.clear(scaleInput);
+ await user.type(scaleInput, '0.001');
+ expect(scaleInput).toBeValid();
+ expect(screen.getByLabelText('Seed')).toBeRequired();
+ expect(screen.getByLabelText('size')).toHaveAttribute('min', '0.01');
+ expect(screen.getByLabelText('amplitude')).toHaveAttribute('max', '100');
+ });
});
diff --git a/client/src/pages/PersistentMindTools.test.jsx b/client/src/pages/PersistentMindTools.test.jsx
index 5db91cd806..47bde53ebf 100644
--- a/client/src/pages/PersistentMindTools.test.jsx
+++ b/client/src/pages/PersistentMindTools.test.jsx
@@ -75,7 +75,7 @@ describe('PersistentMindTools', () => {
await user.click(toggle);
await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(
- { persistentMindCapabilities: { schemaVersion: 4, createTasks: true, manageMind: false, callUser: false, readPortos: false, writePortos: false, taskModelAllowlist: [] } },
+ { persistentMindCapabilities: { schemaVersion: 5, createTasks: true, manageMind: false, manageEidoverse: false, callUser: false, readPortos: false, writePortos: false, taskModelAllowlist: [] } },
{ silent: true },
));
expect(await screen.findByText(/persistent-mind capabilities granted/)).toHaveTextContent('1 of 1');
@@ -95,9 +95,10 @@ describe('PersistentMindTools', () => {
await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(
{ persistentMindCapabilities: {
- schemaVersion: 4,
+ schemaVersion: 5,
createTasks: false,
manageMind: true,
+ manageEidoverse: false,
callUser: false,
readPortos: false,
writePortos: false,
@@ -129,9 +130,10 @@ describe('PersistentMindTools', () => {
await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(
{ persistentMindCapabilities: {
- schemaVersion: 4,
+ schemaVersion: 5,
createTasks: true,
manageMind: false,
+ manageEidoverse: false,
callUser: false,
readPortos: false,
writePortos: false,
@@ -192,9 +194,10 @@ describe('PersistentMindTools', () => {
await user.click(callToggle);
await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(
{ persistentMindCapabilities: {
- schemaVersion: 4,
+ schemaVersion: 5,
createTasks: false,
manageMind: false,
+ manageEidoverse: false,
callUser: true,
readPortos: false,
writePortos: false,
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index d0c29892c3..e65f1e2d98 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -87,6 +87,30 @@ export const startEidoverseHost = (options = {}) => request('/settings/features/
method: 'POST',
...options,
});
+export const getEidoverseWorldStatus = (options) => request('/eidoverse/world/status', options);
+export const updateEidoverseWorldConfig = (payload, options = {}) => request('/eidoverse/world/config', {
+ method: 'PUT',
+ body: JSON.stringify(payload),
+ ...options,
+});
+export const ensureEidoverseWorldPresence = (options = {}) => request('/eidoverse/world/presence', {
+ method: 'POST',
+ ...options,
+});
+export const projectEidoverseWorld = (options = {}) => request('/eidoverse/world/project', {
+ method: 'POST',
+ ...options,
+});
+export const augmentEidoverseWorld = (operations, options = {}) => request('/eidoverse/world/augment', {
+ method: 'POST',
+ body: JSON.stringify({ operations }),
+ ...options,
+});
+export const sayInEidoverseWorld = (text, options = {}) => request('/eidoverse/world/say', {
+ method: 'POST',
+ body: JSON.stringify({ text }),
+ ...options,
+});
export const updateSettings = (data, options) => request('/settings', {
method: 'PUT',
body: JSON.stringify(data),
diff --git a/client/src/utils/navWorkingSet.js b/client/src/utils/navWorkingSet.js
index a1c3241422..20649ff4eb 100644
--- a/client/src/utils/navWorkingSet.js
+++ b/client/src/utils/navWorkingSet.js
@@ -57,10 +57,16 @@ export const migrateLegacyNavPath = (path, commands) => {
const base = staticBase(previous);
if (!base || !(path === base || path.startsWith(`${base}/`))) continue;
// Longest base wins, so `/media/universe-builder` beats `/universe-builder`.
- if (!best || base.length > best.base.length) best = { base, to: command.path };
+ if (!best || base.length > best.base.length) {
+ best = {
+ base,
+ to: command.path,
+ preserveSuffix: command.preservePreviousPathSuffix !== false,
+ };
+ }
}
}
- return best ? `${best.to}${path.slice(best.base.length)}` : path;
+ return best ? `${best.to}${best.preserveSuffix ? path.slice(best.base.length) : ''}` : path;
};
// Resolve stored recent paths against the server-backed nav manifest. Exact
diff --git a/client/src/utils/navWorkingSet.test.js b/client/src/utils/navWorkingSet.test.js
index 420a0e1e95..17ff9d0b87 100644
--- a/client/src/utils/navWorkingSet.test.js
+++ b/client/src/utils/navWorkingSet.test.js
@@ -79,22 +79,23 @@ describe('migrateLegacyNavPath', () => {
// Shaped like the real manifest: `previousPaths` is declared on the entry that
// moved (server/lib/navManifest.js) and ships whole in the palette payload.
const commands = [
- { id: 'nav.openworld', path: '/openworld', label: 'OpenWorld', previousPaths: ['/city'] },
+ { id: 'nav.eidoverse', path: '/eidoverse', label: 'Eidoverse', previousPaths: ['/openworld', '/city'], preservePreviousPathSuffix: false },
{ id: 'nav.sprites', path: '/sprites', label: 'Sprites', previousPaths: ['/media/sprites', '/media/sprites/:id'] },
{ id: 'nav.universes', path: '/universes', label: 'Universes', previousPaths: ['/media/universe-builder', '/universe-builder'] },
{ id: 'nav.cityscape', path: '/cityscape', label: 'Cityscape' },
];
it('maps a moved page onto its current path', () => {
- expect(migrateLegacyNavPath('/city', commands)).toBe('/openworld');
+ expect(migrateLegacyNavPath('/city', commands)).toBe('/eidoverse');
expect(migrateLegacyNavPath('/media/sprites', commands)).toBe('/sprites');
});
it('carries the trailing path across, including a subtree the manifest never spells out', () => {
- // `/media/sprites/:id` declares the deep link; `/city/settings` is covered by
- // the bare `/city` base the same way App.jsx's `city/*` redirect covers it.
+ // Record-detail moves retain the selection. Retired OpenWorld subroutes do
+ // not exist in Eidoverse, so its manifest explicitly collapses the suffix.
expect(migrateLegacyNavPath('/media/sprites/s-1', commands)).toBe('/sprites/s-1');
- expect(migrateLegacyNavPath('/city/apps/portos', commands)).toBe('/openworld/apps/portos');
+ expect(migrateLegacyNavPath('/city/apps/portos', commands)).toBe('/eidoverse');
+ expect(migrateLegacyNavPath('/openworld/region/example', commands)).toBe('/eidoverse');
});
it('is segment-anchored, so a sibling route that merely shares a prefix is untouched', () => {
@@ -107,7 +108,7 @@ describe('migrateLegacyNavPath', () => {
});
it('returns a current path, an unknown path, and a non-path unchanged', () => {
- expect(migrateLegacyNavPath('/openworld', commands)).toBe('/openworld');
+ expect(migrateLegacyNavPath('/eidoverse', commands)).toBe('/eidoverse');
expect(migrateLegacyNavPath('/whatever', commands)).toBe('/whatever');
expect(migrateLegacyNavPath('//example.com', commands)).toBe('//example.com');
expect(migrateLegacyNavPath(null, commands)).toBe(null);
diff --git a/data.reference/cos/state.json b/data.reference/cos/state.json
index 3dc6b63e56..59aaef9b23 100644
--- a/data.reference/cos/state.json
+++ b/data.reference/cos/state.json
@@ -30,7 +30,17 @@
"autoStart": false,
"alwaysOn": false,
"selfImprovementEnabled": true,
- "dynamicAvatar": true
+ "dynamicAvatar": true,
+ "persistentMindCapabilities": {
+ "schemaVersion": 5,
+ "createTasks": false,
+ "manageMind": false,
+ "manageEidoverse": false,
+ "callUser": false,
+ "readPortos": false,
+ "writePortos": false,
+ "taskModelAllowlist": []
+ }
},
"stats": {
"tasksCompleted": 0,
diff --git a/docs/API.md b/docs/API.md
index 5258366f0b..0cc87667fe 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -312,7 +312,26 @@ Context tools remain read-only. Semantic reads and writes are independent, defau
| GET | `/usage/daily` | Get daily activity |
| GET | `/usage/hourly` | Get hourly activity |
-### CyberCity
+### Eidoverse Worlds
+
+The PortOS-owned Eidoverse adapter is private and install-local. It stores its
+identity and projection recipe under `data/eidoverse/`, joins the separately
+installed Eidoverse runtime through its WebSocket protocol, and does not
+federate world records.
+
+| Method | Endpoint | Description |
+|--------|----------|-------------|
+| GET | `/eidoverse/world/status` | Private world identity, CoS presence, projection recipe, setup, and storage boundary |
+| PUT | `/eidoverse/world/config` | Persist the world identity and deterministic resource projection recipe |
+| POST | `/eidoverse/world/presence` | Establish the install's persistent CoS agent presence |
+| POST | `/eidoverse/world/project` | Project current PortOS resources into the world using the saved recipe |
+| POST | `/eidoverse/world/augment` | Apply bounded, allowlisted world construction/role operations |
+| POST | `/eidoverse/world/say` | Send a bounded message as the PortOS CoS presence |
+
+### Legacy OpenWorld / CyberCity
+
+The old UI routes redirect to Eidoverse; these APIs remain available as
+backward-compatible historical snapshot/introspection endpoints.
| Method | Endpoint | Description |
|--------|----------|-------------|
@@ -581,7 +600,8 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom
| `/api/legacy-export` | Legacy data export |
| `/api/database` | Postgres introspection |
| `/api/image-clean` | Image metadata cleaning |
-| `/api/openworld`, `/api/city` | OpenWorld and CyberCity 3D snapshots/introspection |
+| `/api/eidoverse/world` | Private Eidoverse identity, projection, presence, augmentation, and chat adapter |
+| `/api/openworld`, `/api/city` | Legacy OpenWorld/CyberCity snapshots and introspection |
| `/api/cos/gsd` | CoS GSD workflow |
| `/api/feature-agents` | Feature agent runs |
| `/api/feeds` | RSS/content feeds |
diff --git a/docs/README.md b/docs/README.md
index 645e969add..70dc6cc374 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -44,7 +44,7 @@ Identity & self: [digital-twin](./features/digital-twin.md) · [identity-system]
Knowledge: [brain-system](./features/brain-system.md) · [messages-security](./features/messages-security.md)
-Create: [writers-room](./features/writers-room.md) · [fableloom](./features/fableloom.md) · [openworld](./features/openworld.md) · [Eidoverse Worlds integration](./features/eidoverse.md) · [sprite-export-contract](./features/sprite-export-contract.md) · [video-text-encoders](./features/video-text-encoders.md) · [video-speed-profiles](./features/video-speed-profiles.md)
+Create: [writers-room](./features/writers-room.md) · [fableloom](./features/fableloom.md) · [Eidoverse Worlds integration](./features/eidoverse.md) · [OpenWorld historical reference](./features/openworld.md) · [sprite-export-contract](./features/sprite-export-contract.md) · [video-text-encoders](./features/video-text-encoders.md) · [video-speed-profiles](./features/video-speed-profiles.md)
Comms & voice: [openclaw-operator-chat](./features/openclaw-operator-chat.md) ([pre-build audit](./research/2026-03-31-openclaw-operator-chat-audit.md)) · [stacker-news](./features/stacker-news.md) · [voice](./features/voice.md)
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index 4f36c7b97b..ce3a5435ee 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -59,7 +59,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 world logs — `data/eidoverse/worlds`. The external Eidoverse runtime owns these append-only world files; PortOS only selects their location through `.env.portos`. They are `file-primary`, included in filesystem backups, and intentionally machine-local — never federated by PortOS. The separately licensed git checkouts 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, projection recipe, and last-good projection 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 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.md
index 598a57aeac..92d4613f0b 100644
--- a/docs/features/eidoverse.md
+++ b/docs/features/eidoverse.md
@@ -47,21 +47,113 @@ Apps launch action works from a Tailscale MagicDNS session. Managed updates pull
both the selected Worlds checkout and its companion video runtime before using
Bun's frozen lockfile rather than npm.
-When the feature is enabled, **Eidoverse** appears beside OpenWorld in PortOS's
-primary navigation. Opening it starts the managed app when needed and embeds its
-web client in a full-width PortOS page. OpenWorld remains available during this
-evaluation; replacing or redirecting it is a separate product decision after
-the Eidoverse integration proves the required behavior.
+When the feature is enabled, **Eidoverse** is the primary PortOS world surface.
+Opening it starts the managed app when needed and embeds its web client in a
+full-width PortOS page. The retired OpenWorld paths remain as compatibility
+redirects to Eidoverse, so old bookmarks do not create a second world renderer.
Durable Eidoverse world logs live at `data/eidoverse/worlds`. This is
machine-local `file-primary` data: PortOS backups include it, but PortOS does
not federate it to peers. The git checkouts remain under `data/repos`, which is
the existing re-cloneable repository backup class.
-Disabling the feature does not delete repositories, unregister the app, stop a
-running process, or remove world history. It only records that this PortOS
-instance is not actively using the integration. Destructive uninstall remains
-an explicit manual operation.
+## Private persistence and identity
+
+This is a private world for one PortOS install. It is not a public Eidoverse
+world and PortOS does not publish its world records or expose them through the
+peer-sync record layer. Trusted machines may reach the instance through the
+install's existing Tailscale boundary; the install remains the authority for
+the world and its history.
+
+PortOS-owned integration state is stored in
+`data/eidoverse/portos-world.json`. It contains the selected world, the human
+display name, the stable Persistent Mind/CoS identity and local role
+observations, the projection recipe, and the last projection checkpoint.
+The human name can be configured explicitly. If it is cleared, PortOS derives a
+stable fallback from the persisted PortOS instance identity (using the instance
+name when available and a non-identifying instance-id-derived label otherwise).
+The browser receives that same identity in the Eidoverse launch URL, so a
+reload or a second trusted machine does not create a new anonymous user.
+The default installation uses Eidoverse's name-based join protocol with the
+empty join-token setting; the URL supplies the durable world, name, and avatar
+instead of inventing a browser-local account. If an operator later adds a
+join-token policy in the independent Eidoverse runtime, that policy remains an
+explicit runtime configuration rather than a secret stored in PortOS state.
+
+The Eidoverse runtime remains responsible for its own append-only world log,
+snapshot, roles, chat, poses, and assets under `data/eidoverse/worlds`. PortOS
+joins through the runtime's public WebSocket protocol and never edits the
+external checkout to seed content. On a fresh world, PortOS establishes the
+configured human identity first so it can own the world, then reconnects the
+stable CoS identity as an agent and grants it an owner role. Eidoverse reserves
+terrain, sky, and role handoff for owners, so the persistent CoS must retain
+that role to maintain the projected world and hand ownership to a renamed
+human identity. Once the new identity owns the world, PortOS demotes the prior
+identity to visitor so a rename does not leave a stale owner behind. PortOS
+exposes that authority through the separate, disabled-by-default **Manage the
+private Eidoverse world** grant in both the Persistent Mind controls and the
+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 rather
+than browser-session conveniences.
+
+## PortOS projection recipe
+
+The PortOS projection is deterministic and local. It turns current PortOS
+resources into Eidoverse entities without an LLM call. The default lanes are:
+
+- managed apps, active agents, open CoS tasks, enabled features, and federated
+ peer summaries become individual model-backed entities;
+- goals and current-sprint Jira tickets become bounded individual entities;
+- productivity and activity become compact summary/history entities;
+- memory becomes category/graph summaries only (raw memory and journal bodies
+ are not copied into the world component payload);
+- storage becomes bounded PostgreSQL table and `data/` domain summaries;
+- health becomes one aggregate, while operations becomes one compact hub for
+ CoS/AI state, review, backup, inbox, notifications, voice, character,
+ chronotype, health metrics, and disk state;
+- the recipe controls which families are included, per-family caps, layout
+ spacing/scales, model assets, and procedural terrain parameters;
+- stable entity ids make repeated projections update existing buildings,
+ vehicles, crates, drones, and landmarks instead of accumulating duplicates;
+- an unavailable source is preserved as unknown and does not delete its last
+ good entities; a confirmed empty source may remove the generated entities for
+ that family.
+
+The Eidoverse renderer receives the resource label, source id, status, and
+bounded fields as generic `portos` component metadata alongside each model.
+That keeps the world useful even when a source is sparse and leaves the
+Eidoverse scene graph/inspector as the authoritative detail view; the PortOS
+adapter does not pretend that arbitrary metadata is a persistent 3D text label.
+
+The Eidoverse page exposes **Project PortOS now** and a recipe editor. The
+Persistent Mind and explicitly granted local CoS agents can use the governed
+`eidoverse.status`, `eidoverse.project`, `eidoverse.augment`, and
+`eidoverse.say` tools. `eidoverse.augment` accepts only bounded world verbs (for
+example `spawn`, `place`, `comp`, `light`, `terrain`, `sky`, and `grant`); it
+cannot execute arbitrary runtime behavior or modify the installed Eidoverse
+source. Status requires bounded PortOS read access; projection additionally
+requires the dedicated Eidoverse-management grant, while augmentation and
+world chat require that dedicated grant without widening generic PortOS
+record-write authority.
+
+## Growth and automation
+
+The projection recipe is intentionally separate from the current world log.
+As PortOS gains resources, the deterministic projection runs when the hosted
+page opens and can also be run manually, from a CoS task, or through the
+disabled-by-default autonomous job
+`job-eidoverse-projection`. Enabling that job is an explicit install-local
+choice; it performs no provider calls and only reflects resources that already
+exist. The hosted page starts the managed runtime when it is opened; an
+automated projection run expects that managed app to remain available, and
+records a failed run instead of silently publishing stale or fabricated data.
+CoS tasks can also augment the world with bounded authored landmarks or
+messages, while recipe changes remain visible and editable in PortOS.
+
+Disabling the feature hides the optional navigation entry but does not delete
+repositories, unregister the app, stop a running process, block the direct
+`/eidoverse` route, disable a separately configured projection job, or remove
+world history. Destructive uninstall remains an explicit manual operation.
## Network boundary
@@ -81,7 +173,7 @@ returns an explicit unavailable state when the runtime does not become ready.
## PortOS bridge boundary
-The hosted UI and runtime management do not yet bridge Persistent Mind presence,
-agent identity, or dynamic PortOS buildings/assets. Those should be implemented
-as explicit adapters across the two projects' public protocols. They must remain
-opt-in and must not cause provider calls at PortOS boot.
+The hosted page, identity bridge, projection service, and CoS tools are explicit
+PortOS adapters across the two projects' public protocols. They remain
+deterministic and install-local: opening PortOS does not call an AI provider,
+and no raw Eidoverse world log is copied to another machine by federation.
diff --git a/docs/features/openworld.md b/docs/features/openworld.md
index 806f279acf..45bd70c7b0 100644
--- a/docs/features/openworld.md
+++ b/docs/features/openworld.md
@@ -1,7 +1,17 @@
# OpenWorld
-> **Renamed 2026-08-19.** This surface shipped as *CyberCity* at `/city`. It is now
-> **OpenWorld** at `/openworld`; the `/city` routes redirect so existing bookmarks,
+> **Retired in favor of Eidoverse.** The implementation remains in the checkout
+> for compatibility and reference, but `/openworld` and `/city` now redirect to
+> the private, persistent Eidoverse PortOS world. New world content and PortOS
+> resource projection belong in [Eidoverse Worlds](./eidoverse.md).
+
+The historical snapshot scheduler is no longer started at PortOS boot. Existing
+snapshot files and compatibility endpoints remain readable for older clients;
+new automatic world synchronization is owned by Eidoverse's page-open refresh
+and optional install-local projection job.
+
+> **Historical rename (2026-08-19).** This surface shipped as *CyberCity* at `/city`.
+> It was renamed **OpenWorld** at `/openworld`; the `/city` routes redirected so existing bookmarks,
> pinned rows, palette history, and peer deep links keep working. Persisted nav-command
> ids remain unchanged.
@@ -107,13 +117,11 @@ These mappings are symbolic and read-only. OpenWorld may navigate to an existing
but it must not invent an implicit write path or trigger an automation merely because the
player approached something.
-## Views and URL Contracts
+## Historical Views and URL Contracts
-- `/openworld` is the whole-world route.
-- `/openworld/apps/:appId` focuses one live app borough.
-- `/openworld/region/:regionId` focuses or warps to one named destination.
-- `/openworld/settings` opens world settings.
-- Legacy `/city` routes redirect to the equivalent OpenWorld route.
+- `/openworld` and `/city` redirect to `/eidoverse`.
+- Historical `/openworld/apps/:appId`, `/openworld/region/:regionId`, and
+ `/openworld/settings` paths are caught by the compatibility redirect.
Selection remains in the URL. Building focus and region travel are bookmarkable,
back/forward safe, and reachable from the command palette and voice navigation.
diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.md
index c26a57a186..045c4b4abc 100644
--- a/docs/features/product-surfaces.md
+++ b/docs/features/product-surfaces.md
@@ -183,8 +183,8 @@ Unified communication channels, local voice assistant, community stewardship, an
| **Evergreen Personal Wiki** | `/wiki/*` | Curated personal knowledge base with markdown editing, link graphs, and full-text search. | — |
| **Voice Mode** | `/settings/voice` | Hands-free voice assistant with continuous VAD (AudioWorklet), speech-to-text (Whisper local or Web Speech), local LLM orchestration, text-to-speech (Kokoro-82M in-process or Piper), barge-in support, and `ui_navigate` tool execution. | [Voice Mode](./voice.md) |
| **Ambient Display Mode** | `/ambient` | Fullscreen idle dashboard, ambient animations, system status ticker, and display screensaver. | — |
-| **OpenWorld 3D Spatial Map** | `/openworld`, `/openworld/settings` | Interactive 3D visualization of the PortOS ecosystem rendered in Three.js / React Three Fiber. Apps appear as skyscrapers with live PM2 metrics, glowing holograms, and operational alert states. | [OpenWorld](./openworld.md) |
-| **OpenWorld Fast-Travel Regions** | `/openworld/region/:id` | Fast-travel destinations across 14 distinct city regions: Downtown (Apps District), AI Core Plaza, Task Queue, Wellness Tower, Archive District, Quiet Corner, Productivity Terrace, Backup Vault, Memory Quarter, Sprint Yard (JIRA), Voice Beacon, Goal Monuments, Hall of Achievements, and Data Harbor. | [OpenWorld](./openworld.md) |
+| **Eidoverse Worlds** | `/eidoverse` | Private, install-local 3D world for the human and Persistent Mind/CoS agents, with durable name-based identity, world history, deterministic PortOS resource projection, and governed world augmentation. | [Eidoverse Worlds](./eidoverse.md) |
+| **OpenWorld (retired compatibility surface)** | `/openworld`, `/city` | Historical Three.js / React Three Fiber world; legacy routes redirect to Eidoverse so existing bookmarks remain usable. | [OpenWorld](./openworld.md) |
---
@@ -216,7 +216,7 @@ When performing a **repo-study** task (`server/services/repoIntake.js`) or propo
| External Repository Domain | Target PortOS Product Surface(s) | Primary Lens & Considerations |
|---|---|---|
-| **3D Scenes, WebGL, Game Engines** | **Create → 3D & Sprites** (`/3d`, `/sprites`, `/game`) or **Main → OpenWorld** (`/openworld`) | Visual asset pipeline, procedural geometry, Three.js shaders, low-poly rendering, sprite sheet compilation. |
+| **3D Scenes, WebGL, Game Engines** | **Create → 3D & Sprites** (`/3d`, `/sprites`, `/game`) or **Main → Eidoverse Worlds** (`/eidoverse`) | Visual asset pipeline, procedural geometry, Three.js shaders, low-poly rendering, and install-local PortOS world projection. |
| **Chatbots, Conversational LLMs, Assistants** | **Chief of Staff → Persistent Mind** (`/cos/mind`) or **Settings → Voice** (`/settings/voice`) or **Settings → OpenClaw** (`/openclaw`) | Context memory, MCP tool calling, speech-to-text/text-to-speech integration, barge-in support. |
| **Note-Taking, Markdown Wikis, Second Brains** | **Brain → Inbox & Notes** (`/brain/*`) or **Brain → Wiki** (`/wiki/*`) or **Brain → Rapid Reader** (`/rapid-reader`) | Knowledge graphs, AI thought classification, RSVP speed-reading, Obsidian sync. |
| **Writing Tools, Fiction Generators, Storyboarding** | **Create → Writers Room** (`/writers-room`), **Story Builder** (`/story-builder`), or **FableLoom** (`/fableloom`) | Prose editing, chapter versioning, interactive branching graphs, character consistency. |
diff --git a/scripts/migrations/320-persistent-mind-eidoverse-capability.js b/scripts/migrations/320-persistent-mind-eidoverse-capability.js
new file mode 100644
index 0000000000..e9df26b9a4
--- /dev/null
+++ b/scripts/migrations/320-persistent-mind-eidoverse-capability.js
@@ -0,0 +1,58 @@
+/**
+ * Seed the dedicated, default-off Persistent Mind Eidoverse grant.
+ *
+ * Generic PortOS write access pre-dates this capability but must not imply
+ * authority to build, grant roles, or speak in the private world. Existing
+ * installs therefore receive an explicit false value during upgrade.
+ */
+
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { atomicWrite, safeJSONParse } from '../../server/lib/fileUtils.js';
+
+// Historical migrations pin their source/target versions. Importing the live
+// schema constant would make a future schema bump reinterpret this migration
+// and could revoke an explicit grant when an applied-migration ledger is
+// rebuilt.
+const TARGET_SCHEMA_VERSION = 5;
+
+export default {
+ async up({ rootDir }) {
+ const statePath = join(rootDir, 'data', 'cos', 'state.json');
+ const raw = await readFile(statePath, '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-state' };
+ }
+
+ const config = state.config && typeof state.config === 'object' && !Array.isArray(state.config)
+ ? state.config
+ : {};
+ const existing = config.persistentMindCapabilities
+ && typeof config.persistentMindCapabilities === 'object'
+ && !Array.isArray(config.persistentMindCapabilities)
+ ? config.persistentMindCapabilities
+ : {};
+ if (Number.isInteger(existing.schemaVersion)
+ && existing.schemaVersion >= TARGET_SCHEMA_VERSION) {
+ return { updated: 0, reason: 'already-applied' };
+ }
+
+ state.config = {
+ ...config,
+ persistentMindCapabilities: {
+ ...existing,
+ schemaVersion: TARGET_SCHEMA_VERSION,
+ manageEidoverse: false,
+ },
+ };
+ await atomicWrite(statePath, state);
+ console.log('🌐 migration 320: seeded the default-off Persistent Mind Eidoverse grant');
+ return { updated: 1 };
+ },
+};
diff --git a/scripts/migrations/320-persistent-mind-eidoverse-capability.test.js b/scripts/migrations/320-persistent-mind-eidoverse-capability.test.js
new file mode 100644
index 0000000000..c7c57c5153
--- /dev/null
+++ b/scripts/migrations/320-persistent-mind-eidoverse-capability.test.js
@@ -0,0 +1,82 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import migration from './320-persistent-mind-eidoverse-capability.js';
+
+let rootDir;
+
+afterEach(async () => {
+ if (rootDir) await rm(rootDir, { recursive: true, force: true });
+ rootDir = null;
+});
+
+const statePath = () => join(rootDir, 'data', 'cos', 'state.json');
+const readCapabilities = async () => JSON.parse(await readFile(statePath(), 'utf8')).config.persistentMindCapabilities;
+
+describe('migration 320 — Persistent Mind Eidoverse capability', () => {
+ beforeEach(async () => {
+ rootDir = await mkdtemp(join(tmpdir(), 'portos-eidoverse-capability-'));
+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });
+ });
+
+ it('adds the dedicated grant as disabled without changing prior authority', async () => {
+ await writeFile(statePath(), JSON.stringify({
+ config: {
+ persistentMindCapabilities: {
+ schemaVersion: 4,
+ createTasks: true,
+ writePortos: true,
+ futureField: 'preserve',
+ },
+ },
+ }));
+
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 1 });
+ expect(await readCapabilities()).toMatchObject({
+ schemaVersion: 5,
+ createTasks: true,
+ writePortos: true,
+ manageEidoverse: false,
+ futureField: 'preserve',
+ });
+ });
+
+ it('does not treat a pre-schema hand edit as an authority grant', async () => {
+ await writeFile(statePath(), JSON.stringify({
+ config: { persistentMindCapabilities: { schemaVersion: 4, manageEidoverse: true } },
+ }));
+
+ await migration.up({ rootDir });
+ expect((await readCapabilities()).manageEidoverse).toBe(false);
+ });
+
+ it('is idempotent after the current schema has an explicit value', async () => {
+ const current = {
+ schemaVersion: 5,
+ manageEidoverse: true,
+ };
+ await writeFile(statePath(), JSON.stringify({ config: { persistentMindCapabilities: current } }));
+
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });
+ expect(await readCapabilities()).toEqual(current);
+ });
+
+ it('does not downgrade or revoke a grant from a future schema during replay', async () => {
+ const future = {
+ schemaVersion: 6,
+ manageEidoverse: true,
+ futureField: 'preserve',
+ };
+ await writeFile(statePath(), JSON.stringify({ config: { persistentMindCapabilities: future } }));
+
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });
+ expect(await readCapabilities()).toEqual(future);
+ });
+
+ it('leaves missing and invalid state untouched', async () => {
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'no-state' });
+ await writeFile(statePath(), '{broken');
+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'invalid-state' });
+ });
+});
diff --git a/server/index.js b/server/index.js
index 3cd98bf91f..875fd33ac2 100644
--- a/server/index.js
+++ b/server/index.js
@@ -87,6 +87,7 @@ import autobiographyRoutes from './routes/autobiography.js';
import backupRoutes from './routes/backup.js';
import legacyExportRoutes from './routes/legacyExport.js';
import openWorldRoutes from './routes/openWorldRoutes.js';
+import eidoverseWorldRoutes from './routes/eidoverseWorldRoutes.js';
import databaseRoutes from './routes/database.js';
import localLlmRoutes from './routes/localLlm.js';
import codeReviewRoutes from './routes/codeReview.js';
@@ -296,6 +297,7 @@ app.use('/api/client-errors', clientErrorsRoutes);
app.use('/api/autofix', autoFixMetricsRoutes);
app.use('/api/backup', backupRoutes);
app.use('/api/legacy-export', legacyExportRoutes);
+app.use('/api/eidoverse/world', eidoverseWorldRoutes);
app.use('/api/openworld', openWorldRoutes);
// Keep the pre-rename API prefix available to older clients and installed voice tools.
app.use('/api/city', openWorldRoutes);
diff --git a/server/lib/README.md b/server/lib/README.md
index 610bd4c002..39a2c070dd 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -49,7 +49,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `agentRunReconcile.js` | CoS run reconciliation (#4540) — pure diff between a ledger projection (`projectRunStates`) and the durable run record. Closed finding vocabulary `RUN_RECONCILE_FINDINGS` (`record-open`, `record-missing`, `verdict-mismatch`, `ledger-open`), `diffRunRecord()`, `reconcileRunRecords()` with a zero-filled per-kind summary, and `planRunRecordRepair()` — the metadata patch that closes a record the ledger proves is finished. Repairs are one-directional (ledger → record) by design: a record closed while the ledger missed the close is reported, never back-filled, so the stream stays an audit of the record rather than a copy of it. I/O half: `services/agentRunReconciler.js`. |
| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME`, `doneSentinelName(agentId)` → the per-instance filename `.agent-done-<agentId>` (worktree-less agents share one workspace, so a shared name lets concurrent runs clobber — and finalize on — each other's signal), `doneSentinelPath(workspacePath, agentId)` → the single path every producer and consumer resolves, + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. `extractSentinelPayloadFromTranscript(transcript, isPayload)` (async) is the third tier for programmatic-I/O types ONLY — scans the ANSI-stripped PTY transcript, newest balanced JSON block first, for a payload the model PRINTED instead of writing, and adopts it only if the owning hook's shape predicate accepts it (#3640). `PROGRAMMATIC_OUTPUT_COMPLETION_HEADING` names the briefing section that prints this run's absolute sentinel path — a task-type hook renders its prompt before spawn, so it points the agent at that section by name rather than at a filename it cannot know. |
| `persistentMind.js` | Pure persistent-CoS-mind runtime state: default-off durable shape, normalization, FIFO-message/self-wake selection, interrupted-wake requeue, image-work rollback guard, bounded exponential backoff, watchdog staleness, and next-wake projection. |
-| `persistentMindCapabilities.js` | Default-off persistent-mind action grants plus bounded typed CoS-task and self-cleanup contracts (app/provider/model/effort, PR completion policy, the optional exact provider/model task allowlist, and mind-owned context scopes). |
+| `persistentMindCapabilities.js` | Default-off persistent-mind action grants plus bounded typed CoS-task, private-Eidoverse, and self-cleanup contracts (app/provider/model/effort, PR completion policy, the optional exact provider/model task allowlist, and mind-owned context scopes). |
| `cosToolContracts.js` | Provider-neutral `portos_tool` catalog/call schema version, request-id and per-turn bounds, catalog query formats, and Persistent Mind tool-call shape. |
| `persistentMindTrajectory.js` | Pure persistent-mind trajectory vocabulary, sequence cursor parsing, replay projection, provenance-tagged rollup validation, and hard-budget context assembly with explicit empty/missing/failed/stale summary states. |
| `persistentMindProfile.js` | Versioned, default-off persistent-mind provider profile (`enabled`, provider/model/effort, text interface, maximum quiet interval), its strict API schema, duration resolver, and safe partial-update merge that clears model/effort on a provider switch. |
diff --git a/server/lib/agentContextValidation.js b/server/lib/agentContextValidation.js
index 534c17103a..9316e378dc 100644
--- a/server/lib/agentContextValidation.js
+++ b/server/lib/agentContextValidation.js
@@ -4,7 +4,7 @@ import {
portosSemanticToolGrantsSchema,
} from './cosToolContracts.js';
-export const AGENT_CONTEXT_SCHEMA_VERSION = 3;
+export const AGENT_CONTEXT_SCHEMA_VERSION = 4;
export const AGENT_CONTEXT_PROTOCOL_VERSION = '2025-11-25';
export const AGENT_CONTEXT_SUPPORTED_PROTOCOL_VERSIONS = Object.freeze([
'2025-03-26',
diff --git a/server/lib/agentContextValidation.test.js b/server/lib/agentContextValidation.test.js
index 4bd205866f..440ebce3b9 100644
--- a/server/lib/agentContextValidation.test.js
+++ b/server/lib/agentContextValidation.test.js
@@ -19,12 +19,12 @@ describe('agentContextValidation', () => {
enabled: true,
profile: 'metadata',
scopes: ['navigation', 'brain'],
- actions: { readPortos: true, writePortos: false },
+ actions: { readPortos: true, writePortos: false, manageEidoverse: true },
})).toEqual({
enabled: true,
profile: 'metadata',
scopes: ['navigation', 'brain'],
- actions: { readPortos: true, writePortos: false },
+ actions: { readPortos: true, writePortos: false, manageEidoverse: true },
});
expect(agentContextSettingsSchema.safeParse({ scopes: ['brain', 'brain'] }).success).toBe(false);
expect(agentContextSettingsSchema.safeParse({ scopes: ['privacy-vault'] }).success).toBe(false);
diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.json
index c4a1d4be1b..15f7d3363f 100644
--- a/server/lib/apiRouteCatalog.generated.json
+++ b/server/lib/apiRouteCatalog.generated.json
@@ -52,6 +52,7 @@
"/api/digital-twin/autobiography",
"/api/digital-twin/identity",
"/api/digital-twin/social-accounts",
+ "/api/eidoverse/world",
"/api/fableloom",
"/api/feature-agents",
"/api/federation/media/v1",
@@ -8717,6 +8718,72 @@
}
]
},
+ {
+ "method": "POST",
+ "path": "/api/eidoverse/world/augment",
+ "mountPath": "/api/eidoverse/world",
+ "sources": [
+ {
+ "source": "server/routes/eidoverseWorldRoutes.js",
+ "line": 56
+ }
+ ]
+ },
+ {
+ "method": "PUT",
+ "path": "/api/eidoverse/world/config",
+ "mountPath": "/api/eidoverse/world",
+ "sources": [
+ {
+ "source": "server/routes/eidoverseWorldRoutes.js",
+ "line": 36
+ }
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/eidoverse/world/presence",
+ "mountPath": "/api/eidoverse/world",
+ "sources": [
+ {
+ "source": "server/routes/eidoverseWorldRoutes.js",
+ "line": 43
+ }
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/eidoverse/world/project",
+ "mountPath": "/api/eidoverse/world",
+ "sources": [
+ {
+ "source": "server/routes/eidoverseWorldRoutes.js",
+ "line": 50
+ }
+ ]
+ },
+ {
+ "method": "POST",
+ "path": "/api/eidoverse/world/say",
+ "mountPath": "/api/eidoverse/world",
+ "sources": [
+ {
+ "source": "server/routes/eidoverseWorldRoutes.js",
+ "line": 63
+ }
+ ]
+ },
+ {
+ "method": "GET",
+ "path": "/api/eidoverse/world/status",
+ "mountPath": "/api/eidoverse/world",
+ "sources": [
+ {
+ "source": "server/routes/eidoverseWorldRoutes.js",
+ "line": 30
+ }
+ ]
+ },
{
"method": "GET",
"path": "/api/fableloom",
@@ -23564,9 +23631,9 @@
}
],
"stats": {
- "mounts": 145,
- "operations": 2126,
- "declarations": 2129,
- "sourceFiles": 225
+ "mounts": 146,
+ "operations": 2132,
+ "declarations": 2135,
+ "sourceFiles": 226
}
}
diff --git a/server/lib/cosToolContracts.js b/server/lib/cosToolContracts.js
index 8e1378664e..cb50427f21 100644
--- a/server/lib/cosToolContracts.js
+++ b/server/lib/cosToolContracts.js
@@ -3,7 +3,11 @@
import { z } from 'zod';
export const COS_TOOL_SCHEMA_VERSION = 1;
-export const PORTOS_SEMANTIC_TOOL_GRANT_KEYS = Object.freeze(['readPortos', 'writePortos']);
+export const PORTOS_SEMANTIC_TOOL_GRANT_KEYS = Object.freeze([
+ 'readPortos',
+ 'writePortos',
+ 'manageEidoverse',
+]);
export const COS_TOOL_CALL_LIMITS = Object.freeze({
requestIdChars: 200,
nameChars: 100,
@@ -16,11 +20,13 @@ export const COS_TOOL_CALL_LIMITS = Object.freeze({
export const portosSemanticToolGrantsSchema = z.object({
readPortos: z.boolean().optional(),
writePortos: z.boolean().optional(),
+ manageEidoverse: z.boolean().optional(),
}).strict();
export const createDefaultPortosSemanticToolGrants = () => ({
readPortos: false,
writePortos: false,
+ manageEidoverse: false,
});
export const normalizePortosSemanticToolGrants = (raw) => {
@@ -28,6 +34,7 @@ export const normalizePortosSemanticToolGrants = (raw) => {
return {
readPortos: source.readPortos === true,
writePortos: source.writePortos === true,
+ manageEidoverse: source.manageEidoverse === true,
};
};
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 13503e3ecc..a047f10f5a 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -1,6 +1,6 @@
// Single source of truth for PortOS navigation. Consumed by the sidebar,
// server/services/voice/tools.js#ui_navigate, and the Cmd+K palette.
-// Entry: { id, path, label, section, aliases?, keywords?, previousPaths? }.
+// Entry: { id, path, label, section, aliases?, keywords?, previousPaths?, preservePreviousPathSuffix? }.
// See AGENTS.md "Command Palette & Voice Nav" for the contract.
//
// `previousPaths` lists every path this page has ANSWERED TO BEFORE — including
@@ -16,43 +16,6 @@
import { PORTOS_APP_ID } from './appIdentity.js';
-// Fast-travel destinations — one command per region in the client's OPEN_WORLD_REGIONS
-// registry (client/src/utils/openWorldRegions.js), so ⌘K and voice ("take me to the
-// memory quarter") can warp straight into the world. The list is duplicated rather than
-// imported because a server lib can't reach into client code; navManifest.test.js scrapes
-// the registry and fails on drift in the paths, the labels, AND the aliases.
-// Written as [id, label, aliases, feature?] tuples so the axis that varies is the only thing repeated.
-//
-// Aliases are authored in the human phrasing the fast-travel search box uses ("memory
-// quarter") and registered KEBAB-CASED, because resolveNavCommand normalizes its input to
-// kebab before matching: a space-separated alias can never be hit. Registering them raw
-// didn't just fail to resolve — the fallback tiers matched a substring against an unrelated
-// command, so "memory quarter" landed on /brain/memory and "voice beacon" on /settings/voice.
-const OPEN_WORLD_REGION_COMMANDS = [
- ['downtown', 'Village Green', ['downtown', 'apps district', 'app towers', 'village green']],
- ['ai-core', 'PortOS Common', ['ai core', 'core plaza', 'the core', 'reactor', 'common']],
- ['task-queue', 'Task Workshop', ['task queue', 'queue', 'cos queue', 'task workshop']],
- ['wellness', 'Wellness Greenhouse', ['wellness tower', 'health tower', 'vitals tower', 'greenhouse']],
- ['archive', 'Archive Lodge', ['archive district', 'warehouse', 'cold storage', 'archive lodge']],
- ['quiet-corner', 'Quiet Corner', ['quiet corner', 'easter eggs']],
- ['productivity', 'Focus Farm', ['productivity terrace', 'productivity', 'throughput district', 'streak district', 'focus farm']],
- ['backup-vault', 'Backup Cottage', ['backup vault', 'the vault', 'backup cottage']],
- ['memory', 'Memory House', ['memory quarter', 'memory district', 'knowledge district', 'memory house']],
- ['sprint-yard', 'Sprint Studio', ['sprint yard', 'jira yard', 'sprint district', 'sprint studio'], 'jira'],
- ['voice', 'Voice Radio', ['voice beacon', 'the beacon', 'voice radio']],
- ['goals', 'Goals Lodge', ['goal monuments', 'monuments', 'goals district', 'goals lodge']],
- ['artifacts', 'Trophy House', ['hall of achievements', 'artifact hall', 'achievements hall', 'trophy house']],
- ['data-harbor', 'Data Pier', ['data harbor', 'the harbor', 'piers', 'data pier']],
-].map(([id, label, aliases, feature]) => ({
- id: `nav.openworld.region.${id}`,
- path: `/openworld/region/${id}`,
- label,
- section: 'Main',
- aliases: aliases.map((a) => a.replace(/\s+/g, '-')),
- keywords: ['openworld', 'fast travel', 'warp', 'region', 'teleport'],
- ...(feature ? { feature } : {}),
-}));
-
// Sections whose every page belongs to one optional instance feature, so a page
// added there inherits the gate with no edit. A single page inside an otherwise
// ungated section (DataDog, JIRA) carries `feature` on its own entry instead.
@@ -68,10 +31,7 @@ export const SECTION_FEATURE = new Map([
const RAW_NAV_COMMANDS = [
{ id: 'nav.dashboard', path: '/', label: 'Dashboard', section: 'Main', aliases: ['dashboard', 'home'], keywords: ['overview', 'start'] },
{ id: 'nav.review-hub', path: '/review', label: 'Review Hub', section: 'Main', aliases: ['review', 'review-hub'] },
- { id: 'nav.eidoverse', path: '/eidoverse', label: 'Eidoverse', section: 'Main', feature: 'eidoverse', aliases: ['eidoverse', 'eidoverse-worlds', 'worlds'], keywords: ['3d', 'world', 'agents', 'spatial', 'managed app'] },
- { id: 'nav.cybercity', path: '/openworld', label: 'OpenWorld', section: 'Main', previousPaths: ['/city'], aliases: ['openworld', 'open world', 'open-world', 'city'], keywords: ['3d', 'visualization', 'game', 'map', 'explore'] },
- { id: 'nav.cybercity.settings', path: '/openworld/settings', label: 'OpenWorld Settings', section: 'Main', aliases: ['openworld settings', 'open world settings', 'world settings', 'city settings', 'city-settings', 'openworld-config'], keywords: ['openworld', 'settings', '3d', 'configure', 'world style', 'low poly'] },
- ...OPEN_WORLD_REGION_COMMANDS,
+ { id: 'nav.eidoverse', path: '/eidoverse', label: 'Eidoverse', section: 'Main', feature: 'eidoverse', previousPaths: ['/openworld', '/city'], preservePreviousPathSuffix: false, aliases: ['eidoverse', 'eidoverse-worlds', 'worlds', 'openworld', 'open-world', 'city'], keywords: ['3d', 'world', 'agents', 'spatial', 'managed app', 'private environment'] },
{ id: 'nav.apps', path: '/apps', label: 'Apps', section: 'Main', aliases: ['apps'] },
// Submodules are per-app (a tab on the app detail page), so this entry is
// explicitly PortOS's own — the only repo whose app id is a fixed constant.
diff --git a/server/lib/navManifest.test.js b/server/lib/navManifest.test.js
index f8b124eb34..3d750e805e 100644
--- a/server/lib/navManifest.test.js
+++ b/server/lib/navManifest.test.js
@@ -41,11 +41,6 @@ const TABBED_PAGES = [
{ prefix: '/music', file: 'client/src/pages/Music.jsx', kind: 'ids', constName: 'TABS', allowBasePrefix: true },
{ prefix: '/sharing', file: 'client/src/pages/Sharing.jsx', kind: 'links', constName: 'SECTIONS' },
{ prefix: '/system-resources', file: 'client/src/pages/SystemHealthPage.jsx', kind: 'ids', constName: 'RESOURCE_TABS', allowBasePrefix: true },
- // OpenWorld's fast-travel destinations aren't page tabs, but they follow the same
- // contract: one `/openworld/region/<id>` nav command per region in the client's
- // registry, so every warp target is reachable from ⌘K and voice — and a region
- // added without a command (or a command left behind by a deleted region) fails here.
- { prefix: '/openworld/region', file: 'client/src/utils/openWorldRegions.js', kind: 'ids', constName: 'OPEN_WORLD_REGIONS' },
// POST's morse tab has routed `:mode` sub-pages (/post/morse/copy|send) and the
// memory tab has the Elements study sub-page (/post/memory/elements) plus its
// own routed practice modes — none are top-level switch cases, so declare their
@@ -345,94 +340,6 @@ describe('nav contract — tabbed pages match their tab constants', () => {
}
});
-// The `ids` guard above pins the region PATHS, but a region's user-visible label and its
-// spoken/typed aliases live in the client registry too — and those are what ⌘K and voice
-// actually match on. Without this, the two lists can pass the path guard while the alias
-// sets silently diverge, so "take me to the memory quarter" resolves in the panel's search
-// box but not in the palette. Read straight out of the registry source so there is one
-// source of truth for what a region is called.
-describe('nav contract — OpenWorld regions match the registry labels and aliases', () => {
- const REGIONS_FILE = 'client/src/utils/openWorldRegions.js';
-
- // Each registry entry is one `{ … }` object literal on its own line; pull the fields the
- // nav manifest also declares. Read inside it() bodies so a moved file fails focused.
- const readRegistry = () => {
- const src = fs.readFileSync(path.join(REPO_ROOT, REGIONS_FILE), 'utf8');
- const block = src.match(/export const OPEN_WORLD_REGIONS\s*=\s*\[([\s\S]*?)^\];/m);
- if (!block) throw new Error('No exported OPEN_WORLD_REGIONS array found');
- return [...block[1].matchAll(/\{[^{}]*\}/g)].map((m) => {
- const entry = m[0];
- const field = (name) => entry.match(new RegExp(`${name}:\\s*'([^']*)'`))?.[1];
- const aliases = entry.match(/aliases:\s*\[([^\]]*)\]/)?.[1] || '';
- return {
- id: field('id'),
- label: field('label'),
- feature: field('feature'),
- aliases: [...aliases.matchAll(/'([^']*)'/g)].map((a) => a[1]),
- };
- });
- };
-
- const navByPath = new Map(NAV_COMMANDS.map((c) => [c.path, c]));
-
- it('reads a non-empty registry (the extractor still matches the file shape)', () => {
- const regions = readRegistry();
- expect(regions.length).toBeGreaterThan(0);
- expect(regions.every((r) => r.id && r.label)).toBe(true);
- });
-
- it('every region command carries the registry label', () => {
- const wrong = readRegistry()
- .map((r) => ({ r, cmd: navByPath.get(`/openworld/region/${r.id}`) }))
- .filter(({ r, cmd }) => cmd && cmd.label !== r.label)
- .map(({ r, cmd }) => `${r.id}: nav "${cmd.label}" ≠ registry "${r.label}"`);
- expect(wrong).toEqual([]);
- });
-
- it('keeps each region feature gate mirrored between the registry and nav command', () => {
- const wrong = readRegistry()
- .map((r) => ({ r, cmd: navByPath.get(`/openworld/region/${r.id}`) }))
- .filter(({ r, cmd }) => (cmd?.feature || null) !== (r.feature || null))
- .map(({ r, cmd }) => `${r.id}: nav "${cmd?.feature || 'none'}" ≠ registry "${r.feature || 'none'}"`);
- expect(wrong).toEqual([]);
- });
-
- it('every registry alias is addressable as a nav alias', () => {
- // The registry authors aliases in human phrasing ("memory quarter"); the manifest
- // registers them kebab-cased, because that is the form resolveNavCommand matches on.
- const kebab = (a) => a.replace(/\s+/g, '-');
- const missing = readRegistry().flatMap((r) => {
- const cmd = navByPath.get(`/openworld/region/${r.id}`);
- if (!cmd) return [];
- const navAliases = new Set(cmd.aliases || []);
- return r.aliases.filter((a) => !navAliases.has(kebab(a))).map((a) => `${r.id}: "${a}"`);
- });
- expect(missing).toEqual([]);
- });
-
- it('every region alias actually RESOLVES to its own region', () => {
- // Parity with the registry is not enough on its own: resolveNavCommand normalizes its
- // input to kebab-case, so a space-separated alias never matches exactly and instead
- // falls through to the substring tiers — which is how "memory quarter" resolved to
- // /brain/memory and "voice beacon" to /settings/voice while every parity check passed.
- // Assert the behavior users actually get, phrased the way they'd say it.
- const wrong = readRegistry().flatMap((r) => {
- const want = `/openworld/region/${r.id}`;
- return r.aliases
- .map((alias) => ({ alias, got: resolveNavCommand(alias)?.path ?? null }))
- .filter(({ got }) => got !== want)
- .map(({ alias, got }) => `${r.id}: "${alias}" → ${got ?? 'NULL'} (want ${want})`);
- });
- expect(wrong).toEqual([]);
- });
-
- it('resolves a region by its label as spoken', () => {
- for (const r of readRegistry()) {
- expect(resolveNavCommand(r.label)?.path).toBe(`/openworld/region/${r.id}`);
- }
- });
-});
-
// Settings is the one tabbed page whose tab bar (SettingsTabsHeader.jsx `TABS`,
// the nav guard's source of truth for /settings) and render dispatch live in
// separate files: `Settings.jsx`'s `switch (activeTab)`. They're hand-kept in
@@ -694,7 +601,7 @@ describe('nav coverage — every navigable App.jsx route has a manifest entry',
// A pinned sidebar row is a STORED route path, so an undeclared move made
// the pin stop resolving and vanish on the next update — the client reads
// these to map a stored path onto where its page lives now.
- '/city', // OpenWorld's rename (whole subtree)
+ '/openworld', '/city', // retired OpenWorld routes
'/devtools/submodules',
'/devtools/runs',
'/settings/contacts',
diff --git a/server/lib/persistentMindCapabilities.js b/server/lib/persistentMindCapabilities.js
index dc133a5e05..9fb477b9c1 100644
--- a/server/lib/persistentMindCapabilities.js
+++ b/server/lib/persistentMindCapabilities.js
@@ -14,12 +14,12 @@ import {
portosSemanticToolGrantsSchema,
} from './cosToolContracts.js';
-export const PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION = 4;
+export const PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION = 5;
// Every wire version this server still accepts on input. Installs upgrade on
// their own schedule, so a browser bundle (or a route caller) pinned at an
// older version must keep being able to toggle the grants it already knows
// about; normalization always writes the current version forward.
-const ACCEPTED_CAPABILITIES_SCHEMA_VERSIONS = Object.freeze([2, 3, 4]);
+const ACCEPTED_CAPABILITIES_SCHEMA_VERSIONS = Object.freeze([2, 3, 4, 5]);
export const PERSISTENT_MIND_TASK_MODEL_ALLOWLIST_LIMITS = Object.freeze({
MAX_ENTRIES: 200,
@@ -95,6 +95,19 @@ export const PERSISTENT_MIND_TOOL_CATALOG = Object.freeze([
'Calls use stable request ids so retries within the bounded retention window cannot repeat an accepted action',
],
}),
+ Object.freeze({
+ id: 'eidoverse.manage',
+ capability: 'manageEidoverse',
+ name: 'Manage the private Eidoverse world',
+ description: 'Project PortOS resources, build bounded world content, manage local world roles, and speak as the persistent PortOS CoS identity.',
+ kind: 'semantic-tools',
+ defaultEnabled: false,
+ guardrails: [
+ 'Applies only to this install\'s machine-local private Eidoverse world',
+ 'Uses the bounded Eidoverse operation schemas; no arbitrary runtime behavior, shell, filesystem, or source mutation',
+ 'Independent of generic PortOS record writes and disabled for fresh and upgraded installs',
+ ],
+ }),
Object.freeze({
id: 'mind.cleanup',
capability: 'manageMind',
@@ -129,7 +142,7 @@ export const PERSISTENT_MIND_TOOL_CATALOG = Object.freeze([
export const PERSISTENT_MIND_TOOL_BOUNDARIES = Object.freeze([
'No arbitrary shell or file-system access',
- "No raw HTTP proxy, browser controls, process control, or paid generation, and no external messaging except the granted voice.call-user action to the user's own configured handle",
+ "No raw HTTP proxy, browser controls, process control, or paid generation, and no external messaging except the granted voice.call-user action to the user's own configured handle or the granted install-local eidoverse.say action",
'No provider credentials or hidden reasoning tokens are exposed as tools',
]);
@@ -228,6 +241,7 @@ export function createDefaultPersistentMindCapabilities() {
schemaVersion: PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,
createTasks: false,
manageMind: false,
+ manageEidoverse: false,
callUser: false,
readPortos: false,
writePortos: false,
diff --git a/server/lib/persistentMindCapabilities.test.js b/server/lib/persistentMindCapabilities.test.js
index 6ae2f3eda2..5e34e0098b 100644
--- a/server/lib/persistentMindCapabilities.test.js
+++ b/server/lib/persistentMindCapabilities.test.js
@@ -18,6 +18,7 @@ describe('persistent mind capabilities', () => {
expect.objectContaining({ id: 'cos.create-task', capability: 'createTasks', defaultEnabled: false }),
expect.objectContaining({ id: 'portos.read', capability: 'readPortos', defaultEnabled: false }),
expect.objectContaining({ id: 'portos.write', capability: 'writePortos', defaultEnabled: false }),
+ expect.objectContaining({ id: 'eidoverse.manage', capability: 'manageEidoverse', defaultEnabled: false }),
expect.objectContaining({ id: 'mind.cleanup', capability: 'manageMind', defaultEnabled: false }),
expect.objectContaining({ id: 'voice.call-user', capability: 'callUser', kind: 'typed-action', defaultEnabled: false }),
]);
@@ -32,22 +33,23 @@ describe('persistent mind capabilities', () => {
});
it('keeps task creation opt-in across fresh and legacy config', () => {
- expect(createDefaultPersistentMindCapabilities()).toMatchObject({ createTasks: false, manageMind: false, callUser: false, readPortos: false, writePortos: false });
+ expect(createDefaultPersistentMindCapabilities()).toMatchObject({ createTasks: false, manageMind: false, manageEidoverse: false, callUser: false, readPortos: false, writePortos: false });
// An install upgrading with the mind already running must gain no new
// authority: stored config that predates the grant reads as false.
expect(normalizePersistentMindCapabilities({ schemaVersion: 3, createTasks: true })).toMatchObject({ callUser: false });
- expect(normalizePersistentMindCapabilities(null)).toMatchObject({ createTasks: false, manageMind: false, callUser: false, readPortos: false, writePortos: false });
+ expect(normalizePersistentMindCapabilities(null)).toMatchObject({ createTasks: false, manageMind: false, manageEidoverse: false, callUser: false, readPortos: false, writePortos: false });
expect(normalizePersistentMindCapabilities({ createTasks: 'true', readPortos: 'true' })).toMatchObject({ createTasks: false, readPortos: false });
});
it('validates and merges the explicit task-creation grant', () => {
- expect(persistentMindCapabilitiesSchema.safeParse({ createTasks: true, manageMind: true, readPortos: true, writePortos: false }).success).toBe(true);
+ expect(persistentMindCapabilitiesSchema.safeParse({ createTasks: true, manageMind: true, manageEidoverse: true, readPortos: true, writePortos: false }).success).toBe(true);
expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 2, createTasks: true }).success).toBe(true);
expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 3, callUser: true }).success).toBe(true);
- expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 5 }).success).toBe(false);
+ expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 5 }).success).toBe(true);
+ expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 6 }).success).toBe(false);
expect(persistentMindCapabilitiesSchema.safeParse({ taskModelAllowlist: [{ providerId: 'ollama', model: 'example-local' }] }).success).toBe(true);
expect(normalizePersistentMindCapabilities({ schemaVersion: 2, createTasks: true }))
- .toMatchObject({ schemaVersion: 4, createTasks: true, manageMind: false, callUser: false });
+ .toMatchObject({ schemaVersion: 5, createTasks: true, manageMind: false, manageEidoverse: false, callUser: false });
expect(persistentMindCapabilitiesSchema.safeParse({ allowedAppIds: ['example-app', 'second-app'] }).success).toBe(true);
expect(persistentMindCapabilitiesSchema.safeParse({ allowedAppIds: Array.from({ length: 51 }, (_, index) => `app-${index}`) }).success).toBe(false);
expect(persistentMindCapabilitiesSchema.safeParse({ createTasks: true, shell: true }).success).toBe(false);
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 10f9456c35..3163f73093 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -800,6 +800,173 @@ export const instanceFeatureUpdateSchema = z.object({
enabled: z.boolean(),
}).strict();
+// =============================================================================
+// EIDOVERSE WORLD PROJECTION
+// =============================================================================
+
+// Eidoverse identities are currently name-based when no archipelago session is
+// present. Keep the PortOS-side contract deliberately conservative: names and
+// ids are durable world keys, while display metadata stays in the private
+// world log and never becomes a federation payload.
+const eidoverseWorldNameSchema = z.string().trim().min(1).max(64).regex(
+ /^[a-z0-9_-]+$/i,
+ 'must contain only letters, numbers, hyphens, and underscores',
+);
+const eidoverseIdentitySchema = z.string().trim().min(1).max(64).regex(
+ /^[^\u0000-\u001f\u007f]+$/,
+ 'must not contain control characters',
+);
+const eidoverseVector3Schema = z.array(z.number().finite()).length(3);
+const eidoverseAssetPathSchema = z.string().trim().min(1).max(512).refine((value) => {
+ const normalized = value.replaceAll('\\', '/');
+ return !normalized.startsWith('/')
+ && !normalized.includes('..')
+ && (/^eidoverse\//i.test(normalized) || /^store\//i.test(normalized));
+}, 'must be a relative Eidoverse library or store asset path');
+
+// These are the resource lanes that the deterministic PortOS projection may
+// materialize. Keep the list explicit: a recipe must opt into known data
+// families rather than accepting an arbitrary source key that the service
+// would not know how to sanitize.
+export const EIDOVERSE_PROJECTION_SOURCE_KEYS = Object.freeze([
+ 'apps',
+ 'agents',
+ 'tasks',
+ 'features',
+ 'peers',
+ 'health',
+ 'productivity',
+ 'activity',
+ 'goals',
+ 'memory',
+ 'storage',
+ 'jira',
+ 'operations',
+]);
+
+const eidoverseProjectionIncludesSchema = z.object({
+ apps: z.boolean(),
+ agents: z.boolean(),
+ tasks: z.boolean(),
+ features: z.boolean(),
+ peers: z.boolean(),
+ health: z.boolean(),
+ productivity: z.boolean(),
+ activity: z.boolean(),
+ goals: z.boolean(),
+ memory: z.boolean(),
+ storage: z.boolean(),
+ jira: z.boolean(),
+ operations: z.boolean(),
+}).strict();
+
+const eidoverseProjectionAssetsSchema = z.object({
+ app: eidoverseAssetPathSchema,
+ agent: eidoverseAssetPathSchema,
+ task: eidoverseAssetPathSchema,
+ feature: eidoverseAssetPathSchema,
+ peer: eidoverseAssetPathSchema,
+ health: eidoverseAssetPathSchema,
+ productivity: eidoverseAssetPathSchema,
+ activity: eidoverseAssetPathSchema,
+ goal: eidoverseAssetPathSchema,
+ memory: eidoverseAssetPathSchema,
+ storage: eidoverseAssetPathSchema,
+ jira: eidoverseAssetPathSchema,
+ operations: eidoverseAssetPathSchema,
+}).strict();
+
+const eidoverseProjectionTerrainLayerSchema = z.object({
+ color: z.string().trim().min(1).max(32),
+ repeat: z.number().finite().positive().max(128),
+}).strict();
+
+const eidoverseProjectionTerrainSchema = z.object({
+ seed: z.string().trim().min(1).max(64),
+ size: z.number().finite().positive().max(512),
+ segments: z.number().int().min(2).max(512),
+ amplitude: z.number().finite().min(0).max(100),
+ flatRadius: z.number().finite().min(0).max(256),
+ layers: z.array(eidoverseProjectionTerrainLayerSchema).max(8),
+}).strict();
+
+export const eidoverseProjectionRecipeSchema = z.object({
+ version: z.literal(1),
+ includes: eidoverseProjectionIncludesSchema,
+ limits: z.object({
+ apps: z.number().int().min(0).max(100),
+ agents: z.number().int().min(0).max(100),
+ tasks: z.number().int().min(0).max(100),
+ features: z.number().int().min(0).max(100),
+ peers: z.number().int().min(0).max(100),
+ health: z.number().int().min(0).max(100),
+ productivity: z.number().int().min(0).max(100),
+ activity: z.number().int().min(0).max(100),
+ goals: z.number().int().min(0).max(100),
+ memory: z.number().int().min(0).max(100),
+ storage: z.number().int().min(0).max(100),
+ jira: z.number().int().min(0).max(100),
+ operations: z.number().int().min(0).max(100),
+ }).strict(),
+ layout: z.object({
+ origin: eidoverseVector3Schema,
+ spacing: z.number().finite().min(2).max(100),
+ laneGap: z.number().finite().min(2).max(100),
+ columns: z.number().int().min(1).max(32),
+ }).strict(),
+ scale: z.object({
+ app: z.number().finite().positive().max(20),
+ agent: z.number().finite().positive().max(20),
+ task: z.number().finite().positive().max(20),
+ feature: z.number().finite().positive().max(20),
+ peer: z.number().finite().positive().max(20),
+ health: z.number().finite().positive().max(20),
+ productivity: z.number().finite().positive().max(20),
+ activity: z.number().finite().positive().max(20),
+ goal: z.number().finite().positive().max(20),
+ memory: z.number().finite().positive().max(20),
+ storage: z.number().finite().positive().max(20),
+ jira: z.number().finite().positive().max(20),
+ operations: z.number().finite().positive().max(20),
+ }).strict(),
+ assets: eidoverseProjectionAssetsSchema,
+ terrain: eidoverseProjectionTerrainSchema,
+}).strict();
+
+// This is intentionally an opaque, bounded argument bag at the HTTP boundary.
+// The PortOS service applies the narrower verb-specific checks immediately
+// before sending it to Eidoverse, which keeps this public schema forward-
+// compatible with the external world's evolving component vocabulary without
+// accepting unbounded payloads.
+const eidoverseAugmentArgsSchema = z.record(z.string().max(80), z.unknown()).superRefine((value, ctx) => {
+ if (JSON.stringify(value).length > 8192) {
+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: 'arguments must be at most 8KB' });
+ }
+});
+
+export const EIDOVERSE_AUGMENT_VERBS = ['spawn', 'place', 'remove', 'comp', 'light', 'terrain', 'grass', 'sky', 'grant'];
+
+export const eidoverseWorldAugmentSchema = z.object({
+ operations: z.array(z.object({
+ verb: z.enum(EIDOVERSE_AUGMENT_VERBS),
+ args: eidoverseAugmentArgsSchema,
+ }).strict()).min(1).max(100),
+}).strict();
+
+export const eidoverseWorldSaySchema = z.object({
+ text: z.string().trim().min(1).max(2000),
+}).strict();
+
+export const eidoverseWorldConfigPatchSchema = z.object({
+ world: eidoverseWorldNameSchema.optional(),
+ humanName: eidoverseIdentitySchema.nullable().optional(),
+ humanAvatar: eidoverseAssetPathSchema.nullable().optional(),
+ cosId: eidoverseIdentitySchema.optional(),
+ cosAvatar: eidoverseAssetPathSchema.nullable().optional(),
+ cosEnabled: z.boolean().optional(),
+ recipe: eidoverseProjectionRecipeSchema.optional(),
+}).strict();
+
export const subdirFilterSchema = z.string()
.refine(isSafeSubdirFilter, 'subdirFilter must be a relative path with no wildcard, ".." , or leading "/" segments');
diff --git a/server/routes/agentContextMcp.test.js b/server/routes/agentContextMcp.test.js
index b61f835f47..9fb444d35b 100644
--- a/server/routes/agentContextMcp.test.js
+++ b/server/routes/agentContextMcp.test.js
@@ -28,7 +28,7 @@ const enabledManifest = {
configurationValid: true,
profile: 'metadata',
scopes: ['navigation', 'workspaces'],
- actions: { readPortos: false, writePortos: false },
+ actions: { readPortos: false, writePortos: false, manageEidoverse: false },
tools: [{ name: 'context_profile', inputSchema: { type: 'object' } }],
};
@@ -105,7 +105,7 @@ describe('agentContextMcp route', () => {
enabled: true,
profile: 'metadata',
scopes: ['navigation', 'workspaces'],
- actions: { readPortos: false, writePortos: false },
+ actions: { readPortos: false, writePortos: false, manageEidoverse: false },
},
}, {
requestId: expect.stringMatching(/^agent-mcp:/),
diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.js
index 524c1e1a54..d95ff134bf 100644
--- a/server/routes/cosMindRoutes.test.js
+++ b/server/routes/cosMindRoutes.test.js
@@ -184,7 +184,7 @@ describe('persistent mind routes', () => {
thinkingInterface: 'text',
wakeIntervalMinutes: 30,
},
- capabilities: { schemaVersion: 4, createTasks: true, manageMind: false, callUser: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },
+ capabilities: { schemaVersion: 5, createTasks: true, manageMind: false, manageEidoverse: false, callUser: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },
harness: { type: 'api', recommendation: 'recommended' },
imageCapability: { status: 'unknown' },
autonomyMode: 'execute',
@@ -218,8 +218,8 @@ describe('persistent mind routes', () => {
const res = await get('/mind/tools');
expect(res.status).toBe(200);
expect(res.body).toMatchObject({
- schemaVersion: 4,
- capabilities: { schemaVersion: 4, createTasks: true, manageMind: false, callUser: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },
+ schemaVersion: 5,
+ capabilities: { schemaVersion: 5, createTasks: true, manageMind: false, manageEidoverse: false, callUser: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },
boundaries: expect.arrayContaining([expect.stringMatching(/arbitrary shell/i)]),
tools: expect.arrayContaining([
expect.objectContaining({ id: 'cos.create-task', capability: 'createTasks', granted: true, defaultEnabled: false }),
diff --git a/server/routes/eidoverseWorldRoutes.js b/server/routes/eidoverseWorldRoutes.js
new file mode 100644
index 0000000000..400e10f60c
--- /dev/null
+++ b/server/routes/eidoverseWorldRoutes.js
@@ -0,0 +1,68 @@
+/**
+ * PortOS-owned Eidoverse world controls.
+ *
+ * The hosted Eidoverse client remains the renderer. These routes own the
+ * install-local identity, projection recipe, deterministic projection, and
+ * the narrow set of world operations that PortOS is allowed to submit.
+ */
+
+import { Router } from 'express';
+import { asyncHandler } from '../lib/errorHandler.js';
+import {
+ eidoverseWorldAugmentSchema,
+ eidoverseWorldConfigPatchSchema,
+ eidoverseWorldSaySchema,
+ validateRequest,
+} from '../lib/validation.js';
+import {
+ augmentEidoverseWorld,
+ ensureEidoverseWorldPresence,
+ getEidoverseWorldStatus,
+ projectEidoverseWorld,
+ sayInEidoverseWorld,
+ updateEidoverseWorldConfig,
+} from '../services/eidoverseWorld.js';
+
+const router = Router();
+
+// GET /api/eidoverse/world/status — install-local identity, recipe, and
+// runtime/presence state for the hosted world page.
+router.get('/status', asyncHandler(async (_req, res) => {
+ res.json(await getEidoverseWorldStatus());
+}));
+
+// PUT /api/eidoverse/world/config — persist the human/CoS identity and
+// deterministic PortOS projection recipe for this install.
+router.put('/config', asyncHandler(async (req, res) => {
+ const patch = validateRequest(eidoverseWorldConfigPatchSchema, req.body || {});
+ res.json({ success: true, ...(await updateEidoverseWorldConfig(patch)) });
+}));
+
+// POST /api/eidoverse/world/presence — establish the persistent CoS agent
+// presence without requiring a browser tab to remain open.
+router.post('/presence', asyncHandler(async (_req, res) => {
+ res.json(await ensureEidoverseWorldPresence());
+}));
+
+// POST /api/eidoverse/world/project — refresh the world from live PortOS
+// resources using the saved recipe. This is deterministic and makes no AI
+// provider call.
+router.post('/project', asyncHandler(async (_req, res) => {
+ res.json(await projectEidoverseWorld());
+}));
+
+// POST /api/eidoverse/world/augment — apply bounded, allowlisted world verbs
+// for manual or CoS-authored augmentation.
+router.post('/augment', asyncHandler(async (req, res) => {
+ const { operations } = validateRequest(eidoverseWorldAugmentSchema, req.body || {});
+ res.json(await augmentEidoverseWorld(operations));
+}));
+
+// POST /api/eidoverse/world/say — persist a PortOS/CoS message in the world
+// chat through the same authoritative world protocol.
+router.post('/say', asyncHandler(async (req, res) => {
+ const { text } = validateRequest(eidoverseWorldSaySchema, req.body || {});
+ res.json(await sayInEidoverseWorld(text));
+}));
+
+export default router;
diff --git a/server/routes/eidoverseWorldRoutes.test.js b/server/routes/eidoverseWorldRoutes.test.js
new file mode 100644
index 0000000000..8bc4051a27
--- /dev/null
+++ b/server/routes/eidoverseWorldRoutes.test.js
@@ -0,0 +1,77 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+const mocks = vi.hoisted(() => ({
+ augment: vi.fn(),
+ ensurePresence: vi.fn(),
+ getStatus: vi.fn(),
+ project: vi.fn(),
+ say: vi.fn(),
+ updateConfig: vi.fn(),
+}));
+
+vi.mock('../services/eidoverseWorld.js', () => ({
+ augmentEidoverseWorld: mocks.augment,
+ ensureEidoverseWorldPresence: mocks.ensurePresence,
+ getEidoverseWorldStatus: mocks.getStatus,
+ projectEidoverseWorld: mocks.project,
+ sayInEidoverseWorld: mocks.say,
+ updateEidoverseWorldConfig: mocks.updateConfig,
+}));
+
+const { default: eidoverseWorldRoutes } = await import('./eidoverseWorldRoutes.js');
+
+const makeApp = () => {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/eidoverse/world', eidoverseWorldRoutes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+describe('Eidoverse world routes', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getStatus.mockResolvedValue({ world: 'portos', identity: { name: 'example-user' } });
+ mocks.updateConfig.mockResolvedValue({ world: 'portos', human: { name: 'example-user' } });
+ mocks.ensurePresence.mockResolvedValue({ connected: true, role: 'owner' });
+ mocks.project.mockResolvedValue({ success: true, summary: { operationCount: 0 } });
+ mocks.augment.mockResolvedValue({ success: true, applied: 1 });
+ mocks.say.mockResolvedValue({ success: true });
+ });
+
+ it('returns private world status from the service boundary', async () => {
+ const res = await request(makeApp()).get('/api/eidoverse/world/status');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({ world: 'portos', identity: { name: 'example-user' } });
+ expect(mocks.getStatus).toHaveBeenCalledOnce();
+ });
+
+ it('validates and persists a configuration patch', async () => {
+ const res = await request(makeApp()).put('/api/eidoverse/world/config').send({ humanName: 'Example User' });
+ expect(res.status).toBe(200);
+ expect(mocks.updateConfig).toHaveBeenCalledWith({ humanName: 'Example User' });
+ });
+
+ it('rejects verbs outside the bounded augmentation contract', async () => {
+ const res = await request(makeApp()).post('/api/eidoverse/world/augment').send({
+ operations: [{ verb: 'behavior', args: {} }],
+ });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('VALIDATION_ERROR');
+ expect(mocks.augment).not.toHaveBeenCalled();
+ });
+
+ it('passes valid augmentation and chat requests to the service', async () => {
+ const operations = [{ verb: 'spawn', args: { id: 'example-prop', lib: 'eidoverse/assets/models/example.glb' } }];
+ const augmentResponse = await request(makeApp()).post('/api/eidoverse/world/augment').send({ operations });
+ const sayResponse = await request(makeApp()).post('/api/eidoverse/world/say').send({ text: 'Example message' });
+
+ expect(augmentResponse.status).toBe(200);
+ expect(mocks.augment).toHaveBeenCalledWith(operations);
+ expect(sayResponse.status).toBe(200);
+ expect(mocks.say).toHaveBeenCalledWith('Example message');
+ });
+});
diff --git a/server/services/agentContextMcp.test.js b/server/services/agentContextMcp.test.js
index 6ce6589335..ebdcbe1393 100644
--- a/server/services/agentContextMcp.test.js
+++ b/server/services/agentContextMcp.test.js
@@ -77,8 +77,8 @@ describe('agentContextMcp service', () => {
expect(manifest.scopes).toEqual(['navigation', 'workspaces']);
expect(manifest.transport).toMatchObject({ loopbackOnly: true, stateful: false });
expect(manifest).toMatchObject({
- schemaVersion: 3,
- actions: { readPortos: false, writePortos: false },
+ schemaVersion: 4,
+ actions: { readPortos: false, writePortos: false, manageEidoverse: false },
limits: { maxApproxTokens: 5_000 },
});
expect(manifest.exclusions.join(' ')).toMatch(/Privacy Vault/);
@@ -95,7 +95,7 @@ describe('agentContextMcp service', () => {
agentContext: {
enabled: true,
scopes: ['navigation'],
- actions: { readPortos: true, writePortos: false },
+ actions: { readPortos: true, writePortos: false, manageEidoverse: true },
},
};
const manifest = await getAgentContextManifest();
@@ -105,7 +105,10 @@ describe('agentContextMcp service', () => {
expect(result.isError).toBeUndefined();
expect(mocks.executeCosToolCall).toHaveBeenCalledWith(expect.objectContaining({
call: expect.objectContaining({ requestId: 'agent-mcp:test', name: 'brain.search' }),
- authority: { scope: 'agent', capabilities: { readPortos: true, writePortos: false } },
+ authority: {
+ scope: 'agent',
+ capabilities: { readPortos: true, writePortos: false, manageEidoverse: true },
+ },
}));
});
diff --git a/server/services/autonomousJobs/defaults.js b/server/services/autonomousJobs/defaults.js
index 601b8c554b..e400030b08 100644
--- a/server/services/autonomousJobs/defaults.js
+++ b/server/services/autonomousJobs/defaults.js
@@ -224,6 +224,22 @@ Phase 4 — Report:
createdAt: null,
updatedAt: null
},
+ {
+ id: 'job-eidoverse-projection',
+ name: 'Eidoverse PortOS World Projection',
+ description: 'Project current PortOS apps, agents, tasks, features, peers, productivity, goals, memory summaries, storage, Jira, operations, and health into the private Eidoverse world. Deterministic and does not call an AI provider.',
+ category: 'eidoverse-projection',
+ interval: 'custom',
+ intervalMs: 15 * 60 * 1000,
+ enabled: false,
+ priority: 'LOW',
+ type: 'script',
+ scriptHandler: 'eidoverse-projection',
+ lastRun: null,
+ runCount: 0,
+ createdAt: null,
+ updatedAt: null
+ },
{
id: 'job-agent-data-cleanup',
name: 'Agent Data Cleanup',
diff --git a/server/services/autonomousJobs/scriptHandlers.js b/server/services/autonomousJobs/scriptHandlers.js
index 9414f79839..2c5f6b38c7 100644
--- a/server/services/autonomousJobs/scriptHandlers.js
+++ b/server/services/autonomousJobs/scriptHandlers.js
@@ -18,6 +18,14 @@ import { getActiveAgentIds } from '../agentState.js'
import { runSelfDiagnostics } from './selfDiagnostics.js'
import { runBrainParitySweep } from './brainParitySweep.js'
+// Loaded lazily to keep the built-in handler registry free of an import cycle:
+// the projection reads CoS state, while this registry is loaded by the CoS job
+// store itself. The job remains deterministic and makes no provider call.
+async function eidoverseProjection() {
+ const { projectEidoverseWorld } = await import('../eidoverseWorld.js')
+ return projectEidoverseWorld()
+}
+
/**
* Run the moltworld-explore.mjs script as a child process (no AI agent needed).
* Returns a summary object when the script exits.
@@ -148,11 +156,12 @@ const SCRIPT_HANDLERS = {
// Federation brain-parity sweep (#4519): audits every federating peer for
// record-level divergence the cursor-based sync cycle cannot see. Default
// job ships disabled — deterministic, no LLM calls.
- 'brain-parity-sweep': runBrainParitySweep
+ 'brain-parity-sweep': runBrainParitySweep,
+ 'eidoverse-projection': eidoverseProjection
// 'layered-intelligence' retired here (#2322): LI is now a per-app scheduled
// task, not a global autonomous-job sweep. It runs as a normal reasoning agent
// with programmatic-I/O hooks — see taskTypeHooks.js +
// autonomousJobs/layeredIntelligenceHooks.js.
}
-export { runMoltworldExploration, agentDataCleanup, SCRIPT_HANDLERS }
+export { runMoltworldExploration, agentDataCleanup, eidoverseProjection, SCRIPT_HANDLERS }
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index c380d3a8e3..c0943e983a 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -83,7 +83,6 @@ import { startPrivacyRecheckScheduler } from './privacyRecheckScheduler.js';
import { startQuotaBurnScheduler } from './quotaBurnRunner.js';
import { startSeriesAutopilotScheduler } from './seriesAutopilotScheduler.js';
import { startCommissionScheduler } from './creativeCommissions/scheduler.js';
-import { startOpenWorldSnapshotScheduler } from './openWorldSnapshotScheduler.js';
import { startImessageScheduler } from './imessageScheduler.js';
import { startSignalScheduler } from './signalScheduler.js';
import { startSpotifyScheduler } from './spotifyScheduler.js';
@@ -400,9 +399,9 @@ const startBackgroundServices = ({ spawnerReady }) => {
backfillProjectCommissionIds,
startCommissionScheduler
});
- // Initialize OpenWorld snapshot scheduler — records periodic city-state frames
- // for the historical timeline scrubber (issue #877).
- startOpenWorldSnapshotScheduler().catch(err => console.error(`❌ OpenWorld snapshot scheduler init failed: ${err.message}`));
+ // OpenWorld's historical snapshot scheduler is retired with its UI. The
+ // legacy read/capture routes remain available for old clients, but Eidoverse
+ // is now the only automatic world projection path.
// Initialize iMessage sync scheduler — OFF by default; only polls chat.db when
// the user opts in from the iMessage Settings drawer on Comms → Messages → iMessage
// (needs macOS Full Disk Access) (#2151).
diff --git a/server/services/cosToolRegistry.js b/server/services/cosToolRegistry.js
index bd741ee3e0..6235452015 100644
--- a/server/services/cosToolRegistry.js
+++ b/server/services/cosToolRegistry.js
@@ -18,6 +18,10 @@ import {
persistentMindCleanupRequestSchema,
persistentMindTaskRequestSchema,
} from '../lib/persistentMindCapabilities.js';
+import {
+ eidoverseWorldAugmentSchema,
+ eidoverseWorldSaySchema,
+} from '../lib/validation.js';
import { dispatchTool, getToolSpecs, getToolSpecsForIntent } from './voice/tools.js';
import { executePersistentMindTaskRequests } from './persistentMindTaskCapability.js';
import { cleanupPersistentMind } from './persistentMindMaintenance.js';
@@ -135,7 +139,88 @@ const mindCleanupTool = Object.freeze({
adapter: { kind: 'persistent-mind-maintenance' },
});
-const toolCatalog = (intent) => [taskTool, mindCleanupTool, ...voiceTools(intent)];
+const eidoverseStatusTool = Object.freeze({
+ type: 'portos_tool',
+ name: 'eidoverse.status',
+ version: COS_TOOL_SCHEMA_VERSION,
+ providerName: 'eidoverse_status',
+ aliases: ['eidoverse_status'],
+ description: 'Read the private PortOS Eidoverse world identity, projection recipe, CoS presence, and setup state.',
+ input_schema: zodToOpenApiSchema(z.object({}).strict()),
+ output_schema: objectOutputSchema,
+ policy: {
+ scopes: ['agent', 'mind', 'ui', 'voice'],
+ requiredCapabilities: ['readPortos'],
+ sideEffect: 'read',
+ idempotent: true,
+ async: false,
+ confirmation: 'none',
+ },
+ adapter: { kind: 'eidoverse-world', operation: 'status' },
+});
+
+const eidoverseProjectTool = Object.freeze({
+ type: 'portos_tool',
+ name: 'eidoverse.project',
+ version: COS_TOOL_SCHEMA_VERSION,
+ providerName: 'eidoverse_project',
+ aliases: ['eidoverse_project'],
+ description: 'Synchronize current PortOS apps, agents, tasks, features, peers, productivity, goals, memory summaries, storage, Jira, operations, and health into the private Eidoverse world using its saved deterministic recipe.',
+ input_schema: zodToOpenApiSchema(z.object({}).strict()),
+ output_schema: objectOutputSchema,
+ policy: {
+ scopes: ['agent', 'mind', 'ui'],
+ requiredCapabilities: ['readPortos', 'manageEidoverse'],
+ sideEffect: 'write',
+ idempotent: true,
+ async: false,
+ confirmation: 'capability-grant',
+ },
+ adapter: { kind: 'eidoverse-world', operation: 'project' },
+});
+
+const eidoverseAugmentTool = Object.freeze({
+ type: 'portos_tool',
+ name: 'eidoverse.augment',
+ version: COS_TOOL_SCHEMA_VERSION,
+ providerName: 'eidoverse_augment',
+ aliases: ['eidoverse_augment'],
+ description: 'Apply bounded, allowlisted construction or role operations to the private Eidoverse world.',
+ input_schema: zodToOpenApiSchema(eidoverseWorldAugmentSchema),
+ output_schema: objectOutputSchema,
+ policy: {
+ scopes: ['agent', 'mind', 'ui'],
+ requiredCapabilities: ['manageEidoverse'],
+ sideEffect: 'write',
+ idempotent: false,
+ async: false,
+ confirmation: 'capability-grant',
+ },
+ adapter: { kind: 'eidoverse-world', operation: 'augment' },
+});
+
+const eidoverseSayTool = Object.freeze({
+ type: 'portos_tool',
+ name: 'eidoverse.say',
+ version: COS_TOOL_SCHEMA_VERSION,
+ providerName: 'eidoverse_say',
+ aliases: ['eidoverse_say'],
+ description: 'Send a message into the private Eidoverse world as the persistent PortOS CoS presence.',
+ input_schema: zodToOpenApiSchema(eidoverseWorldSaySchema),
+ output_schema: objectOutputSchema,
+ policy: {
+ scopes: ['agent', 'mind', 'ui'],
+ requiredCapabilities: ['manageEidoverse'],
+ sideEffect: 'write',
+ idempotent: false,
+ async: false,
+ confirmation: 'capability-grant',
+ },
+ adapter: { kind: 'eidoverse-world', operation: 'say' },
+});
+
+const eidoverseTools = [eidoverseStatusTool, eidoverseProjectTool, eidoverseAugmentTool, eidoverseSayTool];
+const toolCatalog = (intent) => [taskTool, mindCleanupTool, ...eidoverseTools, ...voiceTools(intent)];
const toolCalls = new Map();
const toolCallFingerprints = new Map();
@@ -271,6 +356,13 @@ const executeAdapter = async (tool, args, context) => {
preserveMessageId: context.wake?.kind === 'message' ? context.wake.message?.id || null : null,
});
}
+ if (tool.adapter.kind === 'eidoverse-world') {
+ const world = await import('./eidoverseWorld.js');
+ if (tool.adapter.operation === 'status') return world.getEidoverseWorldStatus();
+ if (tool.adapter.operation === 'project') return world.projectEidoverseWorld({ signal: context.signal });
+ if (tool.adapter.operation === 'augment') return world.augmentEidoverseWorld(args.operations, { signal: context.signal });
+ return world.sayInEidoverseWorld(args.text, { signal: context.signal });
+ }
const [outcome] = await executePersistentMindTaskRequests({
taskRequests: [args],
turnId: context.turnId,
diff --git a/server/services/cosToolRegistry.test.js b/server/services/cosToolRegistry.test.js
index b9bc0d3880..2bd3cab195 100644
--- a/server/services/cosToolRegistry.test.js
+++ b/server/services/cosToolRegistry.test.js
@@ -4,6 +4,10 @@ const mocks = vi.hoisted(() => ({
dispatch: vi.fn(),
executeTasks: vi.fn(),
cleanupMind: vi.fn(),
+ worldStatus: vi.fn(),
+ worldProject: vi.fn(),
+ worldAugment: vi.fn(),
+ worldSay: vi.fn(),
}));
const specs = [
@@ -44,6 +48,12 @@ vi.mock('./persistentMindTaskCapability.js', () => ({
vi.mock('./persistentMindMaintenance.js', () => ({
cleanupPersistentMind: (...args) => mocks.cleanupMind(...args),
}));
+vi.mock('./eidoverseWorld.js', () => ({
+ getEidoverseWorldStatus: (...args) => mocks.worldStatus(...args),
+ projectEidoverseWorld: (...args) => mocks.worldProject(...args),
+ augmentEidoverseWorld: (...args) => mocks.worldAugment(...args),
+ sayInEidoverseWorld: (...args) => mocks.worldSay(...args),
+}));
import {
__testing,
@@ -60,16 +70,30 @@ beforeEach(() => {
mocks.dispatch.mockResolvedValue({ ok: true });
mocks.executeTasks.mockResolvedValue([{ success: true, task: { id: 'task-1' }, duplicate: false }]);
mocks.cleanupMind.mockResolvedValue({ ok: true, success: true, state: 'completed', historyEventsCleared: 8 });
+ mocks.worldStatus.mockResolvedValue({ world: 'portos', presence: { connected: true } });
+ mocks.worldProject.mockResolvedValue({ success: true, summary: { operationCount: 2 } });
+ mocks.worldAugment.mockResolvedValue({ success: true, applied: 1 });
+ mocks.worldSay.mockResolvedValue({ success: true, world: 'portos' });
});
describe('cosToolRegistry', () => {
it('exports a compact canonical catalog and provider translations', () => {
const catalog = getCosToolCatalog({ scope: 'mind', capabilities: { readPortos: true } });
- expect(catalog.tools.map((tool) => tool.name)).toEqual(['cos.create-task', 'mind.cleanup', 'brain.search', 'brain.capture']);
+ expect(catalog.tools.map((tool) => tool.name)).toEqual([
+ 'cos.create-task',
+ 'mind.cleanup',
+ 'eidoverse.status',
+ 'eidoverse.project',
+ 'eidoverse.augment',
+ 'eidoverse.say',
+ 'brain.search',
+ 'brain.capture',
+ ]);
expect(catalog.tools.find((tool) => tool.name === 'brain.search').granted).toBe(true);
expect(catalog.tools.find((tool) => tool.name === 'brain.capture').granted).toBe(false);
const openai = formatCosToolCatalog(catalog, 'openai');
expect(openai.tools).toEqual([
+ expect.objectContaining({ type: 'function', function: expect.objectContaining({ name: 'eidoverse_status' }) }),
expect.objectContaining({ type: 'function', function: expect.objectContaining({ name: 'brain_search' }) }),
]);
const mcp = formatCosToolCatalog(catalog, 'mcp');
@@ -104,6 +128,62 @@ describe('cosToolRegistry', () => {
})).rejects.toMatchObject({ code: 'TOOL_CAPABILITY_DENIED' });
});
+ it('keeps private-world management separate from generic PortOS writes and propagates cancellation', async () => {
+ const signal = new AbortController().signal;
+ await expect(executeCosToolCall({
+ call: { requestId: 'world-status-denied', name: 'eidoverse.status', arguments: {} },
+ authority: { scope: 'mind', capabilities: { manageEidoverse: true } },
+ })).rejects.toMatchObject({ code: 'TOOL_CAPABILITY_DENIED' });
+ await expect(executeCosToolCall({
+ call: { requestId: 'world-project-write-only', name: 'eidoverse.project', arguments: {} },
+ authority: { scope: 'mind', capabilities: { readPortos: true, writePortos: true } },
+ })).rejects.toMatchObject({ code: 'TOOL_CAPABILITY_DENIED' });
+
+ const status = await executeCosToolCall({
+ call: { requestId: 'world-status', name: 'eidoverse.status', arguments: {} },
+ authority: { scope: 'mind', capabilities: { readPortos: true } },
+ context: { signal },
+ });
+ const project = await executeCosToolCall({
+ call: { requestId: 'world-project', name: 'eidoverse.project', arguments: {} },
+ authority: { scope: 'mind', capabilities: { readPortos: true, manageEidoverse: true } },
+ context: { signal },
+ });
+ const augment = await executeCosToolCall({
+ call: {
+ requestId: 'world-augment',
+ name: 'eidoverse.augment',
+ arguments: { operations: [{ verb: 'spawn', args: { id: 'example', lib: 'eidoverse/assets/example.glb' } }] },
+ },
+ authority: { scope: 'mind', capabilities: { manageEidoverse: true } },
+ context: { signal },
+ });
+ const say = await executeCosToolCall({
+ call: { requestId: 'world-say', name: 'eidoverse.say', arguments: { text: 'Example message' } },
+ authority: { scope: 'mind', capabilities: { manageEidoverse: true } },
+ context: { signal },
+ });
+ const agentAugment = await executeCosToolCall({
+ call: {
+ requestId: 'agent-world-augment',
+ name: 'eidoverse.augment',
+ arguments: { operations: [{ verb: 'remove', args: { id: 'example' } }] },
+ },
+ authority: { scope: 'agent', capabilities: { manageEidoverse: true } },
+ context: { signal },
+ });
+
+ expect([status.state, project.state, augment.state, say.state, agentAugment.state])
+ .toEqual(['completed', 'completed', 'completed', 'completed', 'completed']);
+ expect(mocks.worldStatus).toHaveBeenCalledWith();
+ expect(mocks.worldProject).toHaveBeenCalledWith({ signal });
+ expect(mocks.worldAugment).toHaveBeenCalledWith(
+ [{ verb: 'spawn', args: { id: 'example', lib: 'eidoverse/assets/example.glb' } }],
+ { signal },
+ );
+ expect(mocks.worldSay).toHaveBeenCalledWith('Example message', { signal });
+ });
+
it('executes cleanup only with the dedicated mind capability and preserves current provenance', async () => {
const signal = new AbortController().signal;
const call = { requestId: 'cleanup-1', name: 'mind.cleanup', arguments: { scopes: ['history'], reason: 'Stale failures' } };
diff --git a/server/services/eidoverseWorld.js b/server/services/eidoverseWorld.js
new file mode 100644
index 0000000000..4b54fb96ef
--- /dev/null
+++ b/server/services/eidoverseWorld.js
@@ -0,0 +1,1821 @@
+/**
+ * PortOS-owned Eidoverse world integration.
+ *
+ * Eidoverse owns the append-only world log and its derived snapshot. PortOS
+ * owns the install-local identity/configuration that decides who enters the
+ * world and how PortOS resources are projected into it. The projection is
+ * deterministic and uses the Eidoverse world protocol; it never edits the
+ * external checkout or calls an AI provider.
+ */
+
+import { createHash } from 'node:crypto';
+import { statfs } from 'node:fs/promises';
+import { join } from 'node:path';
+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 { getAllApps, getAppStatuses } from './apps.js';
+import { getStatus as getCosStatus, getAgents, getCosTasks, getTodayActivity } from './cos.js';
+import { getPendingCounts } from './review.js';
+import { getSelf, getPeers, ensureSelf } from './instances.js';
+import { getInstanceFeatures } from './instanceFeatures.js';
+import * as backup from './backup.js';
+import { getCountsByType } from './notifications.js';
+import { getCharacter } from './character.js';
+import { getLatestMetricValues } from './appleHealthQuery.js';
+import { getVoiceConfig } from './voice/config.js';
+import { getMemoryStats } from '../lib/memoryStats.js';
+import { getGoals, getChronotype } from './identity.js';
+import { getActivityCalendar, getVelocityMetrics } from './productivity.js';
+import { getBrainGraphOverview } from './brainGraph.js';
+import { getInboxLogCounts } from './brainStorage.js';
+import { getOpenWorldIntrospection } from './openWorldIntrospection.js';
+import { fetchMyCurrentSprintTickets } from './jira.js';
+import { getEidoverseStatus, EIDOVERSE_PORT } from './eidoverse.js';
+
+const DATA_DIR = dataPath('eidoverse');
+const STATE_FILE = join(DATA_DIR, 'portos-world.json');
+const WORLD_NAME_RE = /^[a-z0-9_-]{1,64}$/i;
+const ENTITY_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
+const COMPONENT_TYPE_RE = /^[A-Za-z0-9._:-]{1,32}$/;
+const ASSET_PATH_RE = /^(?:eidoverse|store)\//i;
+const PROJECTION_ID_PREFIX = 'portos-projection-';
+const COMPONENT_TYPE = 'portos';
+const COMPONENT_RESOURCE_BY_KIND = Object.freeze({
+ app: 'apps',
+ agent: 'agents',
+ task: 'tasks',
+ feature: 'features',
+ peer: 'peers',
+ health: 'health',
+ productivity: 'productivity',
+ activity: 'activity',
+ goal: 'goals',
+ memory: 'memory',
+ storage: 'storage',
+ jira: 'jira',
+ operations: 'operations',
+});
+const DEFAULT_WORLD = 'portos';
+const DEFAULT_HUMAN_AVATAR = 'eidoverse/assets/vrms/claude.vrm';
+const DEFAULT_COS_ID = 'portos-cos';
+const DEFAULT_COS_AVATAR = 'eidoverse/assets/vrms/claude_suit.vrm';
+const PROJECTION_VERB_INTERVAL_MS = 350;
+const WORLD_ROLES = new Set(['owner', 'builder', 'visitor']);
+
+const MODEL_ROOT = 'eidoverse/assets/models/';
+const HEALTH_METRIC_KEYS = ['heart_rate', 'step_count', 'active_energy', 'sleep_analysis'];
+
+export const DEFAULT_EIDOVERSE_PROJECTION_RECIPE = Object.freeze({
+ version: 1,
+ includes: {
+ apps: true,
+ agents: true,
+ tasks: true,
+ features: true,
+ peers: true,
+ health: true,
+ productivity: true,
+ activity: true,
+ goals: true,
+ memory: true,
+ storage: true,
+ jira: true,
+ operations: true,
+ },
+ limits: {
+ apps: 48,
+ agents: 24,
+ tasks: 48,
+ features: 32,
+ peers: 16,
+ health: 1,
+ productivity: 1,
+ activity: 24,
+ goals: 32,
+ memory: 16,
+ storage: 48,
+ jira: 48,
+ operations: 1,
+ },
+ layout: {
+ origin: [-24, 0, -24],
+ spacing: 7,
+ // Keep the expanded resource lanes compact enough to stay near the
+ // authored terrain while still leaving a visible gap between families.
+ laneGap: 6,
+ columns: 8,
+ },
+ scale: {
+ app: 1,
+ agent: 1,
+ task: 0.8,
+ feature: 1,
+ peer: 1.2,
+ health: 1.2,
+ productivity: 1.2,
+ activity: 0.55,
+ goal: 1.1,
+ memory: 0.9,
+ storage: 0.8,
+ jira: 0.75,
+ operations: 1.3,
+ },
+ assets: {
+ app: `${MODEL_ROOT}computer_servers_rack_with_fans_on_back_row_of_four_4_columns.glb`,
+ agent: `${MODEL_ROOT}scifi_quad_small_drone_blue.glb`,
+ task: `${MODEL_ROOT}scifi_cyberpunk_intermodal_shipping_container_crate_blue.glb`,
+ feature: `${MODEL_ROOT}inanna_tech_cyber_scifi_sphere_orb.glb`,
+ peer: `${MODEL_ROOT}modern_sedan_car_blue_vehicle_generic.glb`,
+ health: `${MODEL_ROOT}inanna_tech_cyber_scifi_sumerian_retrofuturist_vehicle_car_light.glb`,
+ productivity: `${MODEL_ROOT}inanna_tech_cyber_scifi_sumerian_retrofuturist_vehicle_car_light.glb`,
+ activity: `${MODEL_ROOT}inanna_tech_cyber_scifi_sphere_orb.glb`,
+ goal: `${MODEL_ROOT}inanna_tech_cyber_scifi_sphere_orb.glb`,
+ memory: `${MODEL_ROOT}inanna_tech_cyber_scifi_sphere_orb.glb`,
+ storage: `${MODEL_ROOT}computer_servers_rack_with_fans_on_back_row_of_four_4_columns.glb`,
+ jira: `${MODEL_ROOT}scifi_cyberpunk_intermodal_shipping_container_crate_blue.glb`,
+ operations: `${MODEL_ROOT}inanna_tech_cyber_scifi_sumerian_retrofuturist_vehicle_car_light.glb`,
+ },
+ terrain: {
+ seed: 'portos',
+ size: 128,
+ segments: 64,
+ amplitude: 1.8,
+ flatRadius: 28,
+ layers: [
+ { color: '#142338', repeat: 18 },
+ { color: '#1c3b43', repeat: 10 },
+ ],
+ },
+});
+
+const DEFAULT_STATE = {
+ schemaVersion: 1,
+ world: DEFAULT_WORLD,
+ human: {
+ name: null,
+ avatar: DEFAULT_HUMAN_AVATAR,
+ source: null,
+ role: null,
+ },
+ cos: {
+ id: DEFAULT_COS_ID,
+ avatar: DEFAULT_COS_AVATAR,
+ enabled: true,
+ role: null,
+ },
+ ownership: {
+ retired: [],
+ },
+ recipe: DEFAULT_EIDOVERSE_PROJECTION_RECIPE,
+ projection: {
+ lastRunAt: null,
+ lastSuccessAt: null,
+ lastError: null,
+ lastSummary: null,
+ },
+};
+
+const stateLock = createMutex();
+const worldLock = createMutex();
+let cosPresence = null;
+
+const clone = (value) => structuredClone(value);
+
+function abortError(signal) {
+ return signal?.reason instanceof Error
+ ? signal.reason
+ : new DOMException(String(signal?.reason || 'The Eidoverse operation was canceled.'), 'AbortError');
+}
+
+function throwIfAborted(signal) {
+ if (signal?.aborted) throw abortError(signal);
+}
+
+function waitWithSignal(promise, signal) {
+ if (!signal) return promise;
+ throwIfAborted(signal);
+ return new Promise((resolve, reject) => {
+ let settled = false;
+ const finish = (callback, value) => {
+ if (settled) return;
+ settled = true;
+ signal.removeEventListener('abort', onAbort);
+ callback(value);
+ };
+ const onAbort = () => finish(reject, abortError(signal));
+ signal.addEventListener('abort', onAbort, { once: true });
+ Promise.resolve(promise).then(
+ (value) => finish(resolve, value),
+ (error) => finish(reject, error),
+ );
+ });
+}
+
+function abortableDelay(ms, signal) {
+ if (!signal) return new Promise((resolve) => setTimeout(resolve, ms));
+ throwIfAborted(signal);
+ return new Promise((resolve, reject) => {
+ const onAbort = () => {
+ clearTimeout(timer);
+ reject(abortError(signal));
+ };
+ const timer = setTimeout(() => {
+ signal.removeEventListener('abort', onAbort);
+ resolve();
+ }, ms);
+ signal.addEventListener('abort', onAbort, { once: true });
+ });
+}
+
+function stableStringify(value) {
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
+ if (value && typeof value === 'object') {
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`;
+ }
+ return JSON.stringify(value);
+}
+
+function shortHash(value) {
+ return createHash('sha256').update(String(value)).digest('hex').slice(0, 12);
+}
+
+function safeText(value, fallback = '', max = 160) {
+ if (typeof value !== 'string') return fallback;
+ const clean = value.replace(/[\u0000-\u001f\u007f]/g, ' ').trim();
+ return clean ? clean.slice(0, max) : fallback;
+}
+
+function validWorldName(value, fallback = DEFAULT_WORLD) {
+ const clean = safeText(value, '').toLowerCase();
+ return WORLD_NAME_RE.test(clean) ? clean : fallback;
+}
+
+function validIdentity(value, fallback) {
+ const clean = safeText(value, '').slice(0, 64);
+ if (!clean || /^(world|\*)$/i.test(clean) || /^bhv:/i.test(clean)) return fallback;
+ return clean;
+}
+
+function validRole(value) {
+ return WORLD_ROLES.has(value) ? value : null;
+}
+
+function validEntityId(value) {
+ const clean = safeText(value, '').slice(0, 64);
+ if (!ENTITY_ID_RE.test(clean)) {
+ throw new ServerError('Eidoverse entity ids must contain only letters, numbers, hyphens, and underscores.', {
+ status: 400,
+ code: 'EIDOVERSE_ARGUMENT_INVALID',
+ });
+ }
+ return clean;
+}
+
+function validAssetPath(value) {
+ const clean = safeText(value, '').replaceAll('\\', '/');
+ if (!isSafeAssetPath(clean)) {
+ throw new ServerError('Eidoverse assets must use a relative eidoverse library or store path.', {
+ status: 400,
+ code: 'EIDOVERSE_ARGUMENT_INVALID',
+ });
+ }
+ return clean;
+}
+
+function isSafeAssetPath(value) {
+ return Boolean(value)
+ && !value.startsWith('/')
+ && !value.includes('..')
+ && ASSET_PATH_RE.test(value);
+}
+
+function vector3(value, field) {
+ if (!Array.isArray(value) || value.length !== 3 || value.some((part) => typeof part !== 'number' || !Number.isFinite(part))) {
+ throw new ServerError(`${field} must be a finite [x, y, z] vector.`, {
+ status: 400,
+ code: 'EIDOVERSE_ARGUMENT_INVALID',
+ });
+ }
+ return value.map(Number);
+}
+
+function safeNumber(value, field, { min = -Infinity, max = Infinity, fallback = undefined } = {}) {
+ if (value === undefined && fallback !== undefined) return fallback;
+ const number = Number(value);
+ if (!Number.isFinite(number) || number < min || number > max) {
+ throw new ServerError(`${field} must be a finite number between ${min} and ${max}.`, {
+ status: 400,
+ code: 'EIDOVERSE_ARGUMENT_INVALID',
+ });
+ }
+ return number;
+}
+
+function mergeRecipe(recipe) {
+ const input = recipe && typeof recipe === 'object' && !Array.isArray(recipe) ? recipe : {};
+ const defaults = DEFAULT_EIDOVERSE_PROJECTION_RECIPE;
+ return {
+ version: 1,
+ includes: { ...defaults.includes, ...(input.includes || {}) },
+ limits: { ...defaults.limits, ...(input.limits || {}) },
+ layout: { ...defaults.layout, ...(input.layout || {}) },
+ scale: { ...defaults.scale, ...(input.scale || {}) },
+ assets: { ...defaults.assets, ...(input.assets || {}) },
+ terrain: {
+ ...defaults.terrain,
+ ...(input.terrain || {}),
+ layers: Array.isArray(input.terrain?.layers)
+ ? input.terrain.layers.map((layer) => ({ ...layer }))
+ : defaults.terrain.layers.map((layer) => ({ ...layer })),
+ },
+ };
+}
+
+function normalizeRetiredOwners(value) {
+ if (!Array.isArray(value)) return [];
+ const entries = new Map();
+ for (const candidate of value) {
+ const world = validWorldName(candidate?.world, '');
+ const id = validIdentity(candidate?.id, '');
+ if (!world || !id) continue;
+ const key = `${world}\0${id}`;
+ const actorId = validIdentity(candidate?.actorId, '');
+ const normalizedAvatar = safeText(candidate?.actorAvatar, '').replaceAll('\\', '/');
+ entries.set(key, {
+ world,
+ id,
+ ...(actorId ? {
+ actorId,
+ actorAvatar: isSafeAssetPath(normalizedAvatar) ? normalizedAvatar : DEFAULT_COS_AVATAR,
+ } : {}),
+ });
+ }
+ return [...entries.values()];
+}
+
+function rememberRetiredOwner(state, world, id, actor) {
+ state.ownership ||= { retired: [] };
+ state.ownership.retired = normalizeRetiredOwners([
+ ...state.ownership.retired,
+ { world, id, actorId: actor?.id, actorAvatar: actor?.avatar },
+ ]);
+}
+
+function normalizeState(raw) {
+ const input = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
+ return {
+ schemaVersion: 1,
+ world: validWorldName(input.world),
+ human: {
+ ...DEFAULT_STATE.human,
+ ...(input.human && typeof input.human === 'object' ? input.human : {}),
+ role: validRole(input.human?.role),
+ },
+ cos: {
+ ...DEFAULT_STATE.cos,
+ ...(input.cos && typeof input.cos === 'object' ? input.cos : {}),
+ role: validRole(input.cos?.role),
+ },
+ ownership: {
+ retired: normalizeRetiredOwners(input.ownership?.retired),
+ },
+ recipe: mergeRecipe(input.recipe),
+ projection: {
+ ...DEFAULT_STATE.projection,
+ ...(input.projection && typeof input.projection === 'object' ? input.projection : {}),
+ },
+ };
+}
+
+async function loadState() {
+ return normalizeState(await readJSONFile(STATE_FILE, clone(DEFAULT_STATE), { strict: true }));
+}
+
+async function mutateState(mutator) {
+ return stateLock(async () => {
+ const state = await loadState();
+ const result = await mutator(state);
+ await ensureDir(DATA_DIR);
+ await atomicWrite(STATE_FILE, state);
+ return result;
+ });
+}
+
+function fallbackIdentity(self) {
+ const instanceId = self?.instanceId || 'uninitialized-instance';
+ const instanceName = validIdentity(self?.name, '');
+ if (instanceName) return { name: instanceName, source: 'instance-name' };
+ return { name: `portos-${shortHash(instanceId)}`, source: 'instance-id' };
+}
+
+function configFromState(state, presence = cosPresence) {
+ const activePresence = presence?.connection?.isOpen()
+ && presence.connection.world === state.world
+ && presence.connection.id === state.cos.id
+ ? presence
+ : null;
+ return {
+ schemaVersion: state.schemaVersion,
+ world: state.world,
+ human: {
+ id: state.human.name,
+ name: state.human.name,
+ avatar: state.human.avatar,
+ source: state.human.source,
+ role: validRole(state.human.role),
+ },
+ cos: {
+ id: state.cos.id,
+ avatar: state.cos.avatar,
+ enabled: state.cos.enabled,
+ connected: Boolean(activePresence),
+ role: activePresence
+ ? (activePresence.snapshot?.yourRights?.role || roleFromSnapshot(activePresence.snapshot, state.cos.id))
+ : validRole(state.cos.role),
+ gen: activePresence?.snapshot?.yourRights?.gen === true,
+ },
+ recipe: state.recipe,
+ projection: state.projection,
+ };
+}
+
+function applyConfigDefaults(state, fallback) {
+ let changed = false;
+ if (!validIdentity(state.human.name, '')) {
+ state.human.name = fallback.name;
+ state.human.source = fallback.source;
+ changed = true;
+ } else if (!state.human.source) {
+ state.human.source = 'configured';
+ changed = true;
+ }
+ if (!validIdentity(state.cos.id, '')) {
+ state.cos.id = DEFAULT_COS_ID;
+ changed = true;
+ }
+ if (!isSafeAssetPath(state.human.avatar || DEFAULT_HUMAN_AVATAR)) {
+ state.human.avatar = DEFAULT_HUMAN_AVATAR;
+ changed = true;
+ }
+ if (!isSafeAssetPath(state.cos.avatar || DEFAULT_COS_AVATAR)) {
+ state.cos.avatar = DEFAULT_COS_AVATAR;
+ changed = true;
+ }
+ return changed;
+}
+
+async function readEidoverseWorldConfig(self) {
+ const state = await loadState();
+ applyConfigDefaults(state, fallbackIdentity(self));
+ return configFromState(state);
+}
+
+export async function ensureEidoverseWorldConfig() {
+ const self = await ensureSelf();
+ const fallback = fallbackIdentity(self);
+ return mutateState((state) => {
+ applyConfigDefaults(state, fallback);
+ return configFromState(state);
+ });
+}
+
+export async function updateEidoverseWorldConfig(patch) {
+ return worldLock(async () => {
+ const self = await ensureSelf();
+ const fallback = fallbackIdentity(self);
+ const updated = await mutateState((state) => {
+ const previousPresenceConfig = {
+ world: state.world,
+ humanName: state.human.name,
+ humanAvatar: state.human.avatar,
+ cosId: state.cos.id,
+ cosAvatar: state.cos.avatar,
+ cosEnabled: state.cos.enabled,
+ };
+ if (patch.world !== undefined) state.world = validWorldName(patch.world);
+ if (Object.hasOwn(patch, 'humanName')) {
+ state.human.name = patch.humanName
+ ? validIdentity(patch.humanName, fallback.name)
+ : fallback.name;
+ state.human.source = patch.humanName ? 'configured' : fallback.source;
+ }
+ if (Object.hasOwn(patch, 'humanAvatar')) state.human.avatar = patch.humanAvatar || DEFAULT_HUMAN_AVATAR;
+ if (patch.cosId !== undefined) state.cos.id = validIdentity(patch.cosId, DEFAULT_COS_ID);
+ if (Object.hasOwn(patch, 'cosAvatar')) state.cos.avatar = patch.cosAvatar || DEFAULT_COS_AVATAR;
+ if (patch.cosEnabled !== undefined) state.cos.enabled = patch.cosEnabled;
+ if (patch.recipe !== undefined) state.recipe = mergeRecipe(patch.recipe);
+ const worldChanged = previousPresenceConfig.world !== state.world;
+ const humanChanged = previousPresenceConfig.humanName !== state.human.name;
+ const cosChanged = previousPresenceConfig.cosId !== state.cos.id;
+ const previousOwner = {
+ id: previousPresenceConfig.cosId,
+ avatar: previousPresenceConfig.cosAvatar,
+ };
+ if (humanChanged) {
+ rememberRetiredOwner(
+ state,
+ previousPresenceConfig.world,
+ previousPresenceConfig.humanName,
+ previousOwner,
+ );
+ }
+ if (cosChanged) {
+ rememberRetiredOwner(
+ state,
+ previousPresenceConfig.world,
+ previousPresenceConfig.cosId,
+ previousOwner,
+ );
+ }
+ if (worldChanged || humanChanged) state.human.role = null;
+ if (worldChanged || cosChanged) state.cos.role = null;
+ state.ownership.retired = state.ownership.retired.filter((entry) => !(
+ entry.world === state.world
+ && (entry.id === state.human.name || entry.id === state.cos.id)
+ ));
+ return { previousPresenceConfig, config: configFromState(state) };
+ });
+ const currentPresenceConfig = {
+ world: updated.config.world,
+ humanName: updated.config.human.name,
+ humanAvatar: updated.config.human.avatar,
+ cosId: updated.config.cos.id,
+ cosAvatar: updated.config.cos.avatar,
+ cosEnabled: updated.config.cos.enabled,
+ };
+ if (Object.keys(currentPresenceConfig).some((key) => (
+ updated.previousPresenceConfig[key] !== currentPresenceConfig[key]
+ ))) {
+ await closeCosPresenceInternal();
+ }
+ return readEidoverseWorldConfig(self);
+ });
+}
+
+function resolveWorldWsUrl() {
+ const configured = typeof process.env.EIDOVERSE_WS_URL === 'string' ? process.env.EIDOVERSE_WS_URL.trim() : '';
+ return configured || `ws://127.0.0.1:${EIDOVERSE_PORT}/ws`;
+}
+
+function asConnectionError(error, fallback = 'Eidoverse Worlds is unavailable.') {
+ if (error instanceof ServerError) return error;
+ return new ServerError(`${fallback} ${error?.message || ''}`.trim(), {
+ status: 503,
+ code: 'EIDOVERSE_WORLD_UNAVAILABLE',
+ });
+}
+
+function createWorldConnection({ world, id, avatar, agent = true, onClosed = null }) {
+ const socket = new WebSocket(resolveWorldWsUrl());
+ let closed = false;
+ let failure = null;
+ let openSettled = false;
+ let snapshotSettled = false;
+ let snapshotValue = null;
+ let closeTimer = null;
+ let openTimer = null;
+ let snapshotTimer = null;
+ let closeResolver = null;
+ let messageTail = Promise.resolve();
+ const pendingVerbs = [];
+
+ const cleanupPending = (pending) => {
+ clearTimeout(pending.timer);
+ pending.signal?.removeEventListener('abort', pending.onAbort);
+ };
+
+ let resolveOpen;
+ let rejectOpen;
+ const openPromise = new Promise((resolve, reject) => {
+ resolveOpen = resolve;
+ rejectOpen = reject;
+ });
+
+ let resolveSnapshot;
+ let rejectSnapshot;
+ const snapshotPromise = new Promise((resolve, reject) => {
+ resolveSnapshot = resolve;
+ rejectSnapshot = reject;
+ });
+
+ const settleOpen = (error = null) => {
+ if (openSettled) return;
+ openSettled = true;
+ if (error) rejectOpen(error);
+ else resolveOpen();
+ };
+
+ const settleSnapshot = (value, error = null) => {
+ if (snapshotSettled) return;
+ snapshotSettled = true;
+ clearTimeout(snapshotTimer);
+ snapshotTimer = null;
+ if (error) rejectSnapshot(error);
+ else {
+ snapshotValue = value;
+ resolveSnapshot(value);
+ }
+ };
+
+ const rejectPending = (error) => {
+ while (pendingVerbs.length) {
+ const pending = pendingVerbs.shift();
+ cleanupPending(pending);
+ pending.reject(error);
+ }
+ };
+
+ const fail = (error, fallback) => {
+ const normalized = asConnectionError(error, fallback);
+ failure ||= normalized;
+ settleOpen(failure);
+ settleSnapshot(null, failure);
+ rejectPending(failure);
+ return failure;
+ };
+
+ const finishClose = () => {
+ clearTimeout(closeTimer);
+ closeTimer = null;
+ if (closeResolver) {
+ const resolve = closeResolver;
+ closeResolver = null;
+ resolve();
+ }
+ };
+
+ const handleMessage = (raw) => {
+ let message;
+ try {
+ message = JSON.parse(String(raw));
+ } catch {
+ return;
+ }
+
+ if (message?.type === 'snapshot') {
+ settleSnapshot(message);
+ return;
+ }
+ if (message?.type === 'error') {
+ fail(new ServerError(String(message.error || 'Eidoverse rejected the request.'), {
+ status: 409,
+ code: 'EIDOVERSE_WORLD_VERB_REJECTED',
+ }));
+ return;
+ }
+ if (message?.type !== 'log' || !message.entry || !pendingVerbs.length) return;
+ const pending = pendingVerbs[0];
+ if (message.entry.actor !== id || message.entry.verb !== pending.verb) return;
+ pendingVerbs.shift();
+ cleanupPending(pending);
+ pending.resolve(message.entry);
+ };
+
+ const subscribe = socket.on.bind(socket);
+
+ subscribe('open', () => {
+ clearTimeout(openTimer);
+ settleOpen();
+ snapshotTimer = setTimeout(() => {
+ fail(new Error('snapshot timeout'), 'Eidoverse Worlds did not send a snapshot in time.');
+ socket.terminate();
+ }, 10000);
+ const join = {
+ type: 'join',
+ world,
+ id,
+ agent,
+ avatar,
+ };
+ socket.send(JSON.stringify(join), (error) => {
+ if (error) fail(error, 'Eidoverse Worlds rejected the join connection.');
+ });
+ });
+
+ subscribe('message', (raw) => {
+ messageTail = messageTail
+ .then(() => handleMessage(raw))
+ .catch((error) => {
+ console.error(`❌ Eidoverse world message handling failed: ${error.message}`);
+ });
+ });
+
+ subscribe('error', (error) => {
+ fail(error, 'Eidoverse Worlds could not be reached.');
+ });
+
+ subscribe('close', () => {
+ closed = true;
+ clearTimeout(openTimer);
+ if (!failure) fail(new Error('the world connection closed'), 'Eidoverse World connection closed.');
+ finishClose();
+ onClosed?.();
+ });
+
+ openTimer = setTimeout(() => {
+ fail(new Error('connection timeout'), 'Eidoverse Worlds did not accept the connection in time.');
+ socket.terminate();
+ }, 8000);
+
+ const waitForSnapshot = async ({ signal } = {}) => {
+ await waitWithSignal(openPromise, signal);
+ return waitWithSignal(snapshotPromise, signal);
+ };
+
+ const sendVerb = async (verb, args, { signal } = {}) => {
+ await waitWithSignal(openPromise, signal);
+ throwIfAborted(signal);
+ if (closed || socket.readyState !== WebSocket.OPEN) throw failure || asConnectionError(new Error('socket is not open'));
+ return new Promise((resolve, reject) => {
+ const pending = {
+ verb,
+ resolve,
+ reject,
+ signal,
+ onAbort: null,
+ timer: setTimeout(() => {
+ const index = pendingVerbs.indexOf(pending);
+ if (index >= 0) pendingVerbs.splice(index, 1);
+ cleanupPending(pending);
+ reject(new ServerError(`Eidoverse did not acknowledge the ${verb} operation.`, {
+ status: 504,
+ code: 'EIDOVERSE_WORLD_ACK_TIMEOUT',
+ }));
+ socket.terminate();
+ }, 10000),
+ };
+ if (signal) {
+ pending.onAbort = () => {
+ const index = pendingVerbs.indexOf(pending);
+ if (index >= 0) pendingVerbs.splice(index, 1);
+ cleanupPending(pending);
+ reject(abortError(signal));
+ socket.terminate();
+ };
+ signal.addEventListener('abort', pending.onAbort, { once: true });
+ }
+ pendingVerbs.push(pending);
+ if (signal?.aborted) {
+ pending.onAbort();
+ return;
+ }
+ socket.send(JSON.stringify({ type: 'verb', verb, args }), (error) => {
+ if (!error) return;
+ const index = pendingVerbs.indexOf(pending);
+ if (index >= 0) pendingVerbs.splice(index, 1);
+ cleanupPending(pending);
+ reject(asConnectionError(error, 'Eidoverse Worlds could not receive the operation.'));
+ socket.terminate();
+ });
+ });
+ };
+
+ const sendPose = (pose) => {
+ if (closed || socket.readyState !== WebSocket.OPEN) return false;
+ socket.send(JSON.stringify({ type: 'pose', pose }));
+ return true;
+ };
+
+ const close = () => {
+ if (closed || socket.readyState === WebSocket.CLOSED) return Promise.resolve();
+ return new Promise((resolve) => {
+ closeResolver = resolve;
+ closeTimer = setTimeout(() => {
+ socket.terminate();
+ finishClose();
+ }, 1500);
+ socket.close();
+ });
+ };
+
+ return Object.freeze({
+ id,
+ world,
+ waitForSnapshot,
+ sendVerb,
+ sendPose,
+ close,
+ isOpen: () => !closed && socket.readyState === WebSocket.OPEN,
+ getSnapshot: () => snapshotValue,
+ });
+}
+
+function presenceSummary(presence = cosPresence) {
+ return {
+ connected: Boolean(presence?.connection?.isOpen()),
+ id: presence?.connection?.id || null,
+ world: presence?.connection?.world || null,
+ role: presence?.snapshot?.yourRights?.role || null,
+ gen: presence?.snapshot?.yourRights?.gen === true,
+ joinedAt: presence?.joinedAt || null,
+ };
+}
+
+async function assertInstalled() {
+ const setup = await getEidoverseStatus();
+ if (setup.installed) return setup;
+ throw new ServerError('Install and start Eidoverse Worlds before using the PortOS world projection.', {
+ status: 409,
+ code: 'EIDOVERSE_NOT_INSTALLED',
+ });
+}
+
+async function closeCosPresenceInternal() {
+ const current = cosPresence;
+ cosPresence = null;
+ if (current?.connection) await current.connection.close();
+}
+
+function roleFromSnapshot(snapshot, id) {
+ const role = snapshot?.state?.roles?.[id];
+ return validRole(typeof role === 'string' ? role : role?.role);
+}
+
+async function rememberObservedRoles({ humanRole, cosRole }) {
+ return mutateState((state) => {
+ if (humanRole !== undefined) state.human.role = validRole(humanRole);
+ if (cosRole !== undefined) state.cos.role = validRole(cosRole);
+ return state;
+ });
+}
+
+async function forgetRetiredOwners(targets) {
+ if (!targets.length) return;
+ const revoked = new Set(targets.map((entry) => `${entry.world}\0${entry.id}`));
+ await mutateState((current) => {
+ current.ownership.retired = current.ownership.retired.filter((entry) => (
+ !revoked.has(`${entry.world}\0${entry.id}`)
+ ));
+ return current;
+ });
+}
+
+async function demoteRetiredOwners(connection, targets, { signal } = {}) {
+ const ordered = [...targets].sort((left, right) => (
+ Number(left.id === connection.id) - Number(right.id === connection.id)
+ ));
+ for (const target of ordered) {
+ throwIfAborted(signal);
+ await connection.sendVerb('grant', { id: target.id, role: 'visitor' }, { signal });
+ }
+ await forgetRetiredOwners(targets);
+}
+
+async function revokeRetiredOwners(connection, config, { signal } = {}) {
+ const state = await loadState();
+ const targets = state.ownership.retired.filter((entry) => (
+ entry.world !== config.world
+ || (entry.id !== config.human.id && entry.id !== config.cos.id)
+ ));
+ if (!targets.length) return [];
+
+ const currentWorldTargets = targets.filter((entry) => entry.world === config.world);
+ if (currentWorldTargets.length) {
+ await demoteRetiredOwners(connection, currentWorldTargets, { signal });
+ }
+
+ const priorWorldGroups = new Map();
+ for (const target of targets.filter((entry) => entry.world !== config.world)) {
+ const actorId = target.actorId || config.cos.id;
+ const actorAvatar = target.actorAvatar || config.cos.avatar;
+ const key = `${target.world}\0${actorId}\0${actorAvatar}`;
+ const group = priorWorldGroups.get(key) || {
+ world: target.world,
+ actorId,
+ actorAvatar,
+ targets: [],
+ };
+ group.targets.push(target);
+ priorWorldGroups.set(key, group);
+ }
+
+ for (const group of priorWorldGroups.values()) {
+ throwIfAborted(signal);
+ const priorConnection = createWorldConnection({
+ world: group.world,
+ id: group.actorId,
+ avatar: group.actorAvatar,
+ agent: true,
+ });
+ await priorConnection.waitForSnapshot({ signal }).then(async (snapshot) => {
+ const actorRole = snapshot?.yourRights?.role || roleFromSnapshot(snapshot, group.actorId);
+ if (actorRole !== 'owner') {
+ throw new ServerError('PortOS could not retire a previous Eidoverse owner identity.', {
+ status: 409,
+ code: 'EIDOVERSE_OWNER_HANDOFF_FAILED',
+ });
+ }
+ await demoteRetiredOwners(priorConnection, group.targets, { signal });
+ }).finally(() => priorConnection.close());
+ }
+
+ return targets;
+}
+
+/**
+ * Join as the configured human before the CoS connection. This makes the
+ * install's known human identity the first embodied joiner when a world is
+ * created, so the world grants that identity ownership rather than allowing a
+ * scheduled CoS projection to claim ownership by accident. If the human is an
+ * owner, persist the CoS owner role through Eidoverse's own grant verb. The
+ * projection manages terrain, sky, and role handoff, which are owner-only in
+ * Eidoverse; this authority is separately default-off in PortOS.
+ * The connection is intentionally short-lived; the browser performs the live
+ * user session with the same durable id from the URL query parameters.
+ */
+async function seedHumanRoleAndCosGrant(config, { signal } = {}) {
+ throwIfAborted(signal);
+ let connection;
+ connection = createWorldConnection({
+ world: config.world,
+ id: config.human.id,
+ avatar: config.human.avatar,
+ agent: false,
+ });
+ return connection.waitForSnapshot({ signal }).then(async (snapshot) => {
+ const humanRole = snapshot?.yourRights?.role || roleFromSnapshot(snapshot, config.human.id);
+ let cosRole = roleFromSnapshot(snapshot, config.cos.id);
+ if (config.human.id !== config.cos.id
+ && humanRole === 'owner'
+ && cosRole !== 'owner') {
+ await connection.sendVerb('grant', { id: config.cos.id, role: 'owner' }, { signal });
+ cosRole = 'owner';
+ }
+ return { humanRole, cosRole };
+ }).then((roles) => connection.close().then(async () => {
+ await rememberObservedRoles(roles);
+ return roles;
+ }), (error) => connection.close().then(() => { throw error; }));
+}
+
+async function ensureCosPresenceInternal({ fresh = false, signal } = {}) {
+ throwIfAborted(signal);
+ const config = await ensureEidoverseWorldConfig();
+ throwIfAborted(signal);
+ if (!config.cos.enabled) {
+ throw new ServerError('The PortOS CoS presence is disabled in the Eidoverse world configuration.', {
+ status: 409,
+ code: 'EIDOVERSE_COS_DISABLED',
+ });
+ }
+ if (fresh || (cosPresence && !cosPresence.connection.isOpen())) await closeCosPresenceInternal();
+ if (cosPresence?.connection.isOpen()) return cosPresence;
+
+ await seedHumanRoleAndCosGrant(config, { signal });
+
+ let connection;
+ connection = createWorldConnection({
+ world: config.world,
+ id: config.cos.id,
+ avatar: config.cos.avatar,
+ agent: true,
+ onClosed: () => {
+ if (cosPresence?.connection === connection) cosPresence = null;
+ },
+ });
+ return connection.waitForSnapshot({ signal }).then(async (snapshot) => {
+ const cosRole = snapshot?.yourRights?.role || roleFromSnapshot(snapshot, config.cos.id);
+ let humanRole = roleFromSnapshot(snapshot, config.human.id);
+ if (config.human.id !== config.cos.id && cosRole === 'owner' && humanRole !== 'owner') {
+ await connection.sendVerb('grant', { id: config.human.id, role: 'owner' }, { signal });
+ humanRole = 'owner';
+ }
+ if (cosRole === 'owner') await revokeRetiredOwners(connection, config, { signal });
+ return rememberObservedRoles({ humanRole, cosRole }).then(() => {
+ cosPresence = {
+ connection,
+ snapshot,
+ joinedAt: new Date().toISOString(),
+ };
+ return cosPresence;
+ });
+ }).catch((error) => connection.close().then(() => { throw error; }));
+}
+
+export async function ensureEidoverseWorldPresence() {
+ return worldLock(async () => {
+ await assertInstalled();
+ const presence = await ensureCosPresenceInternal();
+ return presenceSummary(presence);
+ });
+}
+
+async function getDiskUsagePercent() {
+ const stats = await statfs('/').catch(() => null);
+ if (!stats) return null;
+ const total = stats.blocks * stats.bsize;
+ if (!(total > 0)) return null;
+ return Math.round(((total - stats.bavail * stats.bsize) / total) * 100);
+}
+
+function appSummary(apps) {
+ if (!Array.isArray(apps)) return null;
+ return {
+ total: apps.length,
+ online: apps.filter((app) => app.overallStatus === 'online').length,
+ stopped: apps.filter((app) => app.overallStatus === 'stopped').length,
+ notStarted: apps.filter((app) => app.overallStatus === 'not_started').length,
+ unknown: apps.filter((app) => app.overallStatus === 'unknown').length,
+ };
+}
+
+function finiteOrNull(value) {
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
+}
+
+function nonNegativeOrNull(value) {
+ const number = finiteOrNull(value);
+ return number === null ? null : Math.max(0, number);
+}
+
+function percentageOrNull(value) {
+ const number = finiteOrNull(value);
+ return number === null ? null : Math.max(0, Math.min(100, number));
+}
+
+function projectedProductivity(todayActivity, velocity, taskState) {
+ if (!todayActivity && !velocity) return null;
+ const stats = todayActivity?.stats || {};
+ const queue = {
+ pendingApprovals: Array.isArray(taskState?.awaitingApproval) ? taskState.awaitingApproval.length : null,
+ pendingTasks: Array.isArray(taskState?.tasks)
+ ? taskState.tasks.filter((task) => !['completed', 'done', 'archived'].includes(String(task?.status || '').toLowerCase())).length
+ : null,
+ };
+ queue.total = [queue.pendingApprovals, queue.pendingTasks].every((value) => value !== null)
+ ? queue.pendingApprovals + queue.pendingTasks
+ : null;
+ return [{
+ id: 'summary',
+ label: 'Productivity',
+ completedToday: nonNegativeOrNull(stats.completed ?? velocity?.today),
+ succeededToday: nonNegativeOrNull(stats.succeeded ?? velocity?.todaySuccesses),
+ failedToday: nonNegativeOrNull(stats.failed ?? velocity?.todayFailures),
+ successRate: percentageOrNull(stats.successRate),
+ velocity: finiteOrNull(velocity?.velocity),
+ velocityLabel: safeText(velocity?.velocityLabel, ''),
+ averagePerDay: nonNegativeOrNull(velocity?.avgPerDay),
+ historicalDays: nonNegativeOrNull(velocity?.historicalDays),
+ queue,
+ running: todayActivity?.isRunning === true,
+ paused: todayActivity?.isPaused === true,
+ }];
+}
+
+function projectedActivity(calendar) {
+ if (!calendar || !Array.isArray(calendar.weeks)) return null;
+ const days = calendar.weeks
+ .flatMap((week) => Array.isArray(week) ? week : [])
+ .filter((day) => day && typeof day === 'object' && day.isFuture !== true);
+ const today = days.find((day) => day.isToday === true);
+ const activeDays = days.filter((day) => (nonNegativeOrNull(day.tasks) || 0) > 0).slice(-99);
+ const summary = calendar.summary || {};
+ return [
+ {
+ id: 'summary',
+ label: 'Activity calendar',
+ weeks: calendar.weeks.length,
+ activeDays: nonNegativeOrNull(summary.activeDays),
+ totalTasks: nonNegativeOrNull(summary.totalTasks),
+ totalSuccesses: nonNegativeOrNull(summary.totalSuccesses),
+ successRate: percentageOrNull(summary.successRate),
+ maxTasks: nonNegativeOrNull(calendar.maxTasks),
+ todayTasks: nonNegativeOrNull(today?.tasks),
+ },
+ ...activeDays.map((day, index) => ({
+ id: safeText(day.date, `day-${index}`),
+ label: safeText(day.date, 'Activity day'),
+ tasks: nonNegativeOrNull(day.tasks) ?? 0,
+ successes: nonNegativeOrNull(day.successes) ?? 0,
+ failures: nonNegativeOrNull(day.failures) ?? 0,
+ successRate: percentageOrNull(day.successRate),
+ isToday: day.isToday === true,
+ })),
+ ];
+}
+
+function projectedGoals(goalsData) {
+ if (!Array.isArray(goalsData?.goals)) return null;
+ const goals = goalsData.goals;
+ const children = new Map(goals.map((goal) => [goal?.id, 0]));
+ goals.forEach((goal) => {
+ if (goal?.parentId && children.has(goal.parentId)) children.set(goal.parentId, children.get(goal.parentId) + 1);
+ });
+ return goals.map((goal, index) => {
+ const milestones = Array.isArray(goal?.milestones) ? goal.milestones : [];
+ const todos = Array.isArray(goal?.todos) ? goal.todos : [];
+ return {
+ id: safeText(goal?.id, `goal-${index}`),
+ label: safeText(goal?.title, 'Goal'),
+ status: safeText(goal?.status, 'active'),
+ progress: percentageOrNull(goal?.progress) ?? 0,
+ goalType: safeText(goal?.goalType, ''),
+ targetDate: safeText(goal?.targetDate, ''),
+ milestoneTotal: milestones.length,
+ milestoneDone: milestones.filter((milestone) => milestone?.completed === true || Boolean(safeText(milestone?.completedAt, ''))).length,
+ todoTotal: todos.length,
+ todoPending: todos.filter((todo) => !['completed', 'done'].includes(String(todo?.status || '').toLowerCase()) && todo?.completed !== true).length,
+ childCount: children.get(goal?.id) || 0,
+ };
+ });
+}
+
+function projectedMemory(graph) {
+ if (!graph || !Array.isArray(graph.nodes)) return null;
+ const buckets = new Map();
+ const categoryById = new Map();
+ for (const node of graph.nodes) {
+ const category = safeText(node?.category || node?.brainType, 'other').toLowerCase() || 'other';
+ categoryById.set(node?.id, category);
+ const bucket = buckets.get(category) || { count: 0, importance: 0 };
+ bucket.count += 1;
+ bucket.importance += Math.max(0, finiteOrNull(node?.importance) ?? 1);
+ buckets.set(category, bucket);
+ }
+ const bridgeCounts = new Map();
+ for (const edge of Array.isArray(graph.edges) ? graph.edges : []) {
+ const from = categoryById.get(edge?.source);
+ const to = categoryById.get(edge?.target);
+ if (!from || !to || from === to) continue;
+ bridgeCounts.set(from, (bridgeCounts.get(from) || 0) + 1);
+ bridgeCounts.set(to, (bridgeCounts.get(to) || 0) + 1);
+ }
+ return [...buckets.entries()]
+ .sort(([a, left], [b, right]) => right.count - left.count || a.localeCompare(b))
+ .map(([category, bucket]) => ({
+ id: category,
+ label: `Memory ${category}`,
+ category,
+ count: bucket.count,
+ importance: bucket.importance,
+ bridgeCount: bridgeCounts.get(category) || 0,
+ totalMemories: graph.nodes.length,
+ totalEdges: Array.isArray(graph.edges) ? graph.edges.length : 0,
+ hasEmbeddings: graph.hasEmbeddings === true,
+ }));
+}
+
+function projectedStorage(introspection) {
+ if (!introspection || typeof introspection !== 'object') return null;
+ const items = [];
+ const db = introspection.db;
+ const fsSection = introspection.fs;
+ const dbOnline = Array.isArray(db?.tables);
+ items.push({
+ id: 'database',
+ label: 'PostgreSQL',
+ area: 'database',
+ status: db === null ? 'offline' : (dbOnline ? 'online' : 'unknown'),
+ tableCount: dbOnline ? db.tables.length : null,
+ sizeBytes: finiteOrNull(db?.sizeBytes),
+ migrations: db?.migrations?.applied === undefined ? null : nonNegativeOrNull(db.migrations.applied),
+ });
+ if (dbOnline) {
+ db.tables.forEach((table, index) => items.push({
+ id: `db-table-${shortHash(table?.name || index)}`,
+ label: safeText(table?.name, 'Database table'),
+ area: 'database-table',
+ status: 'online',
+ rowEstimate: nonNegativeOrNull(table?.rowEstimate),
+ sizeBytes: nonNegativeOrNull(table?.totalBytes),
+ hasEmbedding: table?.hasEmbedding === true,
+ }));
+ }
+ const fsOnline = Array.isArray(fsSection?.domains);
+ items.push({
+ id: 'filesystem',
+ label: 'PortOS data files',
+ area: 'filesystem',
+ status: fsSection === null ? 'offline' : (fsOnline ? 'online' : 'unknown'),
+ domainCount: fsOnline ? fsSection.domains.length : null,
+ sizeBytes: finiteOrNull(fsSection?.totalBytes),
+ fileCount: nonNegativeOrNull(fsSection?.totalFiles),
+ });
+ if (fsOnline) {
+ fsSection.domains.forEach((domain, index) => items.push({
+ id: `data-domain-${shortHash(domain?.name || index)}`,
+ label: safeText(domain?.name, 'Data domain'),
+ area: 'data-domain',
+ status: 'online',
+ sizeBytes: nonNegativeOrNull(domain?.bytes),
+ fileCount: nonNegativeOrNull(domain?.files),
+ }));
+ }
+ return items;
+}
+
+function projectedOperations({ cosStatus, review, backupState, notifications, character, healthMetrics, voiceConfig, memory, diskPercent, chronotype, inboxCounts }) {
+ const values = [cosStatus, review, backupState, notifications, character, healthMetrics, voiceConfig, memory, diskPercent, chronotype, inboxCounts];
+ if (!values.some((value) => value !== null && value !== undefined)) return null;
+ return [{
+ id: 'overview',
+ label: 'PortOS operations',
+ cos: cosStatus ? {
+ running: cosStatus.running === true,
+ paused: cosStatus.paused === true,
+ activeAgents: nonNegativeOrNull(cosStatus.activeAgents),
+ pausedAgents: nonNegativeOrNull(cosStatus.pausedAgents),
+ provider: safeText(cosStatus.provider?.name, ''),
+ } : null,
+ ai: cosStatus ? {
+ running: cosStatus.running === true,
+ activeAgents: nonNegativeOrNull(cosStatus.activeAgents),
+ provider: safeText(cosStatus.provider?.name, ''),
+ } : null,
+ review: review ? {
+ total: nonNegativeOrNull(review.total),
+ cos: nonNegativeOrNull(review.cos),
+ alerts: nonNegativeOrNull(review.alert),
+ } : null,
+ backup: backupState ? {
+ status: safeText(backupState.status, 'unknown'),
+ lastRun: safeText(backupState.lastRun, ''),
+ filesChanged: nonNegativeOrNull(backupState.filesChanged),
+ } : null,
+ notifications: notifications ? {
+ total: nonNegativeOrNull(notifications.total),
+ unread: nonNegativeOrNull(notifications.unread),
+ } : null,
+ inbox: inboxCounts ? {
+ total: nonNegativeOrNull(inboxCounts.total),
+ needsReview: nonNegativeOrNull(inboxCounts.needs_review),
+ classifying: nonNegativeOrNull(inboxCounts.classifying),
+ } : null,
+ character: character ? {
+ level: nonNegativeOrNull(character.level),
+ } : null,
+ chronotype: chronotype ? {
+ type: safeText(chronotype.type, ''),
+ confidence: percentageOrNull(typeof chronotype.confidence === 'number' ? chronotype.confidence * 100 : chronotype.confidence),
+ peakFocusStart: safeText(chronotype.recommendations?.peakFocusStart, ''),
+ peakFocusEnd: safeText(chronotype.recommendations?.peakFocusEnd, ''),
+ sleepTime: safeText(chronotype.recommendations?.sleepTime, ''),
+ } : null,
+ voice: voiceConfig ? {
+ enabled: voiceConfig.enabled === true,
+ sttEngine: safeText(voiceConfig.stt?.engine, ''),
+ ttsEngine: safeText(voiceConfig.tts?.engine, ''),
+ } : null,
+ memory: memory ? {
+ usedPercent: memory.total > 0 ? Math.round((memory.used / memory.total) * 100) : null,
+ source: safeText(memory.source, 'unknown'),
+ } : null,
+ healthMetrics: healthMetrics ?? null,
+ diskPercent: percentageOrNull(diskPercent),
+ }];
+}
+
+async function projectedJira(appConfig, featuresState) {
+ if (!Array.isArray(featuresState?.features)) return null;
+ const jiraFeature = featuresState.features.find((feature) => feature?.id === 'jira');
+ if (!jiraFeature) return null;
+ if (jiraFeature.enabled !== true) return [];
+ if (!Array.isArray(appConfig)) return null;
+ const specs = [...new Map(appConfig
+ .filter((app) => app?.jira?.enabled && app.jira.instanceId && app.jira.projectKey)
+ .map((app) => [`${app.jira.instanceId}/${app.jira.projectKey}`, {
+ instanceId: app.jira.instanceId,
+ projectKey: app.jira.projectKey,
+ }]))
+ .values()];
+ if (specs.length === 0) return [];
+ const batches = await Promise.all(specs.map((spec) => fetchMyCurrentSprintTickets(spec.instanceId, spec.projectKey)
+ .then((tickets) => Array.isArray(tickets) ? { tickets, failed: false } : { tickets: [], failed: true })
+ .catch(() => ({ tickets: [], failed: true }))));
+ if (batches.some((batch) => batch.failed)) return null;
+ const byKey = new Map();
+ batches.flatMap((batch) => batch.tickets).forEach((ticket, index) => {
+ if (!ticket?.key || byKey.has(ticket.key)) return;
+ byKey.set(ticket.key, {
+ id: safeText(ticket.key, `ticket-${index}`),
+ label: safeText(ticket.summary, ticket.key),
+ status: safeText(ticket.statusCategory || ticket.status, 'todo'),
+ statusCategory: safeText(ticket.statusCategory, ''),
+ priority: safeText(ticket.priority, ''),
+ issueType: safeText(ticket.issueType, ''),
+ storyPoints: nonNegativeOrNull(ticket.storyPoints),
+ });
+ });
+ return [...byKey.values()].sort((a, b) => a.id.localeCompare(b.id));
+}
+
+function healthSnapshot({ apps, cosStatus, review, backupState, notifications, character, healthMetrics, voiceConfig, memory, diskPercent }) {
+ const health = {
+ apps: appSummary(apps),
+ cos: cosStatus
+ ? {
+ running: cosStatus.running === true,
+ activeAgents: nonNegativeOrNull(cosStatus.activeAgents),
+ pausedAgents: nonNegativeOrNull(cosStatus.pausedAgents),
+ }
+ : null,
+ review: review ? {
+ total: nonNegativeOrNull(review.total),
+ cos: nonNegativeOrNull(review.cos),
+ alerts: nonNegativeOrNull(review.alert),
+ } : null,
+ backup: backupState ? {
+ status: safeText(backupState.status, 'unknown'),
+ lastRun: safeText(backupState.lastRun, ''),
+ filesChanged: nonNegativeOrNull(backupState.filesChanged),
+ } : null,
+ memory: memory ? {
+ usedPercent: memory.total > 0 ? Math.round((memory.used / memory.total) * 100) : null,
+ source: safeText(memory.source, 'unknown'),
+ } : null,
+ notifications: notifications ? {
+ total: nonNegativeOrNull(notifications.total),
+ unread: nonNegativeOrNull(notifications.unread),
+ } : null,
+ character: character ? {
+ level: nonNegativeOrNull(character.level),
+ } : null,
+ metrics: healthMetrics ?? null,
+ voice: voiceConfig ? {
+ enabled: voiceConfig.enabled === true,
+ sttEngine: safeText(voiceConfig.stt?.engine, ''),
+ ttsEngine: safeText(voiceConfig.tts?.engine, ''),
+ } : null,
+ diskPercent: percentageOrNull(diskPercent),
+ };
+ const available = [apps, cosStatus, review, backupState, notifications, character, healthMetrics, voiceConfig, memory, diskPercent]
+ .some((value) => value !== null && value !== undefined);
+ return available ? health : null;
+}
+
+async function collectProjectionSources({ signal } = {}) {
+ throwIfAborted(signal);
+ const [apps, appConfig, agents, taskState, cosStatus, review, featuresState, peers, backupState, notifications, character, healthMetrics, voiceConfig, memory, diskPercent, todayActivity, velocity, activityCalendar, goalsData, chronotype, memoryGraph, inboxCounts, introspection] = await waitWithSignal(Promise.all([
+ getAppStatuses().catch(() => null),
+ getAllApps({ includeArchived: false }).catch(() => null),
+ getAgents().catch(() => null),
+ getCosTasks().catch(() => null),
+ getCosStatus().catch(() => null),
+ getPendingCounts().catch(() => null),
+ getInstanceFeatures().catch(() => null),
+ getPeers().catch(() => null),
+ backup.getState().catch(() => null),
+ getCountsByType().catch(() => null),
+ getCharacter({ withSkills: false, withMetrics: false }).catch(() => null),
+ getLatestMetricValues(HEALTH_METRIC_KEYS).catch(() => null),
+ getVoiceConfig().catch(() => null),
+ getMemoryStats().catch(() => null),
+ getDiskUsagePercent(),
+ getTodayActivity().catch(() => null),
+ getVelocityMetrics().catch(() => null),
+ getActivityCalendar(12).catch(() => null),
+ getGoals().catch(() => null),
+ getChronotype().catch(() => null),
+ getBrainGraphOverview({ limit: 100 }).catch(() => null),
+ getInboxLogCounts().catch(() => null),
+ getOpenWorldIntrospection().catch(() => null),
+ ]), signal);
+
+ const projectedAgents = Array.isArray(agents)
+ ? agents
+ .filter((agent) => ['running', 'paused'].includes(agent?.status))
+ .map((agent) => ({
+ id: safeText(agent.id, 'agent'),
+ status: safeText(agent.status, 'unknown'),
+ taskId: safeText(agent.taskId, ''),
+ phase: safeText(agent.metadata?.phase, ''),
+ appName: safeText(agent.metadata?.taskAppName, ''),
+ }))
+ : null;
+ const projectedTasks = Array.isArray(taskState?.tasks)
+ ? taskState.tasks
+ .filter((task) => !['completed', 'done', 'archived'].includes(String(task?.status || '').toLowerCase()))
+ .map((task) => ({
+ id: safeText(task.id, 'task'),
+ label: safeText(task.title || task.name || task.description, 'CoS task').split('\n')[0].slice(0, 140),
+ status: safeText(task.status, 'pending'),
+ priority: safeText(task.priority, ''),
+ type: safeText(task.type, ''),
+ }))
+ : null;
+ const projectedFeatures = Array.isArray(featuresState?.features)
+ ? featuresState.features.map((feature) => ({
+ id: safeText(feature.id, 'feature'),
+ label: safeText(feature.label || feature.id, 'Feature'),
+ enabled: feature.enabled === true,
+ }))
+ : null;
+ const projectedPeers = Array.isArray(peers)
+ ? peers.map((peer) => ({
+ id: safeText(peer.instanceId || peer.id, 'peer'),
+ label: safeText(peer.name, 'Federated peer'),
+ enabled: peer.enabled !== false,
+ fullSync: peer.fullSync === true,
+ status: safeText(peer.status, ''),
+ }))
+ : null;
+
+ const health = healthSnapshot({ apps, cosStatus, review, backupState, notifications, character, healthMetrics, voiceConfig, memory, diskPercent });
+ const jira = await waitWithSignal(projectedJira(appConfig, featuresState), signal);
+
+ return {
+ apps: Array.isArray(apps)
+ ? apps.map((app) => ({
+ id: safeText(app.id, 'app'),
+ label: safeText(app.name, 'Managed app'),
+ status: safeText(app.overallStatus, 'unknown'),
+ type: safeText(app.type, ''),
+ managed: app.managed === true,
+ }))
+ : null,
+ agents: projectedAgents,
+ tasks: projectedTasks,
+ features: projectedFeatures,
+ peers: projectedPeers,
+ health,
+ productivity: projectedProductivity(todayActivity, velocity, taskState),
+ activity: projectedActivity(activityCalendar),
+ goals: projectedGoals(goalsData),
+ memory: projectedMemory(memoryGraph),
+ storage: projectedStorage(introspection),
+ jira,
+ operations: projectedOperations({ cosStatus, review, backupState, notifications, character, healthMetrics, voiceConfig, memory, diskPercent, chronotype, inboxCounts }),
+ };
+}
+
+const PROJECTION_KINDS = [
+ { kind: 'app', source: 'apps' },
+ { kind: 'agent', source: 'agents' },
+ { kind: 'task', source: 'tasks' },
+ { kind: 'feature', source: 'features' },
+ { kind: 'peer', source: 'peers' },
+ { kind: 'health', source: 'health' },
+ { kind: 'productivity', source: 'productivity' },
+ { kind: 'activity', source: 'activity' },
+ { kind: 'goal', source: 'goals' },
+ { kind: 'memory', source: 'memory' },
+ { kind: 'storage', source: 'storage' },
+ { kind: 'jira', source: 'jira' },
+ { kind: 'operations', source: 'operations' },
+];
+
+function sourceAvailable(source, key) {
+ if (key === 'health') return source.health !== null && source.health !== undefined;
+ return Array.isArray(source[key]);
+}
+
+function projectionEntityId(kind, sourceId, index) {
+ return `${PROJECTION_ID_PREFIX}${kind}-${shortHash(`${kind}:${sourceId || index}`)}`;
+}
+
+function componentFor(kind, item) {
+ if (kind === 'health') return { resource: 'health', label: 'PortOS health', ...item };
+ const component = {
+ resource: COMPONENT_RESOURCE_BY_KIND[kind] || kind,
+ sourceId: safeText(item.id, 'unknown'),
+ label: safeText(item.label, kind),
+ };
+ for (const [key, value] of Object.entries(item)) {
+ if (key === 'id' || key === 'label' || value === undefined) continue;
+ if (typeof value === 'string') component[key] = safeText(value, '', 300);
+ else if (typeof value === 'number' && Number.isFinite(value)) component[key] = value;
+ else if (typeof value === 'boolean') component[key] = value;
+ else if (value !== null && typeof value === 'object') component[key] = clone(value);
+ }
+ return component;
+}
+
+function entityPosition(index, kind, recipe) {
+ const { origin, spacing, laneGap, columns } = recipe.layout;
+ const lane = PROJECTION_KINDS.findIndex((entry) => entry.kind === kind);
+ const column = index % columns;
+ const row = Math.floor(index / columns);
+ return [
+ origin[0] + column * spacing,
+ origin[1],
+ origin[2] + lane * laneGap + row * spacing,
+ ];
+}
+
+function equal(valueA, valueB) {
+ return stableStringify(valueA) === stableStringify(valueB);
+}
+
+/**
+ * Build the deterministic world operations without opening a socket. This is
+ * 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 = {} }) {
+ const effectiveRecipe = mergeRecipe(recipe);
+ const stateEntities = currentState?.entities && typeof currentState.entities === 'object'
+ ? currentState.entities
+ : {};
+ const operations = [];
+ const desiredIds = new Set();
+ const removableKinds = new Set();
+ const sourceAvailability = {};
+ let created = 0;
+ let updated = 0;
+ let removed = 0;
+
+ sourceAvailability.terrain = currentState?.terrain !== undefined;
+ if (!equal(currentState?.terrain || null, effectiveRecipe.terrain)) {
+ operations.push({ verb: 'terrain', args: effectiveRecipe.terrain });
+ }
+
+ for (const { kind, source: sourceKey } of PROJECTION_KINDS) {
+ const available = sourceAvailable(source, sourceKey);
+ sourceAvailability[sourceKey] = available;
+ if (!effectiveRecipe.includes[`${sourceKey}`]) {
+ removableKinds.add(kind);
+ continue;
+ }
+ if (!available) continue;
+ removableKinds.add(kind);
+ const values = kind === 'health' ? [source.health] : source[sourceKey];
+ const limited = values.slice(0, effectiveRecipe.limits[sourceKey] ?? values.length);
+ limited.forEach((item, index) => {
+ const sourceId = kind === 'health' ? 'health' : item.id || `${kind}-${index}`;
+ const id = projectionEntityId(kind, sourceId, index);
+ const pos = entityPosition(index, kind, effectiveRecipe);
+ const spawn = {
+ id,
+ lib: effectiveRecipe.assets[kind],
+ pos,
+ yaw: 0,
+ scale: effectiveRecipe.scale[kind],
+ collide: 'box',
+ };
+ const existing = stateEntities[id];
+ desiredIds.add(id);
+ if (!existing || existing.lib !== spawn.lib) {
+ if (existing) {
+ operations.push({ verb: 'remove', args: { id } });
+ removed += 1;
+ }
+ operations.push({ verb: 'spawn', args: spawn });
+ created += 1;
+ } else if (!equal({ pos: existing.pos, yaw: existing.yaw, scale: existing.scale }, {
+ pos: spawn.pos,
+ yaw: spawn.yaw,
+ scale: spawn.scale,
+ })) {
+ operations.push({ verb: 'place', args: { id, pos, yaw: 0, scale: spawn.scale } });
+ updated += 1;
+ }
+ const component = componentFor(kind, item);
+ if (!equal(existing?.comp?.[COMPONENT_TYPE], component)) {
+ operations.push({ verb: 'comp', args: { id, type: COMPONENT_TYPE, data: component } });
+ if (existing) updated += 1;
+ }
+ });
+ }
+
+ for (const id of Object.keys(stateEntities)) {
+ if (!id.startsWith(PROJECTION_ID_PREFIX) || desiredIds.has(id)) continue;
+ const kind = id.slice(PROJECTION_ID_PREFIX.length).split('-')[0];
+ if (!removableKinds.has(kind)) continue;
+ operations.push({ verb: 'remove', args: { id } });
+ removed += 1;
+ }
+
+ return {
+ operations,
+ summary: {
+ created,
+ updated,
+ removed,
+ operationCount: operations.length,
+ sourceAvailability,
+ sourceCounts: Object.fromEntries(PROJECTION_KINDS.map(({ kind, source: sourceKey }) => [
+ sourceKey,
+ sourceAvailable(source, sourceKey)
+ ? (kind === 'health' ? 1 : source[sourceKey].length)
+ : null,
+ ])),
+ },
+ };
+}
+
+async function sendOperations(connection, operations, { signal } = {}) {
+ for (let index = 0; index < operations.length; index += 1) {
+ throwIfAborted(signal);
+ if (index > 0) await abortableDelay(PROJECTION_VERB_INTERVAL_MS, signal);
+ const operation = operations[index];
+ await connection.sendVerb(operation.verb, operation.args, { signal });
+ }
+}
+
+async function recordProjection({ success, summary = null, error = null }) {
+ const now = new Date().toISOString();
+ return mutateState((state) => {
+ state.projection = {
+ ...state.projection,
+ lastRunAt: now,
+ ...(success ? { lastSuccessAt: now, lastError: null, lastSummary: summary } : {
+ lastError: safeText(error?.message || error, 'Projection failed', 500),
+ }),
+ };
+ return state.projection;
+ });
+}
+
+export async function projectEidoverseWorld({ signal } = {}) {
+ const run = async () => {
+ throwIfAborted(signal);
+ await assertInstalled();
+ const config = await ensureEidoverseWorldConfig();
+ const presence = await ensureCosPresenceInternal({ fresh: true, signal });
+ const source = await collectProjectionSources({ signal });
+ throwIfAborted(signal);
+ const plan = buildProjectionPlan({
+ source,
+ recipe: config.recipe,
+ currentState: presence.snapshot?.state || {},
+ });
+ await sendOperations(presence.connection, plan.operations, { signal });
+ const summary = {
+ world: config.world,
+ cosId: config.cos.id,
+ ...plan.summary,
+ };
+ const projection = await recordProjection({ success: true, summary });
+ return {
+ success: true,
+ summary,
+ projection,
+ presence: presenceSummary(presence),
+ };
+ };
+
+ return worldLock(() => run().catch(async (error) => {
+ await recordProjection({ success: false, error });
+ throw error;
+ }));
+}
+
+function objectArgs(args) {
+ if (!args || typeof args !== 'object' || Array.isArray(args)) {
+ throw new ServerError('Eidoverse operation args must be an object.', {
+ status: 400,
+ code: 'EIDOVERSE_ARGUMENT_INVALID',
+ });
+ }
+ if (JSON.stringify(args).length > 8192) {
+ throw new ServerError('Eidoverse operation args must be at most 8KB.', {
+ status: 400,
+ code: 'EIDOVERSE_ARGUMENT_INVALID',
+ });
+ }
+ return args;
+}
+
+function normalizeAugmentOperation(operation) {
+ const args = objectArgs(operation.args);
+ switch (operation.verb) {
+ case 'spawn': {
+ const normalized = {
+ id: validEntityId(args.id),
+ lib: validAssetPath(args.lib),
+ pos: args.pos === undefined ? [0, 0, 0] : vector3(args.pos, 'spawn.pos'),
+ yaw: safeNumber(args.yaw, 'spawn.yaw', { fallback: 0 }),
+ scale: safeNumber(args.scale, 'spawn.scale', { min: 0.01, max: 20, fallback: 1 }),
+ };
+ if (args.collide !== undefined) {
+ if (!['box', 'exact'].includes(args.collide)) {
+ throw new ServerError('spawn.collide must be box or exact.', { status: 400, code: 'EIDOVERSE_ARGUMENT_INVALID' });
+ }
+ normalized.collide = args.collide;
+ }
+ return { verb: operation.verb, args: normalized };
+ }
+ case 'place': {
+ const normalized = { id: validEntityId(args.id) };
+ if (args.pos !== undefined) normalized.pos = vector3(args.pos, 'place.pos');
+ if (args.yaw !== undefined) normalized.yaw = safeNumber(args.yaw, 'place.yaw');
+ if (args.scale !== undefined) normalized.scale = safeNumber(args.scale, 'place.scale', { min: 0.01, max: 20 });
+ if (Object.keys(normalized).length === 1) {
+ throw new ServerError('place needs pos, yaw, or scale.', { status: 400, code: 'EIDOVERSE_ARGUMENT_INVALID' });
+ }
+ return { verb: operation.verb, args: normalized };
+ }
+ case 'remove':
+ return { verb: operation.verb, args: { id: validEntityId(args.id) } };
+ case 'comp': {
+ const id = validEntityId(args.id);
+ const type = safeText(args.type, '').slice(0, 32);
+ if (!COMPONENT_TYPE_RE.test(type)) {
+ throw new ServerError('comp.type is invalid.', { status: 400, code: 'EIDOVERSE_ARGUMENT_INVALID' });
+ }
+ const data = args.data === undefined ? null : args.data;
+ if (JSON.stringify(data).length > 8192) {
+ throw new ServerError('comp.data must be at most 8KB.', { status: 400, code: 'EIDOVERSE_ARGUMENT_INVALID' });
+ }
+ return { verb: operation.verb, args: { id, type, data } };
+ }
+ case 'light':
+ return {
+ verb: operation.verb,
+ args: {
+ id: validEntityId(args.id),
+ pos: args.pos === undefined ? [0, 1, 0] : vector3(args.pos, 'light.pos'),
+ color: safeNumber(args.color, 'light.color', { min: 0, max: 0xffffff, fallback: 0xffd9a0 }),
+ intensity: safeNumber(args.intensity, 'light.intensity', { min: 0, max: 100, fallback: 16 }),
+ range: safeNumber(args.range, 'light.range', { min: 0.1, max: 100, fallback: 10 }),
+ },
+ };
+ case 'grant': {
+ const id = validEntityId(args.id);
+ const normalized = { id };
+ if (args.role !== undefined) {
+ if (!['owner', 'builder', 'visitor'].includes(args.role)) {
+ throw new ServerError('grant.role must be owner, builder, or visitor.', { status: 400, code: 'EIDOVERSE_ARGUMENT_INVALID' });
+ }
+ normalized.role = args.role;
+ }
+ if (args.gen !== undefined) {
+ if (typeof args.gen !== 'boolean') {
+ throw new ServerError('grant.gen must be boolean.', { status: 400, code: 'EIDOVERSE_ARGUMENT_INVALID' });
+ }
+ normalized.gen = args.gen;
+ }
+ if (!Object.hasOwn(normalized, 'role') && !Object.hasOwn(normalized, 'gen')) {
+ throw new ServerError('grant needs role or gen.', { status: 400, code: 'EIDOVERSE_ARGUMENT_INVALID' });
+ }
+ return { verb: operation.verb, args: normalized };
+ }
+ case 'terrain':
+ case 'grass':
+ case 'sky':
+ return { verb: operation.verb, args: JSON.parse(JSON.stringify(args)) };
+ default:
+ throw new ServerError(`Eidoverse verb is not available through PortOS: ${operation.verb}`, {
+ status: 400,
+ code: 'EIDOVERSE_ARGUMENT_INVALID',
+ });
+ }
+}
+
+export async function augmentEidoverseWorld(operations, { signal } = {}) {
+ return worldLock(async () => {
+ throwIfAborted(signal);
+ await assertInstalled();
+ const presence = await ensureCosPresenceInternal({ signal });
+ const normalized = operations.map(normalizeAugmentOperation);
+ await sendOperations(presence.connection, normalized, { signal });
+ return {
+ success: true,
+ world: presence.connection.world,
+ applied: normalized.length,
+ presence: presenceSummary(presence),
+ };
+ });
+}
+
+export async function sayInEidoverseWorld(text, { signal } = {}) {
+ return worldLock(async () => {
+ throwIfAborted(signal);
+ await assertInstalled();
+ const presence = await ensureCosPresenceInternal({ signal });
+ const message = safeText(text, '', 2000);
+ if (!message) {
+ throw new ServerError('A non-empty Eidoverse message is required.', {
+ status: 400,
+ code: 'EIDOVERSE_ARGUMENT_INVALID',
+ });
+ }
+ await presence.connection.sendVerb('say', { text: message }, { signal });
+ return { success: true, world: presence.connection.world, id: presence.connection.id };
+ });
+}
+
+export async function getEidoverseWorldStatus() {
+ const [setup, self] = await Promise.all([getEidoverseStatus(), getSelf()]);
+ const config = await readEidoverseWorldConfig(self);
+ return {
+ ...config,
+ identity: config.human,
+ presence: presenceSummary(),
+ setup: {
+ installed: setup.installed,
+ runtimeStatus: setup.runtimeStatus,
+ appId: setup.appId,
+ worldDataReady: setup.worldDataReady,
+ },
+ instance: {
+ id: self?.instanceId || null,
+ name: self?.name || null,
+ },
+ storage: {
+ classification: 'file-primary',
+ portosConfig: 'data/eidoverse/portos-world.json',
+ worldData: 'data/eidoverse/worlds',
+ federation: 'machine-local',
+ externalRuntime: 'private Eidoverse checkout state',
+ },
+ };
+}
+
+export async function closeEidoverseWorldConnections() {
+ return worldLock(() => closeCosPresenceInternal());
+}
+
+export const __resetEidoverseWorldForTests = closeEidoverseWorldConnections;
diff --git a/server/services/eidoverseWorld.runtime.test.js b/server/services/eidoverseWorld.runtime.test.js
new file mode 100644
index 0000000000..a16d25e3cd
--- /dev/null
+++ b/server/services/eidoverseWorld.runtime.test.js
@@ -0,0 +1,303 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ persistedState: null,
+ writes: 0,
+ worlds: new Map(),
+ sent: [],
+ deferredVerbAcks: [],
+ deferVerbAcks: 0,
+ appStatuses: [],
+ appStatusReads: 0,
+ self: { instanceId: 'instance-example', name: 'Example PortOS' },
+}));
+
+vi.mock('../lib/fileUtils.js', async (importActual) => {
+ const actual = await importActual();
+ return {
+ ...actual,
+ dataPath: (...segments) => `/mock/data/${segments.join('/')}`,
+ ensureDir: vi.fn(async () => {}),
+ readJSONFile: vi.fn(async (_path, fallback) => structuredClone(mocks.persistedState ?? fallback)),
+ atomicWrite: vi.fn(async (_path, value) => {
+ mocks.persistedState = structuredClone(value);
+ mocks.writes += 1;
+ }),
+ };
+});
+
+vi.mock('./instances.js', () => ({
+ getSelf: vi.fn(async () => mocks.self),
+ ensureSelf: vi.fn(async () => mocks.self),
+ getPeers: vi.fn(async () => []),
+}));
+
+vi.mock('./apps.js', () => ({
+ getAllApps: vi.fn(async () => []),
+ getAppStatuses: vi.fn(async () => {
+ mocks.appStatusReads += 1;
+ return mocks.appStatuses;
+ }),
+}));
+
+vi.mock('./eidoverse.js', () => ({
+ EIDOVERSE_PORT: 8940,
+ getEidoverseStatus: vi.fn(async () => ({
+ installed: true,
+ runtimeStatus: 'online',
+ appId: 'app-eidoverse',
+ worldDataReady: true,
+ })),
+}));
+
+vi.mock('ws', () => {
+ class FakeWebSocket {
+ static OPEN = 1;
+ static CLOSED = 3;
+
+ constructor() {
+ this.readyState = 0;
+ this.listeners = new Map();
+ this.identity = null;
+ this.world = null;
+ queueMicrotask(() => {
+ this.readyState = FakeWebSocket.OPEN;
+ this.emit('open');
+ });
+ }
+
+ on(event, listener) {
+ const listeners = this.listeners.get(event) || [];
+ listeners.push(listener);
+ this.listeners.set(event, listeners);
+ return this;
+ }
+
+ emit(event, value) {
+ for (const listener of this.listeners.get(event) || []) listener(value);
+ }
+
+ send(raw, callback) {
+ const message = JSON.parse(String(raw));
+ if (message.type === 'join') {
+ this.identity = message.id;
+ this.world = message.world;
+ const state = mocks.worlds.get(message.world) || { roles: {} };
+ if (!Object.keys(state.roles).length) state.roles[message.id] = { role: 'owner' };
+ else state.roles[message.id] ||= { role: 'visitor' };
+ mocks.worlds.set(message.world, state);
+ mocks.sent.push({ type: 'join', world: message.world, actor: message.id, agent: message.agent });
+ queueMicrotask(() => {
+ callback?.(null);
+ this.emit('message', JSON.stringify({
+ type: 'snapshot',
+ yourRights: { role: state.roles[message.id].role, gen: false },
+ state: structuredClone(state),
+ }));
+ });
+ return;
+ }
+ if (message.type === 'verb') {
+ const state = mocks.worlds.get(this.world);
+ if (message.verb === 'grant') {
+ state.roles[message.args.id] = {
+ ...(state.roles[message.args.id] || {}),
+ ...(message.args.role ? { role: message.args.role } : {}),
+ ...(message.args.gen !== undefined ? { gen: message.args.gen } : {}),
+ };
+ }
+ mocks.sent.push({
+ type: 'verb',
+ world: this.world,
+ actor: this.identity,
+ verb: message.verb,
+ args: structuredClone(message.args),
+ });
+ queueMicrotask(() => callback?.(null));
+ const acknowledge = () => {
+ if (this.readyState !== FakeWebSocket.OPEN) return;
+ this.emit('message', JSON.stringify({
+ type: 'log',
+ entry: { actor: this.identity, verb: message.verb, args: message.args },
+ }));
+ };
+ if (mocks.deferVerbAcks > 0) {
+ mocks.deferVerbAcks -= 1;
+ mocks.deferredVerbAcks.push(acknowledge);
+ } else {
+ queueMicrotask(acknowledge);
+ }
+ }
+ }
+
+ close() {
+ if (this.readyState === FakeWebSocket.CLOSED) return;
+ this.readyState = FakeWebSocket.CLOSED;
+ queueMicrotask(() => this.emit('close'));
+ }
+
+ terminate() {
+ this.close();
+ }
+ }
+
+ return { WebSocket: FakeWebSocket };
+});
+
+const world = await import('./eidoverseWorld.js');
+
+beforeEach(async () => {
+ await world.__resetEidoverseWorldForTests();
+ mocks.persistedState = null;
+ mocks.writes = 0;
+ mocks.worlds.clear();
+ mocks.sent.length = 0;
+ mocks.deferredVerbAcks.length = 0;
+ mocks.deferVerbAcks = 0;
+ mocks.appStatuses = [];
+ mocks.appStatusReads = 0;
+});
+
+describe('Eidoverse private-world lifecycle', () => {
+ it('keeps status read-only when config has not been persisted yet', async () => {
+ const status = await world.getEidoverseWorldStatus();
+
+ expect(status).toMatchObject({
+ world: 'portos',
+ identity: { name: 'Example PortOS', source: 'instance-name' },
+ presence: { connected: false },
+ });
+ expect(mocks.writes).toBe(0);
+ expect(mocks.persistedState).toBeNull();
+ });
+
+ it('gives the human and persistent CoS owner roles and hands ownership to a renamed human', async () => {
+ const first = await world.ensureEidoverseWorldPresence();
+
+ expect(first).toMatchObject({ connected: true, id: 'portos-cos', role: 'owner' });
+ expect(mocks.worlds.get('portos').roles).toMatchObject({
+ 'Example PortOS': { role: 'owner' },
+ 'portos-cos': { role: 'owner' },
+ });
+
+ await world.updateEidoverseWorldConfig({ humanName: 'Second Example User' });
+ expect(await world.getEidoverseWorldStatus()).toMatchObject({
+ identity: { name: 'Second Example User', role: null },
+ presence: { connected: false, role: null },
+ });
+ const reconnected = await world.ensureEidoverseWorldPresence();
+
+ expect(reconnected.role).toBe('owner');
+ expect(mocks.worlds.get('portos').roles['Second Example User']).toMatchObject({ role: 'owner' });
+ expect(mocks.worlds.get('portos').roles['Example PortOS']).toMatchObject({ role: 'visitor' });
+ expect(mocks.sent).toContainEqual(expect.objectContaining({
+ actor: 'portos-cos',
+ verb: 'grant',
+ args: { id: 'Second Example User', role: 'owner' },
+ }));
+ expect(mocks.sent).toContainEqual(expect.objectContaining({
+ actor: 'portos-cos',
+ verb: 'grant',
+ args: { id: 'Example PortOS', role: 'visitor' },
+ }));
+ expect(mocks.persistedState.ownership.retired).toEqual([]);
+ });
+
+ it('clears observed roles when switching worlds or CoS identities', async () => {
+ await world.ensureEidoverseWorldPresence();
+ await world.updateEidoverseWorldConfig({ world: 'second-world', cosId: 'second-cos' });
+
+ expect(await world.getEidoverseWorldStatus()).toMatchObject({
+ world: 'second-world',
+ identity: { role: null },
+ cos: { id: 'second-cos', connected: false, role: null },
+ presence: { connected: false, role: null },
+ });
+ });
+
+ it('retires the prior human owner when the world and human identity change together', async () => {
+ await world.ensureEidoverseWorldPresence();
+ await world.updateEidoverseWorldConfig({
+ world: 'second-world',
+ humanName: 'Second Example User',
+ });
+ await world.ensureEidoverseWorldPresence();
+
+ expect(mocks.worlds.get('portos').roles['Example PortOS']).toMatchObject({ role: 'visitor' });
+ expect(mocks.worlds.get('second-world').roles).toMatchObject({
+ 'Second Example User': { role: 'owner' },
+ 'portos-cos': { role: 'owner' },
+ });
+ expect(mocks.sent).toContainEqual(expect.objectContaining({
+ world: 'portos',
+ actor: 'portos-cos',
+ verb: 'grant',
+ args: { id: 'Example PortOS', role: 'visitor' },
+ }));
+ expect(mocks.persistedState.ownership.retired).toEqual([]);
+ });
+
+ it('closes the persistent connection when the CoS presence is disabled', async () => {
+ await world.ensureEidoverseWorldPresence();
+ await world.updateEidoverseWorldConfig({ cosEnabled: false });
+
+ expect((await world.getEidoverseWorldStatus()).presence.connected).toBe(false);
+ await expect(world.ensureEidoverseWorldPresence()).rejects.toMatchObject({ code: 'EIDOVERSE_COS_DISABLED' });
+ });
+
+ it('stops a multi-operation augmentation before sending the next verb when canceled', async () => {
+ await world.ensureEidoverseWorldPresence();
+ mocks.sent.length = 0;
+ const controller = new AbortController();
+ const pending = world.augmentEidoverseWorld([
+ { verb: 'spawn', args: { id: 'example-one', lib: 'eidoverse/assets/models/example.glb' } },
+ { verb: 'spawn', args: { id: 'example-two', lib: 'eidoverse/assets/models/example.glb' } },
+ ], { signal: controller.signal });
+
+ await vi.waitFor(() => {
+ expect(mocks.sent).toContainEqual(expect.objectContaining({ verb: 'spawn', args: expect.objectContaining({ id: 'example-one' }) }));
+ });
+ controller.abort();
+
+ await expect(pending).rejects.toMatchObject({ name: 'AbortError' });
+ expect(mocks.sent).not.toContainEqual(expect.objectContaining({ verb: 'spawn', args: expect.objectContaining({ id: 'example-two' }) }));
+ });
+
+ it('drops a canceled verb connection so its late acknowledgement cannot satisfy a retry', async () => {
+ await world.ensureEidoverseWorldPresence();
+ mocks.sent.length = 0;
+ mocks.deferVerbAcks = 2;
+ const operation = [{ verb: 'spawn', args: { id: 'example-one', lib: 'eidoverse/assets/models/example.glb' } }];
+ const controller = new AbortController();
+ const first = world.augmentEidoverseWorld(operation, { signal: controller.signal });
+
+ await vi.waitFor(() => expect(mocks.deferredVerbAcks).toHaveLength(1));
+ controller.abort();
+ await expect(first).rejects.toMatchObject({ name: 'AbortError' });
+
+ let retrySettled = false;
+ const retry = world.augmentEidoverseWorld(operation).finally(() => { retrySettled = true; });
+ await vi.waitFor(() => expect(mocks.deferredVerbAcks).toHaveLength(2));
+ mocks.deferredVerbAcks[0]();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ expect(retrySettled).toBe(false);
+
+ mocks.deferredVerbAcks[1]();
+ await expect(retry).resolves.toMatchObject({ success: true, applied: 1 });
+ });
+
+ it('releases a canceled projection without waiting for a slow source read', async () => {
+ let resolveAppStatuses;
+ mocks.appStatuses = new Promise((resolve) => {
+ resolveAppStatuses = resolve;
+ });
+ const controller = new AbortController();
+ const pending = world.projectEidoverseWorld({ signal: controller.signal });
+
+ await vi.waitFor(() => expect(mocks.appStatusReads).toBe(1));
+ controller.abort();
+
+ await expect(pending).rejects.toMatchObject({ name: 'AbortError' });
+ resolveAppStatuses([]);
+ });
+});
diff --git a/server/services/eidoverseWorld.test.js b/server/services/eidoverseWorld.test.js
new file mode 100644
index 0000000000..71165f85b3
--- /dev/null
+++ b/server/services/eidoverseWorld.test.js
@@ -0,0 +1,142 @@
+import { describe, expect, it } from 'vitest';
+import {
+ buildProjectionPlan,
+ DEFAULT_EIDOVERSE_PROJECTION_RECIPE,
+} from './eidoverseWorld.js';
+import { eidoverseProjectionRecipeSchema } from '../lib/validation.js';
+
+const emptySources = () => ({
+ apps: [],
+ agents: [],
+ tasks: [],
+ features: [],
+ peers: [],
+ health: null,
+ productivity: [],
+ activity: [],
+ goals: [],
+ memory: [],
+ storage: [],
+ jira: [],
+ operations: [],
+});
+
+const appSource = () => ({
+ ...emptySources(),
+ apps: [{ id: 'app-example', label: 'Example app', status: 'online', type: 'bun', managed: true }],
+ health: { apps: { total: 1, online: 1 } },
+});
+
+describe('Eidoverse PortOS projection plan', () => {
+ it('keeps the shipped recipe valid at the route schema boundary', () => {
+ expect(eidoverseProjectionRecipeSchema.parse(DEFAULT_EIDOVERSE_PROJECTION_RECIPE)).toEqual(
+ DEFAULT_EIDOVERSE_PROJECTION_RECIPE,
+ );
+ });
+
+ it('creates stable model and metadata operations for available sources', () => {
+ const first = buildProjectionPlan({ source: appSource() });
+ const second = buildProjectionPlan({ source: appSource() });
+
+ expect(second).toEqual(first);
+ expect(first.summary.sourceAvailability).toMatchObject({ apps: true, agents: true, health: true });
+ expect(first.operations).toEqual(expect.arrayContaining([
+ expect.objectContaining({ verb: 'terrain' }),
+ expect.objectContaining({ verb: 'spawn', args: expect.objectContaining({ lib: DEFAULT_EIDOVERSE_PROJECTION_RECIPE.assets.app }) }),
+ expect.objectContaining({ verb: 'comp', args: expect.objectContaining({ type: 'portos' }) }),
+ ]));
+ expect(first.summary.created).toBe(2);
+ });
+
+ it('treats a zero limit as intentional and does not fall back to the source length', () => {
+ const recipe = {
+ ...DEFAULT_EIDOVERSE_PROJECTION_RECIPE,
+ limits: { ...DEFAULT_EIDOVERSE_PROJECTION_RECIPE.limits, apps: 0 },
+ };
+ const plan = buildProjectionPlan({
+ source: appSource(),
+ recipe,
+ currentState: { terrain: recipe.terrain, entities: {} },
+ });
+
+ expect(plan.operations.some((operation) => operation.verb === 'spawn' && operation.args.lib === recipe.assets.app)).toBe(false);
+ expect(plan.summary.sourceCounts.apps).toBe(1);
+ });
+
+ it('does not remove generated entities when their source is temporarily unavailable', () => {
+ const created = buildProjectionPlan({ source: appSource(), currentState: { terrain: DEFAULT_EIDOVERSE_PROJECTION_RECIPE.terrain } });
+ const appSpawn = created.operations.find((operation) => operation.verb === 'spawn' && operation.args.lib === DEFAULT_EIDOVERSE_PROJECTION_RECIPE.assets.app);
+ const unavailable = buildProjectionPlan({
+ source: { ...emptySources(), apps: null },
+ currentState: {
+ terrain: DEFAULT_EIDOVERSE_PROJECTION_RECIPE.terrain,
+ entities: { [appSpawn.args.id]: appSpawn.args },
+ },
+ });
+
+ expect(unavailable.summary.sourceAvailability.apps).toBe(false);
+ expect(unavailable.operations).not.toContainEqual({ verb: 'remove', args: { id: appSpawn.args.id } });
+ });
+
+ it('removes generated entities after a confirmed empty source read', () => {
+ const created = buildProjectionPlan({ source: appSource(), currentState: { terrain: DEFAULT_EIDOVERSE_PROJECTION_RECIPE.terrain } });
+ const appSpawn = created.operations.find((operation) => operation.verb === 'spawn' && operation.args.lib === DEFAULT_EIDOVERSE_PROJECTION_RECIPE.assets.app);
+ const empty = buildProjectionPlan({
+ source: { ...emptySources(), health: { apps: { total: 0, online: 0 } } },
+ currentState: {
+ terrain: DEFAULT_EIDOVERSE_PROJECTION_RECIPE.terrain,
+ entities: { [appSpawn.args.id]: appSpawn.args },
+ },
+ });
+
+ expect(empty.operations).toContainEqual({ verb: 'remove', args: { id: appSpawn.args.id } });
+ expect(empty.summary.removed).toBe(1);
+ });
+
+ it('materializes the expanded OpenWorld resource contract as stable model metadata', () => {
+ const source = {
+ ...emptySources(),
+ health: { apps: { total: 1, online: 1 }, diskPercent: 42 },
+ productivity: [{ id: 'summary', label: 'Productivity', completedToday: 3 }],
+ activity: [{ id: 'summary', label: 'Activity calendar', activeDays: 2 }],
+ goals: [{ id: 'goal-example', label: 'Example goal', progress: 50 }],
+ memory: [{ id: 'projects', label: 'Memory projects', count: 4 }],
+ storage: [{ id: 'database', label: 'PostgreSQL', status: 'online', tableCount: 3 }],
+ jira: [{ id: 'EX-1', label: 'Example ticket', status: 'To Do' }],
+ operations: [{ id: 'overview', label: 'PortOS operations', inbox: { total: 2 } }],
+ };
+ const plan = buildProjectionPlan({
+ source,
+ currentState: { terrain: DEFAULT_EIDOVERSE_PROJECTION_RECIPE.terrain },
+ });
+
+ expect(plan.summary.sourceAvailability).toMatchObject({
+ productivity: true,
+ activity: true,
+ goals: true,
+ memory: true,
+ storage: true,
+ jira: true,
+ operations: true,
+ });
+ expect(plan.summary.sourceCounts).toMatchObject({
+ productivity: 1,
+ activity: 1,
+ goals: 1,
+ memory: 1,
+ storage: 1,
+ jira: 1,
+ operations: 1,
+ });
+
+ const components = new Map(
+ plan.operations
+ .filter((operation) => operation.verb === 'comp')
+ .map((operation) => [operation.args.data.sourceId, operation.args.data]),
+ );
+ expect(components.get('goal-example')).toMatchObject({ resource: 'goals', progress: 50 });
+ expect(components.get('database')).toMatchObject({ resource: 'storage', tableCount: 3 });
+ expect(components.get('overview')).toMatchObject({ resource: 'operations', inbox: { total: 2 } });
+ expect(plan.operations.filter((operation) => operation.verb === 'spawn')).toHaveLength(8);
+ });
+});
diff --git a/server/test/fixtures/agent-context-eval.json b/server/test/fixtures/agent-context-eval.json
index add2c1c415..42f59b8013 100644
--- a/server/test/fixtures/agent-context-eval.json
+++ b/server/test/fixtures/agent-context-eval.json
@@ -89,7 +89,7 @@
"advertisedToolsCovered": true,
"readOnlyTools": true,
"equals": [
- { "path": "manifest.schemaVersion", "value": 3 },
+ { "path": "manifest.schemaVersion", "value": 4 },
{ "path": "manifest.limits.maxApproxTokens", "value": 5000 },
{ "path": "manifest.tools.length", "value": 5 }
],