Skip to content

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

feat(alerts): add AI usage spike detection to proactive alerts

Adam Eivycd64fb925c89
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 011fff4ed6..3bbcd2a20a 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,7 @@
## Added
+- AI usage spike detection in proactive alerts — detects when daily token or session counts exceed 2.5x the 14-day rolling average
- PR reviewer now scans for malicious content (prompt injection, data exfiltration, supply chain attacks) and verifies GOALS.md alignment before approving
- PR reviewer verifies CI/CD passes and auto-merges clean PRs with squash + branch cleanup
- Global Pause toggle with info tooltip on task schedule UI — replaces ambiguous "Enabled" toggle
diff --git a/PLAN.md b/PLAN.md
index d7bff1849e..9618ca7fe9 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -25,7 +25,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
- **Identity Context Injection** — Per-task-type digital twin preamble toggle
- **Agent Confidence & Autonomy Levels** — Dynamic tiers based on success rates
- **Content Calendar** — Unified calendar across platforms
-- **Proactive Insight Alerts** — Brain connections, success drops, goal stalls, cost spikes
+- [x] **Proactive Insight Alerts** — Brain connections, success drops, goal stalls, cost spikes
- **Goal Decomposition Engine** — Auto-decompose goals into task sequences
- **Knowledge Graph Visualization** — Extend BrainGraph 3D to full knowledge graph
- [x] **Time Capsule Snapshots** — Periodic versioned digital twin archives
diff --git a/client/src/components/ProactiveAlertsWidget.jsx b/client/src/components/ProactiveAlertsWidget.jsx
index 5cff8c9ae8..bcb3e8389c 100644
--- a/client/src/components/ProactiveAlertsWidget.jsx
+++ b/client/src/components/ProactiveAlertsWidget.jsx
@@ -7,6 +7,7 @@ import {
AlertOctagon,
Target,
TrendingDown,
+ TrendingUp,
Cpu,
BookOpen,
CheckCircle
@@ -23,6 +24,7 @@ const SEVERITY_STYLES = {
const TYPE_ICONS = {
goal_stall: Target,
success_drop: TrendingDown,
+ cost_spike: TrendingUp,
system_resource: Cpu,
process_error: AlertOctagon,
learning_health: BookOpen
diff --git a/server/services/proactiveAlerts.js b/server/services/proactiveAlerts.js
index 5e7b3a32d7..332f339c4d 100644
--- a/server/services/proactiveAlerts.js
+++ b/server/services/proactiveAlerts.js
@@ -6,6 +6,7 @@
* - 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)
+ * - AI usage spikes (token/session usage significantly above rolling average)
*
* Designed to be called on-demand from the dashboard widget
* and optionally from autonomous jobs.
@@ -15,12 +16,15 @@ import os from 'os';
import { getGoals } from './identity.js';
import { getPerformanceSummary, getLearningSummary } from './taskLearning.js';
import { listProcesses } from './pm2.js';
+import { getUsage } from './usage.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;
+const USAGE_SPIKE_MULTIPLIER = 2.5;
+const USAGE_MIN_HISTORY_DAYS = 3;
/**
* Detect goals that have stalled (no progress update in 14+ days)
@@ -162,6 +166,66 @@ async function checkLearningHealth() {
return alerts;
}
+/**
+ * Detect AI usage spikes (tokens or sessions significantly above rolling average)
+ */
+async function checkUsageSpikes() {
+ const usage = getUsage();
+ if (!usage?.dailyActivity) return [];
+
+ const daily = usage.dailyActivity;
+ const today = new Date().toISOString().split('T')[0];
+
+ // Collect recent days (excluding today since it's incomplete)
+ const recentDays = [];
+ for (let i = 1; i <= 14; i++) {
+ const d = new Date();
+ d.setDate(d.getDate() - i);
+ const dateStr = d.toISOString().split('T')[0];
+ const dayData = daily[dateStr];
+ if (dayData && dayData.sessions > 0) {
+ recentDays.push(dayData);
+ }
+ }
+
+ if (recentDays.length < USAGE_MIN_HISTORY_DAYS) return [];
+
+ const avgTokens = recentDays.reduce((sum, d) => sum + (d.tokens || 0), 0) / recentDays.length;
+ const avgSessions = recentDays.reduce((sum, d) => sum + (d.sessions || 0), 0) / recentDays.length;
+
+ const alerts = [];
+ const todayData = daily[today];
+
+ if (todayData && avgTokens > 0) {
+ const tokenRatio = todayData.tokens / avgTokens;
+ if (tokenRatio >= USAGE_SPIKE_MULTIPLIER) {
+ const formatTokens = (t) => t >= 1000 ? `${(t / 1000).toFixed(1)}k` : String(t);
+ alerts.push({
+ type: 'cost_spike',
+ severity: tokenRatio >= 5 ? 'high' : 'medium',
+ title: 'AI token usage spike',
+ detail: `${formatTokens(todayData.tokens)} tokens today vs ${formatTokens(Math.round(avgTokens))} avg/day (${tokenRatio.toFixed(1)}x)`,
+ link: '/devtools/usage',
+ metadata: { resource: 'tokens', today: todayData.tokens, average: Math.round(avgTokens), ratio: Math.round(tokenRatio * 10) / 10 }
+ });
+ }
+
+ const sessionRatio = todayData.sessions / avgSessions;
+ if (sessionRatio >= USAGE_SPIKE_MULTIPLIER && avgSessions > 0) {
+ alerts.push({
+ type: 'cost_spike',
+ severity: sessionRatio >= 5 ? 'high' : 'medium',
+ title: 'AI session spike',
+ detail: `${todayData.sessions} sessions today vs ${Math.round(avgSessions)} avg/day (${sessionRatio.toFixed(1)}x)`,
+ link: '/devtools/usage',
+ metadata: { resource: 'sessions', today: todayData.sessions, average: Math.round(avgSessions), ratio: Math.round(sessionRatio * 10) / 10 }
+ });
+ }
+ }
+
+ return alerts;
+}
+
/**
* Generate all proactive alerts by running all checks.
* Returns a sorted list with critical/high items first.
@@ -169,14 +233,15 @@ async function checkLearningHealth() {
export async function generateAlerts() {
const startMs = Date.now();
- const [goalAlerts, successAlerts, systemAlerts, learningAlerts] = await Promise.all([
+ const [goalAlerts, successAlerts, systemAlerts, learningAlerts, usageAlerts] = await Promise.all([
checkGoalStalls(),
checkSuccessRates(),
checkSystemHealth(),
- checkLearningHealth()
+ checkLearningHealth(),
+ checkUsageSpikes()
]);
- const all = [...goalAlerts, ...successAlerts, ...systemAlerts, ...learningAlerts];
+ const all = [...goalAlerts, ...successAlerts, ...systemAlerts, ...learningAlerts, ...usageAlerts];
// Sort by severity: critical > high > medium > low
const severityOrder = { critical: 0, high: 1, medium: 2, low: 3 };