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(alerts): add proactive alerts system with dashboard widget
Adam Eivy269a664eafda
diff --git a/client/src/components/ProactiveAlertsWidget.jsx b/client/src/components/ProactiveAlertsWidget.jsxnew file mode 100644index 0000000000..a19a9cbcf6--- /dev/null+++ b/client/src/components/ProactiveAlertsWidget.jsx@@ -0,0 +1,133 @@+import { memo } from 'react';+import { Link } from 'react-router-dom';+import {+ Bell,+ ChevronRight,+ AlertTriangle,+ AlertOctagon,+ Target,+ TrendingDown,+ Cpu,+ BookOpen,+ CheckCircle+} from 'lucide-react';+import * as api from '../services/api';+import { useAutoRefetch } from '../hooks/useAutoRefetch';++const SEVERITY_STYLES = {+ critical: { bg: 'bg-port-error/10', text: 'text-port-error', border: 'border-port-error/30', dot: 'bg-port-error' },+ high: { bg: 'bg-port-warning/10', text: 'text-port-warning', border: 'border-port-warning/30', dot: 'bg-port-warning' },+ medium: { bg: 'bg-port-accent/10', text: 'text-port-accent', border: 'border-port-accent/30', dot: 'bg-port-accent' }+};++const TYPE_ICONS = {+ goal_stall: Target,+ success_drop: TrendingDown,+ system_resource: Cpu,+ process_error: AlertOctagon,+ learning_health: BookOpen+};++const ProactiveAlertsWidget = memo(function ProactiveAlertsWidget() {+ const { data, loading } = useAutoRefetch(+ () => api.getAlertsSummary({ silent: true }).catch(() => null),+ 120000 // Refresh every 2 minutes+ );++ if (loading) return null;+ if (!data) return null;++ const { alerts, counts } = data;+ const hasAlerts = counts.total > 0;++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-4 sm:p-6">+ {/* Header */}+ <div className="flex items-center justify-between mb-3">+ <div className="flex items-center gap-3">+ <div className={`p-2 rounded-lg ${hasAlerts ? 'bg-port-warning/10' : 'bg-port-success/10'}`}>+ {hasAlerts ? (+ <Bell className="w-5 h-5 text-port-warning" />+ ) : (+ <CheckCircle className="w-5 h-5 text-port-success" />+ )}+ </div>+ <div>+ <h3 className="text-lg font-semibold text-white">Proactive Alerts</h3>+ <p className="text-sm text-gray-500">+ {hasAlerts+ ? `${counts.total} alert${counts.total !== 1 ? 's' : ''} detected`+ : 'All systems nominal'}+ </p>+ </div>+ </div>+ {hasAlerts && counts.total > 5 && (+ <Link+ to="/cos"+ className="flex items-center gap-1 text-sm text-port-accent hover:text-port-accent/80 transition-colors min-h-[40px] px-2"+ >+ <span className="hidden sm:inline">View All</span>+ <ChevronRight size={16} />+ </Link>+ )}+ </div>++ {/* Severity badges */}+ {hasAlerts && (+ <div className="flex gap-2 mb-3">+ {counts.critical > 0 && (+ <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs bg-port-error/20 text-port-error">+ <AlertOctagon size={10} />+ {counts.critical} critical+ </span>+ )}+ {counts.high > 0 && (+ <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs bg-port-warning/20 text-port-warning">+ <AlertTriangle size={10} />+ {counts.high} high+ </span>+ )}+ {counts.medium > 0 && (+ <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-xs bg-port-accent/20 text-port-accent">+ {counts.medium} medium+ </span>+ )}+ </div>+ )}++ {/* Alert list */}+ {hasAlerts ? (+ <div className="space-y-2">+ {alerts.map((alert, idx) => {+ const style = SEVERITY_STYLES[alert.severity] || SEVERITY_STYLES.medium;+ const Icon = TYPE_ICONS[alert.type] || AlertTriangle;+ return (+ <Link+ key={idx}+ to={alert.link || '/cos'}+ className={`flex items-start gap-3 p-2.5 rounded-lg border ${style.border} ${style.bg} hover:brightness-110 transition-all group`}+ >+ <Icon size={14} className={`mt-0.5 shrink-0 ${style.text}`} />+ <div className="min-w-0 flex-1">+ <div className={`text-sm font-medium ${style.text} truncate`}>+ {alert.title}+ </div>+ <div className="text-xs text-gray-500 truncate">+ {alert.detail}+ </div>+ </div>+ <ChevronRight size={14} className="mt-0.5 shrink-0 text-gray-600 opacity-0 group-hover:opacity-100 transition-opacity" />+ </Link>+ );+ })}+ </div>+ ) : (+ <div className="text-center py-4 text-gray-500 text-sm">+ No issues detected — goals progressing, tasks succeeding, system healthy+ </div>+ )}+ </div>+ );+});++export default ProactiveAlertsWidget;diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsxindex b9ecd95001..6b101e9595 100644--- a/client/src/pages/Dashboard.jsx+++ b/client/src/pages/Dashboard.jsx@@ -9,6 +9,7 @@ import GoalProgressWidget from '../components/GoalProgressWidget';import UpcomingTasksWidget from '../components/UpcomingTasksWidget';import DecisionLogWidget from '../components/DecisionLogWidget';import DeathClockWidget from '../components/DeathClockWidget';+import ProactiveAlertsWidget from '../components/ProactiveAlertsWidget';import QuickBrainCapture from '../components/QuickBrainCapture';import QuickTaskWidget from '../components/QuickTaskWidget';import ReviewHubCard from '../components/ReviewHubCard';@@ -148,6 +149,7 @@ export default function Dashboard() {{/* Row 4 — Status, stats, decisions */}<div className="grid grid-cols-1 lg:grid-cols-4 gap-4">+ <ProactiveAlertsWidget /><ReviewHubCard /><SystemHealthWidget /><BackupWidget />diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 1942676862..a7aa3060e3 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -87,6 +87,9 @@ export const uploadAppleHealthXml = (file) => {});};+// Alerts+export const getAlertsSummary = (options) => request('/alerts/summary', options);+// Healthexport const checkHealth = () => request('/system/health');export const getSystemHealth = (options) => request('/system/health/details', options);diff --git a/server/index.js b/server/index.jsindex 2b619b9042..606246cf2e 100644--- a/server/index.js+++ b/server/index.js@@ -8,6 +8,7 @@ import { PATHS } from './lib/fileUtils.js';import { existsSync } from 'fs';import { readFile, unlink } from 'fs/promises';+import alertsRoutes from './routes/alerts.js';import appleHealthRoutes from './routes/appleHealth.js';import systemHealthRoutes from './routes/systemHealth.js';import appsRoutes from './routes/apps.js';@@ -200,6 +201,7 @@ app.use(express.urlencoded({ limit: '50mb', extended: true }));app.set('io', io);// API Routes+app.use('/api/alerts', alertsRoutes);app.use('/api/system', systemHealthRoutes);app.use('/api/apps', appsRoutes);app.use('/api/ports', portsRoutes);diff --git a/server/routes/alerts.js b/server/routes/alerts.jsnew file mode 100644index 0000000000..8a1e2ec39d--- /dev/null+++ b/server/routes/alerts.js@@ -0,0 +1,27 @@+/**+ * Proactive Alerts Routes+ *+ * REST API for proactive system alerts:+ * GET /api/alerts — full alert list with counts+ * GET /api/alerts/summary — compact summary for dashboard widget+ */++import { Router } from 'express';+import { asyncHandler } from '../lib/errorHandler.js';+import { generateAlerts, getAlertsSummary } from '../services/proactiveAlerts.js';++const router = Router();++// GET /api/alerts — full alert list+router.get('/', asyncHandler(async (req, res) => {+ const result = await generateAlerts();+ res.json(result);+}));++// GET /api/alerts/summary — compact summary for dashboard+router.get('/summary', asyncHandler(async (req, res) => {+ const result = await getAlertsSummary();+ res.json(result);+}));++export default router;diff --git a/server/services/proactiveAlerts.js b/server/services/proactiveAlerts.jsnew file mode 100644index 0000000000..bbce7f7e30--- /dev/null+++ b/server/services/proactiveAlerts.js@@ -0,0 +1,211 @@+/**+ * Proactive Alerts Service+ *+ * Analyzes system data to surface actionable alerts proactively:+ * - Goal stalls (no progress in 14+ days)+ * - Task success rate drops (task types with low success rates)+ * - System health warnings (high memory/CPU, errored processes)+ * - Learning health issues (skipped or critical task types)+ *+ * Designed to be called on-demand from the dashboard widget+ * and optionally from autonomous jobs.+ */++import os from 'os';+import { getGoals } from './identity.js';+import { getPerformanceSummary, getLearningSummary } from './taskLearning.js';+import { listProcesses } from './pm2.js';++const STALL_THRESHOLD_DAYS = 14;+const SUCCESS_RATE_WARNING = 50;+const MEMORY_WARNING_PCT = 85;+const MEMORY_CRITICAL_PCT = 95;+const CPU_WARNING_PCT = 90;++/**+ * Detect goals that have stalled (no progress update in 14+ days)+ */+async function checkGoalStalls() {+ const goalsData = await getGoals().catch(() => null);+ if (!goalsData?.goals?.length) return [];++ const now = Date.now();+ const alerts = [];++ for (const goal of goalsData.goals) {+ if (goal.status !== 'active' || goal.parentId) continue;++ const lastUpdate = goal.progressHistory?.length+ ? goal.progressHistory.reduce((a, b) => b.timestamp > a.timestamp ? b : a).timestamp+ : goal.createdAt;++ if (!lastUpdate) continue;++ const daysSince = Math.floor((now - new Date(lastUpdate).getTime()) / 86400000);+ if (daysSince >= STALL_THRESHOLD_DAYS) {+ alerts.push({+ type: 'goal_stall',+ severity: daysSince >= 30 ? 'high' : 'medium',+ title: `Goal stalled: ${goal.title}`,+ detail: `No progress in ${daysSince} days`,+ link: '/goals',+ metadata: { goalId: goal.id, daysSince, progress: goal.progress || 0 }+ });+ }+ }++ return alerts;+}++/**+ * Detect task types with poor success rates+ */+async function checkSuccessRates() {+ const perf = await getPerformanceSummary().catch(() => null);+ if (!perf) return [];++ return (perf.needsAttention || []).map(item => ({+ type: 'success_drop',+ severity: item.successRate < 30 ? 'high' : 'medium',+ title: `Low success rate: ${item.taskType}`,+ detail: `${item.successRate}% success across ${item.completed} tasks`,+ link: '/cos/learning',+ metadata: { taskType: item.taskType, successRate: item.successRate, completed: item.completed }+ }));+}++/**+ * Check for system resource warnings (memory, CPU, errored processes)+ */+async function checkSystemHealth() {+ const alerts = [];++ // Memory check+ const totalMem = os.totalmem();+ const freeMem = os.freemem();+ const memPct = Math.round(((totalMem - freeMem) / totalMem) * 100);++ if (memPct >= MEMORY_WARNING_PCT) {+ const formatGB = (bytes) => `${(bytes / (1024 * 1024 * 1024)).toFixed(1)}GB`;+ alerts.push({+ type: 'system_resource',+ severity: memPct >= MEMORY_CRITICAL_PCT ? 'critical' : 'high',+ title: 'High memory usage',+ detail: `${memPct}% — ${formatGB(totalMem - freeMem)} / ${formatGB(totalMem)}`,+ link: '/apps',+ metadata: { resource: 'memory', percent: memPct }+ });+ }++ // CPU check+ const cpuLoad = os.loadavg()[0];+ const cpuCount = os.cpus().length;+ const cpuPct = Math.round((cpuLoad / cpuCount) * 100);++ if (cpuPct >= CPU_WARNING_PCT) {+ alerts.push({+ type: 'system_resource',+ severity: 'high',+ title: 'High CPU usage',+ detail: `${cpuPct}% across ${cpuCount} cores`,+ link: '/apps',+ metadata: { resource: 'cpu', percent: cpuPct }+ });+ }++ // PM2 process errors+ const processes = await listProcesses().catch(() => []);+ const errored = processes.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 ${processes.length} processes in error state`,+ link: '/apps',+ metadata: { errored, total: processes.length }+ });+ }++ return alerts;+}++/**+ * Check task learning health for critical issues+ */+async function checkLearningHealth() {+ const summary = await getLearningSummary().catch(() => null);+ if (!summary || summary.status === 'good' || summary.status === 'none') return [];++ const alerts = [];++ if (summary.skipped > 0) {+ alerts.push({+ type: 'learning_health',+ severity: 'high',+ title: `${summary.skipped} task type${summary.skipped > 1 ? 's' : ''} being skipped`,+ detail: 'Very low success rates caused automatic skip — review task configuration',+ link: '/cos/learning',+ metadata: { skipped: summary.skipped, critical: summary.critical }+ });+ } else if (summary.critical > 0) {+ alerts.push({+ type: 'learning_health',+ severity: 'medium',+ title: `${summary.critical} task type${summary.critical > 1 ? 's' : ''} need attention`,+ detail: `Success rates below ${SUCCESS_RATE_WARNING}% — may need provider or prompt adjustments`,+ link: '/cos/learning',+ metadata: { critical: summary.critical, warning: summary.warning }+ });+ }++ return alerts;+}++/**+ * Generate all proactive alerts by running all checks.+ * Returns a sorted list with critical/high items first.+ */+export async function generateAlerts() {+ const startMs = Date.now();++ const [goalAlerts, successAlerts, systemAlerts, learningAlerts] = await Promise.all([+ checkGoalStalls(),+ checkSuccessRates(),+ checkSystemHealth(),+ checkLearningHealth()+ ]);++ const all = [...goalAlerts, ...successAlerts, ...systemAlerts, ...learningAlerts];++ // Sort by severity: critical > high > medium > low+ const severityOrder = { critical: 0, high: 1, medium: 2, low: 3 };+ all.sort((a, b) => (severityOrder[a.severity] ?? 3) - (severityOrder[b.severity] ?? 3));++ const durationMs = Date.now() - startMs;+ console.log(`🔔 Proactive alerts: ${all.length} alert${all.length !== 1 ? 's' : ''} generated in ${durationMs}ms`);++ return {+ alerts: all,+ counts: {+ total: all.length,+ critical: all.filter(a => a.severity === 'critical').length,+ high: all.filter(a => a.severity === 'high').length,+ medium: all.filter(a => a.severity === 'medium').length+ },+ checkedAt: new Date().toISOString()+ };+}++/**+ * Get a compact summary suitable for dashboard display.+ * Returns top 5 alerts and aggregate counts.+ */+export async function getAlertsSummary() {+ const result = await generateAlerts();+ return {+ alerts: result.alerts.slice(0, 5),+ counts: result.counts,+ checkedAt: result.checkedAt+ };+}