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
fix: stabilize health action identities by condition and resource (#7736)
[._.]/ Adam Eivy5af76d7e4b71
diff --git a/server/services/proactiveAlerts.js b/server/services/proactiveAlerts.jsindex f174788df2..e0b0aec601 100644--- a/server/services/proactiveAlerts.js+++ b/server/services/proactiveAlerts.js@@ -31,6 +31,21 @@ const CPU_WARNING_PCT = 90;const USAGE_SPIKE_MULTIPLIER = 2.5;const USAGE_MIN_HISTORY_DAYS = 3;+/**+ * Condition + explicit resource identity, never presentation text or position.+ * Encode each segment separately so a resource containing ':' cannot collide.+ * These keys name the active condition; severity/wording changes keep the key.+ * Domain-wide checks use an explicit 'all' resource. Recurring product actions+ * supply their own IDs. Missing resource identity is a failed source read,+ * not permission to mint a positional ID or claim the queue is empty.+ */+function alertId(condition, resource) {+ const valid = typeof resource === 'string' ? resource.trim().length > 0+ : Number.isSafeInteger(resource) && resource >= 0;+ if (!valid) throw new Error('Alert resource identity is unavailable');+ return `${condition}:${encodeURIComponent(resource)}`;+}+/*** Detect goals that have stalled (no progress update in 14+ days)*/@@ -53,6 +68,7 @@ async function checkGoalStalls() {const daysSince = Math.floor((now - new Date(lastUpdate).getTime()) / 86400000);if (daysSince >= STALL_THRESHOLD_DAYS) {alerts.push({+ id: alertId('goal_stall', goal.id),type: 'goal_stall',severity: daysSince >= 30 ? 'high' : 'medium',title: `Goal stalled: ${goal.title}`,@@ -85,6 +101,7 @@ async function checkSuccessRates() {return (perf.needsAttention || []).filter(hasCurrentPerformanceEvidence).map(item => ({+ id: alertId('success_drop', item.taskType),type: 'success_drop',severity: item.successRate < 30 ? 'high' : 'medium',title: `Low success rate: ${item.taskType}`,@@ -106,6 +123,7 @@ async function checkSystemHealth() {if (memPct >= MEMORY_WARNING_PCT) {const formatGB = (bytes) => `${(bytes / (1024 * 1024 * 1024)).toFixed(1)}GB`;alerts.push({+ id: alertId('system_resource', 'memory'),type: 'system_resource',severity: memPct >= MEMORY_CRITICAL_PCT ? 'critical' : 'high',title: 'High memory usage',@@ -122,6 +140,7 @@ async function checkSystemHealth() {if (cpuPct >= CPU_WARNING_PCT) {alerts.push({+ id: alertId('system_resource', 'cpu'),type: 'system_resource',severity: 'high',title: 'High CPU usage',@@ -136,29 +155,29 @@ async function checkSystemHealth() {// would report every play session as a failure. See issue #2991.const processes = await listProcesses().catch(() => []);const alertable = (await annotateExpectedExit(processes)).filter(p => !p.expectedExit);- const errored = alertable.filter(p => p.status === 'errored').length;- if (errored > 0) {- alerts.push({- type: 'process_error',- severity: 'high',- title: `${errored} errored process${errored > 1 ? 'es' : ''}`,- detail: `${errored} of ${alertable.length} processes in error state`,- link: '/apps',- metadata: { errored, total: alertable.length }- });- }-- const crashing = alertable.filter(p => (p.unstableRestarts || 0) > 0);- if (crashing.length > 0) {- const total = crashing.reduce((sum, p) => sum + (p.unstableRestarts || 0), 0);- alerts.push({- type: 'process_error',- severity: 'high',- title: `${crashing.length} process${crashing.length > 1 ? 'es' : ''} in crash loop`,- detail: `${total} crash-loop restart${total === 1 ? '' : 's'}: ${crashing.map(p => p.name).join(', ')}`,- link: '/apps',- metadata: { unstableRestarts: total, names: crashing.map(p => p.name) }- });+ for (const process of alertable) {+ if (process.status === 'errored') {+ alerts.push({+ id: alertId('process_errored', process.pm_id),+ type: 'process_error',+ severity: 'high',+ title: `Errored process: ${process.name}`,+ detail: 'Review the process logs and restart it after addressing the failure',+ link: '/apps',+ metadata: { processId: process.pm_id, errored: 1, total: alertable.length }+ });+ }+ if ((process.unstableRestarts || 0) > 0) {+ alerts.push({+ id: alertId('process_crash_loop', process.pm_id),+ type: 'process_error',+ severity: 'high',+ title: `Process in crash loop: ${process.name}`,+ detail: `${process.unstableRestarts} crash-loop restarts — review the process logs`,+ link: '/apps',+ metadata: { processId: process.pm_id, unstableRestarts: process.unstableRestarts, names: [process.name] }+ });+ }}return alerts;@@ -179,6 +198,7 @@ async function checkLearningHealth() {if (skipped > 0) {alerts.push({+ id: alertId('learning_skipped', 'all'),type: 'learning_health',severity: 'high',title: `${skipped} task type${skipped > 1 ? 's' : ''} being skipped`,@@ -188,6 +208,7 @@ async function checkLearningHealth() {});} else if (critical > 0) {alerts.push({+ id: alertId('learning_critical', 'all'),type: 'learning_health',severity: 'medium',title: `${critical} task type${critical > 1 ? 's' : ''} need attention`,@@ -235,6 +256,7 @@ async function checkUsageSpikes() {if (tokenRatio >= USAGE_SPIKE_MULTIPLIER) {const formatTokens = (t) => t >= 1000 ? `${(t / 1000).toFixed(1)}k` : String(t);alerts.push({+ id: alertId('cost_spike', 'tokens'),type: 'cost_spike',severity: tokenRatio >= 5 ? 'high' : 'medium',title: 'AI token usage spike',@@ -247,6 +269,7 @@ async function checkUsageSpikes() {const sessionRatio = todayData.sessions / avgSessions;if (sessionRatio >= USAGE_SPIKE_MULTIPLIER && avgSessions > 0) {alerts.push({+ id: alertId('cost_spike', 'sessions'),type: 'cost_spike',severity: sessionRatio >= 5 ? 'high' : 'medium',title: 'AI session spike',@@ -271,6 +294,7 @@ async function checkTribeCadence() {const names = summary.overdue.map((p) => p.name).filter(Boolean).join(', ');const overflow = summary.overdueCount > summary.overdue.length ? ', …' : '';return [{+ id: alertId('tribe_cadence', 'all'),type: 'tribe_cadence',severity: summary.overdueCount >= 3 ? 'high' : 'medium',title: `${summary.overdueCount} ${summary.overdueCount === 1 ? 'person is' : 'people are'} overdue for contact`,@@ -296,6 +320,7 @@ async function checkUnansweredTribeThreads() {return threads.map((t) => {const snippet = t.snippet ? `“${t.snippet}”` : 'their message';return {+ id: alertId('tribe_unanswered', t.conversationKey),type: 'tribe_unanswered',// A week-stale unanswered message from someone you care about is worth more// than a fresh one still within normal reply latency.diff --git a/server/services/proactiveAlerts.test.js b/server/services/proactiveAlerts.test.jsindex d601a81a15..00ca0b3c57 100644--- a/server/services/proactiveAlerts.test.js+++ b/server/services/proactiveAlerts.test.js@@ -1,13 +1,15 @@import { describe, it, expect, vi, beforeEach } from 'vitest';const mock = vi.hoisted(() => ({+ goals: [],+ memory: { used: 1, total: 100 },processes: [],desktopProcessNames: new Set(),desktopLookupError: null,performance: { needsAttention: [], skipped: [] }}));-vi.mock('./identity.js', () => ({ getGoals: vi.fn(async () => []) }));+vi.mock('./identity.js', () => ({ getGoals: vi.fn(async () => ({ goals: mock.goals })) }));vi.mock('./taskLearning.js', () => ({getPerformanceSummary: vi.fn(async () => mock.performance)}));@@ -25,12 +27,14 @@ vi.mock('./tribe.js', () => ({ getCareSummary: vi.fn(async () => ({ overdueCountvi.mock('./tribeOutreach.js', () => ({ findUnansweredTribeThreads: vi.fn(async () => []) }));// Keep memory/CPU below their warning thresholds so only process alerts surface.vi.mock('../lib/memoryStats.js', () => ({- getMemoryStats: vi.fn(async () => ({ used: 1, total: 100 }))+ getMemoryStats: vi.fn(async () => mock.memory)}));vi.mock('./portosProductMetrics.js', () => ({getProductEngagement: vi.fn(async () => ({ actions: [] }))}));+vi.mock('os', () => ({ default: { loadavg: () => [0], cpus: () => [{}] } }));+import { generateAlerts } from './proactiveAlerts.js';const processAlerts = async () => {@@ -50,14 +54,14 @@ describe('proactiveAlerts — desktop (GUI) process exemption (#2991)', () => {it('does not alert when the only errored process is a quit game window', async () => {// Force-quitting a game leaves PM2 `errored`; that is a normal end to a play// session, not a failure to notify about.- mock.processes = [{ name: 'game', status: 'errored' }];+ mock.processes = [{ pm_id: 1, name: 'game', status: 'errored' }];mock.desktopProcessNames = new Set(['game']);expect(await processAlerts()).toEqual([]);});it('still alerts on a genuinely errored web process', async () => {- mock.processes = [{ name: 'web', status: 'errored' }];+ mock.processes = [{ pm_id: 0, name: 'web', status: 'errored' }];const alerts = await processAlerts();expect(alerts).toHaveLength(1);@@ -66,9 +70,9 @@ describe('proactiveAlerts — desktop (GUI) process exemption (#2991)', () => {it('excludes the desktop process from both the count and the total', async () => {mock.processes = [- { name: 'game', status: 'errored' },- { name: 'web', status: 'errored' },- { name: 'api', status: 'online' }+ { pm_id: 1, name: 'game', status: 'errored' },+ { pm_id: 0, name: 'web', status: 'errored' },+ { pm_id: 2, name: 'api', status: 'online' }];mock.desktopProcessNames = new Set(['game']);@@ -76,25 +80,48 @@ describe('proactiveAlerts — desktop (GUI) process exemption (#2991)', () => {expect(alerts).toHaveLength(1);// 1 of 2 — the game is not part of the denominator either, so the ratio// the user reads is not diluted by an exempt process.- expect(alerts[0].metadata).toEqual({ errored: 1, total: 2 });+ expect(alerts[0].metadata).toEqual({ processId: 0, errored: 1, total: 2 });});it('does not report a desktop app restart loop as crashing', async () => {- mock.processes = [{ name: 'game', status: 'online', unstableRestarts: 3 }];+ mock.processes = [{ pm_id: 1, name: 'game', status: 'online', unstableRestarts: 3 }];mock.desktopProcessNames = new Set(['game']);expect(await processAlerts()).toEqual([]);});it('still reports unstable restarts for a non-desktop process', async () => {- mock.processes = [{ name: 'web', status: 'online', unstableRestarts: 3 }];+ mock.processes = [{ pm_id: 0, name: 'web', status: 'online', unstableRestarts: 3 }];const alerts = await processAlerts();expect(alerts).toHaveLength(1);});- it('alerts normally when the registry read fails (exempts nothing)', async () => {+ it('keeps per-process condition IDs through reorder, renaming and recovery', async () => {+ mock.processes = [+ { pm_id: 0, name: 'web', status: 'errored', unstableRestarts: 3 },+ { pm_id: 2, name: 'api', status: 'errored' }+ ];+ const first = await processAlerts();+ expect(first.map(a => a.id).sort()).toEqual([+ 'process_crash_loop:0', 'process_errored:0', 'process_errored:2'+ ]);+ mock.processes = [+ { pm_id: 2, name: 'renamed api', status: 'errored' },+ { pm_id: 0, name: 'web', status: 'online', unstableRestarts: 4 }+ ];+ const second = await processAlerts();+ expect(second.map(a => a.id).sort()).toEqual(['process_crash_loop:0', 'process_errored:2']);+ expect(second.find(a => a.id === 'process_crash_loop:0').metadata.unstableRestarts).toBe(4);+ });++ it('reports missing process identity as unavailable rather than inventing a key', async () => {mock.processes = [{ name: 'web', status: 'errored' }];+ await expect(generateAlerts()).rejects.toThrow('Alert resource identity is unavailable');+ });++ it('alerts normally when the registry read fails (exempts nothing)', async () => {+ mock.processes = [{ pm_id: 0, name: 'web', status: 'errored' }];mock.desktopLookupError = new Error('registry unreadable');const alerts = await processAlerts();@@ -144,3 +171,25 @@ describe('proactiveAlerts — current task performance', () => {});});});++describe('proactiveAlerts — resource identities', () => {+ it('keys goals and resource conditions independently of their presentation', async () => {+ mock.processes = [];+ mock.performance = { needsAttention: [], skipped: [] };+ mock.goals = [+ { id: 'example:one', title: 'Same title', status: 'active', createdAt: '2020-01-01' },+ { id: 'example%3Aone', title: 'Same title', status: 'active', createdAt: '2020-01-01' }+ ];+ mock.memory = { used: 90, total: 100 };+ const first = await generateAlerts();+ expect(first.alerts.map(a => a.id).sort()).toEqual([+ 'goal_stall:example%253Aone', 'goal_stall:example%3Aone', 'system_resource:memory'+ ]);+ mock.goals.reverse();+ mock.goals[0].title = 'Renamed goal';+ mock.memory = { used: 99, total: 100 };+ const next = await generateAlerts();+ expect(next.alerts.map(a => a.id).sort()).toEqual(first.alerts.map(a => a.id).sort());+ expect(next.alerts.find(a => a.id === 'system_resource:memory').severity).toBe('critical');+ });+});diff --git a/server/services/reviewQueue.js b/server/services/reviewQueue.jsindex 24641eadd0..0cc56a73f3 100644--- a/server/services/reviewQueue.js+++ b/server/services/reviewQueue.js@@ -284,18 +284,30 @@ const PRODUCERS = [async gather() {// System/health alerts; only surface the ones worth interrupting for.const { alerts = [] } = await getAlertsCached();- return alerts.filter(a => a.severity === 'critical' || a.severity === 'high');+ const byId = new Map();+ for (const alert of alerts) {+ if (alert.severity !== 'critical' && alert.severity !== 'high') continue;+ if (typeof alert.id !== 'string' || !alert.id.trim()) {+ throw new Error('Health alert identity is unavailable');+ }+ // Deduplicate before the per-source cap/count. If two observations of+ // a condition disagree, retain its strongest severity.+ const previous = byId.get(alert.id);+ if (!previous || SEVERITY_ORDER[alert.severity] < SEVERITY_ORDER[previous.severity]) {+ byId.set(alert.id, alert);+ }+ }+ return [...byId.values()];},- // proactiveAlerts emits { type, severity, title, detail, link } with no- // stable id and possibly-repeating types, so key on the array index too.- map(alert, index) {+ // The collector owns semantic identity; the queue only namespaces it.+ map(alert) {// Surface the alert category (system_resource / goal_stall / …) so the// user can tell at a glance what kind of anomaly it is. Absent → omitted.const alertType = typeof alert.type === 'string' && alert.type.trim()? alert.type.trim(): null;return {- id: `health:${alert.type || 'alert'}:${index}`,+ id: `health:${alert.id}`,title: alert.title || `${alert.type || 'System'} alert`,summary: (alert.detail || alert.message || '').slice(0, 200),timestamp: alert.timestamp || null,diff --git a/server/services/reviewQueue.test.js b/server/services/reviewQueue.test.jsindex 62fac311d7..c32e5cc60d 100644--- a/server/services/reviewQueue.test.js+++ b/server/services/reviewQueue.test.js@@ -132,10 +132,10 @@ describe('reviewQueue.buildQueue', () => {});it('only surfaces critical/high health alerts and a failed backup', async () => {- // Real proactiveAlerts shape: { type, severity, title, detail, link }.+ // Real proactiveAlerts shape: { id, type, severity, title, detail, link }.proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [- { type: 'system_resource', severity: 'critical', title: 'High memory usage', detail: '95% used', link: '/apps' },- { type: 'goal_stall', severity: 'medium', title: 'meh', detail: 'low' }+ { id: 'system_resource:memory', type: 'system_resource', severity: 'critical', title: 'High memory usage', detail: '95% used', link: '/apps' },+ { id: 'goal_stall:example-goal', type: 'goal_stall', severity: 'medium', title: 'meh', detail: 'low' }] });// Real backup failure shape: status 'error' with an `error` field.backup.getState.mockResolvedValue({ status: 'error', error: 'disk full', lastRun: '2026-06-03T07:00:00.000Z' });@@ -156,19 +156,53 @@ describe('reviewQueue.buildQueue', () => {expect(row).toMatchObject({ title: 'Backup degraded (DB dump failed)', severity: 'normal' });});- it('gives same-type health alerts unique ids', async () => {+ it('preserves condition identity through reorder, wording changes and severity escalation', async () => {+ const memory = { id: 'system_resource:memory', type: 'system_resource', severity: 'high', title: 'High memory', detail: 'mem', link: '/apps' };+ const cpu = { id: 'system_resource:cpu', type: 'system_resource', severity: 'high', title: 'High CPU', detail: 'cpu', link: '/apps' };+ proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [memory, cpu] });+ const first = await buildQueue();+ expect(first.items.map(i => i.id).sort()).toEqual(['health:system_resource:cpu', 'health:system_resource:memory']);++ __resetAlertsCache();+ proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [+ cpu, { ...memory, title: 'Memory pressure', severity: 'critical' },+ { id: 'goal_stall:example', type: 'goal_stall', severity: 'high', title: 'Check goal' }+ ] });+ const next = await buildQueue();+ expect(next.items.find(i => i.title === 'Memory pressure')).toMatchObject({+ id: 'health:system_resource:memory', severity: 'critical'+ });+ expect(next.items.find(i => i.title === 'High CPU').id).toBe('health:system_resource:cpu');++ __resetAlertsCache();+ proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [cpu] });+ expect((await buildQueue()).items.map(i => i.id)).toEqual(['health:system_resource:cpu']);+ });++ it('deduplicates before caps and counts while retaining severity escalation', async () => {+ const memory = { id: 'system_resource:memory', type: 'system_resource', severity: 'high' };proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [- { type: 'system_resource', severity: 'high', title: 'High memory', detail: 'mem', link: '/apps' },- { type: 'system_resource', severity: 'high', title: 'High CPU', detail: 'cpu', link: '/apps' }+ ...Array.from({ length: 30 }, () => memory),+ { ...memory, severity: 'critical' },+ { id: 'system_resource:cpu', type: 'system_resource', severity: 'high' }] });const queue = await buildQueue();- const ids = queue.items.filter(i => i.source === 'health').map(i => i.id);- expect(new Set(ids).size).toBe(2);+ expect(queue.items.map(i => i.id)).toEqual(['health:system_resource:memory', 'health:system_resource:cpu']);+ expect(queue.sources.health).toMatchObject({ total: 2, shown: 2, error: null });+ expect(queue.counts).toEqual({ total: 2, critical: 1, high: 1 });+ });++ it('reports missing health identity without hiding healthy sources', async () => {+ proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [{ type: 'system_resource', severity: 'critical' }] });+ brain.getInboxLog.mockResolvedValue([{ id: 'b1', capturedText: 'classify' }]);+ const queue = await buildQueue();+ expect(queue.sources.health.error).toBe('Health alert identity is unavailable');+ expect(queue.items.map(i => i.id)).toEqual(['brain:b1']);});it('sorts by severity then recency', async () => {brain.getInboxLog.mockResolvedValue([{ id: 'b1', capturedText: 'normal', capturedAt: '2026-06-03T12:00:00.000Z' }]);- proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [{ type: 'disk', severity: 'critical', title: 'crit', detail: 'full', link: '/apps', timestamp: '2026-06-03T01:00:00.000Z' }] });+ proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [{ id: 'disk:primary', type: 'disk', severity: 'critical', title: 'crit', detail: 'full', link: '/apps', timestamp: '2026-06-03T01:00:00.000Z' }] });const queue = await buildQueue();// critical alert sorts ahead of the (newer) normal brain itemexpect(queue.items[0].severity).toBe('critical');@@ -207,7 +241,7 @@ describe('reviewQueue.buildQueue', () => {brain.getInboxLog.mockResolvedValue([{ id: 'b1', capturedText: 'classify', capturedAt: '2026-06-03T10:00:00.000Z' }]);cosTaskStore.getCosTasks.mockResolvedValue({ awaitingApproval: [{ id: 'sys-1', description: 'approve me', priority: 'HIGH', createdAt: '2026-06-03T09:00:00.000Z' }] });askConversations.listConversations.mockResolvedValue([{ id: 'a1', title: 'promote me', promoted: false, turnCount: 1, assistantTurnCount: 1 }]);- proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [{ type: 'disk', severity: 'critical', title: 'crit', detail: 'full', link: '/apps' }] });+ proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [{ id: 'disk:primary', type: 'disk', severity: 'critical', title: 'crit', detail: 'full', link: '/apps' }] });backup.getState.mockResolvedValue({ status: 'error', error: 'disk full' });const queue = await buildQueue();expect(queue.items.find(i => i.source === 'brain').action).toBe('Done');@@ -225,7 +259,7 @@ describe('reviewQueue.buildQueue', () => {askConversations.listConversations.mockResolvedValue([{ id: 'a1', title: 'promote me', promoted: false, turnCount: 4, assistantTurnCount: 2 }]);cosTaskStore.getCosTasks.mockResolvedValue({ awaitingApproval: [{ id: 'sys-1', description: 'approve me', priority: 'MEDIUM', createdAt: '2026-06-03T09:00:00.000Z' }] });messageDrafts.listDrafts.mockResolvedValue([{ id: 'd1', status: 'draft', subject: 's', to: ['[email protected]'], sendVia: 'gmail', updatedAt: '2026-06-03T08:00:00.000Z' }]);- proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [{ type: 'system_resource', severity: 'critical', title: 'mem', detail: 'high', link: '/apps' }] });+ proactiveAlerts.generateAlerts.mockResolvedValue({ alerts: [{ id: 'system_resource:memory', type: 'system_resource', severity: 'critical', title: 'mem', detail: 'high', link: '/apps' }] });const queue = await buildQueue();expect(queue.items.find(i => i.source === 'brain').meta).toEqual({ captureSource: 'voice' });expect(queue.items.find(i => i.source === 'ask').meta).toEqual({ turnCount: 4 });