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

refactor: keep Eidoverse signal helpers independent of source reads (#7105)

[._.]/ Adam Eivy108894fbd93e
diff --git a/docs/features/eidoverse.md b/docs/features/eidoverse.md
index 5d604c9edd..008f4d662b 100644
--- a/docs/features/eidoverse.md
+++ b/docs/features/eidoverse.md
@@ -7,6 +7,16 @@ installs, and enables the runtime; the ordinary feature toggle never installs it
If Bun is not already available, the same action first runs Bun's official
platform installer under the PortOS service account on Windows, macOS, or Linux.
+## Signal ownership
+
+`server/services/eidoverseWorldSources.js` owns local reads, cancellation, Jira
+fetching, and destination lookup. It passes snapshots to the pure
+`server/lib/eidoverseWorldSignals.js` owner for bounded aggregates and stable
+opaque IDs. `server/services/eidoverseWorldProjection.js` then plans world verbs
+from those signals. World orchestration loads the collector only during explicit
+projection; identity and travel consumers import the pure signal owner directly.
+The collector and world service retain their historical helper exports.
+
## What PortOS installs
The installer keeps the two AGPL-3.0 projects as independent git checkouts. The
diff --git a/server/lib/README.md b/server/lib/README.md
index a916d7dfad..a540e45a69 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -552,6 +552,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `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/V3 registry, override migration, semantic districts, 48-signal ceiling, and install-local asset locks for PortOS Commons. |
| `eidoverseWorldLabels.js` | The `comp.label` component PortOS attaches to every entity it projects into Eidoverse (eidoverse-worlds#5), so a rendered building says what it represents instead of only naming its decorative model. `buildEidoverseLabel(component, alias?)` reads one already-built `comp.portos` payload and returns `{name, description?, visibility, offset?}` — district and world-identity landmarks always visible, live indicators labelled `nearby`, path markers `inspect`-only so a walkway cannot bury the district it leads to — and `null` for anything not `managedBy: 'portos'`, so a caller cannot label somebody else's entity. Names and descriptions are built from PortOS's own vocabulary (district label, kind label, resource category, coarse status, freshness) plus an opaque hashed resource ref for disambiguation, never from record contents, machine identity, addresses, or filesystem paths — the append-only world log is the strictest privacy boundary PortOS writes to. Also owns bounded opaque-key alias normalization and V1 renderer capability parsing; aliases are explicit opt-in names and are never inferred from private records. Owns `safeWorldText`, the one control-character/length sanitizer shared with `services/eidoverseWorldProjection.js` so a component field and the label built from it cannot disagree about what is safe. Pure. |
+| `eidoverseWorldSignals.js` | Pure raw-source-to-signal shaping: `buildEidoverseWorldSignals`, stable opaque host/peer IDs, storage and Jira aggregates; no service reads. |
| `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. Re-exported by `client/src/lib/extensionErrors.js`, so both sides classify identically. |
| `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/eidoverseWorldSignals.js b/server/lib/eidoverseWorldSignals.js
new file mode 100644
index 0000000000..6b98d9af48
--- /dev/null
+++ b/server/lib/eidoverseWorldSignals.js
@@ -0,0 +1,399 @@
+/**
+ * Pure raw-source-to-signal boundary for Eidoverse.
+ * Only bounded aggregates and opaque identities leave this module; private
+ * record contents never become world labels or signal payloads.
+ */
+
+import { createHash } from 'node:crypto';
+import { safeWorldText as safeText } from './eidoverseWorldLabels.js';
+
+const opaqueDigest = (namespace, value, fallback) => {
+ const source = safeText(value, fallback, 256);
+ return createHash('sha256').update(`${namespace}:${source}`).digest('hex').slice(0, 12);
+};
+
+const opaqueId = (namespace, value, fallback) => `${namespace}-${opaqueDigest(namespace, value, fallback)}`;
+
+/**
+ * The install's public host identity. Anyone who can reach the Eidoverse door
+ * reads this, so it is a one-way digest of the federation instance id — never
+ * the hostname, tailnet name, address, OS user, or a filesystem path.
+ */
+export const eidoversePeerId = (peer) => opaqueId('peer', peer.instanceId || peer.id, 'unknown-peer');
+
+export const eidoverseHostId = (instanceId) => `hst_${opaqueDigest('hst', instanceId, 'unknown-instance')}`;
+
+const coarseStatus = (value) => {
+ const status = String(value || '').toLowerCase();
+ if (/error|failed|unhealthy|offline|crash|blocked/.test(status)) return 'error';
+ if (/paused|stopped|pending|unknown|not.started|todo|to do/.test(status)) return 'attention';
+ if (/active|running|online|healthy|success|progress/.test(status)) return 'active';
+ return 'steady';
+};
+
+const finiteOrNull = (value) => typeof value === 'number' && Number.isFinite(value) ? value : null;
+const nonNegativeOrNull = (value) => {
+ const number = finiteOrNull(value);
+ return number === null ? null : Math.max(0, number);
+};
+const percentageOrNull = (value) => {
+ const number = finiteOrNull(value);
+ return number === null ? null : Math.max(0, Math.min(100, number));
+};
+
+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 projectedApps(apps) {
+ if (!Array.isArray(apps)) return null;
+ const groups = new Map();
+ for (const app of apps) {
+ const status = coarseStatus(app?.overallStatus);
+ const group = groups.get(status) || { count: 0, managed: 0 };
+ group.count += 1;
+ if (app?.managed === true) group.managed += 1;
+ groups.set(status, group);
+ }
+ return [...groups.entries()]
+ .sort(([left], [right]) => left.localeCompare(right))
+ .map(([status, group]) => ({
+ id: `apps-${status}`,
+ label: 'Managed app group',
+ status,
+ count: group.count,
+ managed: group.managed,
+ }));
+}
+
+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),
+ 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;
+ if (calendar.weeks.length === 0) return [];
+ 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)
+ .reverse();
+ 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: opaqueId('activity-day', day.date, `day-${index}`),
+ label: '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: opaqueId('goal', goal?.id, `goal-${index}`),
+ label: 'Active goal',
+ status: coarseStatus(goal?.status || 'active'),
+ progress: percentageOrNull(goal?.progress) ?? 0,
+ 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: opaqueId('memory-category', category, 'other'),
+ label: 'Memory 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,
+ }));
+}
+
+export 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),
+ });
+ 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 (!dbOnline) items.push({ id: 'database-attention', label: 'Data attention', area: 'anomaly', status: db === null ? 'offline' : 'unknown', count: 1 });
+ if (!fsOnline) items.push({ id: 'filesystem-attention', label: 'Data attention', area: 'anomaly', status: fsSection === null ? 'offline' : 'unknown', count: 1 });
+ return items;
+}
+
+function projectedOperations({ cosStatus, review, backupState, notifications, character, voiceConfig, memory, diskPercent, inboxCounts }) {
+ const values = [cosStatus, review, backupState, notifications, character, voiceConfig, memory, diskPercent, inboxCounts];
+ if (!values.some((value) => value !== null && value !== undefined)) return null;
+ const status = /failed|error|unhealthy/i.test(String(backupState?.status || ''))
+ ? 'error'
+ : ((review?.alert || 0) > 0 || cosStatus?.paused === true ? 'attention' : (cosStatus?.running ? 'active' : 'steady'));
+ return [{
+ id: 'overview',
+ label: 'PortOS operations',
+ status,
+ cos: cosStatus ? {
+ running: cosStatus.running === true,
+ paused: cosStatus.paused === true,
+ activeAgents: nonNegativeOrNull(cosStatus.activeAgents),
+ pausedAgents: nonNegativeOrNull(cosStatus.pausedAgents),
+ } : null,
+ ai: cosStatus ? {
+ running: cosStatus.running === true,
+ activeAgents: nonNegativeOrNull(cosStatus.activeAgents),
+ } : null,
+ review: review ? {
+ total: nonNegativeOrNull(review.total),
+ cos: nonNegativeOrNull(review.cos),
+ alerts: nonNegativeOrNull(review.alert),
+ } : null,
+ backup: backupState ? {
+ status: coarseStatus(backupState.status),
+ 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,
+ voice: voiceConfig ? {
+ enabled: voiceConfig.enabled === true,
+ } : null,
+ memory: memory ? {
+ usedPercent: memory.total > 0 ? Math.round((memory.used / memory.total) * 100) : null,
+ } : null,
+ diskPercent: percentageOrNull(diskPercent),
+ }];
+}
+
+export function projectedJiraTickets(tickets) {
+ const groups = new Map();
+ for (const ticket of Array.isArray(tickets) ? tickets : []) {
+ const rawStatus = String(ticket?.statusCategory || ticket?.status || '').toLowerCase();
+ if (/done|complete|closed/.test(rawStatus)) continue;
+ const status = /progress|active|doing/.test(rawStatus) ? 'active' : (/block|error|fail/.test(rawStatus) ? 'blocked' : 'pending');
+ const current = groups.get(status) || { count: 0, storyPoints: 0, urgent: 0 };
+ current.count += 1;
+ current.storyPoints += nonNegativeOrNull(ticket?.storyPoints) || 0;
+ if (/highest|critical|urgent/i.test(String(ticket?.priority || ''))) current.urgent += 1;
+ groups.set(status, current);
+ }
+ return [...groups.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([status, values]) => ({
+ id: `jira-${status}`,
+ label: 'Current work summary',
+ status,
+ ...values,
+ }));
+}
+
+function healthSnapshot({ apps, cosStatus, review, backupState, notifications, character, voiceConfig, memory, diskPercent }) {
+ const health = {
+ id: 'overview',
+ label: 'PortOS 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: coarseStatus(backupState.status),
+ filesChanged: nonNegativeOrNull(backupState.filesChanged),
+ } : null,
+ memory: memory ? {
+ usedPercent: memory.total > 0 ? Math.round((memory.used / memory.total) * 100) : null,
+ } : null,
+ notifications: notifications ? {
+ total: nonNegativeOrNull(notifications.total),
+ unread: nonNegativeOrNull(notifications.unread),
+ } : null,
+ character: character ? { level: nonNegativeOrNull(character.level) } : null,
+ voice: voiceConfig ? {
+ enabled: voiceConfig.enabled === true,
+ } : null,
+ diskPercent: percentageOrNull(diskPercent),
+ };
+ const available = [apps, cosStatus, review, backupState, notifications, character, voiceConfig, memory, diskPercent]
+ .some((value) => value !== null && value !== undefined);
+ if (!available) return null;
+ const hasError = /failed|error|unhealthy/i.test(String(health.backup?.status || ''))
+ || (health.diskPercent ?? 0) >= 95
+ || (health.memory?.usedPercent ?? 0) >= 95;
+ const needsAttention = (health.apps?.stopped || 0) > 0
+ || (health.apps?.unknown || 0) > 0
+ || (health.review?.alerts || 0) > 0
+ || cosStatus?.paused === true
+ || (health.diskPercent ?? 0) >= 85
+ || (health.memory?.usedPercent ?? 0) >= 85;
+ health.status = hasError ? 'error' : (needsAttention ? 'attention' : 'healthy');
+ return health;
+}
+
+/**
+ * Shape already-read local snapshots, resolved Jira signals, and the Set of
+ * available destination peer IDs. Null means unavailable; [] means empty.
+ */
+export function buildEidoverseWorldSignals({
+ apps, agents, taskState, cosStatus, review, featuresState, peers,
+ backupState, notifications, character, voiceConfig, memory, diskPercent,
+ todayActivity, velocity, activityCalendar, goalsData, memoryGraph,
+ inboxCounts, introspection, jira, destinations,
+}) {
+ const projectedAgents = Array.isArray(agents)
+ ? agents.filter((agent) => ['running', 'paused'].includes(agent?.status)).map((agent, index) => ({
+ id: opaqueId('agent', agent.id, `agent-${index}`), label: 'Active agent', status: coarseStatus(agent.status),
+ }))
+ : null;
+ const projectedTasks = Array.isArray(taskState?.tasks)
+ ? taskState.tasks
+ .filter((task) => !['completed', 'done', 'archived'].includes(String(task?.status || '').toLowerCase()))
+ .map((task, index) => ({
+ id: opaqueId('task', task.id, `task-${index}`), label: 'Active task', status: coarseStatus(task.status || 'pending'),
+ }))
+ : null;
+ const projectedFeatures = Array.isArray(featuresState?.features)
+ ? featuresState.features.map((feature) => ({
+ id: safeText(feature.id, 'feature'), label: 'District feature', enabled: feature.enabled === true,
+ }))
+ : null;
+ const projectedPeers = Array.isArray(peers)
+ ? peers.map((peer) => ({
+ id: eidoversePeerId(peer),
+ label: 'Federated peer',
+ travelAvailable: destinations.has(eidoversePeerId(peer)),
+ enabled: peer.enabled !== false,
+ fullSync: peer.fullSync === true,
+ status: coarseStatus(peer.status),
+ }))
+ : null;
+ const health = healthSnapshot({ apps, cosStatus, review, backupState, notifications, character, voiceConfig, memory, diskPercent });
+
+ return {
+ apps: projectedApps(apps),
+ 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, voiceConfig, memory, diskPercent, inboxCounts }),
+ };
+}
diff --git a/server/lib/eidoverseWorldSignals.test.js b/server/lib/eidoverseWorldSignals.test.js
new file mode 100644
index 0000000000..add3686d51
--- /dev/null
+++ b/server/lib/eidoverseWorldSignals.test.js
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+import { eidoverseHostId, eidoversePeerId } from './eidoverseWorldSignals.js';
+
+describe('Eidoverse public identity compatibility', () => {
+ // Fixed outputs from the pre-extraction collector: changing these identities
+ // breaks persisted world metadata and destination links across upgrades.
+ it('preserves namespaces, normalization, fallback selection, and the 256-character input cap', () => {
+ const fixtures = [
+ ['fixture-instance', 'hst_25cf5b1a0b1f', 'peer-bd6bd9c7a57a'],
+ ['\t fixture\u0000instance\u007f \n', 'hst_8df6a4a59860', 'peer-7282d94f0db2'],
+ ['', 'hst_fe23cde7412c', 'peer-170b31bba778'],
+ [undefined, 'hst_fe23cde7412c', 'peer-170b31bba778'],
+ [123, 'hst_fe23cde7412c', 'peer-f486350022b1'],
+ ['x'.repeat(257), 'hst_4c1dcf8b9a4e', 'peer-5db89d907972'],
+ ];
+ for (const [instanceId, hostId, peerId] of fixtures) {
+ expect(eidoverseHostId(instanceId)).toBe(hostId);
+ expect(eidoversePeerId({ instanceId, id: 'legacy-peer' })).toBe(peerId);
+ }
+ expect(eidoversePeerId({})).toBe('peer-f486350022b1');
+ });
+});
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.js
index db382c86ff..a22ba0bcda 100644
--- a/server/lib/importScoping.test.js
+++ b/server/lib/importScoping.test.js
@@ -38,6 +38,17 @@ const reaches = (entry, target) => staticImportClosure(abs(entry)).files.has(abs
// Each row: the entry that was narrowed, the module it must no longer
const NARROWED = [
+ ['services/eidoverseWorld.js', 'services/eidoverseWorldSources.js',
+ 'uses pure Eidoverse signals without eagerly loading source readers'],
+ ['services/eidoverseTravel.js', 'services/eidoverseWorldSources.js',
+ 'uses pure Eidoverse signals without eagerly loading source readers'],
+ ['services/eidoverseWorld.test.js', 'services/eidoverseWorldSources.js',
+ 'uses pure Eidoverse signals without eagerly loading source readers'],
+ ['services/eidoverseTravel.test.js', 'services/eidoverseWorldSources.js',
+ 'uses pure Eidoverse signals without eagerly loading source readers'],
+ ['lib/eidoverseWorldSignals.js', 'services/eidoverseWorldSources.js',
+ 'uses pure Eidoverse signals without eagerly loading source readers'],
+
['services/imageGen/local.js', 'services/localMemory.js',
'loads GPU memory management only for generation, not gallery reads'],
['services/imageGen/local.js', 'services/imageGen/regen.js',
@@ -120,6 +131,11 @@ describe('narrowed imports stay narrow (#6009)', () => {
// Positive controls. Without these the negatives above would also pass if
// `staticImportClosure` stopped resolving these files at all.
it('still sees the modules the narrowed entries were pointed AT', () => {
+ expect(reaches('services/eidoverseWorld.js', 'lib/eidoverseWorldSignals.js')).toBe(true);
+ expect(reaches('services/eidoverseTravel.js', 'lib/eidoverseWorldSignals.js')).toBe(true);
+ expect(reaches('services/eidoverseWorld.test.js', 'services/eidoverseWorldProjection.js')).toBe(true);
+ expect(reaches('services/eidoverseWorldSources.js', 'lib/eidoverseWorldSignals.js')).toBe(true);
+ expect(reaches('services/eidoverseWorldSources.js', 'services/apps.js')).toBe(true);
expect(reaches('services/persistentMindSupervisor.js', 'services/persistentMindAttachments.js')).toBe(true);
expect(reaches('services/persistentMindAttachments.js', 'lib/fileUtils.js')).toBe(true);
expect(reaches('services/mtplxModelManager.js', 'services/huggingFaceMetadata.js')).toBe(true);
diff --git a/server/lib/index.js b/server/lib/index.js
index 67e0d4bbfd..3bee132887 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -537,6 +537,7 @@ export * from './domainAutonomy.js';
export * from './domainBudgets.js';
export * from './eidoverseWorldDesign.js';
export * from './eidoverseWorldLabels.js';
+export * from './eidoverseWorldSignals.js';
export * from './errorHandler.js';
export * from './extensionErrors.js';
export * from './fetchErrorChain.js';
diff --git a/server/services/eidoverseTravel.js b/server/services/eidoverseTravel.js
index cac5b86304..ab2321f266 100644
--- a/server/services/eidoverseTravel.js
+++ b/server/services/eidoverseTravel.js
@@ -9,7 +9,7 @@ import { getPeers } from './instances.js';
import { getInstanceFeatures } from './instanceFeatures.js';
import { ensureEidoverseHost } from './eidoverseHost.js';
import { admitEidoverseGuest, supportsEidoverseGuestEntry, getEidoverseWorldStatus } from './eidoverseWorld.js';
-import { eidoversePeerId } from './eidoverseWorldSources.js';
+import { eidoversePeerId } from '../lib/eidoverseWorldSignals.js';
const VERSION = 1;
const TTL = 30 * 60 * 1000;
diff --git a/server/services/eidoverseTravel.test.js b/server/services/eidoverseTravel.test.js
index d7665f66a4..0e9bd3ec34 100644
--- a/server/services/eidoverseTravel.test.js
+++ b/server/services/eidoverseTravel.test.js
@@ -10,7 +10,7 @@ vi.mock('./eidoverseHost.js', () => ({ ensureEidoverseHost: async () => ({ proto
vi.mock('./eidoverseWorld.js', () => ({ supportsEidoverseGuestEntry: async () => mocks.protocol, getEidoverseWorldStatus: async () => ({ setup: { installed: true, runtimeStatus: 'online', worldDataReady: true }, cos: { enabled: true } }), admitEidoverseGuest: (...args) => mocks.admission(...args) }));
import router from '../routes/eidoverseTravelRoutes.js';
-import { eidoversePeerId } from './eidoverseWorldSources.js';
+import { eidoversePeerId } from '../lib/eidoverseWorldSignals.js';
import { errorMiddleware } from '../lib/errorHandler.js';
import { eidoverseVisitChat, getEidoverseGuestDescriptor, leaveEidoversePeer, listEidoverseDestinations, receiveEidoverseChat, receiveEidoverseLeave, visitEidoversePeer } from './eidoverseTravel.js';
diff --git a/server/services/eidoverseWorld.js b/server/services/eidoverseWorld.js
index 6a62396d44..12a53242f9 100644
--- a/server/services/eidoverseWorld.js
+++ b/server/services/eidoverseWorld.js
@@ -40,11 +40,10 @@ import {
EIDOVERSE_PROJECTION_KINDS,
} from './eidoverseWorldProjection.js';
import {
- collectEidoverseWorldSources,
eidoverseHostId,
projectedJiraTickets,
projectedStorage,
-} from './eidoverseWorldSources.js';
+} from '../lib/eidoverseWorldSignals.js';
export { buildProjectionPlan, DEFAULT_EIDOVERSE_PROJECTION_RECIPE, projectedJiraTickets, projectedStorage };
@@ -1804,6 +1803,7 @@ export async function projectEidoverseWorld({ signal, compact = false, verbInter
const config = await ensureEidoverseWorldConfig();
const lockedConfig = await resolveAndLockAssets(config, { signal });
const presence = await ensureCosPresenceInternal({ fresh: true, signal, verbIntervalMs });
+ const { collectEidoverseWorldSources } = await import('./eidoverseWorldSources.js');
const source = await collectEidoverseWorldSources({ signal });
const hostId = eidoverseHostId(await getInstanceId());
throwIfAborted(signal);
diff --git a/server/services/eidoverseWorld.test.js b/server/services/eidoverseWorld.test.js
index ff4bae8fc2..16db39a5ad 100644
--- a/server/services/eidoverseWorld.test.js
+++ b/server/services/eidoverseWorld.test.js
@@ -2,9 +2,8 @@ import { describe, expect, it } from 'vitest';
import {
buildProjectionPlan,
DEFAULT_EIDOVERSE_PROJECTION_RECIPE,
- projectedJiraTickets,
- projectedStorage,
-} from './eidoverseWorld.js';
+} from './eidoverseWorldProjection.js';
+import { projectedJiraTickets, projectedStorage } from '../lib/eidoverseWorldSignals.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';
diff --git a/server/services/eidoverseWorldSources.js b/server/services/eidoverseWorldSources.js
index 4b58650f1b..9df38921f6 100644
--- a/server/services/eidoverseWorldSources.js
+++ b/server/services/eidoverseWorldSources.js
@@ -6,7 +6,6 @@
* readings, prompts, journals, and transcripts never leave this module.
*/
-import { createHash } from 'node:crypto';
import { statfs } from 'node:fs/promises';
import { parseFilesystemStats } from '../lib/fileCore.js';
import { getAllApps, getAppStatuses } from './apps.js';
@@ -26,35 +25,10 @@ import { getInboxLogCounts } from './brainStorage.js';
import { getDataIntrospection } from './dataIntrospection.js';
import { fetchMyCurrentSprintTickets } from './jira.js';
-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;
-};
+import { buildEidoverseWorldSignals, projectedJiraTickets } from '../lib/eidoverseWorldSignals.js';
-const opaqueDigest = (namespace, value, fallback) => {
- const source = safeText(value, fallback, 256);
- return createHash('sha256').update(`${namespace}:${source}`).digest('hex').slice(0, 12);
-};
-
-const opaqueId = (namespace, value, fallback) => `${namespace}-${opaqueDigest(namespace, value, fallback)}`;
-
-/**
- * The install's public host identity. Anyone who can reach the Eidoverse door
- * reads this, so it is a one-way digest of the federation instance id — never
- * the hostname, tailnet name, address, OS user, or a filesystem path.
- */
-export const eidoversePeerId = (peer) => opaqueId('peer', peer.instanceId || peer.id, 'unknown-peer');
-
-export const eidoverseHostId = (instanceId) => `hst_${opaqueDigest('hst', instanceId, 'unknown-instance')}`;
-
-const coarseStatus = (value) => {
- const status = String(value || '').toLowerCase();
- if (/error|failed|unhealthy|offline|crash|blocked/.test(status)) return 'error';
- if (/paused|stopped|pending|unknown|not.started|todo|to do/.test(status)) return 'attention';
- if (/active|running|online|healthy|success|progress/.test(status)) return 'active';
- return 'steady';
-};
+// Preserve the historical collector import paths.
+export { eidoversePeerId, eidoverseHostId, projectedStorage, projectedJiraTickets } from '../lib/eidoverseWorldSignals.js';
const abortError = (signal) => signal?.reason instanceof Error
? signal.reason
@@ -83,254 +57,11 @@ function waitWithSignal(promise, signal) {
});
}
-const finiteOrNull = (value) => typeof value === 'number' && Number.isFinite(value) ? value : null;
-const nonNegativeOrNull = (value) => {
- const number = finiteOrNull(value);
- return number === null ? null : Math.max(0, number);
-};
-const percentageOrNull = (value) => {
- const number = finiteOrNull(value);
- return number === null ? null : Math.max(0, Math.min(100, number));
-};
-
async function getDiskUsagePercent() {
const stats = await statfs('/').catch(() => null);
return parseFilesystemStats(stats)?.usagePercent ?? null;
}
-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 projectedApps(apps) {
- if (!Array.isArray(apps)) return null;
- const groups = new Map();
- for (const app of apps) {
- const status = coarseStatus(app?.overallStatus);
- const group = groups.get(status) || { count: 0, managed: 0 };
- group.count += 1;
- if (app?.managed === true) group.managed += 1;
- groups.set(status, group);
- }
- return [...groups.entries()]
- .sort(([left], [right]) => left.localeCompare(right))
- .map(([status, group]) => ({
- id: `apps-${status}`,
- label: 'Managed app group',
- status,
- count: group.count,
- managed: group.managed,
- }));
-}
-
-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),
- 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;
- if (calendar.weeks.length === 0) return [];
- 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)
- .reverse();
- 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: opaqueId('activity-day', day.date, `day-${index}`),
- label: '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: opaqueId('goal', goal?.id, `goal-${index}`),
- label: 'Active goal',
- status: coarseStatus(goal?.status || 'active'),
- progress: percentageOrNull(goal?.progress) ?? 0,
- 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: opaqueId('memory-category', category, 'other'),
- label: 'Memory 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,
- }));
-}
-
-export 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),
- });
- 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 (!dbOnline) items.push({ id: 'database-attention', label: 'Data attention', area: 'anomaly', status: db === null ? 'offline' : 'unknown', count: 1 });
- if (!fsOnline) items.push({ id: 'filesystem-attention', label: 'Data attention', area: 'anomaly', status: fsSection === null ? 'offline' : 'unknown', count: 1 });
- return items;
-}
-
-function projectedOperations({ cosStatus, review, backupState, notifications, character, voiceConfig, memory, diskPercent, inboxCounts }) {
- const values = [cosStatus, review, backupState, notifications, character, voiceConfig, memory, diskPercent, inboxCounts];
- if (!values.some((value) => value !== null && value !== undefined)) return null;
- const status = /failed|error|unhealthy/i.test(String(backupState?.status || ''))
- ? 'error'
- : ((review?.alert || 0) > 0 || cosStatus?.paused === true ? 'attention' : (cosStatus?.running ? 'active' : 'steady'));
- return [{
- id: 'overview',
- label: 'PortOS operations',
- status,
- cos: cosStatus ? {
- running: cosStatus.running === true,
- paused: cosStatus.paused === true,
- activeAgents: nonNegativeOrNull(cosStatus.activeAgents),
- pausedAgents: nonNegativeOrNull(cosStatus.pausedAgents),
- } : null,
- ai: cosStatus ? {
- running: cosStatus.running === true,
- activeAgents: nonNegativeOrNull(cosStatus.activeAgents),
- } : null,
- review: review ? {
- total: nonNegativeOrNull(review.total),
- cos: nonNegativeOrNull(review.cos),
- alerts: nonNegativeOrNull(review.alert),
- } : null,
- backup: backupState ? {
- status: coarseStatus(backupState.status),
- 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,
- voice: voiceConfig ? {
- enabled: voiceConfig.enabled === true,
- } : null,
- memory: memory ? {
- usedPercent: memory.total > 0 ? Math.round((memory.used / memory.total) * 100) : null,
- } : 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');
@@ -352,74 +83,6 @@ async function projectedJira(appConfig, featuresState) {
return projectedJiraTickets(batches.flatMap((batch) => batch.tickets));
}
-export function projectedJiraTickets(tickets) {
- const groups = new Map();
- for (const ticket of Array.isArray(tickets) ? tickets : []) {
- const rawStatus = String(ticket?.statusCategory || ticket?.status || '').toLowerCase();
- if (/done|complete|closed/.test(rawStatus)) continue;
- const status = /progress|active|doing/.test(rawStatus) ? 'active' : (/block|error|fail/.test(rawStatus) ? 'blocked' : 'pending');
- const current = groups.get(status) || { count: 0, storyPoints: 0, urgent: 0 };
- current.count += 1;
- current.storyPoints += nonNegativeOrNull(ticket?.storyPoints) || 0;
- if (/highest|critical|urgent/i.test(String(ticket?.priority || ''))) current.urgent += 1;
- groups.set(status, current);
- }
- return [...groups.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([status, values]) => ({
- id: `jira-${status}`,
- label: 'Current work summary',
- status,
- ...values,
- }));
-}
-
-function healthSnapshot({ apps, cosStatus, review, backupState, notifications, character, voiceConfig, memory, diskPercent }) {
- const health = {
- id: 'overview',
- label: 'PortOS 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: coarseStatus(backupState.status),
- filesChanged: nonNegativeOrNull(backupState.filesChanged),
- } : null,
- memory: memory ? {
- usedPercent: memory.total > 0 ? Math.round((memory.used / memory.total) * 100) : null,
- } : null,
- notifications: notifications ? {
- total: nonNegativeOrNull(notifications.total),
- unread: nonNegativeOrNull(notifications.unread),
- } : null,
- character: character ? { level: nonNegativeOrNull(character.level) } : null,
- voice: voiceConfig ? {
- enabled: voiceConfig.enabled === true,
- } : null,
- diskPercent: percentageOrNull(diskPercent),
- };
- const available = [apps, cosStatus, review, backupState, notifications, character, voiceConfig, memory, diskPercent]
- .some((value) => value !== null && value !== undefined);
- if (!available) return null;
- const hasError = /failed|error|unhealthy/i.test(String(health.backup?.status || ''))
- || (health.diskPercent ?? 0) >= 95
- || (health.memory?.usedPercent ?? 0) >= 95;
- const needsAttention = (health.apps?.stopped || 0) > 0
- || (health.apps?.unknown || 0) > 0
- || (health.review?.alerts || 0) > 0
- || cosStatus?.paused === true
- || (health.diskPercent ?? 0) >= 85
- || (health.memory?.usedPercent ?? 0) >= 85;
- health.status = hasError ? 'error' : (needsAttention ? 'attention' : 'healthy');
- return health;
-}
-
export async function collectEidoverseWorldSources({ signal } = {}) {
throwIfAborted(signal);
const reads = await waitWithSignal(Promise.all([
@@ -447,51 +110,14 @@ export async function collectEidoverseWorldSources({ signal } = {}) {
]), signal);
const [apps, appConfig, agents, taskState, cosStatus, review, featuresState, peers, backupState, notifications, character, voiceConfig, memory, diskPercent, todayActivity, velocity, activityCalendar, goalsData, memoryGraph, inboxCounts, introspection] = reads;
- const projectedAgents = Array.isArray(agents)
- ? agents.filter((agent) => ['running', 'paused'].includes(agent?.status)).map((agent, index) => ({
- id: opaqueId('agent', agent.id, `agent-${index}`), label: 'Active agent', status: coarseStatus(agent.status),
- }))
- : null;
- const projectedTasks = Array.isArray(taskState?.tasks)
- ? taskState.tasks
- .filter((task) => !['completed', 'done', 'archived'].includes(String(task?.status || '').toLowerCase()))
- .map((task, index) => ({
- id: opaqueId('task', task.id, `task-${index}`), label: 'Active task', status: coarseStatus(task.status || 'pending'),
- }))
- : null;
- const projectedFeatures = Array.isArray(featuresState?.features)
- ? featuresState.features.map((feature) => ({
- id: safeText(feature.id, 'feature'), label: 'District feature', enabled: feature.enabled === true,
- }))
- : null;
const travel = await import('./eidoverseTravel.js').then((service) => service.listEidoverseDestinations()).catch(() => ({ destinations: [] }));
const destinations = new Set(travel.destinations.map((entry) => entry.peerId));
- const projectedPeers = Array.isArray(peers)
- ? peers.map((peer) => ({
- id: eidoversePeerId(peer),
- label: 'Federated peer',
- travelAvailable: destinations.has(eidoversePeerId(peer)),
- enabled: peer.enabled !== false,
- fullSync: peer.fullSync === true,
- status: coarseStatus(peer.status),
- }))
- : null;
- const health = healthSnapshot({ apps, cosStatus, review, backupState, notifications, character, voiceConfig, memory, diskPercent });
const jira = await waitWithSignal(projectedJira(appConfig, featuresState), signal);
- return {
- apps: projectedApps(apps),
- 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, voiceConfig, memory, diskPercent, inboxCounts }),
- };
+ return buildEidoverseWorldSignals({
+ apps, agents, taskState, cosStatus, review, featuresState, peers,
+ backupState, notifications, character, voiceConfig, memory, diskPercent,
+ todayActivity, velocity, activityCalendar, goalsData, memoryGraph,
+ inboxCounts, introspection, jira, destinations,
+ });
}