Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: label projected Eidoverse objects with what they represent (#6275)
[._.]/ Adam Eivy2634cd3d7f29
diff --git a/server/lib/README.md b/server/lib/README.mdindex 466b8d3276..a257259b42 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -479,6 +479,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `domainAutonomy.js` | Per-domain autonomy guardrails (pure). `AUTONOMY_DOMAINS`/`DOMAIN_IDS`/`DOMAIN_MODES` (`off`/`dry-run`/`execute`), `getDomainMode(config, id)`, and `normalizeDomainAutonomy(raw)` to coerce a hand-edited/partial map. Default per domain is `execute` (reproduces pre-#711 behavior, so no migration needed). Also `CREATIVE_DOMAIN`/`getCreativeAutonomyMode(config)` (#2183) — the Creative Director orchestrator domain, kept out of `DOMAIN_IDS` and defaulting to mirror the `cos` mode. || `domainBudgets.js` | Per-domain daily autonomy budgets (pure). `BUDGET_LIMIT_FIELDS` (`maxActionsPerDay`/`maxMinutesPerDay`), `getDomainBudget(config, id)`, `normalizeDomainBudgets(raw)`, `hasBudget(budget)`, and `evaluateBudget(budget, usage)` → `{ withinBudget, exceeded }`. A `null`/non-positive cap means unlimited (default per domain, so no migration needed). Token/$ caps are intentionally absent — CLI subscription providers expose no per-run metering. Usage ledger + gate wiring live in `services/domainUsage.js`. || `eidoverseWorldDesign.js` | Immutable Eidoverse World Design V1/V2 registry, legacy override migration, semantic district contract, 48-signal ceiling, and deterministic library-only asset-recipe resolution/locking for the PortOS Luminous Systems Garden. |+| `eidoverseWorldLabels.js` | The `comp.label` component PortOS attaches to every entity it projects into Eidoverse (eidoverse-worlds#5), so a rendered building says what it represents instead of only naming its decorative model. `buildEidoverseLabel(component)` reads one already-built `comp.portos` payload and returns `{name, description?, visibility, offset?}` — district and world-identity landmarks always visible, live indicators labelled `nearby`, path markers `inspect`-only so a walkway cannot bury the district it leads to — and `null` for anything not `managedBy: 'portos'`, so a caller cannot label somebody else's entity. Names and descriptions are built from PortOS's own vocabulary (district label, kind label, resource category, coarse status, freshness) plus an opaque hashed resource ref for disambiguation, never from record contents, machine identity, addresses, or filesystem paths — the append-only world log is the strictest privacy boundary PortOS writes to. Also owns `safeWorldText`, the one control-character/length sanitizer shared with `services/eidoverseWorldProjection.js` so a component field and the label built from it cannot disagree about what is safe. Pure. || `errorHandler.js` | `ServerError` + `asyncHandler` middleware, plus `sendErrorResponse`/`buildErrorEnvelope` for the standard `{ error, code, timestamp }` body outside a handler's catch. || `extensionErrors.js` | `isExtensionError(payload)` — true when a client error report came from a browser extension's injected content script (extension URL scheme in `source`/`stack`/`message`, or a short list of vendor/runtime message signatures) rather than from PortOS. Consumed by `services/clientErrors.js` to keep un-actionable extension noise out of the Review Hub *and* out of the 1/sec throttle slot, where it would displace real errors. **Authoritative copy** — mirrored at `client/src/lib/extensionErrors.js`, parity enforced by `extensionErrors.mirror.test.js`. || `fetchErrorChain.js` | `describeFetchError(err)` flattens a fetch rejection's whole `cause` chain (depth-bounded, cycle-guarded) into one searchable `code: message` string — undici reports every network failure as the same opaque `TypeError: fetch failed` with the real reason nested inside, so a classifier reading only `err.message` misjudges every one of them. `isReplayableConnectionError(err)` is the narrow predicate over that string for connection-REUSE artifacts (HTTP/2 GOAWAY, reset, hang-up) that are safe to replay once via `fetchWithTimeout`'s `shouldRetry`; it deliberately EXCLUDES timeouts, which broader classifiers like `ollamaManager`'s `isTransientPullError` include. |diff --git a/server/lib/eidoverseWorldLabels.js b/server/lib/eidoverseWorldLabels.jsnew file mode 100644index 0000000000..33c411d674--- /dev/null+++ b/server/lib/eidoverseWorldLabels.js@@ -0,0 +1,145 @@+/**+ * Human-readable labels for the entities PortOS projects into Eidoverse.+ *+ * A projected building renders, but a model file cannot say what it stands for.+ * `buildEidoverseLabel` turns one already-built `comp.portos` payload into the+ * renderer-generic `comp.label` component (eidoverse-worlds#5), so the initial+ * projection, ordinary updates, and stale-resource retention all derive the+ * same text from the same place instead of each inventing its own.+ *+ * Every string here is generated from PortOS's own vocabulary — district and+ * kind names, coarse status, freshness — plus an opaque hashed resource ref.+ * Nothing that could name a record, a machine, a network, or a filesystem ever+ * reaches the append-only world log, and a label describes what an object+ * represents rather than the decorative asset standing in for it.+ */++export const EIDOVERSE_LABEL_COMPONENT_TYPE = 'label';+export const EIDOVERSE_LABEL_VISIBILITIES = Object.freeze(['always', 'nearby', 'inspect']);++const MAX_NAME_CHARS = 72;+const MAX_DESCRIPTION_CHARS = 240;+// Landmarks are large and read from across a district; indicators and the+// world-identity marker are small, so their plaques sit just above the model.+const LANDMARK_OFFSET = Object.freeze([0, 4, 0]);+const MARKER_OFFSET = Object.freeze([0, 1.5, 0]);++/**+ * The one sanitizer for text PortOS writes into a world: control characters+ * out, trimmed, hard length cap. Shared with the projector so a component field+ * and the label built from it can never disagree about what is safe.+ */+export function safeWorldText(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;+}++// What a projected indicator stands for, in category terms only. These are+// PortOS's own words for its own feature areas — never a record's own name.+const RESOURCE_MEANING = Object.freeze({+ apps: 'an app this install manages',+ agents: 'a Chief of Staff agent run',+ tasks: 'a scheduled or queued task',+ features: 'an optional instance feature',+ peers: 'a federated PortOS peer',+ health: 'the install-wide health rollup',+ productivity: 'the productivity queue rollup',+ activity: 'a recent activity pulse',+ goals: 'a tracked goal',+ memory: 'a memory-store aggregate',+ storage: 'a datastore rollup',+ jira: 'a current-work rollup',+ operations: 'the operations rollup',+});++const FRESHNESS_PHRASE = Object.freeze({+ current: 'data is current',+ stale: 'data is stale because its source is unavailable',+});++/** Opaque disambiguator so two indicators of one kind are tellable apart. */+function resourceRef(resourceKey) {+ const hash = safeWorldText(resourceKey, '', 64).split('-').pop() || '';+ return /^[0-9a-f]{6,}$/.test(hash) ? hash.slice(0, 6) : '';+}++function label({ name, description, visibility, offset }) {+ const safeName = safeWorldText(name, '', MAX_NAME_CHARS);+ if (!safeName) return null;+ const safeDescription = safeWorldText(description, '', MAX_DESCRIPTION_CHARS);+ return {+ name: safeName,+ ...(safeDescription ? { description: safeDescription } : {}),+ visibility,+ ...(offset ? { offset: [...offset] } : {}),+ };+}++function districtLabel(component) {+ const enabled = Array.isArray(component.enabledSources) ? component.enabledSources : [];+ return label({+ name: component.label,+ description: `${[+ `PortOS ${safeWorldText(component.direction, 'central', 40).toLowerCase()} district`,+ `landmark: ${safeWorldText(component.landmark, 'district marker', 60)}`,+ enabled.length ? `projecting ${enabled.join(', ')}` : 'no sources enabled',+ ].join('. ')}.`,+ visibility: 'always',+ offset: LANDMARK_OFFSET,+ });+}++function pathNodeLabel(component) {+ const route = safeWorldText(component.label, 'district walkway', MAX_NAME_CHARS);+ return label({+ name: route,+ description: `Walkway marker ${component.node} on the ${route} route.`,+ // Path markers are numerous and tiny; a floating plaque on each would bury+ // the districts they lead to, so they answer only when inspected.+ visibility: 'inspect',+ });+}++function worldMetaLabel(component) {+ return label({+ name: component.meta?.title,+ description: 'This world is projected by PortOS. Every landmark and indicator in it is generated from aggregate signals, never from record contents.',+ visibility: 'always',+ offset: MARKER_OFFSET,+ });+}++function signalLabel(component) {+ const ref = resourceRef(component.resourceKey);+ const kindLabel = safeWorldText(component.label, 'PortOS signal', 48);+ const meaning = RESOURCE_MEANING[component.resource] || 'a PortOS signal';+ const freshness = FRESHNESS_PHRASE[component.freshness]+ || `data is ${safeWorldText(component.freshness, 'unknown', 24)}`;+ return label({+ name: ref ? `${kindLabel} ${ref}` : kindLabel,+ description: `${[+ `In ${safeWorldText(component.districtLabel, 'the PortOS Nexus', 64)}: ${meaning}`,+ 'aggregate counts only, no record names',+ `status is ${safeWorldText(component.status, 'unknown', 24)} and ${freshness}`,+ ].join('. ')}.`,+ visibility: 'nearby',+ offset: MARKER_OFFSET,+ });+}++const LABEL_BUILDERS = Object.freeze({+ district: districtLabel,+ 'path-node': pathNodeLabel,+ 'world-meta': worldMetaLabel,+});++/**+ * Build the `comp.label` payload for a PortOS-owned entity from the+ * `comp.portos` component already computed for it. Returns `null` for anything+ * PortOS does not own, so a caller can never label somebody else's entity.+ */+export function buildEidoverseLabel(component) {+ if (!component || component.managedBy !== 'portos') return null;+ return (LABEL_BUILDERS[component.kind] || signalLabel)(component);+}diff --git a/server/lib/index.js b/server/lib/index.jsindex b81fb5e76c..f162910f2b 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -456,6 +456,7 @@ export * from './dispatchLabels.js';export * from './domainAutonomy.js';export * from './domainBudgets.js';export * from './eidoverseWorldDesign.js';+export * from './eidoverseWorldLabels.js';export * from './errorHandler.js';export * from './extensionErrors.js';export * from './fetchErrorChain.js';diff --git a/server/services/eidoverseWorld.test.js b/server/services/eidoverseWorld.test.jsindex d5b6dfc110..cef3b1ce27 100644--- a/server/services/eidoverseWorld.test.js+++ b/server/services/eidoverseWorld.test.js@@ -7,6 +7,7 @@ import {} from './eidoverseWorld.js';import { eidoverseProjectionRecipeSchema } from '../lib/validation.js';import { EIDOVERSE_META_ENTITY_ID, EIDOVERSE_WORLD_DESIGN_VERSION } from '../lib/eidoverseWorldDesign.js';+import { EIDOVERSE_LABEL_VISIBILITIES } from '../lib/eidoverseWorldLabels.js';const APP_FALLBACK = DEFAULT_EIDOVERSE_PROJECTION_RECIPE.assetRecipe.slots.app.fallback;@@ -783,15 +784,28 @@ describe('Eidoverse world self-description', () => {currentState,});expect(renamed.operations.filter(({ args }) => args?.id === EIDOVERSE_META_ENTITY_ID))- .toEqual([{- layer: 'infrastructure',- verb: 'comp',- args: {- id: EIDOVERSE_META_ENTITY_ID,- type: 'portos',- data: expect.objectContaining({ meta: { title: 'Renamed Garden', hostId: meta.hostId } }),+ .toEqual([+ {+ layer: 'infrastructure',+ verb: 'comp',+ args: {+ id: EIDOVERSE_META_ENTITY_ID,+ type: 'portos',+ data: expect.objectContaining({ meta: { title: 'Renamed Garden', hostId: meta.hostId } }),+ },+ },+ // Renaming the world renames its plaque in the same pass, so the two+ // can never describe different worlds.+ {+ layer: 'infrastructure',+ verb: 'comp',+ args: {+ id: EIDOVERSE_META_ENTITY_ID,+ type: 'label',+ data: expect.objectContaining({ name: 'Renamed Garden', visibility: 'always' }),+ },},- }]);+ ]);});// A managed entity the plan no longer wants is swept by the reconciliation@@ -813,3 +827,145 @@ describe('Eidoverse world self-description', () => {});});});++// Values a live install genuinely holds — invented here, never observed. The+// append-only world log is replicated to a renderer PortOS does not run, so a+// record title, a machine name, an address, or a repository path reaching a+// label is a privacy incident, not a cosmetic bug.+const PRIVATE_FIXTURE_VALUES = [+ 'Acme Payroll Sync',+ 'Ship the Q3 invoice run',+ 'host-XXXX.example.ts.net',+ '192.0.2.10',+ '/Users/example-user/github.com/acme/private-notes',+ '[email protected]',+];++const privateSource = () => ({+ ...emptySources(),+ apps: [{+ id: 'app-acme-payroll',+ label: 'Acme Payroll Sync',+ status: 'online',+ installPath: '/Users/example-user/github.com/acme/private-notes',+ host: 'host-XXXX.example.ts.net',+ restarts: 2,+ }],+ tasks: [{+ id: 'task-invoice',+ title: 'Ship the Q3 invoice run',+ prompt: 'Ship the Q3 invoice run',+ status: 'running',+ }],+ peers: [{ id: 'peer-lab', label: 'host-XXXX.example.ts.net', address: '192.0.2.10', status: 'online' }],+ memory: [{ id: 'memory-inbox', owner: '[email protected]', status: 'active', entries: 12 }],+ health: { id: 'overview', status: 'healthy' },+});++const labelOps = (plan) => plan.operations.filter(({ verb, args }) => verb === 'comp' && args.type === 'label');++const labelFor = (plan, id) => labelOps(plan).find(({ args }) => args.id === id)?.args.data;++describe('Eidoverse projection labels', () => {+ it('names every owned landmark, walkway, world identity and live indicator by what it represents', () => {+ const plan = buildProjectionPlan({ source: appSource(), meta: { title: 'Example Garden', hostId: 'hst_0123456789ab' } });+ const district = labelFor(plan, 'portos-design-v2-infra-apps');+ const pathNode = labelOps(plan).find(({ args }) => args.id.startsWith('portos-design-v2-path-'))?.args.data;+ const worldMeta = labelFor(plan, EIDOVERSE_META_ENTITY_ID);+ const signal = labelFor(plan, signalSpawn(plan, 'app').args.id);++ // Landmarks read from across a district; the walkway markers that lead to+ // them are numerous, so only landmarks and the world identity float.+ expect(district).toMatchObject({ name: 'App Terraces', visibility: 'always' });+ expect(district.description).toContain('service pylons');+ expect(district.description).toContain('apps');+ expect(pathNode).toMatchObject({ visibility: 'inspect' });+ expect(pathNode.name).toBe('Nexus to App Terraces');+ expect(worldMeta).toMatchObject({ name: 'Example Garden', visibility: 'always' });+ expect(signal).toMatchObject({ visibility: 'nearby' });+ expect(signal.name).toMatch(/^Managed app [0-9a-f]{6}$/);+ expect(signal.description).toContain('App Terraces');+ expect(signal.description).toContain('an app this install manages');++ // Every managed model carries one, and none of them describes the+ // decorative asset that happens to stand in for it.+ const managedSpawns = plan.operations+ .filter(({ verb, args }) => verb === 'spawn' && args.id.startsWith('portos-design-v2-'))+ .map(({ args }) => args.id);+ expect(labelOps(plan).map(({ args }) => args.id).sort()).toEqual(managedSpawns.sort());+ expect(labelOps(plan).every(({ args }) => !/\.glb|assets\/models/.test(JSON.stringify(args.data)))).toBe(true);+ // A visibility the renderer does not know is a label it silently drops.+ expect(labelOps(plan).every(({ args }) => EIDOVERSE_LABEL_VISIBILITIES.includes(args.data.visibility))).toBe(true);+ });++ it('keeps record contents, machine identity, addresses and paths out of every projected payload', () => {+ const plan = buildProjectionPlan({+ source: privateSource(),+ meta: { title: 'Example Garden', hostId: 'hst_0123456789ab' },+ });+ const serialized = JSON.stringify(plan.operations);++ for (const value of PRIVATE_FIXTURE_VALUES) {+ expect(serialized).not.toContain(value);+ }+ // The labels are still useful: they name the category and its district.+ expect(labelOps(plan).length).toBeGreaterThan(0);+ expect(labelOps(plan).map(({ args }) => args.data.name)).toEqual(+ expect.arrayContaining([expect.stringContaining('Federated peer')]),+ );+ });++ it('emits no label verbs for an unchanged world and never duplicates a label', () => {+ const first = buildProjectionPlan({ source: appSource(), meta: { title: 'Example Garden', hostId: 'hst_0123456789ab' } });+ const currentState = snapshotFromPlan(first, { foldModelDefaults: true });+ const second = buildProjectionPlan({+ source: appSource(),+ meta: { title: 'Example Garden', hostId: 'hst_0123456789ab' },+ currentState,+ });++ expect(labelOps(second)).toEqual([]);+ const ids = labelOps(first).map(({ args }) => args.id);+ expect(new Set(ids).size).toBe(ids.length);+ });++ it('labels only PortOS-owned entities and drops the label when the world reset sweeps them', () => {+ const first = buildProjectionPlan({ source: appSource() });+ const currentState = snapshotFromPlan(first, { foldModelDefaults: true });+ currentState.entities['example-manual-model'] = {+ id: 'example-manual-model',+ lib: 'store/example-manual-model',+ pos: [1, 0, 1],+ comp: { label: { name: 'Authored by a visitor', visibility: 'always' } },+ };+ const next = buildProjectionPlan({ source: appSource(), currentState });++ expect(next.operations.some(({ args }) => args?.id === 'example-manual-model')).toBe(false);+ // A managed entity is removed whole, so its label leaves with it — PortOS+ // never issues a bare label delete against someone else's entity.+ expect(first.operations.filter(({ verb }) => verb === 'remove')).toEqual([]);+ });++ it('explains why a retained indicator is stale once its source goes away', () => {+ const created = buildProjectionPlan({ source: appSource(), currentState: currentEnvironment() });+ const appSpawn = signalSpawn(created, 'app');+ const entityId = appSpawn.args.id;+ const currentComponent = created.operations.find((operation) => (+ operation.verb === 'comp' && operation.args.id === entityId && operation.args.type === 'portos'+ )).args.data;+ const unavailable = buildProjectionPlan({+ source: { ...emptySources(), apps: null },+ currentState: {+ ...currentEnvironment(),+ entities: {+ [entityId]: {+ ...appSpawn.args,+ comp: { portos: currentComponent, label: labelFor(created, entityId) },+ },+ },+ },+ });++ expect(labelFor(unavailable, entityId).description).toContain('data is stale');+ });+});diff --git a/server/services/eidoverseWorldProjection.js b/server/services/eidoverseWorldProjection.jsindex 764769f6ba..217f9e02de 100644--- a/server/services/eidoverseWorldProjection.js+++ b/server/services/eidoverseWorldProjection.js@@ -21,6 +21,11 @@ import {resolveEidoverseDesign,stableEidoverseUnit,} from '../lib/eidoverseWorldDesign.js';+import {+ buildEidoverseLabel,+ EIDOVERSE_LABEL_COMPONENT_TYPE,+ safeWorldText,+} from '../lib/eidoverseWorldLabels.js';const LEGACY_PROJECTION_ID_PREFIX = 'portos-projection-';const PROJECTION_ID_PREFIX = EIDOVERSE_PROJECTION_PREFIX;@@ -68,11 +73,6 @@ const DISTRICT_SCALE = Object.freeze({export const DEFAULT_EIDOVERSE_PROJECTION_RECIPE = EIDOVERSE_WORLD_DESIGN_V2;-const 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;-};const shortHash = (value) => createHash('sha256').update(String(value)).digest('hex').slice(0, 12);function mergeRecipe(recipe) {@@ -159,7 +159,7 @@ function entityPosition(sourceId, sourceKey, districts) {function worldSignal(kind, sourceKey, item, districts) {const district = districtForSource(districts, sourceKey);- const sourceIdentity = safeText(item?.id, '', 160) || canonicalStringify(item);+ const sourceIdentity = safeWorldText(item?.id, '', 160) || canonicalStringify(item);const resourceKey = `${kind}-${shortHash(`${kind}:${sourceIdentity}`)}`;const metrics = {};for (const [key, value] of Object.entries(item || {}).slice(0, 20)) {@@ -252,6 +252,19 @@ function nexusStatusLight(light, source, existing) {return { ...light, color: 0xa78bfa, intensity: 20 };}+/**+ * The single place a `comp.label` verb is minted. Initial projection, ordinary+ * updates, and stale-resource retention all route through here, so a rendered+ * plaque can never drift from the `comp.portos` payload it describes. Returns+ * `null` when the entity already carries exactly this label, which is what+ * keeps a no-op projection from emitting label verbs.+ */+function labelOperation({ prior, id, component, layer }) {+ const label = buildEidoverseLabel(component);+ if (equal(prior ?? null, label)) return null;+ return { layer, verb: 'comp', args: { id, type: EIDOVERSE_LABEL_COMPONENT_TYPE, data: label } };+}+function upsertModel({operations,stateEntities,@@ -296,6 +309,11 @@ function upsertModel({operations.push({ layer, verb: 'comp', args: { id, type: COMPONENT_TYPE, data: component } });if (existing) updated += 1;}+ const labelOp = labelOperation({ prior: priorComponents?.[EIDOVERSE_LABEL_COMPONENT_TYPE], id, component, layer });+ if (labelOp) {+ operations.push(labelOp);+ if (existing) updated += 1;+ }if (!equal(priorComponents?.motion ?? null, motion)) {operations.push({ layer: motionLayer, verb: 'comp', args: { id, type: 'motion', data: motion } });if (existing) updated += 1;@@ -489,8 +507,8 @@ export function buildProjectionPlan({ source = {}, recipe = DEFAULT_EIDOVERSE_PR// World title and host identity only — never a record, a machine name,// an address, or a filesystem path.meta: {- title: safeText(meta.title, effectiveRecipe.name, 120),- hostId: safeText(meta.hostId, '', 64) || null,+ title: safeWorldText(meta.title, effectiveRecipe.name, 120),+ hostId: safeWorldText(meta.hostId, '', 64) || null,},},layer: 'infrastructure',@@ -612,6 +630,16 @@ export function buildProjectionPlan({ source = {}, recipe = DEFAULT_EIDOVERSE_PRoperations.push({ layer: 'live', verb: 'comp', args: { id, type: COMPONENT_TYPE, data: staleComponent } });updated += 1;}+ const staleLabelOp = labelOperation({+ prior: existing?.comp?.[EIDOVERSE_LABEL_COMPONENT_TYPE],+ id,+ component: staleComponent,+ layer: 'live',+ });+ if (staleLabelOp) {+ operations.push(staleLabelOp);+ updated += 1;+ }const staleMotion = {type: 'bob', amp: 0.12, period: 6,phase: Number((stableEidoverseUnit(`${id}:stale`) * Math.PI * 2).toFixed(4)),